ngram
listlengths
0
82k
[ "= int(tokens[2]) if tokens[2] < tokens[1]: print >>sys.stderr, ( 'Invalid", "= os.path.dirname(os.path.realpath(__file__)) annotated_junctions_ = set() for junction_file in glob.glob( os.path.join(args.annotations,", "datasource_code = file2source[label] unique_junctions = set() #extract_splice_sites_path prints 0-based, exon", "of this script, no lift-over Rips junctions from annotation files", "import glob import os import gzip import sys #file2source =", "-k1,1 -k2,2n -k3,3n | gzip >annotated_junctions.tsv.gz \"\"\" import subprocess import", "0: raise RuntimeError( 'extract_splice_sites.py had nonzero exit code {}.'.format( exit_code", "coords around junctions #hence the +2 for the start here", "stdout, which we record as annotated_junctions.tsv.gz in runs/sra (same directory", "= argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) # Add command-line arguments parser.add_argument('--extract-script-dir', type=str, required=True,", "label, len(unique_junctions) ) junc2datasource = {} for junction in annotated_junctions_:", "= int(tokens[1]) + 2 tokens[2] = int(tokens[2]) if tokens[2] <", "'.join([ sys.executable, extract_splice_sites_path, '<(gzip -cd %s)' % junction_file ]), shell=True,", "sys.executable, extract_splice_sites_path, '<(gzip -cd %s)' % junction_file ]), shell=True, executable='/bin/bash',", "gzipped format') ) args = parser.parse_args() extract_destination = tempfile.mkdtemp() atexit.register(shutil.rmtree,", "is (tab-separated fields), one per junction 1. Chromosome 2. Start", "junction_file in glob.glob( os.path.join(args.annotations, '*') ): label = os.path.basename(junction_file) datasource_code", "format') ) args = parser.parse_args() extract_destination = tempfile.mkdtemp() atexit.register(shutil.rmtree, extract_destination)", "inclusive) 3. End position (1-based, inclusive) 4. Strand (+ or", "print >>sys.stderr, ( 'Invalid junction ({}, {}, {}) from file", "for line in extract_process.stdout: tokens = line.strip().split('\\t') tokens[1] = int(tokens[1])", "RuntimeError( 'extract_splice_sites.py had nonzero exit code {}.'.format( exit_code ) )", "executable='/bin/bash', stdout=subprocess.PIPE ) for line in extract_process.stdout: tokens = line.strip().split('\\t')", "in {}: {}'.format( label, len(unique_junctions) ) junc2datasource = {} for", ") continue tokens.append(datasource_code) junction_to_add = tuple(tokens) annotated_junctions_.add(junction_to_add) unique_junctions.add(junction_to_add) extract_process.stdout.close() exit_code", "subprocess import tarfile import argparse import tempfile import atexit import", "% junction_file ]), shell=True, executable='/bin/bash', stdout=subprocess.PIPE ) for line in", "path/to/jan_24_2016_annotations.tar.gz | sort -k1,1 -k2,2n -k3,3n | gzip >annotated_junctions.tsv.gz \"\"\"", "annotated_junctions_ = set() for junction_file in glob.glob( os.path.join(args.annotations, '*') ):", "2. Start position (1-based, inclusive) 3. End position (1-based, inclusive)", "is required by tables.py. The format of annotated_junctions.tsv.gz is (tab-separated", "around junctions #hence the +2 for the start here extract_process", "| gzip >annotated_junctions.tsv.gz \"\"\" import subprocess import tarfile import argparse", "import argparse import tempfile import atexit import shutil import glob", "junction 1. Chromosome 2. Start position (1-based, inclusive) 3. End", "nonzero exit code {}.'.format( exit_code ) ) print >>sys.stderr, 'Junctions", "sys #file2source = {\"hg19/gencode.v19.annotation.gtf.gz\":\"gC19\",\"hg19/refGene.txt.gz\":\"rG19\",\"hg19/acembly.txt.gz\":\"aC19\",\"hg19/ccdsGene.txt.gz\":\"cG19\",\"hg19/vegaGene.txt.gz\":\"vG19\",\"hg19/knownGene.txt.gz\":\"kG19\",\"hg19/mgcGenes.txt.gz\":\"mG19\",\"hg19/lincRNAsTranscripts.txt.gz\":\"lR19\",\"hg19/sibGene.txt.gz\":\"sG19\",\"hg38/refGene.txt.gz\":\"rG38\",\"hg38/ccdsGene.txt.gz\":\"cG38\",\"hg38/gencode.v24.annotation.gtf.gz\":\"gC38\",\"hg38/knownGene.txt.gz\":\"kG38\",\"hg38/mgcGenes.txt.gz\":\"mG38\",\"hg38/lincRNAsTranscripts.txt.gz\":\"lR38\",\"hg38/sibGene.txt.gz\":\"sG38\"} #file2source = {\"mm10/mouse10_ucsc_genes.gtf.gz\":\"kG10\",\"mm10/mouse10_gencodevm11_comp.gtf.gz\":\"gC11\",\"mm10/mouse10_gencodevm09_comp.gtf.gz\":\"gC09\",\"mm10/mouse10_refseq_refgene.gtf.gz\":\"rG10\"} file2source = {\"mouse10_ucsc_genes.gtf.gz\":\"kG10\",\"mouse10_gencodevm11_comp.gtf.gz\":\"gC11\",\"mouse10_gencodevm09_comp.gtf.gz\":\"gC09\",\"mouse10_refseq_refgene.gtf.gz\":\"rG10\"}", "which we record as annotated_junctions.tsv.gz in runs/sra (same directory as", "annotated_junctions.tsv.gz in runs/sra (same directory as this file). annotated_junctions.tsv.gz is", "#file2source = {\"hg19/gencode.v19.annotation.gtf.gz\":\"gC19\",\"hg19/refGene.txt.gz\":\"rG19\",\"hg19/acembly.txt.gz\":\"aC19\",\"hg19/ccdsGene.txt.gz\":\"cG19\",\"hg19/vegaGene.txt.gz\":\"vG19\",\"hg19/knownGene.txt.gz\":\"kG19\",\"hg19/mgcGenes.txt.gz\":\"mG19\",\"hg19/lincRNAsTranscripts.txt.gz\":\"lR19\",\"hg19/sibGene.txt.gz\":\"sG19\",\"hg38/refGene.txt.gz\":\"rG38\",\"hg38/ccdsGene.txt.gz\":\"cG38\",\"hg38/gencode.v24.annotation.gtf.gz\":\"gC38\",\"hg38/knownGene.txt.gz\":\"kG38\",\"hg38/mgcGenes.txt.gz\":\"mG38\",\"hg38/lincRNAsTranscripts.txt.gz\":\"lR38\",\"hg38/sibGene.txt.gz\":\"sG38\"} #file2source = {\"mm10/mouse10_ucsc_genes.gtf.gz\":\"kG10\",\"mm10/mouse10_gencodevm11_comp.gtf.gz\":\"gC11\",\"mm10/mouse10_gencodevm09_comp.gtf.gz\":\"gC09\",\"mm10/mouse10_refseq_refgene.gtf.gz\":\"rG10\"} file2source = {\"mouse10_ucsc_genes.gtf.gz\":\"kG10\",\"mouse10_gencodevm11_comp.gtf.gz\":\"gC11\",\"mouse10_gencodevm09_comp.gtf.gz\":\"gC09\",\"mouse10_refseq_refgene.gtf.gz\":\"rG10\"} if", "for junction in annotated_junctions_: if junction[:4] not in junc2datasource: junc2datasource[junction[:4]]=set()", "rip_annotated_junctions.py --hisat2-dir /path/to/hisat2-2.0.1-beta --annotations path/to/jan_24_2016_annotations.tar.gz | sort -k1,1 -k2,2n -k3,3n", "for junction in annotated_junctions_: if junction[:4] not in seen: sources", "atexit.register(shutil.rmtree, extract_destination) #with tarfile.open(args.annotations, 'r:gz') as tar: # tar.extractall(path=extract_destination) extract_splice_sites_path", "(from HISAT2)') ) parser.add_argument('--annotations', type=str, required=True, help=('full path to directory", "tokens[0], tokens[1], tokens[2], junction_file ) continue tokens.append(datasource_code) junction_to_add = tuple(tokens)", "{}. ' 'Skipping.' ).format( tokens[0], tokens[1], tokens[2], junction_file ) continue", "= {} for junction in annotated_junctions_: if junction[:4] not in", "Print file's docstring if -h is invoked parser = argparse.ArgumentParser(description=__doc__,", "the start here extract_process = subprocess.Popen(' '.join([ sys.executable, extract_splice_sites_path, '<(gzip", "shell=True, executable='/bin/bash', stdout=subprocess.PIPE ) for line in extract_process.stdout: tokens =", "dumped to stdout, which we record as annotated_junctions.tsv.gz in runs/sra", "shutil import glob import os import gzip import sys #file2source", "script, no lift-over Rips junctions from annotation files contained in", "seen: sources = \",\".join(sorted(junc2datasource[junction[:4]])) print \"%s\\t%s\" % ('\\t'.join(map(str, junction[:4])),sources) seen.add(junction[:4])", "| sort -k1,1 -k2,2n -k3,3n | gzip >annotated_junctions.tsv.gz \"\"\" import", "{\"mm10/mouse10_ucsc_genes.gtf.gz\":\"kG10\",\"mm10/mouse10_gencodevm11_comp.gtf.gz\":\"gC11\",\"mm10/mouse10_gencodevm09_comp.gtf.gz\":\"gC09\",\"mm10/mouse10_refseq_refgene.gtf.gz\":\"rG10\"} file2source = {\"mouse10_ucsc_genes.gtf.gz\":\"kG10\",\"mouse10_gencodevm11_comp.gtf.gz\":\"gC11\",\"mouse10_gencodevm09_comp.gtf.gz\":\"gC09\",\"mouse10_refseq_refgene.gtf.gz\":\"rG10\"} if __name__ == '__main__': # Print", "had nonzero exit code {}.'.format( exit_code ) ) print >>sys.stderr,", "if tokens[2] < tokens[1]: print >>sys.stderr, ( 'Invalid junction ({},", "print >>sys.stderr, 'Junctions in {}: {}'.format( label, len(unique_junctions) ) junc2datasource", "tokens[2], junction_file ) continue tokens.append(datasource_code) junction_to_add = tuple(tokens) annotated_junctions_.add(junction_to_add) unique_junctions.add(junction_to_add)", "os.path.basename(junction_file) datasource_code = file2source[label] unique_junctions = set() #extract_splice_sites_path prints 0-based,", "the +2 for the start here extract_process = subprocess.Popen(' '.join([", "]), shell=True, executable='/bin/bash', stdout=subprocess.PIPE ) for line in extract_process.stdout: tokens", "junction_to_add = tuple(tokens) annotated_junctions_.add(junction_to_add) unique_junctions.add(junction_to_add) extract_process.stdout.close() exit_code = extract_process.wait() if", "annotation files contained in jan_24_2016_annotations.tar.gz, as described in annotation_definition.md. Junctions", "in runs/sra (same directory as this file). annotated_junctions.tsv.gz is required", "parser.add_argument('--annotations', type=str, required=True, help=('full path to directory that has the", "files contained in jan_24_2016_annotations.tar.gz, as described in annotation_definition.md. Junctions are", "os import gzip import sys #file2source = {\"hg19/gencode.v19.annotation.gtf.gz\":\"gC19\",\"hg19/refGene.txt.gz\":\"rG19\",\"hg19/acembly.txt.gz\":\"aC19\",\"hg19/ccdsGene.txt.gz\":\"cG19\",\"hg19/vegaGene.txt.gz\":\"vG19\",\"hg19/knownGene.txt.gz\":\"kG19\",\"hg19/mgcGenes.txt.gz\":\"mG19\",\"hg19/lincRNAsTranscripts.txt.gz\":\"lR19\",\"hg19/sibGene.txt.gz\":\"sG19\",\"hg38/refGene.txt.gz\":\"rG38\",\"hg38/ccdsGene.txt.gz\":\"cG38\",\"hg38/gencode.v24.annotation.gtf.gz\":\"gC38\",\"hg38/knownGene.txt.gz\":\"kG38\",\"hg38/mgcGenes.txt.gz\":\"mG38\",\"hg38/lincRNAsTranscripts.txt.gz\":\"lR38\",\"hg38/sibGene.txt.gz\":\"sG38\"} #file2source =", "junction in annotated_junctions_: if junction[:4] not in seen: sources =", "as annotated_junctions.tsv.gz in runs/sra (same directory as this file). annotated_junctions.tsv.gz", "glob import os import gzip import sys #file2source = {\"hg19/gencode.v19.annotation.gtf.gz\":\"gC19\",\"hg19/refGene.txt.gz\":\"rG19\",\"hg19/acembly.txt.gz\":\"aC19\",\"hg19/ccdsGene.txt.gz\":\"cG19\",\"hg19/vegaGene.txt.gz\":\"vG19\",\"hg19/knownGene.txt.gz\":\"kG19\",\"hg19/mgcGenes.txt.gz\":\"mG19\",\"hg19/lincRNAsTranscripts.txt.gz\":\"lR19\",\"hg19/sibGene.txt.gz\":\"sG19\",\"hg38/refGene.txt.gz\":\"rG38\",\"hg38/ccdsGene.txt.gz\":\"cG38\",\"hg38/gencode.v24.annotation.gtf.gz\":\"gC38\",\"hg38/knownGene.txt.gz\":\"kG38\",\"hg38/mgcGenes.txt.gz\":\"mG38\",\"hg38/lincRNAsTranscripts.txt.gz\":\"lR38\",\"hg38/sibGene.txt.gz\":\"sG38\"}", "has the annotation GTF(s) in gzipped format') ) args =", "start here extract_process = subprocess.Popen(' '.join([ sys.executable, extract_splice_sites_path, '<(gzip -cd", "extract_process.stdout: tokens = line.strip().split('\\t') tokens[1] = int(tokens[1]) + 2 tokens[2]", "tuple(tokens) annotated_junctions_.add(junction_to_add) unique_junctions.add(junction_to_add) extract_process.stdout.close() exit_code = extract_process.wait() if exit_code !=", "= subprocess.Popen(' '.join([ sys.executable, extract_splice_sites_path, '<(gzip -cd %s)' % junction_file", "in gzipped format') ) args = parser.parse_args() extract_destination = tempfile.mkdtemp()", "continue tokens.append(datasource_code) junction_to_add = tuple(tokens) annotated_junctions_.add(junction_to_add) unique_junctions.add(junction_to_add) extract_process.stdout.close() exit_code =", "if junction[:4] not in junc2datasource: junc2datasource[junction[:4]]=set() junc2datasource[junction[:4]].add(junction[4]) seen = set()", "set() #extract_splice_sites_path prints 0-based, exon coords around junctions #hence the", "not in seen: sources = \",\".join(sorted(junc2datasource[junction[:4]])) print \"%s\\t%s\" % ('\\t'.join(map(str,", "os.path.join(args.extract_script_dir, 'extract_splice_sites.py') containing_dir = os.path.dirname(os.path.realpath(__file__)) annotated_junctions_ = set() for junction_file", "tar.extractall(path=extract_destination) extract_splice_sites_path = os.path.join(args.extract_script_dir, 'extract_splice_sites.py') containing_dir = os.path.dirname(os.path.realpath(__file__)) annotated_junctions_ =", "junction ({}, {}, {}) from file {}. ' 'Skipping.' ).format(", "formatter_class=argparse.RawDescriptionHelpFormatter) # Add command-line arguments parser.add_argument('--extract-script-dir', type=str, required=True, help=('path to", "Must have Stats are written to stderr From the runs/sra/v2", "this script, no lift-over Rips junctions from annotation files contained", "junc2datasource = {} for junction in annotated_junctions_: if junction[:4] not", "tar: # tar.extractall(path=extract_destination) extract_splice_sites_path = os.path.join(args.extract_script_dir, 'extract_splice_sites.py') containing_dir = os.path.dirname(os.path.realpath(__file__))", "rip_annotated_junctions.py Non-reference/species verson of this script, no lift-over Rips junctions", "tempfile.mkdtemp() atexit.register(shutil.rmtree, extract_destination) #with tarfile.open(args.annotations, 'r:gz') as tar: # tar.extractall(path=extract_destination)", "'r:gz') as tar: # tar.extractall(path=extract_destination) extract_splice_sites_path = os.path.join(args.extract_script_dir, 'extract_splice_sites.py') containing_dir", "directory as this file). annotated_junctions.tsv.gz is required by tables.py. The", "\"\"\" rip_annotated_junctions.py Non-reference/species verson of this script, no lift-over Rips", "parser.add_argument('--extract-script-dir', type=str, required=True, help=('path to directory containing extract_splice_sites.py script (from", "extract_destination = tempfile.mkdtemp() atexit.register(shutil.rmtree, extract_destination) #with tarfile.open(args.annotations, 'r:gz') as tar:", "from file {}. ' 'Skipping.' ).format( tokens[0], tokens[1], tokens[2], junction_file", "arguments parser.add_argument('--extract-script-dir', type=str, required=True, help=('path to directory containing extract_splice_sites.py script", "{}: {}'.format( label, len(unique_junctions) ) junc2datasource = {} for junction", "code {}.'.format( exit_code ) ) print >>sys.stderr, 'Junctions in {}:", "atexit import shutil import glob import os import gzip import", "exit_code = extract_process.wait() if exit_code != 0: raise RuntimeError( 'extract_splice_sites.py", "as this file). annotated_junctions.tsv.gz is required by tables.py. The format", "glob.glob( os.path.join(args.annotations, '*') ): label = os.path.basename(junction_file) datasource_code = file2source[label]", "1. Chromosome 2. Start position (1-based, inclusive) 3. End position", "gzip import sys #file2source = {\"hg19/gencode.v19.annotation.gtf.gz\":\"gC19\",\"hg19/refGene.txt.gz\":\"rG19\",\"hg19/acembly.txt.gz\":\"aC19\",\"hg19/ccdsGene.txt.gz\":\"cG19\",\"hg19/vegaGene.txt.gz\":\"vG19\",\"hg19/knownGene.txt.gz\":\"kG19\",\"hg19/mgcGenes.txt.gz\":\"mG19\",\"hg19/lincRNAsTranscripts.txt.gz\":\"lR19\",\"hg19/sibGene.txt.gz\":\"sG19\",\"hg38/refGene.txt.gz\":\"rG38\",\"hg38/ccdsGene.txt.gz\":\"cG38\",\"hg38/gencode.v24.annotation.gtf.gz\":\"gC38\",\"hg38/knownGene.txt.gz\":\"kG38\",\"hg38/mgcGenes.txt.gz\":\"mG38\",\"hg38/lincRNAsTranscripts.txt.gz\":\"lR38\",\"hg38/sibGene.txt.gz\":\"sG38\"} #file2source = {\"mm10/mouse10_ucsc_genes.gtf.gz\":\"kG10\",\"mm10/mouse10_gencodevm11_comp.gtf.gz\":\"gC11\",\"mm10/mouse10_gencodevm09_comp.gtf.gz\":\"gC09\",\"mm10/mouse10_refseq_refgene.gtf.gz\":\"rG10\"} file2source", "tokens[1], tokens[2], junction_file ) continue tokens.append(datasource_code) junction_to_add = tuple(tokens) annotated_junctions_.add(junction_to_add)", "path to directory that has the annotation GTF(s) in gzipped", ") args = parser.parse_args() extract_destination = tempfile.mkdtemp() atexit.register(shutil.rmtree, extract_destination) #with", "set() for junction in annotated_junctions_: if junction[:4] not in seen:", "to stdout, which we record as annotated_junctions.tsv.gz in runs/sra (same", "= tempfile.mkdtemp() atexit.register(shutil.rmtree, extract_destination) #with tarfile.open(args.annotations, 'r:gz') as tar: #", "as described in annotation_definition.md. Junctions are dumped to stdout, which", ").format( tokens[0], tokens[1], tokens[2], junction_file ) continue tokens.append(datasource_code) junction_to_add =", "raise RuntimeError( 'extract_splice_sites.py had nonzero exit code {}.'.format( exit_code )", "prints 0-based, exon coords around junctions #hence the +2 for", "we ran pypy rip_annotated_junctions.py --hisat2-dir /path/to/hisat2-2.0.1-beta --annotations path/to/jan_24_2016_annotations.tar.gz | sort", "{\"hg19/gencode.v19.annotation.gtf.gz\":\"gC19\",\"hg19/refGene.txt.gz\":\"rG19\",\"hg19/acembly.txt.gz\":\"aC19\",\"hg19/ccdsGene.txt.gz\":\"cG19\",\"hg19/vegaGene.txt.gz\":\"vG19\",\"hg19/knownGene.txt.gz\":\"kG19\",\"hg19/mgcGenes.txt.gz\":\"mG19\",\"hg19/lincRNAsTranscripts.txt.gz\":\"lR19\",\"hg19/sibGene.txt.gz\":\"sG19\",\"hg38/refGene.txt.gz\":\"rG38\",\"hg38/ccdsGene.txt.gz\":\"cG38\",\"hg38/gencode.v24.annotation.gtf.gz\":\"gC38\",\"hg38/knownGene.txt.gz\":\"kG38\",\"hg38/mgcGenes.txt.gz\":\"mG38\",\"hg38/lincRNAsTranscripts.txt.gz\":\"lR38\",\"hg38/sibGene.txt.gz\":\"sG38\"} #file2source = {\"mm10/mouse10_ucsc_genes.gtf.gz\":\"kG10\",\"mm10/mouse10_gencodevm11_comp.gtf.gz\":\"gC11\",\"mm10/mouse10_gencodevm09_comp.gtf.gz\":\"gC09\",\"mm10/mouse10_refseq_refgene.gtf.gz\":\"rG10\"} file2source = {\"mouse10_ucsc_genes.gtf.gz\":\"kG10\",\"mouse10_gencodevm11_comp.gtf.gz\":\"gC11\",\"mouse10_gencodevm09_comp.gtf.gz\":\"gC09\",\"mouse10_refseq_refgene.gtf.gz\":\"rG10\"} if __name__ ==", "Rips junctions from annotation files contained in jan_24_2016_annotations.tar.gz, as described", "= os.path.join(args.extract_script_dir, 'extract_splice_sites.py') containing_dir = os.path.dirname(os.path.realpath(__file__)) annotated_junctions_ = set() for", "== '__main__': # Print file's docstring if -h is invoked", "docstring if -h is invoked parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) #", "= {\"mm10/mouse10_ucsc_genes.gtf.gz\":\"kG10\",\"mm10/mouse10_gencodevm11_comp.gtf.gz\":\"gC11\",\"mm10/mouse10_gencodevm09_comp.gtf.gz\":\"gC09\",\"mm10/mouse10_refseq_refgene.gtf.gz\":\"rG10\"} file2source = {\"mouse10_ucsc_genes.gtf.gz\":\"kG10\",\"mouse10_gencodevm11_comp.gtf.gz\":\"gC11\",\"mouse10_gencodevm09_comp.gtf.gz\":\"gC09\",\"mouse10_refseq_refgene.gtf.gz\":\"rG10\"} if __name__ == '__main__': #", "extract_process.stdout.close() exit_code = extract_process.wait() if exit_code != 0: raise RuntimeError(", "= set() for junction_file in glob.glob( os.path.join(args.annotations, '*') ): label", "if __name__ == '__main__': # Print file's docstring if -h", "#hence the +2 for the start here extract_process = subprocess.Popen('", "here extract_process = subprocess.Popen(' '.join([ sys.executable, extract_splice_sites_path, '<(gzip -cd %s)'", "(same directory as this file). annotated_junctions.tsv.gz is required by tables.py.", "3. End position (1-based, inclusive) 4. Strand (+ or -)", "0-based, exon coords around junctions #hence the +2 for the", "End position (1-based, inclusive) 4. Strand (+ or -) 5.", "file {}. ' 'Skipping.' ).format( tokens[0], tokens[1], tokens[2], junction_file )", "unique_junctions.add(junction_to_add) extract_process.stdout.close() exit_code = extract_process.wait() if exit_code != 0: raise", "command-line arguments parser.add_argument('--extract-script-dir', type=str, required=True, help=('path to directory containing extract_splice_sites.py", "the annotation GTF(s) in gzipped format') ) args = parser.parse_args()", "type=str, required=True, help=('path to directory containing extract_splice_sites.py script (from HISAT2)')", "annotated_junctions_.add(junction_to_add) unique_junctions.add(junction_to_add) extract_process.stdout.close() exit_code = extract_process.wait() if exit_code != 0:", "ran pypy rip_annotated_junctions.py --hisat2-dir /path/to/hisat2-2.0.1-beta --annotations path/to/jan_24_2016_annotations.tar.gz | sort -k1,1", "= line.strip().split('\\t') tokens[1] = int(tokens[1]) + 2 tokens[2] = int(tokens[2])", "extract_process.wait() if exit_code != 0: raise RuntimeError( 'extract_splice_sites.py had nonzero", "annotated_junctions.tsv.gz is required by tables.py. The format of annotated_junctions.tsv.gz is", "annotated_junctions_: if junction[:4] not in junc2datasource: junc2datasource[junction[:4]]=set() junc2datasource[junction[:4]].add(junction[4]) seen =", "this file). annotated_junctions.tsv.gz is required by tables.py. The format of", "tokens.append(datasource_code) junction_to_add = tuple(tokens) annotated_junctions_.add(junction_to_add) unique_junctions.add(junction_to_add) extract_process.stdout.close() exit_code = extract_process.wait()", "in jan_24_2016_annotations.tar.gz, as described in annotation_definition.md. Junctions are dumped to", "{}'.format( label, len(unique_junctions) ) junc2datasource = {} for junction in", "extract_process = subprocess.Popen(' '.join([ sys.executable, extract_splice_sites_path, '<(gzip -cd %s)' %", "junctions #hence the +2 for the start here extract_process =", "Chromosome 2. Start position (1-based, inclusive) 3. End position (1-based,", "import tempfile import atexit import shutil import glob import os", "__name__ == '__main__': # Print file's docstring if -h is", "): label = os.path.basename(junction_file) datasource_code = file2source[label] unique_junctions = set()", "required by tables.py. The format of annotated_junctions.tsv.gz is (tab-separated fields),", "as tar: # tar.extractall(path=extract_destination) extract_splice_sites_path = os.path.join(args.extract_script_dir, 'extract_splice_sites.py') containing_dir =", "= extract_process.wait() if exit_code != 0: raise RuntimeError( 'extract_splice_sites.py had", "label = os.path.basename(junction_file) datasource_code = file2source[label] unique_junctions = set() #extract_splice_sites_path", "annotated_junctions.tsv.gz is (tab-separated fields), one per junction 1. Chromosome 2.", "runs/sra (same directory as this file). annotated_junctions.tsv.gz is required by", "pypy rip_annotated_junctions.py --hisat2-dir /path/to/hisat2-2.0.1-beta --annotations path/to/jan_24_2016_annotations.tar.gz | sort -k1,1 -k2,2n", "( 'Invalid junction ({}, {}, {}) from file {}. '", "in annotated_junctions_: if junction[:4] not in junc2datasource: junc2datasource[junction[:4]]=set() junc2datasource[junction[:4]].add(junction[4]) seen", "position (1-based, inclusive) 3. End position (1-based, inclusive) 4. Strand", "exon coords around junctions #hence the +2 for the start", "= {\"mouse10_ucsc_genes.gtf.gz\":\"kG10\",\"mouse10_gencodevm11_comp.gtf.gz\":\"gC11\",\"mouse10_gencodevm09_comp.gtf.gz\":\"gC09\",\"mouse10_refseq_refgene.gtf.gz\":\"rG10\"} if __name__ == '__main__': # Print file's docstring", "{}, {}) from file {}. ' 'Skipping.' ).format( tokens[0], tokens[1],", "parser.parse_args() extract_destination = tempfile.mkdtemp() atexit.register(shutil.rmtree, extract_destination) #with tarfile.open(args.annotations, 'r:gz') as", ") junc2datasource = {} for junction in annotated_junctions_: if junction[:4]", "from annotation files contained in jan_24_2016_annotations.tar.gz, as described in annotation_definition.md.", "stderr From the runs/sra/v2 directory, we ran pypy rip_annotated_junctions.py --hisat2-dir", "junction_file ]), shell=True, executable='/bin/bash', stdout=subprocess.PIPE ) for line in extract_process.stdout:", "import shutil import glob import os import gzip import sys", "file2source = {\"mouse10_ucsc_genes.gtf.gz\":\"kG10\",\"mouse10_gencodevm11_comp.gtf.gz\":\"gC11\",\"mouse10_gencodevm09_comp.gtf.gz\":\"gC09\",\"mouse10_refseq_refgene.gtf.gz\":\"rG10\"} if __name__ == '__main__': # Print file's", "{}.'.format( exit_code ) ) print >>sys.stderr, 'Junctions in {}: {}'.format(", "format of annotated_junctions.tsv.gz is (tab-separated fields), one per junction 1.", "extract_destination) #with tarfile.open(args.annotations, 'r:gz') as tar: # tar.extractall(path=extract_destination) extract_splice_sites_path =", "parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) # Add command-line arguments parser.add_argument('--extract-script-dir', type=str,", "lift-over Rips junctions from annotation files contained in jan_24_2016_annotations.tar.gz, as", "inclusive) 4. Strand (+ or -) 5. anno source (abbreviation)", "= os.path.basename(junction_file) datasource_code = file2source[label] unique_junctions = set() #extract_splice_sites_path prints", "#!/usr/bin/env python \"\"\" rip_annotated_junctions.py Non-reference/species verson of this script, no", "that has the annotation GTF(s) in gzipped format') ) args", "file). annotated_junctions.tsv.gz is required by tables.py. The format of annotated_junctions.tsv.gz", "import sys #file2source = {\"hg19/gencode.v19.annotation.gtf.gz\":\"gC19\",\"hg19/refGene.txt.gz\":\"rG19\",\"hg19/acembly.txt.gz\":\"aC19\",\"hg19/ccdsGene.txt.gz\":\"cG19\",\"hg19/vegaGene.txt.gz\":\"vG19\",\"hg19/knownGene.txt.gz\":\"kG19\",\"hg19/mgcGenes.txt.gz\":\"mG19\",\"hg19/lincRNAsTranscripts.txt.gz\":\"lR19\",\"hg19/sibGene.txt.gz\":\"sG19\",\"hg38/refGene.txt.gz\":\"rG38\",\"hg38/ccdsGene.txt.gz\":\"cG38\",\"hg38/gencode.v24.annotation.gtf.gz\":\"gC38\",\"hg38/knownGene.txt.gz\":\"kG38\",\"hg38/mgcGenes.txt.gz\":\"mG38\",\"hg38/lincRNAsTranscripts.txt.gz\":\"lR38\",\"hg38/sibGene.txt.gz\":\"sG38\"} #file2source = {\"mm10/mouse10_ucsc_genes.gtf.gz\":\"kG10\",\"mm10/mouse10_gencodevm11_comp.gtf.gz\":\"gC11\",\"mm10/mouse10_gencodevm09_comp.gtf.gz\":\"gC09\",\"mm10/mouse10_refseq_refgene.gtf.gz\":\"rG10\"} file2source =", "we record as annotated_junctions.tsv.gz in runs/sra (same directory as this", "junction in annotated_junctions_: if junction[:4] not in junc2datasource: junc2datasource[junction[:4]]=set() junc2datasource[junction[:4]].add(junction[4])", "if junction[:4] not in seen: sources = \",\".join(sorted(junc2datasource[junction[:4]])) print \"%s\\t%s\"", "per junction 1. Chromosome 2. Start position (1-based, inclusive) 3.", "tables.py. The format of annotated_junctions.tsv.gz is (tab-separated fields), one per", "if exit_code != 0: raise RuntimeError( 'extract_splice_sites.py had nonzero exit", "4. Strand (+ or -) 5. anno source (abbreviation) Must", "directory containing extract_splice_sites.py script (from HISAT2)') ) parser.add_argument('--annotations', type=str, required=True,", "annotated_junctions_: if junction[:4] not in seen: sources = \",\".join(sorted(junc2datasource[junction[:4]])) print", "< tokens[1]: print >>sys.stderr, ( 'Invalid junction ({}, {}, {})", "fields), one per junction 1. Chromosome 2. Start position (1-based,", "if -h is invoked parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) # Add", "exit_code ) ) print >>sys.stderr, 'Junctions in {}: {}'.format( label,", "+2 for the start here extract_process = subprocess.Popen(' '.join([ sys.executable,", "From the runs/sra/v2 directory, we ran pypy rip_annotated_junctions.py --hisat2-dir /path/to/hisat2-2.0.1-beta", "sort -k1,1 -k2,2n -k3,3n | gzip >annotated_junctions.tsv.gz \"\"\" import subprocess", "#with tarfile.open(args.annotations, 'r:gz') as tar: # tar.extractall(path=extract_destination) extract_splice_sites_path = os.path.join(args.extract_script_dir,", "#extract_splice_sites_path prints 0-based, exon coords around junctions #hence the +2", "have Stats are written to stderr From the runs/sra/v2 directory,", "exit_code != 0: raise RuntimeError( 'extract_splice_sites.py had nonzero exit code", "GTF(s) in gzipped format') ) args = parser.parse_args() extract_destination =", "record as annotated_junctions.tsv.gz in runs/sra (same directory as this file).", "of annotated_junctions.tsv.gz is (tab-separated fields), one per junction 1. Chromosome", "junc2datasource: junc2datasource[junction[:4]]=set() junc2datasource[junction[:4]].add(junction[4]) seen = set() for junction in annotated_junctions_:", "annotation GTF(s) in gzipped format') ) args = parser.parse_args() extract_destination", "set() for junction_file in glob.glob( os.path.join(args.annotations, '*') ): label =", "containing_dir = os.path.dirname(os.path.realpath(__file__)) annotated_junctions_ = set() for junction_file in glob.glob(", "tokens[1] = int(tokens[1]) + 2 tokens[2] = int(tokens[2]) if tokens[2]", "runs/sra/v2 directory, we ran pypy rip_annotated_junctions.py --hisat2-dir /path/to/hisat2-2.0.1-beta --annotations path/to/jan_24_2016_annotations.tar.gz", "import subprocess import tarfile import argparse import tempfile import atexit", "containing extract_splice_sites.py script (from HISAT2)') ) parser.add_argument('--annotations', type=str, required=True, help=('full", "extract_splice_sites_path = os.path.join(args.extract_script_dir, 'extract_splice_sites.py') containing_dir = os.path.dirname(os.path.realpath(__file__)) annotated_junctions_ = set()", "junc2datasource[junction[:4]].add(junction[4]) seen = set() for junction in annotated_junctions_: if junction[:4]", "script (from HISAT2)') ) parser.add_argument('--annotations', type=str, required=True, help=('full path to", "--annotations path/to/jan_24_2016_annotations.tar.gz | sort -k1,1 -k2,2n -k3,3n | gzip >annotated_junctions.tsv.gz", "{}) from file {}. ' 'Skipping.' ).format( tokens[0], tokens[1], tokens[2],", "{} for junction in annotated_junctions_: if junction[:4] not in junc2datasource:", "'*') ): label = os.path.basename(junction_file) datasource_code = file2source[label] unique_junctions =", "seen = set() for junction in annotated_junctions_: if junction[:4] not", "for junction_file in glob.glob( os.path.join(args.annotations, '*') ): label = os.path.basename(junction_file)", "to directory containing extract_splice_sites.py script (from HISAT2)') ) parser.add_argument('--annotations', type=str,", ") for line in extract_process.stdout: tokens = line.strip().split('\\t') tokens[1] =", "len(unique_junctions) ) junc2datasource = {} for junction in annotated_junctions_: if", "python \"\"\" rip_annotated_junctions.py Non-reference/species verson of this script, no lift-over", "HISAT2)') ) parser.add_argument('--annotations', type=str, required=True, help=('full path to directory that", "directory, we ran pypy rip_annotated_junctions.py --hisat2-dir /path/to/hisat2-2.0.1-beta --annotations path/to/jan_24_2016_annotations.tar.gz |", "5. anno source (abbreviation) Must have Stats are written to", "= file2source[label] unique_junctions = set() #extract_splice_sites_path prints 0-based, exon coords", "in seen: sources = \",\".join(sorted(junc2datasource[junction[:4]])) print \"%s\\t%s\" % ('\\t'.join(map(str, junction[:4])),sources)", "({}, {}, {}) from file {}. ' 'Skipping.' ).format( tokens[0],", "(tab-separated fields), one per junction 1. Chromosome 2. Start position", "stdout=subprocess.PIPE ) for line in extract_process.stdout: tokens = line.strip().split('\\t') tokens[1]", "# Add command-line arguments parser.add_argument('--extract-script-dir', type=str, required=True, help=('path to directory", "Add command-line arguments parser.add_argument('--extract-script-dir', type=str, required=True, help=('path to directory containing", "anno source (abbreviation) Must have Stats are written to stderr", "jan_24_2016_annotations.tar.gz, as described in annotation_definition.md. Junctions are dumped to stdout,", "{\"mouse10_ucsc_genes.gtf.gz\":\"kG10\",\"mouse10_gencodevm11_comp.gtf.gz\":\"gC11\",\"mouse10_gencodevm09_comp.gtf.gz\":\"gC09\",\"mouse10_refseq_refgene.gtf.gz\":\"rG10\"} if __name__ == '__main__': # Print file's docstring if", ") ) print >>sys.stderr, 'Junctions in {}: {}'.format( label, len(unique_junctions)", "--hisat2-dir /path/to/hisat2-2.0.1-beta --annotations path/to/jan_24_2016_annotations.tar.gz | sort -k1,1 -k2,2n -k3,3n |", "not in junc2datasource: junc2datasource[junction[:4]]=set() junc2datasource[junction[:4]].add(junction[4]) seen = set() for junction", "argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) # Add command-line arguments parser.add_argument('--extract-script-dir', type=str, required=True, help=('path", "subprocess.Popen(' '.join([ sys.executable, extract_splice_sites_path, '<(gzip -cd %s)' % junction_file ]),", "%s)' % junction_file ]), shell=True, executable='/bin/bash', stdout=subprocess.PIPE ) for line", "annotation_definition.md. Junctions are dumped to stdout, which we record as", "gzip >annotated_junctions.tsv.gz \"\"\" import subprocess import tarfile import argparse import", "type=str, required=True, help=('full path to directory that has the annotation", "to directory that has the annotation GTF(s) in gzipped format')", "= set() for junction in annotated_junctions_: if junction[:4] not in", "2 tokens[2] = int(tokens[2]) if tokens[2] < tokens[1]: print >>sys.stderr,", "The format of annotated_junctions.tsv.gz is (tab-separated fields), one per junction", "\"\"\" import subprocess import tarfile import argparse import tempfile import", "Junctions are dumped to stdout, which we record as annotated_junctions.tsv.gz", "invoked parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) # Add command-line arguments parser.add_argument('--extract-script-dir',", "written to stderr From the runs/sra/v2 directory, we ran pypy", "is invoked parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) # Add command-line arguments", "tarfile.open(args.annotations, 'r:gz') as tar: # tar.extractall(path=extract_destination) extract_splice_sites_path = os.path.join(args.extract_script_dir, 'extract_splice_sites.py')", "for the start here extract_process = subprocess.Popen(' '.join([ sys.executable, extract_splice_sites_path,", "# Print file's docstring if -h is invoked parser =", "# tar.extractall(path=extract_destination) extract_splice_sites_path = os.path.join(args.extract_script_dir, 'extract_splice_sites.py') containing_dir = os.path.dirname(os.path.realpath(__file__)) annotated_junctions_", "junc2datasource[junction[:4]]=set() junc2datasource[junction[:4]].add(junction[4]) seen = set() for junction in annotated_junctions_: if", "-cd %s)' % junction_file ]), shell=True, executable='/bin/bash', stdout=subprocess.PIPE ) for", "or -) 5. anno source (abbreviation) Must have Stats are", "described in annotation_definition.md. Junctions are dumped to stdout, which we", "one per junction 1. Chromosome 2. Start position (1-based, inclusive)", "tempfile import atexit import shutil import glob import os import", "help=('full path to directory that has the annotation GTF(s) in", "by tables.py. The format of annotated_junctions.tsv.gz is (tab-separated fields), one", ">annotated_junctions.tsv.gz \"\"\" import subprocess import tarfile import argparse import tempfile", "in annotated_junctions_: if junction[:4] not in seen: sources = \",\".join(sorted(junc2datasource[junction[:4]]))", "-k2,2n -k3,3n | gzip >annotated_junctions.tsv.gz \"\"\" import subprocess import tarfile", "int(tokens[1]) + 2 tokens[2] = int(tokens[2]) if tokens[2] < tokens[1]:", "tokens[1]: print >>sys.stderr, ( 'Invalid junction ({}, {}, {}) from", "-) 5. anno source (abbreviation) Must have Stats are written", "int(tokens[2]) if tokens[2] < tokens[1]: print >>sys.stderr, ( 'Invalid junction", "= {\"hg19/gencode.v19.annotation.gtf.gz\":\"gC19\",\"hg19/refGene.txt.gz\":\"rG19\",\"hg19/acembly.txt.gz\":\"aC19\",\"hg19/ccdsGene.txt.gz\":\"cG19\",\"hg19/vegaGene.txt.gz\":\"vG19\",\"hg19/knownGene.txt.gz\":\"kG19\",\"hg19/mgcGenes.txt.gz\":\"mG19\",\"hg19/lincRNAsTranscripts.txt.gz\":\"lR19\",\"hg19/sibGene.txt.gz\":\"sG19\",\"hg38/refGene.txt.gz\":\"rG38\",\"hg38/ccdsGene.txt.gz\":\"cG38\",\"hg38/gencode.v24.annotation.gtf.gz\":\"gC38\",\"hg38/knownGene.txt.gz\":\"kG38\",\"hg38/mgcGenes.txt.gz\":\"mG38\",\"hg38/lincRNAsTranscripts.txt.gz\":\"lR38\",\"hg38/sibGene.txt.gz\":\"sG38\"} #file2source = {\"mm10/mouse10_ucsc_genes.gtf.gz\":\"kG10\",\"mm10/mouse10_gencodevm11_comp.gtf.gz\":\"gC11\",\"mm10/mouse10_gencodevm09_comp.gtf.gz\":\"gC09\",\"mm10/mouse10_refseq_refgene.gtf.gz\":\"rG10\"} file2source = {\"mouse10_ucsc_genes.gtf.gz\":\"kG10\",\"mouse10_gencodevm11_comp.gtf.gz\":\"gC11\",\"mouse10_gencodevm09_comp.gtf.gz\":\"gC09\",\"mouse10_refseq_refgene.gtf.gz\":\"rG10\"} if __name__", "required=True, help=('full path to directory that has the annotation GTF(s)", "'Skipping.' ).format( tokens[0], tokens[1], tokens[2], junction_file ) continue tokens.append(datasource_code) junction_to_add", "are written to stderr From the runs/sra/v2 directory, we ran", "(abbreviation) Must have Stats are written to stderr From the", "extract_splice_sites_path, '<(gzip -cd %s)' % junction_file ]), shell=True, executable='/bin/bash', stdout=subprocess.PIPE", "'Junctions in {}: {}'.format( label, len(unique_junctions) ) junc2datasource = {}", "are dumped to stdout, which we record as annotated_junctions.tsv.gz in", "Strand (+ or -) 5. anno source (abbreviation) Must have", "extract_splice_sites.py script (from HISAT2)') ) parser.add_argument('--annotations', type=str, required=True, help=('full path", "Non-reference/species verson of this script, no lift-over Rips junctions from", ") parser.add_argument('--annotations', type=str, required=True, help=('full path to directory that has", "tarfile import argparse import tempfile import atexit import shutil import", "-h is invoked parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) # Add command-line", "verson of this script, no lift-over Rips junctions from annotation", "in glob.glob( os.path.join(args.annotations, '*') ): label = os.path.basename(junction_file) datasource_code =", "= set() #extract_splice_sites_path prints 0-based, exon coords around junctions #hence", "in extract_process.stdout: tokens = line.strip().split('\\t') tokens[1] = int(tokens[1]) + 2", "position (1-based, inclusive) 4. Strand (+ or -) 5. anno", "exit code {}.'.format( exit_code ) ) print >>sys.stderr, 'Junctions in", "junction[:4] not in seen: sources = \",\".join(sorted(junc2datasource[junction[:4]])) print \"%s\\t%s\" %", "contained in jan_24_2016_annotations.tar.gz, as described in annotation_definition.md. Junctions are dumped", "junction[:4] not in junc2datasource: junc2datasource[junction[:4]]=set() junc2datasource[junction[:4]].add(junction[4]) seen = set() for", "(+ or -) 5. anno source (abbreviation) Must have Stats", "os.path.dirname(os.path.realpath(__file__)) annotated_junctions_ = set() for junction_file in glob.glob( os.path.join(args.annotations, '*')", "the runs/sra/v2 directory, we ran pypy rip_annotated_junctions.py --hisat2-dir /path/to/hisat2-2.0.1-beta --annotations", "file's docstring if -h is invoked parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)", "'<(gzip -cd %s)' % junction_file ]), shell=True, executable='/bin/bash', stdout=subprocess.PIPE )", "line in extract_process.stdout: tokens = line.strip().split('\\t') tokens[1] = int(tokens[1]) +", "tokens = line.strip().split('\\t') tokens[1] = int(tokens[1]) + 2 tokens[2] =", "directory that has the annotation GTF(s) in gzipped format') )", "'__main__': # Print file's docstring if -h is invoked parser", "(1-based, inclusive) 4. Strand (+ or -) 5. anno source", "import tarfile import argparse import tempfile import atexit import shutil", "(1-based, inclusive) 3. End position (1-based, inclusive) 4. Strand (+", "/path/to/hisat2-2.0.1-beta --annotations path/to/jan_24_2016_annotations.tar.gz | sort -k1,1 -k2,2n -k3,3n | gzip", "args = parser.parse_args() extract_destination = tempfile.mkdtemp() atexit.register(shutil.rmtree, extract_destination) #with tarfile.open(args.annotations,", "junction_file ) continue tokens.append(datasource_code) junction_to_add = tuple(tokens) annotated_junctions_.add(junction_to_add) unique_junctions.add(junction_to_add) extract_process.stdout.close()", "to stderr From the runs/sra/v2 directory, we ran pypy rip_annotated_junctions.py", "argparse import tempfile import atexit import shutil import glob import", "tokens[2] < tokens[1]: print >>sys.stderr, ( 'Invalid junction ({}, {},", "os.path.join(args.annotations, '*') ): label = os.path.basename(junction_file) datasource_code = file2source[label] unique_junctions", "no lift-over Rips junctions from annotation files contained in jan_24_2016_annotations.tar.gz,", ") print >>sys.stderr, 'Junctions in {}: {}'.format( label, len(unique_junctions) )", "+ 2 tokens[2] = int(tokens[2]) if tokens[2] < tokens[1]: print", "file2source[label] unique_junctions = set() #extract_splice_sites_path prints 0-based, exon coords around", "source (abbreviation) Must have Stats are written to stderr From", "help=('path to directory containing extract_splice_sites.py script (from HISAT2)') ) parser.add_argument('--annotations',", "unique_junctions = set() #extract_splice_sites_path prints 0-based, exon coords around junctions", "in annotation_definition.md. Junctions are dumped to stdout, which we record", "required=True, help=('path to directory containing extract_splice_sites.py script (from HISAT2)') )", "'extract_splice_sites.py had nonzero exit code {}.'.format( exit_code ) ) print", "= parser.parse_args() extract_destination = tempfile.mkdtemp() atexit.register(shutil.rmtree, extract_destination) #with tarfile.open(args.annotations, 'r:gz')", ">>sys.stderr, ( 'Invalid junction ({}, {}, {}) from file {}.", "'extract_splice_sites.py') containing_dir = os.path.dirname(os.path.realpath(__file__)) annotated_junctions_ = set() for junction_file in", "in junc2datasource: junc2datasource[junction[:4]]=set() junc2datasource[junction[:4]].add(junction[4]) seen = set() for junction in", "-k3,3n | gzip >annotated_junctions.tsv.gz \"\"\" import subprocess import tarfile import", "'Invalid junction ({}, {}, {}) from file {}. ' 'Skipping.'", ">>sys.stderr, 'Junctions in {}: {}'.format( label, len(unique_junctions) ) junc2datasource =", "line.strip().split('\\t') tokens[1] = int(tokens[1]) + 2 tokens[2] = int(tokens[2]) if", "#file2source = {\"mm10/mouse10_ucsc_genes.gtf.gz\":\"kG10\",\"mm10/mouse10_gencodevm11_comp.gtf.gz\":\"gC11\",\"mm10/mouse10_gencodevm09_comp.gtf.gz\":\"gC09\",\"mm10/mouse10_refseq_refgene.gtf.gz\":\"rG10\"} file2source = {\"mouse10_ucsc_genes.gtf.gz\":\"kG10\",\"mouse10_gencodevm11_comp.gtf.gz\":\"gC11\",\"mouse10_gencodevm09_comp.gtf.gz\":\"gC09\",\"mouse10_refseq_refgene.gtf.gz\":\"rG10\"} if __name__ == '__main__':", "import gzip import sys #file2source = {\"hg19/gencode.v19.annotation.gtf.gz\":\"gC19\",\"hg19/refGene.txt.gz\":\"rG19\",\"hg19/acembly.txt.gz\":\"aC19\",\"hg19/ccdsGene.txt.gz\":\"cG19\",\"hg19/vegaGene.txt.gz\":\"vG19\",\"hg19/knownGene.txt.gz\":\"kG19\",\"hg19/mgcGenes.txt.gz\":\"mG19\",\"hg19/lincRNAsTranscripts.txt.gz\":\"lR19\",\"hg19/sibGene.txt.gz\":\"sG19\",\"hg38/refGene.txt.gz\":\"rG38\",\"hg38/ccdsGene.txt.gz\":\"cG38\",\"hg38/gencode.v24.annotation.gtf.gz\":\"gC38\",\"hg38/knownGene.txt.gz\":\"kG38\",\"hg38/mgcGenes.txt.gz\":\"mG38\",\"hg38/lincRNAsTranscripts.txt.gz\":\"lR38\",\"hg38/sibGene.txt.gz\":\"sG38\"} #file2source = {\"mm10/mouse10_ucsc_genes.gtf.gz\":\"kG10\",\"mm10/mouse10_gencodevm11_comp.gtf.gz\":\"gC11\",\"mm10/mouse10_gencodevm09_comp.gtf.gz\":\"gC09\",\"mm10/mouse10_refseq_refgene.gtf.gz\":\"rG10\"}", "tokens[2] = int(tokens[2]) if tokens[2] < tokens[1]: print >>sys.stderr, (", "import atexit import shutil import glob import os import gzip", "import os import gzip import sys #file2source = {\"hg19/gencode.v19.annotation.gtf.gz\":\"gC19\",\"hg19/refGene.txt.gz\":\"rG19\",\"hg19/acembly.txt.gz\":\"aC19\",\"hg19/ccdsGene.txt.gz\":\"cG19\",\"hg19/vegaGene.txt.gz\":\"vG19\",\"hg19/knownGene.txt.gz\":\"kG19\",\"hg19/mgcGenes.txt.gz\":\"mG19\",\"hg19/lincRNAsTranscripts.txt.gz\":\"lR19\",\"hg19/sibGene.txt.gz\":\"sG19\",\"hg38/refGene.txt.gz\":\"rG38\",\"hg38/ccdsGene.txt.gz\":\"cG38\",\"hg38/gencode.v24.annotation.gtf.gz\":\"gC38\",\"hg38/knownGene.txt.gz\":\"kG38\",\"hg38/mgcGenes.txt.gz\":\"mG38\",\"hg38/lincRNAsTranscripts.txt.gz\":\"lR38\",\"hg38/sibGene.txt.gz\":\"sG38\"} #file2source", "Stats are written to stderr From the runs/sra/v2 directory, we", "' 'Skipping.' ).format( tokens[0], tokens[1], tokens[2], junction_file ) continue tokens.append(datasource_code)", "!= 0: raise RuntimeError( 'extract_splice_sites.py had nonzero exit code {}.'.format(", "Start position (1-based, inclusive) 3. End position (1-based, inclusive) 4.", "= tuple(tokens) annotated_junctions_.add(junction_to_add) unique_junctions.add(junction_to_add) extract_process.stdout.close() exit_code = extract_process.wait() if exit_code", "junctions from annotation files contained in jan_24_2016_annotations.tar.gz, as described in" ]
[ "range(K): uDiff = uDiff + 1/T*(u_hat_plus[i][n-1,:]-u_hat_plus[i][n-2,:])*np.mat((u_hat_plus[i][n-1,:]-u_hat_plus[i][n-2,:]).conjugate()).H uDiff = np.abs(uDiff) #", "f_mirror = [] temp = signal[0:T//2] f_mirror.extend(temp[::-1]) #temp[::-1] 倒序排列 f_mirror.extend(signal)", "np.abs(uDiff) # ------ Postprocessing and cleanup------- #discard empty space if", "mem u_hat_plus = [np.zeros((N, len(freqs)), dtype=complex) for i in range(K)]", "# start with empty dual variables lambda_hat = np.zeros( (N,", "for k in range(K): u[k,:]=np.real(np.fft.ifft(np.fft.ifftshift(u_hat[:,k]))) #remove mirror part u =", "(np.log(0.5) - np.log(fs)) * np.random.rand(K))) else: omega_plus[0, :] = 0", "#loop counter n = n+1 #converged yet? uDiff = eps", "converged early N = min(N,n) omega = omega_plus[0:N,:] #Signal reconstruction", "uDiff = uDiff + 1/T*(u_hat_plus[i][n-1,:]-u_hat_plus[i][n-2,:])*np.mat((u_hat_plus[i][n-1,:]-u_hat_plus[i][n-2,:]).conjugate()).H uDiff = np.abs(uDiff) # ------", "f_hat f_hat_plus[0:T // 2] = 0 # f_hat_plus[0:T] = 1", "init - 0 = all omegas start at 0 1", "the collection of decomposed modes u_hat - spectra of the", "cleanup------- #discard empty space if converged early N = min(N,n)", "= omega_plus[0:N,:] #Signal reconstruction u_hat = np.zeros((T, K), dtype=complex) temp", "= np.abs(uDiff) # ------ Postprocessing and cleanup------- #discard empty space", "true if the first mode is put and kept at", "K) * i elif init == 2: omega_plus[0, :] =", "#not converged and below iterations limit #update first mode accumulator", "= u[:,T//4:3*T//4] #recompute spectrum u_hat = np.zeros((T//2, K), dtype=complex) for", "- sum_uk - lambda_hat[n-1,:]/2)/(1+Alpha[k+1]*(freqs - omega_plus[n-1,k+1])**2) #center frequencies omega_plus[n,k+1] =", "the first mode is put and kept at DC (0-freq)", "np.zeros((T//2, K), dtype=complex) for k in range(K): u_hat[:,k]= np.squeeze( np.mat(", "但迭代时的频率是变化的。 Input and Parameters: signal - the time domain signal", "DC mode imposed, set its omega to 0 if DC:", "] u_hat[T//2:T,:] = np.squeeze(temp).T temp = np.squeeze(np.mat(temp).conjugate()) u_hat[1:(T//2+1),:] = temp.T[::-1]", "eps for i in range(K): uDiff = uDiff + 1/T*(u_hat_plus[i][n-1,:]-u_hat_plus[i][n-2,:])*np.mat((u_hat_plus[i][n-1,:]-u_hat_plus[i][n-2,:]).conjugate()).H", "f = f_mirror # Time Domain 0 to T (of", "of the dual ascent ( pick 0 for noise-slack )", "empty space if converged early N = min(N,n) omega =", "alpha - the balancing parameter of the data-fidelity constraint tau", "the dual ascent ( pick 0 for noise-slack ) K", "distributed 2 = all omegas initialized randomly tol - tolerance", "accumulator k = 0 sum_uk = u_hat_plus[K-1][n-1,:]+ sum_uk - u_hat_plus[0][n-1,:]", "if DC: omega_plus[0, 0] = 0 # start with empty", "space if converged early N = min(N,n) omega = omega_plus[0:N,:]", "save_T f_mirror = [] temp = signal[0:T//2] f_mirror.extend(temp[::-1]) #temp[::-1] 倒序排列", "its omega to 0 if DC: omega_plus[0, 0] = 0", "= all omegas initialized randomly tol - tolerance of convergence", "= 0 # f_hat_plus[0:T] = 1 #????????????????????????????//////////// # matrix keeping", "time domain signal (1D) to be decomposed alpha - the", "converged yet, then it won't anyway) N = 500 #", "sum_uk - u_hat_plus[0][n-1,:] #sum_uk 一直都等于0(1,2000)???????????????? #update spectrum of first mode", "# Construct and center f_hat transformed = np.fft.fft(f) # 使用fft函数对信号进行快速傅里叶变换。", "start at 0 1 = all omegas start uniformly distributed", "omega if not held at 0 if not DC: omega_plus[n,k]", "= [u_hat_plus[i][N-1,T//2:T] for i in range(K) ] u_hat[T//2:T,:] = np.squeeze(temp).T", "omega_plus[0, :] = 0 # if DC mode imposed, set", "- f_hat_plus) #loop counter n = n+1 #converged yet? uDiff", "- omega_plus[n-1,k])**2) #update first omega if not held at 0", "range(K)],0) - f_hat_plus) #loop counter n = n+1 #converged yet?", "u_hat_plus[K-1][n-1,:]+ sum_uk - u_hat_plus[0][n-1,:] #sum_uk 一直都等于0(1,2000)???????????????? #update spectrum of first", "f_hat_plus) #loop counter n = n+1 #converged yet? uDiff =", "f_hat = np.fft.fftshift(transformed) # 使用fftshift函数进行移频操作。 f_hat_plus = f_hat f_hat_plus[0:T //", "n = n+1 #converged yet? uDiff = eps for i", "range(K): omega_plus[0, i] = (0.5 / K) * i elif", "omegas start at 0 1 = all omegas start uniformly", "generalizations: individual alpha for each mode Alpha = alpha *", "k in range(K): u[k,:]=np.real(np.fft.ifft(np.fft.ifftshift(u_hat[:,k]))) #remove mirror part u = u[:,T//4:3*T//4]", "[i - 0.5 - 1 / T for i in", "进行移位是由于进行傅里叶变换时,会有正负对称的频率,分析时一般只有正频率,所以看到的频谱图是没有负频率的 freqs = np.array( [i - 0.5 - 1 /", "temp = signal[T//2:T] f_mirror.extend(temp[::-1]) f = f_mirror # Time Domain", "#update of any other mode for k in range(K-1): #accumulator", "= 1 / save_T # extend the signal by mirroring镜像延拓", "u_hat_plus[k+1][n-1,:] #mode spectrum u_hat_plus[k+1][n,:] = (f_hat_plus - sum_uk - lambda_hat[n-1,:]/2)/(1+Alpha[k+1]*(freqs", "sum_uk - u_hat_plus[k+1][n-1,:] #mode spectrum u_hat_plus[k+1][n,:] = (f_hat_plus - sum_uk", "= 0 # start with empty dual variables lambda_hat =", "T//2:T])**2).H)/np.sum(np.abs(u_hat_plus[k][n,T//2:T])**2) #update of any other mode for k in range(K-1):", "( pick 0 for noise-slack ) K - the number", "len(f) t = [(i + 1) / T for i", "* np.ones(K) # Construct and center f_hat transformed = np.fft.fft(f)", "u_hat = np.zeros((T//2, K), dtype=complex) for k in range(K): u_hat[:,k]=", "yet? uDiff = eps for i in range(K): uDiff =", "the number of modes to be recovered DC - true", "- omega_plus[n-1,k+1])**2) #center frequencies omega_plus[n,k+1] = (freqs[T//2:T]*np.mat(np.abs(u_hat_plus[k+1][n, T//2:T])**2).H)/np.sum(np.abs(u_hat_plus[k+1][n,T//2:T])**2) #Dual ascent", "一直都等于0(1,2000)???????????????? #update spectrum of first mode through Wiener filter of", "at DC (0-freq) init - 0 = all omegas start", "mode center-frequencies ''' # Period and sampling frequency of input", "of the modes omega - estimated mode center-frequencies ''' #", "= 500 # For future generalizations: individual alpha for each", "- the collection of decomposed modes u_hat - spectra of", "DC (0-freq) init - 0 = all omegas start at", "kept at DC (0-freq) init - 0 = all omegas", "signal (1D) to be decomposed alpha - the balancing parameter", "= np.zeros((K,len(t))) for k in range(K): u[k,:]=np.real(np.fft.ifft(np.fft.ifftshift(u_hat[:,k]))) #remove mirror part", "+ tau*(np.sum([ u_hat_plus[i][n,:] for i in range(K)],0) - f_hat_plus) #loop", "#update spectrum of first mode through Wiener filter of residuals", "f_hat transformed = np.fft.fft(f) # 使用fft函数对信号进行快速傅里叶变换。 f_hat = np.fft.fftshift(transformed) #", "lambda_hat[n-1,:]/2)/(1+Alpha[k]*(freqs - omega_plus[n-1,k])**2) #update first omega if not held at", "length(signal),频率: length(signal)。 save_T = len(signal) fs = 1 / save_T", "#----------- Main loop for iterative updates---------- while (uDiff > tol", "iterations (if not converged yet, then it won't anyway) N", "range(T)] # 列表从1开始 # Spectral Domain discretization #freqs 进行移位是由于进行傅里叶变换时,会有正负对称的频率,分析时一般只有正频率,所以看到的频谱图是没有负频率的 freqs", "# f_hat_plus[0:T] = 1 #????????????????????????????//////////// # matrix keeping track of", "#center frequencies omega_plus[n,k+1] = (freqs[T//2:T]*np.mat(np.abs(u_hat_plus[k+1][n, T//2:T])**2).H)/np.sum(np.abs(u_hat_plus[k+1][n,T//2:T])**2) #Dual ascent lambda_hat[n,:] =", ":] = 0 # if DC mode imposed, set its", "+ eps # update step n = 1 # loop", "#discard empty space if converged early N = min(N,n) omega", "u = u[:,T//4:3*T//4] #recompute spectrum u_hat = np.zeros((T//2, K), dtype=complex)", "put and kept at DC (0-freq) init - 0 =", "(u_hat[-1,:]).conjugate() u = np.zeros((K,len(t))) for k in range(K): u[k,:]=np.real(np.fft.ifft(np.fft.ifftshift(u_hat[:,k]))) #remove", "alpha * np.ones(K) # Construct and center f_hat transformed =", "(N, len(freqs)), dtype=complex) # other inits eps = 2.2204e-16 #", "discarded for mem u_hat_plus = [np.zeros((N, len(freqs)), dtype=complex) for i", "= [] temp = signal[0:T//2] f_mirror.extend(temp[::-1]) #temp[::-1] 倒序排列 f_mirror.extend(signal) temp", "sum_uk - lambda_hat[n-1,:]/2)/(1+Alpha[k+1]*(freqs - omega_plus[n-1,k+1])**2) #center frequencies omega_plus[n,k+1] = (freqs[T//2:T]*np.mat(np.abs(u_hat_plus[k+1][n,", "# Initialization of omega_k omega_plus = np.zeros((N, K)) if init", "// 2] = 0 # f_hat_plus[0:T] = 1 #????????????????????????????//////////// #", "np def vmd( signal, alpha, tau, K, DC, init, tol):", "updates---------- while (uDiff > tol and n < N ):", "and kept at DC (0-freq) init - 0 = all", "= 0 # if DC mode imposed, set its omega", "- estimated mode center-frequencies ''' # Period and sampling frequency", "f_mirror.extend(signal) temp = signal[T//2:T] f_mirror.extend(temp[::-1]) f = f_mirror # Time", "discretization #freqs 进行移位是由于进行傅里叶变换时,会有正负对称的频率,分析时一般只有正频率,所以看到的频谱图是没有负频率的 freqs = np.array( [i - 0.5 -", "dual ascent ( pick 0 for noise-slack ) K -", "#update first mode accumulator k = 0 sum_uk = u_hat_plus[K-1][n-1,:]+", "使用fftshift函数进行移频操作。 f_hat_plus = f_hat f_hat_plus[0:T // 2] = 0 #", "[u_hat_plus[i][N-1,T//2:T] for i in range(K) ] u_hat[T//2:T,:] = np.squeeze(temp).T temp", "/ T for i in range(T)] # 列表从1开始 # Spectral", "f_mirror.extend(temp[::-1]) f = f_mirror # Time Domain 0 to T", "Construct and center f_hat transformed = np.fft.fft(f) # 使用fft函数对信号进行快速傅里叶变换。 f_hat", "for i in t] ) # Maximum number of iterations", "2] = 0 # f_hat_plus[0:T] = 1 #????????????????????????????//////////// # matrix", "of iterations (if not converged yet, then it won't anyway)", "init == 2: omega_plus[0, :] = np.sort(np.exp(np.log(fs) + (np.log(0.5) -", "variables lambda_hat = np.zeros( (N, len(freqs)), dtype=complex) # other inits", "converged and below iterations limit #update first mode accumulator k", "of modes to be recovered DC - true if the", "(f_hat_plus - sum_uk - lambda_hat[n-1,:]/2)/(1+Alpha[k+1]*(freqs - omega_plus[n-1,k+1])**2) #center frequencies omega_plus[n,k+1]", "signal - the time domain signal (1D) to be decomposed", "if converged early N = min(N,n) omega = omega_plus[0:N,:] #Signal", "- time-step of the dual ascent ( pick 0 for", "0 = all omegas start at 0 1 = all", "0 if DC: omega_plus[0, 0] = 0 # start with", "# other inits eps = 2.2204e-16 # python里没有eps功能 uDiff =", "counter n = n+1 #converged yet? uDiff = eps for", "= 0 # accumulator #----------- Main loop for iterative updates----------", "f_mirror.extend(temp[::-1]) #temp[::-1] 倒序排列 f_mirror.extend(signal) temp = signal[T//2:T] f_mirror.extend(temp[::-1]) f =", "= (freqs[T//2:T]*np.mat(np.abs(u_hat_plus[k][n, T//2:T])**2).H)/np.sum(np.abs(u_hat_plus[k][n,T//2:T])**2) #update of any other mode for k", "= n+1 #converged yet? uDiff = eps for i in", "#temp[::-1] 倒序排列 f_mirror.extend(signal) temp = signal[T//2:T] f_mirror.extend(temp[::-1]) f = f_mirror", "== 2: omega_plus[0, :] = np.sort(np.exp(np.log(fs) + (np.log(0.5) - np.log(fs))", "= np.squeeze(np.mat(temp).conjugate()) u_hat[1:(T//2+1),:] = temp.T[::-1] u_hat[0,:] = (u_hat[-1,:]).conjugate() u =", "K), dtype=complex) for k in range(K): u_hat[:,k]= np.squeeze( np.mat( np.fft.fftshift(np.fft.fft(u[k,:]))", "to be recovered DC - true if the first mode", "# 使用fftshift函数进行移频操作。 f_hat_plus = f_hat f_hat_plus[0:T // 2] = 0", "Initialization of omega_k omega_plus = np.zeros((N, K)) if init ==", "u_hat_plus[k][n,:] + sum_uk - u_hat_plus[k+1][n-1,:] #mode spectrum u_hat_plus[k+1][n,:] = (f_hat_plus", "frequencies omega_plus[n,k+1] = (freqs[T//2:T]*np.mat(np.abs(u_hat_plus[k+1][n, T//2:T])**2).H)/np.sum(np.abs(u_hat_plus[k+1][n,T//2:T])**2) #Dual ascent lambda_hat[n,:] = lambda_hat[n-1,:]", "first mode through Wiener filter of residuals u_hat_plus[k][n,:] = (f_hat_plus", "i in range(K): omega_plus[0, i] = (0.5 / K) *", "and Parameters: signal - the time domain signal (1D) to", "residuals u_hat_plus[k][n,:] = (f_hat_plus - sum_uk - lambda_hat[n-1,:]/2)/(1+Alpha[k]*(freqs - omega_plus[n-1,k])**2)", "of every iterant // could be discarded for mem u_hat_plus", "Wiener filter of residuals u_hat_plus[k][n,:] = (f_hat_plus - sum_uk -", "omega_plus[n,k] = (freqs[T//2:T]*np.mat(np.abs(u_hat_plus[k][n, T//2:T])**2).H)/np.sum(np.abs(u_hat_plus[k][n,T//2:T])**2) #update of any other mode for", "(freqs[T//2:T]*np.mat(np.abs(u_hat_plus[k+1][n, T//2:T])**2).H)/np.sum(np.abs(u_hat_plus[k+1][n,T//2:T])**2) #Dual ascent lambda_hat[n,:] = lambda_hat[n-1,:] + tau*(np.sum([ u_hat_plus[i][n,:]", "VMD的输入参数也没有采样频率。 VMD分解出的各分量在输出量 u 中,这个和信号的长度、信号的采样频率没有关系。 迭代时各分量的中心频率在输出量omega,可以用2*pi/fs*omega求出中心频率, 但迭代时的频率是变化的。 Input and Parameters: signal", "#????????????????????????????//////////// # matrix keeping track of every iterant // could", "temp.T[::-1] u_hat[0,:] = (u_hat[-1,:]).conjugate() u = np.zeros((K,len(t))) for k in", "imposed, set its omega to 0 if DC: omega_plus[0, 0]", "step n = 1 # loop counter sum_uk = 0", "= 0 sum_uk = u_hat_plus[K-1][n-1,:]+ sum_uk - u_hat_plus[0][n-1,:] #sum_uk 一直都等于0(1,2000)????????????????", "# Time Domain 0 to T (of mirrored signal) T", "T for i in range(T)] # 列表从1开始 # Spectral Domain", "): #not converged and below iterations limit #update first mode", "to be decomposed alpha - the balancing parameter of the", "0 # start with empty dual variables lambda_hat = np.zeros(", "constraint tau - time-step of the dual ascent ( pick", "/ T for i in t] ) # Maximum number", "tau, K, DC, init, tol): ''' 用VMD分解算法时只要把信号输入进行分解就行了,只是对信号进行分解,和采样频率没有关系, VMD的输入参数也没有采样频率。 VMD分解出的各分量在输出量 u", "1 # loop counter sum_uk = 0 # accumulator #-----------", "won't anyway) N = 500 # For future generalizations: individual", "= save_T f_mirror = [] temp = signal[0:T//2] f_mirror.extend(temp[::-1]) #temp[::-1]", "+ (np.log(0.5) - np.log(fs)) * np.random.rand(K))) else: omega_plus[0, :] =", "the data-fidelity constraint tau - time-step of the dual ascent", "Alpha = alpha * np.ones(K) # Construct and center f_hat", "= (f_hat_plus - sum_uk - lambda_hat[n-1,:]/2)/(1+Alpha[k+1]*(freqs - omega_plus[n-1,k+1])**2) #center frequencies", "temp = signal[0:T//2] f_mirror.extend(temp[::-1]) #temp[::-1] 倒序排列 f_mirror.extend(signal) temp = signal[T//2:T]", "- the balancing parameter of the data-fidelity constraint tau -", "the balancing parameter of the data-fidelity constraint tau - time-step", "then it won't anyway) N = 500 # For future", "- sum_uk - lambda_hat[n-1,:]/2)/(1+Alpha[k]*(freqs - omega_plus[n-1,k])**2) #update first omega if", "for i in range(K): uDiff = uDiff + 1/T*(u_hat_plus[i][n-1,:]-u_hat_plus[i][n-2,:])*np.mat((u_hat_plus[i][n-1,:]-u_hat_plus[i][n-2,:]).conjugate()).H uDiff", "alpha, tau, K, DC, init, tol): ''' 用VMD分解算法时只要把信号输入进行分解就行了,只是对信号进行分解,和采样频率没有关系, VMD的输入参数也没有采样频率。 VMD分解出的各分量在输出量", "spectrum u_hat = np.zeros((T//2, K), dtype=complex) for k in range(K):", "sampling frequency of input signal #分解算法中的采样频率和时间是标准化的,分解信号的采样时间为1s,然后就得到相应的采样频率。采样时间间隔:1/ length(signal),频率: length(signal)。 save_T =", "dual variables lambda_hat = np.zeros( (N, len(freqs)), dtype=complex) # other", "tol and n < N ): #not converged and below", "u - the collection of decomposed modes u_hat - spectra", "for i in range(K)] # Initialization of omega_k omega_plus =", "n < N ): #not converged and below iterations limit", "for k in range(K): u_hat[:,k]= np.squeeze( np.mat( np.fft.fftshift(np.fft.fft(u[k,:])) ).H) return", "k = 0 sum_uk = u_hat_plus[K-1][n-1,:]+ sum_uk - u_hat_plus[0][n-1,:] #sum_uk", "= lambda_hat[n-1,:] + tau*(np.sum([ u_hat_plus[i][n,:] for i in range(K)],0) -", "iterative updates---------- while (uDiff > tol and n < N", "dtype=complex) temp = [u_hat_plus[i][N-1,T//2:T] for i in range(K) ] u_hat[T//2:T,:]", "signal) T = len(f) t = [(i + 1) /", "the time domain signal (1D) to be decomposed alpha -", "- spectra of the modes omega - estimated mode center-frequencies", "Main loop for iterative updates---------- while (uDiff > tol and", "# Maximum number of iterations (if not converged yet, then", "for i in range(T)] # 列表从1开始 # Spectral Domain discretization", "= np.zeros( (N, len(freqs)), dtype=complex) # other inits eps =", "range(K): u_hat[:,k]= np.squeeze( np.mat( np.fft.fftshift(np.fft.fft(u[k,:])) ).H) return u, u_hat, omega", "(0-freq) init - 0 = all omegas start at 0", "VMD分解出的各分量在输出量 u 中,这个和信号的长度、信号的采样频率没有关系。 迭代时各分量的中心频率在输出量omega,可以用2*pi/fs*omega求出中心频率, 但迭代时的频率是变化的。 Input and Parameters: signal -", "# matrix keeping track of every iterant // could be", "T for i in t] ) # Maximum number of", "if the first mode is put and kept at DC", ":] = np.sort(np.exp(np.log(fs) + (np.log(0.5) - np.log(fs)) * np.random.rand(K))) else:", "start uniformly distributed 2 = all omegas initialized randomly tol", "= len(f) t = [(i + 1) / T for", "and cleanup------- #discard empty space if converged early N =", "T = len(f) t = [(i + 1) / T", "randomly tol - tolerance of convergence criterion; typically around 1e-6", "u_hat_plus = [np.zeros((N, len(freqs)), dtype=complex) for i in range(K)] #", "Spectral Domain discretization #freqs 进行移位是由于进行傅里叶变换时,会有正负对称的频率,分析时一般只有正频率,所以看到的频谱图是没有负频率的 freqs = np.array( [i -", "- the number of modes to be recovered DC -", "in range(K)] # Initialization of omega_k omega_plus = np.zeros((N, K))", "all omegas start at 0 1 = all omegas start", "0 1 = all omegas start uniformly distributed 2 =", "#accumulator sum_uk = u_hat_plus[k][n,:] + sum_uk - u_hat_plus[k+1][n-1,:] #mode spectrum", "= (freqs[T//2:T]*np.mat(np.abs(u_hat_plus[k+1][n, T//2:T])**2).H)/np.sum(np.abs(u_hat_plus[k+1][n,T//2:T])**2) #Dual ascent lambda_hat[n,:] = lambda_hat[n-1,:] + tau*(np.sum([", "np.log(fs)) * np.random.rand(K))) else: omega_plus[0, :] = 0 # if", "u_hat = np.zeros((T, K), dtype=complex) temp = [u_hat_plus[i][N-1,T//2:T] for i", "first mode is put and kept at DC (0-freq) init", "reconstruction u_hat = np.zeros((T, K), dtype=complex) temp = [u_hat_plus[i][N-1,T//2:T] for", "uniformly distributed 2 = all omegas initialized randomly tol -", "all omegas initialized randomly tol - tolerance of convergence criterion;", "held at 0 if not DC: omega_plus[n,k] = (freqs[T//2:T]*np.mat(np.abs(u_hat_plus[k][n, T//2:T])**2).H)/np.sum(np.abs(u_hat_plus[k][n,T//2:T])**2)", "[(i + 1) / T for i in range(T)] #", "alpha for each mode Alpha = alpha * np.ones(K) #", "length(signal)。 save_T = len(signal) fs = 1 / save_T #", "= np.fft.fftshift(transformed) # 使用fftshift函数进行移频操作。 f_hat_plus = f_hat f_hat_plus[0:T // 2]", "matrix keeping track of every iterant // could be discarded", "omega_plus[0, :] = np.sort(np.exp(np.log(fs) + (np.log(0.5) - np.log(fs)) * np.random.rand(K)))", "be discarded for mem u_hat_plus = [np.zeros((N, len(freqs)), dtype=complex) for", "使用fft函数对信号进行快速傅里叶变换。 f_hat = np.fft.fftshift(transformed) # 使用fftshift函数进行移频操作。 f_hat_plus = f_hat f_hat_plus[0:T", "min(N,n) omega = omega_plus[0:N,:] #Signal reconstruction u_hat = np.zeros((T, K),", "pick 0 for noise-slack ) K - the number of", "set its omega to 0 if DC: omega_plus[0, 0] =", "signal, alpha, tau, K, DC, init, tol): ''' 用VMD分解算法时只要把信号输入进行分解就行了,只是对信号进行分解,和采样频率没有关系, VMD的输入参数也没有采样频率。", "decomposed alpha - the balancing parameter of the data-fidelity constraint", "i in t] ) # Maximum number of iterations (if", "omega to 0 if DC: omega_plus[0, 0] = 0 #", "# python里没有eps功能 uDiff = tol + eps # update step", "collection of decomposed modes u_hat - spectra of the modes", "= eps for i in range(K): uDiff = uDiff +", "uDiff = np.abs(uDiff) # ------ Postprocessing and cleanup------- #discard empty", "dtype=complex) for i in range(K)] # Initialization of omega_k omega_plus", "first mode accumulator k = 0 sum_uk = u_hat_plus[K-1][n-1,:]+ sum_uk", "= np.squeeze(temp).T temp = np.squeeze(np.mat(temp).conjugate()) u_hat[1:(T//2+1),:] = temp.T[::-1] u_hat[0,:] =", "for i in range(K)],0) - f_hat_plus) #loop counter n =", "[] temp = signal[0:T//2] f_mirror.extend(temp[::-1]) #temp[::-1] 倒序排列 f_mirror.extend(signal) temp =", "= all omegas start at 0 1 = all omegas", "#sum_uk 一直都等于0(1,2000)???????????????? #update spectrum of first mode through Wiener filter", "def vmd( signal, alpha, tau, K, DC, init, tol): '''", "input signal #分解算法中的采样频率和时间是标准化的,分解信号的采样时间为1s,然后就得到相应的采样频率。采样时间间隔:1/ length(signal),频率: length(signal)。 save_T = len(signal) fs =", "ascent ( pick 0 for noise-slack ) K - the", "for noise-slack ) K - the number of modes to", "''' 用VMD分解算法时只要把信号输入进行分解就行了,只是对信号进行分解,和采样频率没有关系, VMD的输入参数也没有采样频率。 VMD分解出的各分量在输出量 u 中,这个和信号的长度、信号的采样频率没有关系。 迭代时各分量的中心频率在输出量omega,可以用2*pi/fs*omega求出中心频率, 但迭代时的频率是变化的。 Input and", "convergence criterion; typically around 1e-6 Output: u - the collection", "1 / T for i in t] ) # Maximum", "at 0 1 = all omegas start uniformly distributed 2", "500 # For future generalizations: individual alpha for each mode", "track of every iterant // could be discarded for mem", "= (0.5 / K) * i elif init == 2:", "if init == 1: for i in range(K): omega_plus[0, i]", "in range(K)],0) - f_hat_plus) #loop counter n = n+1 #converged", "criterion; typically around 1e-6 Output: u - the collection of", "u 中,这个和信号的长度、信号的采样频率没有关系。 迭代时各分量的中心频率在输出量omega,可以用2*pi/fs*omega求出中心频率, 但迭代时的频率是变化的。 Input and Parameters: signal - the", "yet, then it won't anyway) N = 500 # For", "= [np.zeros((N, len(freqs)), dtype=complex) for i in range(K)] # Initialization", "K)) if init == 1: for i in range(K): omega_plus[0,", "# 使用fft函数对信号进行快速傅里叶变换。 f_hat = np.fft.fftshift(transformed) # 使用fftshift函数进行移频操作。 f_hat_plus = f_hat", "u_hat_plus[0][n-1,:] #sum_uk 一直都等于0(1,2000)???????????????? #update spectrum of first mode through Wiener", "u_hat[T//2:T,:] = np.squeeze(temp).T temp = np.squeeze(np.mat(temp).conjugate()) u_hat[1:(T//2+1),:] = temp.T[::-1] u_hat[0,:]", "modes omega - estimated mode center-frequencies ''' # Period and", "= np.zeros((N, K)) if init == 1: for i in", "# loop counter sum_uk = 0 # accumulator #----------- Main", "DC: omega_plus[0, 0] = 0 # start with empty dual", "u_hat_plus[k+1][n,:] = (f_hat_plus - sum_uk - lambda_hat[n-1,:]/2)/(1+Alpha[k+1]*(freqs - omega_plus[n-1,k+1])**2) #center", "Output: u - the collection of decomposed modes u_hat -", "freqs = np.array( [i - 0.5 - 1 / T", "be decomposed alpha - the balancing parameter of the data-fidelity", "lambda_hat = np.zeros( (N, len(freqs)), dtype=complex) # other inits eps", "# Spectral Domain discretization #freqs 进行移位是由于进行傅里叶变换时,会有正负对称的频率,分析时一般只有正频率,所以看到的频谱图是没有负频率的 freqs = np.array( [i", "= f_mirror # Time Domain 0 to T (of mirrored", "= 1 #????????????????????????????//////////// # matrix keeping track of every iterant", "not converged yet, then it won't anyway) N = 500", "and center f_hat transformed = np.fft.fft(f) # 使用fft函数对信号进行快速傅里叶变换。 f_hat =", "utf-8 -*- import numpy as np def vmd( signal, alpha,", "// could be discarded for mem u_hat_plus = [np.zeros((N, len(freqs)),", "and below iterations limit #update first mode accumulator k =", "(uDiff > tol and n < N ): #not converged", "np.zeros( (N, len(freqs)), dtype=complex) # other inits eps = 2.2204e-16", "mirror part u = u[:,T//4:3*T//4] #recompute spectrum u_hat = np.zeros((T//2,", "in range(K): u[k,:]=np.real(np.fft.ifft(np.fft.ifftshift(u_hat[:,k]))) #remove mirror part u = u[:,T//4:3*T//4] #recompute", "np.ones(K) # Construct and center f_hat transformed = np.fft.fft(f) #", "omega_plus[0, i] = (0.5 / K) * i elif init", "Domain 0 to T (of mirrored signal) T = len(f)", "#freqs 进行移位是由于进行傅里叶变换时,会有正负对称的频率,分析时一般只有正频率,所以看到的频谱图是没有负频率的 freqs = np.array( [i - 0.5 - 1", "DC: omega_plus[n,k] = (freqs[T//2:T]*np.mat(np.abs(u_hat_plus[k][n, T//2:T])**2).H)/np.sum(np.abs(u_hat_plus[k][n,T//2:T])**2) #update of any other mode", "''' # Period and sampling frequency of input signal #分解算法中的采样频率和时间是标准化的,分解信号的采样时间为1s,然后就得到相应的采样频率。采样时间间隔:1/", "save_T # extend the signal by mirroring镜像延拓 T = save_T", "- 0.5 - 1 / T for i in t]", "# -*- coding: utf-8 -*- import numpy as np def", "k in range(K): u_hat[:,k]= np.squeeze( np.mat( np.fft.fftshift(np.fft.fft(u[k,:])) ).H) return u,", "parameter of the data-fidelity constraint tau - time-step of the", "np.fft.fft(f) # 使用fft函数对信号进行快速傅里叶变换。 f_hat = np.fft.fftshift(transformed) # 使用fftshift函数进行移频操作。 f_hat_plus =", "u = np.zeros((K,len(t))) for k in range(K): u[k,:]=np.real(np.fft.ifft(np.fft.ifftshift(u_hat[:,k]))) #remove mirror", "modes u_hat - spectra of the modes omega - estimated", "ascent lambda_hat[n,:] = lambda_hat[n-1,:] + tau*(np.sum([ u_hat_plus[i][n,:] for i in", "to T (of mirrored signal) T = len(f) t =", "to 0 if DC: omega_plus[0, 0] = 0 # start", "i in range(K) ] u_hat[T//2:T,:] = np.squeeze(temp).T temp = np.squeeze(np.mat(temp).conjugate())", "not DC: omega_plus[n,k] = (freqs[T//2:T]*np.mat(np.abs(u_hat_plus[k][n, T//2:T])**2).H)/np.sum(np.abs(u_hat_plus[k][n,T//2:T])**2) #update of any other", "data-fidelity constraint tau - time-step of the dual ascent (", "loop for iterative updates---------- while (uDiff > tol and n", "i] = (0.5 / K) * i elif init ==", "omega_k omega_plus = np.zeros((N, K)) if init == 1: for", ") K - the number of modes to be recovered", "is put and kept at DC (0-freq) init - 0", "omega_plus = np.zeros((N, K)) if init == 1: for i", "empty dual variables lambda_hat = np.zeros( (N, len(freqs)), dtype=complex) #", "= u_hat_plus[K-1][n-1,:]+ sum_uk - u_hat_plus[0][n-1,:] #sum_uk 一直都等于0(1,2000)???????????????? #update spectrum of", "import numpy as np def vmd( signal, alpha, tau, K,", "T//2:T])**2).H)/np.sum(np.abs(u_hat_plus[k+1][n,T//2:T])**2) #Dual ascent lambda_hat[n,:] = lambda_hat[n-1,:] + tau*(np.sum([ u_hat_plus[i][n,:] for", "Parameters: signal - the time domain signal (1D) to be", "1: for i in range(K): omega_plus[0, i] = (0.5 /", "= (u_hat[-1,:]).conjugate() u = np.zeros((K,len(t))) for k in range(K): u[k,:]=np.real(np.fft.ifft(np.fft.ifftshift(u_hat[:,k])))", "u[:,T//4:3*T//4] #recompute spectrum u_hat = np.zeros((T//2, K), dtype=complex) for k", "tol + eps # update step n = 1 #", "DC, init, tol): ''' 用VMD分解算法时只要把信号输入进行分解就行了,只是对信号进行分解,和采样频率没有关系, VMD的输入参数也没有采样频率。 VMD分解出的各分量在输出量 u 中,这个和信号的长度、信号的采样频率没有关系。 迭代时各分量的中心频率在输出量omega,可以用2*pi/fs*omega求出中心频率,", "noise-slack ) K - the number of modes to be", "0 # if DC mode imposed, set its omega to", "first omega if not held at 0 if not DC:", "t = [(i + 1) / T for i in", "any other mode for k in range(K-1): #accumulator sum_uk =", "1/T*(u_hat_plus[i][n-1,:]-u_hat_plus[i][n-2,:])*np.mat((u_hat_plus[i][n-1,:]-u_hat_plus[i][n-2,:]).conjugate()).H uDiff = np.abs(uDiff) # ------ Postprocessing and cleanup------- #discard", "dtype=complex) # other inits eps = 2.2204e-16 # python里没有eps功能 uDiff", "u_hat_plus[k][n,:] = (f_hat_plus - sum_uk - lambda_hat[n-1,:]/2)/(1+Alpha[k]*(freqs - omega_plus[n-1,k])**2) #update", "tau*(np.sum([ u_hat_plus[i][n,:] for i in range(K)],0) - f_hat_plus) #loop counter", "f_hat_plus = f_hat f_hat_plus[0:T // 2] = 0 # f_hat_plus[0:T]", "if not DC: omega_plus[n,k] = (freqs[T//2:T]*np.mat(np.abs(u_hat_plus[k][n, T//2:T])**2).H)/np.sum(np.abs(u_hat_plus[k][n,T//2:T])**2) #update of any", "= u_hat_plus[k][n,:] + sum_uk - u_hat_plus[k+1][n-1,:] #mode spectrum u_hat_plus[k+1][n,:] =", "Maximum number of iterations (if not converged yet, then it", "save_T = len(signal) fs = 1 / save_T # extend", "(1D) to be decomposed alpha - the balancing parameter of", "#remove mirror part u = u[:,T//4:3*T//4] #recompute spectrum u_hat =", "by mirroring镜像延拓 T = save_T f_mirror = [] temp =", "= all omegas start uniformly distributed 2 = all omegas", "temp = [u_hat_plus[i][N-1,T//2:T] for i in range(K) ] u_hat[T//2:T,:] =", "and n < N ): #not converged and below iterations", "2 = all omegas initialized randomly tol - tolerance of", "init, tol): ''' 用VMD分解算法时只要把信号输入进行分解就行了,只是对信号进行分解,和采样频率没有关系, VMD的输入参数也没有采样频率。 VMD分解出的各分量在输出量 u 中,这个和信号的长度、信号的采样频率没有关系。 迭代时各分量的中心频率在输出量omega,可以用2*pi/fs*omega求出中心频率, 但迭代时的频率是变化的。", "decomposed modes u_hat - spectra of the modes omega -", "typically around 1e-6 Output: u - the collection of decomposed", "sum_uk = 0 # accumulator #----------- Main loop for iterative", "u[k,:]=np.real(np.fft.ifft(np.fft.ifftshift(u_hat[:,k]))) #remove mirror part u = u[:,T//4:3*T//4] #recompute spectrum u_hat", "else: omega_plus[0, :] = 0 # if DC mode imposed,", "0 for noise-slack ) K - the number of modes", "(f_hat_plus - sum_uk - lambda_hat[n-1,:]/2)/(1+Alpha[k]*(freqs - omega_plus[n-1,k])**2) #update first omega", "every iterant // could be discarded for mem u_hat_plus =", "- lambda_hat[n-1,:]/2)/(1+Alpha[k]*(freqs - omega_plus[n-1,k])**2) #update first omega if not held", "loop counter sum_uk = 0 # accumulator #----------- Main loop", "u_hat[0,:] = (u_hat[-1,:]).conjugate() u = np.zeros((K,len(t))) for k in range(K):", "fs = 1 / save_T # extend the signal by", "mirrored signal) T = len(f) t = [(i + 1)", "mode Alpha = alpha * np.ones(K) # Construct and center", "np.random.rand(K))) else: omega_plus[0, :] = 0 # if DC mode", "uDiff = tol + eps # update step n =", "= tol + eps # update step n = 1", "spectra of the modes omega - estimated mode center-frequencies '''", "range(K)] # Initialization of omega_k omega_plus = np.zeros((N, K)) if", "numpy as np def vmd( signal, alpha, tau, K, DC,", "N = 500 # For future generalizations: individual alpha for", "around 1e-6 Output: u - the collection of decomposed modes", "omegas initialized randomly tol - tolerance of convergence criterion; typically", "= np.zeros((T//2, K), dtype=complex) for k in range(K): u_hat[:,k]= np.squeeze(", "- 1 / T for i in t] ) #", "0 # f_hat_plus[0:T] = 1 #????????????????????????????//////////// # matrix keeping track", "for i in range(K) ] u_hat[T//2:T,:] = np.squeeze(temp).T temp =", "< N ): #not converged and below iterations limit #update", "mode for k in range(K-1): #accumulator sum_uk = u_hat_plus[k][n,:] +", "= [(i + 1) / T for i in range(T)]", "-*- coding: utf-8 -*- import numpy as np def vmd(", "# Period and sampling frequency of input signal #分解算法中的采样频率和时间是标准化的,分解信号的采样时间为1s,然后就得到相应的采样频率。采样时间间隔:1/ length(signal),频率:", "# if DC mode imposed, set its omega to 0", ") # Maximum number of iterations (if not converged yet,", "2.2204e-16 # python里没有eps功能 uDiff = tol + eps # update", "through Wiener filter of residuals u_hat_plus[k][n,:] = (f_hat_plus - sum_uk", "eps = 2.2204e-16 # python里没有eps功能 uDiff = tol + eps", "用VMD分解算法时只要把信号输入进行分解就行了,只是对信号进行分解,和采样频率没有关系, VMD的输入参数也没有采样频率。 VMD分解出的各分量在输出量 u 中,这个和信号的长度、信号的采样频率没有关系。 迭代时各分量的中心频率在输出量omega,可以用2*pi/fs*omega求出中心频率, 但迭代时的频率是变化的。 Input and Parameters:", "np.fft.fftshift(transformed) # 使用fftshift函数进行移频操作。 f_hat_plus = f_hat f_hat_plus[0:T // 2] =", "accumulator #----------- Main loop for iterative updates---------- while (uDiff >", "#converged yet? uDiff = eps for i in range(K): uDiff", "omega_plus[0:N,:] #Signal reconstruction u_hat = np.zeros((T, K), dtype=complex) temp =", "[np.zeros((N, len(freqs)), dtype=complex) for i in range(K)] # Initialization of", "+ 1) / T for i in range(T)] # 列表从1开始", "# update step n = 1 # loop counter sum_uk", "omega_plus[0, 0] = 0 # start with empty dual variables", "sum_uk = u_hat_plus[k][n,:] + sum_uk - u_hat_plus[k+1][n-1,:] #mode spectrum u_hat_plus[k+1][n,:]", "> tol and n < N ): #not converged and", "/ K) * i elif init == 2: omega_plus[0, :]", "in range(K): omega_plus[0, i] = (0.5 / K) * i", "* np.random.rand(K))) else: omega_plus[0, :] = 0 # if DC", "spectrum of first mode through Wiener filter of residuals u_hat_plus[k][n,:]", "列表从1开始 # Spectral Domain discretization #freqs 进行移位是由于进行傅里叶变换时,会有正负对称的频率,分析时一般只有正频率,所以看到的频谱图是没有负频率的 freqs = np.array(", "of the data-fidelity constraint tau - time-step of the dual", "signal by mirroring镜像延拓 T = save_T f_mirror = [] temp", "in range(K): uDiff = uDiff + 1/T*(u_hat_plus[i][n-1,:]-u_hat_plus[i][n-2,:])*np.mat((u_hat_plus[i][n-1,:]-u_hat_plus[i][n-2,:]).conjugate()).H uDiff = np.abs(uDiff)", "frequency of input signal #分解算法中的采样频率和时间是标准化的,分解信号的采样时间为1s,然后就得到相应的采样频率。采样时间间隔:1/ length(signal),频率: length(signal)。 save_T = len(signal)", "# For future generalizations: individual alpha for each mode Alpha", "spectrum u_hat_plus[k+1][n,:] = (f_hat_plus - sum_uk - lambda_hat[n-1,:]/2)/(1+Alpha[k+1]*(freqs - omega_plus[n-1,k+1])**2)", "= np.sort(np.exp(np.log(fs) + (np.log(0.5) - np.log(fs)) * np.random.rand(K))) else: omega_plus[0,", "= min(N,n) omega = omega_plus[0:N,:] #Signal reconstruction u_hat = np.zeros((T,", "coding: utf-8 -*- import numpy as np def vmd( signal,", "mirroring镜像延拓 T = save_T f_mirror = [] temp = signal[0:T//2]", "of input signal #分解算法中的采样频率和时间是标准化的,分解信号的采样时间为1s,然后就得到相应的采样频率。采样时间间隔:1/ length(signal),频率: length(signal)。 save_T = len(signal) fs", "0 if not DC: omega_plus[n,k] = (freqs[T//2:T]*np.mat(np.abs(u_hat_plus[k][n, T//2:T])**2).H)/np.sum(np.abs(u_hat_plus[k][n,T//2:T])**2) #update of", "Input and Parameters: signal - the time domain signal (1D)", "all omegas start uniformly distributed 2 = all omegas initialized", "omegas start uniformly distributed 2 = all omegas initialized randomly", "iterations limit #update first mode accumulator k = 0 sum_uk", "= len(signal) fs = 1 / save_T # extend the", "for i in range(K): omega_plus[0, i] = (0.5 / K)", "= signal[T//2:T] f_mirror.extend(temp[::-1]) f = f_mirror # Time Domain 0", "mode is put and kept at DC (0-freq) init -", "0 to T (of mirrored signal) T = len(f) t", "For future generalizations: individual alpha for each mode Alpha =", "#Signal reconstruction u_hat = np.zeros((T, K), dtype=complex) temp = [u_hat_plus[i][N-1,T//2:T]", "K, DC, init, tol): ''' 用VMD分解算法时只要把信号输入进行分解就行了,只是对信号进行分解,和采样频率没有关系, VMD的输入参数也没有采样频率。 VMD分解出的各分量在输出量 u 中,这个和信号的长度、信号的采样频率没有关系。", "of omega_k omega_plus = np.zeros((N, K)) if init == 1:", "signal[T//2:T] f_mirror.extend(temp[::-1]) f = f_mirror # Time Domain 0 to", "python里没有eps功能 uDiff = tol + eps # update step n", "number of iterations (if not converged yet, then it won't", "= temp.T[::-1] u_hat[0,:] = (u_hat[-1,:]).conjugate() u = np.zeros((K,len(t))) for k", "K), dtype=complex) temp = [u_hat_plus[i][N-1,T//2:T] for i in range(K) ]", "- np.log(fs)) * np.random.rand(K))) else: omega_plus[0, :] = 0 #", "u_hat[1:(T//2+1),:] = temp.T[::-1] u_hat[0,:] = (u_hat[-1,:]).conjugate() u = np.zeros((K,len(t))) for", "= (f_hat_plus - sum_uk - lambda_hat[n-1,:]/2)/(1+Alpha[k]*(freqs - omega_plus[n-1,k])**2) #update first", "* i elif init == 2: omega_plus[0, :] = np.sort(np.exp(np.log(fs)", "it won't anyway) N = 500 # For future generalizations:", "i in range(K): uDiff = uDiff + 1/T*(u_hat_plus[i][n-1,:]-u_hat_plus[i][n-2,:])*np.mat((u_hat_plus[i][n-1,:]-u_hat_plus[i][n-2,:]).conjugate()).H uDiff =", "N ): #not converged and below iterations limit #update first", "f_hat_plus[0:T] = 1 #????????????????????????????//////////// # matrix keeping track of every", "+ 1/T*(u_hat_plus[i][n-1,:]-u_hat_plus[i][n-2,:])*np.mat((u_hat_plus[i][n-1,:]-u_hat_plus[i][n-2,:]).conjugate()).H uDiff = np.abs(uDiff) # ------ Postprocessing and cleanup-------", "iterant // could be discarded for mem u_hat_plus = [np.zeros((N,", "len(signal) fs = 1 / save_T # extend the signal", "for k in range(K-1): #accumulator sum_uk = u_hat_plus[k][n,:] + sum_uk", "transformed = np.fft.fft(f) # 使用fft函数对信号进行快速傅里叶变换。 f_hat = np.fft.fftshift(transformed) # 使用fftshift函数进行移频操作。", "individual alpha for each mode Alpha = alpha * np.ones(K)", "mode accumulator k = 0 sum_uk = u_hat_plus[K-1][n-1,:]+ sum_uk -", "0.5 - 1 / T for i in t] )", "at 0 if not DC: omega_plus[n,k] = (freqs[T//2:T]*np.mat(np.abs(u_hat_plus[k][n, T//2:T])**2).H)/np.sum(np.abs(u_hat_plus[k][n,T//2:T])**2) #update", "the signal by mirroring镜像延拓 T = save_T f_mirror = []", "#Dual ascent lambda_hat[n,:] = lambda_hat[n-1,:] + tau*(np.sum([ u_hat_plus[i][n,:] for i", "np.squeeze(temp).T temp = np.squeeze(np.mat(temp).conjugate()) u_hat[1:(T//2+1),:] = temp.T[::-1] u_hat[0,:] = (u_hat[-1,:]).conjugate()", "signal #分解算法中的采样频率和时间是标准化的,分解信号的采样时间为1s,然后就得到相应的采样频率。采样时间间隔:1/ length(signal),频率: length(signal)。 save_T = len(signal) fs = 1", "in range(T)] # 列表从1开始 # Spectral Domain discretization #freqs 进行移位是由于进行傅里叶变换时,会有正负对称的频率,分析时一般只有正频率,所以看到的频谱图是没有负频率的", "1) / T for i in range(T)] # 列表从1开始 #", "if not held at 0 if not DC: omega_plus[n,k] =", "of any other mode for k in range(K-1): #accumulator sum_uk", "i in range(K)] # Initialization of omega_k omega_plus = np.zeros((N,", "dtype=complex) for k in range(K): u_hat[:,k]= np.squeeze( np.mat( np.fft.fftshift(np.fft.fft(u[k,:])) ).H)", "0] = 0 # start with empty dual variables lambda_hat", "temp = np.squeeze(np.mat(temp).conjugate()) u_hat[1:(T//2+1),:] = temp.T[::-1] u_hat[0,:] = (u_hat[-1,:]).conjugate() u", "could be discarded for mem u_hat_plus = [np.zeros((N, len(freqs)), dtype=complex)", "u_hat_plus[i][n,:] for i in range(K)],0) - f_hat_plus) #loop counter n", "2: omega_plus[0, :] = np.sort(np.exp(np.log(fs) + (np.log(0.5) - np.log(fs)) *", "domain signal (1D) to be decomposed alpha - the balancing", "迭代时各分量的中心频率在输出量omega,可以用2*pi/fs*omega求出中心频率, 但迭代时的频率是变化的。 Input and Parameters: signal - the time domain", "# 列表从1开始 # Spectral Domain discretization #freqs 进行移位是由于进行傅里叶变换时,会有正负对称的频率,分析时一般只有正频率,所以看到的频谱图是没有负频率的 freqs =", "- the time domain signal (1D) to be decomposed alpha", "= np.array( [i - 0.5 - 1 / T for", "(if not converged yet, then it won't anyway) N =", "f_hat_plus[0:T // 2] = 0 # f_hat_plus[0:T] = 1 #????????????????????????????////////////", "np.squeeze(np.mat(temp).conjugate()) u_hat[1:(T//2+1),:] = temp.T[::-1] u_hat[0,:] = (u_hat[-1,:]).conjugate() u = np.zeros((K,len(t)))", "mode imposed, set its omega to 0 if DC: omega_plus[0,", "Period and sampling frequency of input signal #分解算法中的采样频率和时间是标准化的,分解信号的采样时间为1s,然后就得到相应的采样频率。采样时间间隔:1/ length(signal),频率: length(signal)。", "early N = min(N,n) omega = omega_plus[0:N,:] #Signal reconstruction u_hat", "1 #????????????????????????????//////////// # matrix keeping track of every iterant //", "omega_plus[n,k+1] = (freqs[T//2:T]*np.mat(np.abs(u_hat_plus[k+1][n, T//2:T])**2).H)/np.sum(np.abs(u_hat_plus[k+1][n,T//2:T])**2) #Dual ascent lambda_hat[n,:] = lambda_hat[n-1,:] +", "number of modes to be recovered DC - true if", "-*- import numpy as np def vmd( signal, alpha, tau,", "tol): ''' 用VMD分解算法时只要把信号输入进行分解就行了,只是对信号进行分解,和采样频率没有关系, VMD的输入参数也没有采样频率。 VMD分解出的各分量在输出量 u 中,这个和信号的长度、信号的采样频率没有关系。 迭代时各分量的中心频率在输出量omega,可以用2*pi/fs*omega求出中心频率, 但迭代时的频率是变化的。 Input", "- u_hat_plus[0][n-1,:] #sum_uk 一直都等于0(1,2000)???????????????? #update spectrum of first mode through", "of first mode through Wiener filter of residuals u_hat_plus[k][n,:] =", "be recovered DC - true if the first mode is", "keeping track of every iterant // could be discarded for", "n = 1 # loop counter sum_uk = 0 #", "= 1 # loop counter sum_uk = 0 # accumulator", "k in range(K-1): #accumulator sum_uk = u_hat_plus[k][n,:] + sum_uk -", "= uDiff + 1/T*(u_hat_plus[i][n-1,:]-u_hat_plus[i][n-2,:])*np.mat((u_hat_plus[i][n-1,:]-u_hat_plus[i][n-2,:]).conjugate()).H uDiff = np.abs(uDiff) # ------ Postprocessing", "counter sum_uk = 0 # accumulator #----------- Main loop for", "中,这个和信号的长度、信号的采样频率没有关系。 迭代时各分量的中心频率在输出量omega,可以用2*pi/fs*omega求出中心频率, 但迭代时的频率是变化的。 Input and Parameters: signal - the time", "T (of mirrored signal) T = len(f) t = [(i", "lambda_hat[n-1,:]/2)/(1+Alpha[k+1]*(freqs - omega_plus[n-1,k+1])**2) #center frequencies omega_plus[n,k+1] = (freqs[T//2:T]*np.mat(np.abs(u_hat_plus[k+1][n, T//2:T])**2).H)/np.sum(np.abs(u_hat_plus[k+1][n,T//2:T])**2) #Dual", "N = min(N,n) omega = omega_plus[0:N,:] #Signal reconstruction u_hat =", "n+1 #converged yet? uDiff = eps for i in range(K):", "#mode spectrum u_hat_plus[k+1][n,:] = (f_hat_plus - sum_uk - lambda_hat[n-1,:]/2)/(1+Alpha[k+1]*(freqs -", "= f_hat f_hat_plus[0:T // 2] = 0 # f_hat_plus[0:T] =", "1 / save_T # extend the signal by mirroring镜像延拓 T", "for each mode Alpha = alpha * np.ones(K) # Construct", "(freqs[T//2:T]*np.mat(np.abs(u_hat_plus[k][n, T//2:T])**2).H)/np.sum(np.abs(u_hat_plus[k][n,T//2:T])**2) #update of any other mode for k in", "estimated mode center-frequencies ''' # Period and sampling frequency of", "omega = omega_plus[0:N,:] #Signal reconstruction u_hat = np.zeros((T, K), dtype=complex)", "np.array( [i - 0.5 - 1 / T for i", "= alpha * np.ones(K) # Construct and center f_hat transformed", "- u_hat_plus[k+1][n-1,:] #mode spectrum u_hat_plus[k+1][n,:] = (f_hat_plus - sum_uk -", "i in range(K)],0) - f_hat_plus) #loop counter n = n+1", "limit #update first mode accumulator k = 0 sum_uk =", "recovered DC - true if the first mode is put", "np.zeros((N, K)) if init == 1: for i in range(K):", "of residuals u_hat_plus[k][n,:] = (f_hat_plus - sum_uk - lambda_hat[n-1,:]/2)/(1+Alpha[k]*(freqs -", "omega_plus[n-1,k+1])**2) #center frequencies omega_plus[n,k+1] = (freqs[T//2:T]*np.mat(np.abs(u_hat_plus[k+1][n, T//2:T])**2).H)/np.sum(np.abs(u_hat_plus[k+1][n,T//2:T])**2) #Dual ascent lambda_hat[n,:]", "<gh_stars>0 # -*- coding: utf-8 -*- import numpy as np", "len(freqs)), dtype=complex) for i in range(K)] # Initialization of omega_k", "# accumulator #----------- Main loop for iterative updates---------- while (uDiff", "tau - time-step of the dual ascent ( pick 0", "1e-6 Output: u - the collection of decomposed modes u_hat", "np.zeros((T, K), dtype=complex) temp = [u_hat_plus[i][N-1,T//2:T] for i in range(K)", "sum_uk - lambda_hat[n-1,:]/2)/(1+Alpha[k]*(freqs - omega_plus[n-1,k])**2) #update first omega if not", "- lambda_hat[n-1,:]/2)/(1+Alpha[k+1]*(freqs - omega_plus[n-1,k+1])**2) #center frequencies omega_plus[n,k+1] = (freqs[T//2:T]*np.mat(np.abs(u_hat_plus[k+1][n, T//2:T])**2).H)/np.sum(np.abs(u_hat_plus[k+1][n,T//2:T])**2)", "#分解算法中的采样频率和时间是标准化的,分解信号的采样时间为1s,然后就得到相应的采样频率。采样时间间隔:1/ length(signal),频率: length(signal)。 save_T = len(signal) fs = 1 /", "1 = all omegas start uniformly distributed 2 = all", "K - the number of modes to be recovered DC", "as np def vmd( signal, alpha, tau, K, DC, init,", "the modes omega - estimated mode center-frequencies ''' # Period", "modes to be recovered DC - true if the first", "of convergence criterion; typically around 1e-6 Output: u - the", "Domain discretization #freqs 进行移位是由于进行傅里叶变换时,会有正负对称的频率,分析时一般只有正频率,所以看到的频谱图是没有负频率的 freqs = np.array( [i - 0.5", "center-frequencies ''' # Period and sampling frequency of input signal", "== 1: for i in range(K): omega_plus[0, i] = (0.5", "range(K-1): #accumulator sum_uk = u_hat_plus[k][n,:] + sum_uk - u_hat_plus[k+1][n-1,:] #mode", "# ------ Postprocessing and cleanup------- #discard empty space if converged", "omega - estimated mode center-frequencies ''' # Period and sampling", "- true if the first mode is put and kept", "tol - tolerance of convergence criterion; typically around 1e-6 Output:", "u_hat - spectra of the modes omega - estimated mode", "update step n = 1 # loop counter sum_uk =", "in t] ) # Maximum number of iterations (if not", "i in range(T)] # 列表从1开始 # Spectral Domain discretization #freqs", "of decomposed modes u_hat - spectra of the modes omega", "= 2.2204e-16 # python里没有eps功能 uDiff = tol + eps #", "time-step of the dual ascent ( pick 0 for noise-slack", "lambda_hat[n,:] = lambda_hat[n-1,:] + tau*(np.sum([ u_hat_plus[i][n,:] for i in range(K)],0)", "elif init == 2: omega_plus[0, :] = np.sort(np.exp(np.log(fs) + (np.log(0.5)", "with empty dual variables lambda_hat = np.zeros( (N, len(freqs)), dtype=complex)", "center f_hat transformed = np.fft.fft(f) # 使用fft函数对信号进行快速傅里叶变换。 f_hat = np.fft.fftshift(transformed)", "uDiff + 1/T*(u_hat_plus[i][n-1,:]-u_hat_plus[i][n-2,:])*np.mat((u_hat_plus[i][n-1,:]-u_hat_plus[i][n-2,:]).conjugate()).H uDiff = np.abs(uDiff) # ------ Postprocessing and", "(0.5 / K) * i elif init == 2: omega_plus[0,", "filter of residuals u_hat_plus[k][n,:] = (f_hat_plus - sum_uk - lambda_hat[n-1,:]/2)/(1+Alpha[k]*(freqs", "vmd( signal, alpha, tau, K, DC, init, tol): ''' 用VMD分解算法时只要把信号输入进行分解就行了,只是对信号进行分解,和采样频率没有关系,", "lambda_hat[n-1,:] + tau*(np.sum([ u_hat_plus[i][n,:] for i in range(K)],0) - f_hat_plus)", "len(freqs)), dtype=complex) # other inits eps = 2.2204e-16 # python里没有eps功能", "in range(K): u_hat[:,k]= np.squeeze( np.mat( np.fft.fftshift(np.fft.fft(u[k,:])) ).H) return u, u_hat,", "omega_plus[n-1,k])**2) #update first omega if not held at 0 if", "inits eps = 2.2204e-16 # python里没有eps功能 uDiff = tol +", "in range(K-1): #accumulator sum_uk = u_hat_plus[k][n,:] + sum_uk - u_hat_plus[k+1][n-1,:]", "= np.fft.fft(f) # 使用fft函数对信号进行快速傅里叶变换。 f_hat = np.fft.fftshift(transformed) # 使用fftshift函数进行移频操作。 f_hat_plus", "+ sum_uk - u_hat_plus[k+1][n-1,:] #mode spectrum u_hat_plus[k+1][n,:] = (f_hat_plus -", "initialized randomly tol - tolerance of convergence criterion; typically around", "- 0 = all omegas start at 0 1 =", "T = save_T f_mirror = [] temp = signal[0:T//2] f_mirror.extend(temp[::-1])", "倒序排列 f_mirror.extend(signal) temp = signal[T//2:T] f_mirror.extend(temp[::-1]) f = f_mirror #", "# extend the signal by mirroring镜像延拓 T = save_T f_mirror", "signal[0:T//2] f_mirror.extend(temp[::-1]) #temp[::-1] 倒序排列 f_mirror.extend(signal) temp = signal[T//2:T] f_mirror.extend(temp[::-1]) f", "other inits eps = 2.2204e-16 # python里没有eps功能 uDiff = tol", "Postprocessing and cleanup------- #discard empty space if converged early N", "start with empty dual variables lambda_hat = np.zeros( (N, len(freqs)),", "- tolerance of convergence criterion; typically around 1e-6 Output: u", "f_mirror # Time Domain 0 to T (of mirrored signal)", "future generalizations: individual alpha for each mode Alpha = alpha", "other mode for k in range(K-1): #accumulator sum_uk = u_hat_plus[k][n,:]", "sum_uk = u_hat_plus[K-1][n-1,:]+ sum_uk - u_hat_plus[0][n-1,:] #sum_uk 一直都等于0(1,2000)???????????????? #update spectrum", "------ Postprocessing and cleanup------- #discard empty space if converged early", "in range(K) ] u_hat[T//2:T,:] = np.squeeze(temp).T temp = np.squeeze(np.mat(temp).conjugate()) u_hat[1:(T//2+1),:]", "#recompute spectrum u_hat = np.zeros((T//2, K), dtype=complex) for k in", "= np.zeros((T, K), dtype=complex) temp = [u_hat_plus[i][N-1,T//2:T] for i in", "if DC mode imposed, set its omega to 0 if", "Time Domain 0 to T (of mirrored signal) T =", "range(K) ] u_hat[T//2:T,:] = np.squeeze(temp).T temp = np.squeeze(np.mat(temp).conjugate()) u_hat[1:(T//2+1),:] =", "np.sort(np.exp(np.log(fs) + (np.log(0.5) - np.log(fs)) * np.random.rand(K))) else: omega_plus[0, :]", "and sampling frequency of input signal #分解算法中的采样频率和时间是标准化的,分解信号的采样时间为1s,然后就得到相应的采样频率。采样时间间隔:1/ length(signal),频率: length(signal)。 save_T", "while (uDiff > tol and n < N ): #not", "uDiff = eps for i in range(K): uDiff = uDiff", "anyway) N = 500 # For future generalizations: individual alpha", "t] ) # Maximum number of iterations (if not converged", "0 # accumulator #----------- Main loop for iterative updates---------- while", "below iterations limit #update first mode accumulator k = 0", "for iterative updates---------- while (uDiff > tol and n <", "eps # update step n = 1 # loop counter", "range(K): u[k,:]=np.real(np.fft.ifft(np.fft.ifftshift(u_hat[:,k]))) #remove mirror part u = u[:,T//4:3*T//4] #recompute spectrum", "(of mirrored signal) T = len(f) t = [(i +", "each mode Alpha = alpha * np.ones(K) # Construct and", "tolerance of convergence criterion; typically around 1e-6 Output: u -", "init == 1: for i in range(K): omega_plus[0, i] =", "= signal[0:T//2] f_mirror.extend(temp[::-1]) #temp[::-1] 倒序排列 f_mirror.extend(signal) temp = signal[T//2:T] f_mirror.extend(temp[::-1])", "/ save_T # extend the signal by mirroring镜像延拓 T =", "for mem u_hat_plus = [np.zeros((N, len(freqs)), dtype=complex) for i in", "extend the signal by mirroring镜像延拓 T = save_T f_mirror =", "part u = u[:,T//4:3*T//4] #recompute spectrum u_hat = np.zeros((T//2, K),", "not held at 0 if not DC: omega_plus[n,k] = (freqs[T//2:T]*np.mat(np.abs(u_hat_plus[k][n,", "balancing parameter of the data-fidelity constraint tau - time-step of", "DC - true if the first mode is put and", "mode through Wiener filter of residuals u_hat_plus[k][n,:] = (f_hat_plus -", "#update first omega if not held at 0 if not", "np.zeros((K,len(t))) for k in range(K): u[k,:]=np.real(np.fft.ifft(np.fft.ifftshift(u_hat[:,k]))) #remove mirror part u", "i elif init == 2: omega_plus[0, :] = np.sort(np.exp(np.log(fs) +", "0 sum_uk = u_hat_plus[K-1][n-1,:]+ sum_uk - u_hat_plus[0][n-1,:] #sum_uk 一直都等于0(1,2000)???????????????? #update" ]
[ "value): ... def delete_first(self): ... def delete_last(self): ... def first(self):", "delete_first(self): ... def delete_last(self): ... def first(self): ... def last(self):", "... def is_empty(self): ... def __len__(self): ... def __str__(self): ...", "last(self): ... def is_empty(self): ... def __len__(self): ... def __str__(self):", "def delete_first(self): ... def delete_last(self): ... def first(self): ... def", "def add_last(self, value): ... def delete_first(self): ... def delete_last(self): ...", "def last(self): ... def is_empty(self): ... def __len__(self): ... def", "add_first(self, value): ... def add_last(self, value): ... def delete_first(self): ...", "... def delete_last(self): ... def first(self): ... def last(self): ...", "def first(self): ... def last(self): ... def is_empty(self): ... def", "def add_first(self, value): ... def add_last(self, value): ... def delete_first(self):", "add_last(self, value): ... def delete_first(self): ... def delete_last(self): ... def", "Deque: def add_first(self, value): ... def add_last(self, value): ... def", "<reponame>AoWangPhilly/PyDS<gh_stars>0 class Deque: def add_first(self, value): ... def add_last(self, value):", "class Deque: def add_first(self, value): ... def add_last(self, value): ...", "... def delete_first(self): ... def delete_last(self): ... def first(self): ...", "... def add_last(self, value): ... def delete_first(self): ... def delete_last(self):", "first(self): ... def last(self): ... def is_empty(self): ... def __len__(self):", "def delete_last(self): ... def first(self): ... def last(self): ... def", "... def last(self): ... def is_empty(self): ... def __len__(self): ...", "... def first(self): ... def last(self): ... def is_empty(self): ...", "value): ... def add_last(self, value): ... def delete_first(self): ... def", "delete_last(self): ... def first(self): ... def last(self): ... def is_empty(self):" ]
[ "=models.Member(\"mohamed\",30) post1=models.Post(\"Post1\", \"Content1\") post2= models.Post(\"Post2\", \"Content2\") post3= models.Post(\"Post3\", \"Content3\") #member", "\"Content1\") post2= models.Post(\"Post2\", \"Content2\") post3= models.Post(\"Post3\", \"Content3\") #member store member_store=stores.MemberStore()", "models.Post(\"Post2\", \"Content2\") post3= models.Post(\"Post3\", \"Content3\") #member store member_store=stores.MemberStore() member_store.add(member1) member_store.add(member2)", "post2= models.Post(\"Post2\", \"Content2\") post3= models.Post(\"Post3\", \"Content3\") #member store member_store=stores.MemberStore() member_store.add(member1)", "\"Content3\") #member store member_store=stores.MemberStore() member_store.add(member1) member_store.add(member2) print (member_store.get_all()) post_store=stores.PostStore() post_store.add(post1)", "store member_store=stores.MemberStore() member_store.add(member1) member_store.add(member2) print (member_store.get_all()) post_store=stores.PostStore() post_store.add(post1) post_store.add(post2) post_store.add(post3)", "<gh_stars>1-10 import models import stores member1 =models.Member(\"ahmed\",33) member2 =models.Member(\"mohamed\",30) post1=models.Post(\"Post1\",", "=models.Member(\"ahmed\",33) member2 =models.Member(\"mohamed\",30) post1=models.Post(\"Post1\", \"Content1\") post2= models.Post(\"Post2\", \"Content2\") post3= models.Post(\"Post3\",", "post1=models.Post(\"Post1\", \"Content1\") post2= models.Post(\"Post2\", \"Content2\") post3= models.Post(\"Post3\", \"Content3\") #member store", "models.Post(\"Post3\", \"Content3\") #member store member_store=stores.MemberStore() member_store.add(member1) member_store.add(member2) print (member_store.get_all()) post_store=stores.PostStore()", "import models import stores member1 =models.Member(\"ahmed\",33) member2 =models.Member(\"mohamed\",30) post1=models.Post(\"Post1\", \"Content1\")", "stores member1 =models.Member(\"ahmed\",33) member2 =models.Member(\"mohamed\",30) post1=models.Post(\"Post1\", \"Content1\") post2= models.Post(\"Post2\", \"Content2\")", "member2 =models.Member(\"mohamed\",30) post1=models.Post(\"Post1\", \"Content1\") post2= models.Post(\"Post2\", \"Content2\") post3= models.Post(\"Post3\", \"Content3\")", "member_store=stores.MemberStore() member_store.add(member1) member_store.add(member2) print (member_store.get_all()) post_store=stores.PostStore() post_store.add(post1) post_store.add(post2) post_store.add(post3) print", "member1 =models.Member(\"ahmed\",33) member2 =models.Member(\"mohamed\",30) post1=models.Post(\"Post1\", \"Content1\") post2= models.Post(\"Post2\", \"Content2\") post3=", "#member store member_store=stores.MemberStore() member_store.add(member1) member_store.add(member2) print (member_store.get_all()) post_store=stores.PostStore() post_store.add(post1) post_store.add(post2)", "models import stores member1 =models.Member(\"ahmed\",33) member2 =models.Member(\"mohamed\",30) post1=models.Post(\"Post1\", \"Content1\") post2=", "import stores member1 =models.Member(\"ahmed\",33) member2 =models.Member(\"mohamed\",30) post1=models.Post(\"Post1\", \"Content1\") post2= models.Post(\"Post2\",", "post3= models.Post(\"Post3\", \"Content3\") #member store member_store=stores.MemberStore() member_store.add(member1) member_store.add(member2) print (member_store.get_all())", "\"Content2\") post3= models.Post(\"Post3\", \"Content3\") #member store member_store=stores.MemberStore() member_store.add(member1) member_store.add(member2) print", "member_store.add(member1) member_store.add(member2) print (member_store.get_all()) post_store=stores.PostStore() post_store.add(post1) post_store.add(post2) post_store.add(post3) print (post_store.get_all())" ]
[ "try: try: create=open(log_file_name,\"w\") except: print negative+\"\\nError generating log file. Please", "in keywords: keys=keys.replace(\"\\n\",\"\") #To replace newline with empty New_URL =", "\"+website_url conn = urllib2.Request(website_url) urllib2.urlopen(website_url) print positive+\"Connected! Begining to scan", "for keys in keywords: keys=keys.replace(\"\\n\",\"\") #To replace newline with empty", "try: f = open(log_file_name, 'r') return f.read() f.close() except IOError:", "<gh_stars>1-10 #!/usr/bin/env python ''' Author : <NAME> Email : <EMAIL>", "= urlopen(req) except URLError, e: if hasattr(e,'reason'): print negative+\"Not found\"", "URL) : \") parse_url=urlparse(website_url) log_file_name = \"LOG/\"+parse_url.netloc+\".log\" global total_scanned_global global", "open(\"dictionary\",\"r\") except(IOError): print negative+\"Dictionary file not found_scanned_global. Please download the", "shells..\" except (urllib2.HTTPError) as Exit: print negative+\"\\nEither the server is", "wait+\"\\nCreating a persistent connection to site \"+website_url conn = urllib2.Request(website_url)", "else: try: log_file=open(log_file_name,\"a+\") #Appending to it except(IOError): print negative+\"Failed to", "found_scanned_url=New_URL print positive+\"Possible shell found at \",found_scanned_url log_file.writelines(found_scanned_url+\"\\n\") found_scanned_global=found_scanned_global+1 total_scanned_global=total_scanned_global+1", "exist.\" def main(): socket.setdefaulttimeout(10) print wait+\"\\n## ------ Welcome to Shell", "return \"File\" + log_file_name + \"does not exist.\" def main():", "\"does not exist.\" def main(): socket.setdefaulttimeout(10) print wait+\"\\n## ------ Welcome", "------ ##\" website_url = raw_input(\"\\n\\nEnter URL to scan ([eg, http://sitename.com", "\"\\nTotal tries : \", total_scanned_global print positive+\"\\nPossible shells: \",found_scanned_global print", "= open(\"dictionary\",\"r\") except(IOError): print negative+\"Dictionary file not found_scanned_global. Please download", "end of URL) : \") parse_url=urlparse(website_url) log_file_name = \"LOG/\"+parse_url.netloc+\".log\" global", "def OpenLog(log_file_name): try: f = open(log_file_name, 'r') return f.read() f.close()", "all possibilities via dictionary match. ''' import socket import sys", "OpenLog(log_file_name): try: f = open(log_file_name, 'r') return f.read() f.close() except", "'\\033[95m' final = '\\033[93m' total_scanned_global=0 found_scanned_global=0 def OpenLog(log_file_name): try: f", "from github link\" exit() keywords = dictionary.readlines() for keys in", "total_scanned_global+1 elif hasattr(e,'code'): print negative+\"Not found \" total_scanned_global = total_scanned_global+1", "add slash at the end of URL) : \") parse_url=urlparse(website_url)", ": \", total_scanned_global print positive+\"\\nPossible shells: \",found_scanned_global print final+\"\\nFollowing are", "\"+New_URL req=Request(New_URL) try: response = urlopen(req) except URLError, e: if", "it except(IOError): print negative+\"Failed to create log file. Check dir", "of URL) : \") parse_url=urlparse(website_url) log_file_name = \"LOG/\"+parse_url.netloc+\".log\" global total_scanned_global", "##\" website_url = raw_input(\"\\n\\nEnter URL to scan ([eg, http://sitename.com or", "tries : \", total_scanned_global print positive+\"\\nPossible shells: \",found_scanned_global print final+\"\\nFollowing", "conn = urllib2.Request(website_url) urllib2.urlopen(website_url) print positive+\"Connected! Begining to scan for", "shells available and tries all possibilities via dictionary match. '''", "at \",found_scanned_url log_file.writelines(found_scanned_url+\"\\n\") found_scanned_global=found_scanned_global+1 total_scanned_global=total_scanned_global+1 log_file.close() print \"\\nTotal tries :", "#Appending to it except(IOError): print negative+\"Failed to create log file.", "with empty New_URL = website_url+\"/\"+keys print wait+\">>>> \"+New_URL req=Request(New_URL) try:", "internet.\" exit() try: dictionary = open(\"dictionary\",\"r\") except(IOError): print negative+\"Dictionary file", "License V2.0 | Project Source (https://github.com/bhavyanshu/Shell-Finder) ------ ##\" website_url =", "to scan ([eg, http://sitename.com or https://sitename.com/subdir ] | Do not", "Author : <NAME> Email : <EMAIL> Description : shellfind.py is", "permissions.\" print wait+\"\\nCreating a persistent connection to site \"+website_url conn", "the links to possible shells \" print OpenLog(log_file_name) if __name__", "urlparse import urlparse import time as t import urllib2 from", "raw_input(\"\\n\\nEnter URL to scan ([eg, http://sitename.com or https://sitename.com/subdir ] |", "print \"\\nTotal tries : \", total_scanned_global print positive+\"\\nPossible shells: \",found_scanned_global", "line utility which lets you look for shells on a", "keywords: keys=keys.replace(\"\\n\",\"\") #To replace newline with empty New_URL = website_url+\"/\"+keys", "that the hacker must have uploaded. It considers all the", "It considers all the shells available and tries all possibilities", "= website_url+\"/\"+keys print wait+\">>>> \"+New_URL req=Request(New_URL) try: response = urlopen(req)", "+ \"does not exist.\" def main(): socket.setdefaulttimeout(10) print wait+\"\\n## ------", "links to possible shells \" print OpenLog(log_file_name) if __name__ ==", "+ log_file_name + \"does not exist.\" def main(): socket.setdefaulttimeout(10) print", "try: log_file=open(log_file_name,\"a+\") #Appending to it except(IOError): print negative+\"Failed to create", "http://sitename.com or https://sitename.com/subdir ] | Do not add slash at", "the internet.\" exit() try: dictionary = open(\"dictionary\",\"r\") except(IOError): print negative+\"Dictionary", "found_scanned_global=found_scanned_global+1 total_scanned_global=total_scanned_global+1 log_file.close() print \"\\nTotal tries : \", total_scanned_global print", "you are not connected to the internet.\" exit() try: dictionary", "or https://sitename.com/subdir ] | Do not add slash at the", ": <EMAIL> Description : shellfind.py is a Python command line", "positive+\"Possible shell found at \",found_scanned_url log_file.writelines(found_scanned_url+\"\\n\") found_scanned_global=found_scanned_global+1 total_scanned_global=total_scanned_global+1 log_file.close() print", "link\" exit() keywords = dictionary.readlines() for keys in keywords: keys=keys.replace(\"\\n\",\"\")", "command line utility which lets you look for shells on", "lets you look for shells on a site that the", "urllib2 from urllib2 import Request, urlopen, URLError negative = '\\033[91m'", "import Request, urlopen, URLError negative = '\\033[91m' positive = '\\033[32m'", "look for shells on a site that the hacker must", "URLError negative = '\\033[91m' positive = '\\033[32m' wait = '\\033[95m'", "on a site that the hacker must have uploaded. It", "except URLError, e: if hasattr(e,'reason'): print negative+\"Not found\" total_scanned_global =", "dictionary from github link\" exit() keywords = dictionary.readlines() for keys", "the hacker must have uploaded. It considers all the shells", "print negative+\"Dictionary file not found_scanned_global. Please download the latest dictionary", "https://sitename.com/subdir ] | Do not add slash at the end", "shell found at \",found_scanned_url log_file.writelines(found_scanned_url+\"\\n\") found_scanned_global=found_scanned_global+1 total_scanned_global=total_scanned_global+1 log_file.close() print \"\\nTotal", "import urllib2 from urllib2 import Request, urlopen, URLError negative =", "log file. Please check directory access permissions.\" print wait+\"\\nCreating a", "negative+\"Dictionary file not found_scanned_global. Please download the latest dictionary from", "negative+\"\\nEither the server is down or you are not connected", "Exit: print negative+\"\\nEither the server is down or you are", "except(IOError): print negative+\"Failed to create log file. Check dir permissions.\"", "from urllib2 import Request, urlopen, URLError negative = '\\033[91m' positive", "([eg, http://sitename.com or https://sitename.com/subdir ] | Do not add slash", "print positive+\"Connected! Begining to scan for shells..\" except (urllib2.HTTPError) as", "open(log_file_name, 'r') return f.read() f.close() except IOError: return \"File\" +", "keywords = dictionary.readlines() for keys in keywords: keys=keys.replace(\"\\n\",\"\") #To replace", "httplib from urlparse import urlparse import time as t import", "IOError: return \"File\" + log_file_name + \"does not exist.\" def", "empty New_URL = website_url+\"/\"+keys print wait+\">>>> \"+New_URL req=Request(New_URL) try: response", "are the links to possible shells \" print OpenLog(log_file_name) if", "log_file=open(log_file_name,\"a+\") #Appending to it except(IOError): print negative+\"Failed to create log", "python ''' Author : <NAME> Email : <EMAIL> Description :", "except (urllib2.HTTPError) as Exit: print negative+\"\\nEither the server is down", "server is down or you are not connected to the", "e: if hasattr(e,'reason'): print negative+\"Not found\" total_scanned_global = total_scanned_global+1 elif", "'\\033[91m' positive = '\\033[32m' wait = '\\033[95m' final = '\\033[93m'", "newline with empty New_URL = website_url+\"/\"+keys print wait+\">>>> \"+New_URL req=Request(New_URL)", "print negative+\"\\nEither the server is down or you are not", "positive = '\\033[32m' wait = '\\033[95m' final = '\\033[93m' total_scanned_global=0", "print positive+\"Possible shell found at \",found_scanned_url log_file.writelines(found_scanned_url+\"\\n\") found_scanned_global=found_scanned_global+1 total_scanned_global=total_scanned_global+1 log_file.close()", "Begining to scan for shells..\" except (urllib2.HTTPError) as Exit: print", "not connected to the internet.\" exit() try: dictionary = open(\"dictionary\",\"r\")", "Do not add slash at the end of URL) :", "found at \",found_scanned_url log_file.writelines(found_scanned_url+\"\\n\") found_scanned_global=found_scanned_global+1 total_scanned_global=total_scanned_global+1 log_file.close() print \"\\nTotal tries", "urllib2 import Request, urlopen, URLError negative = '\\033[91m' positive =", "the server is down or you are not connected to", "and tries all possibilities via dictionary match. ''' import socket", "\", total_scanned_global print positive+\"\\nPossible shells: \",found_scanned_global print final+\"\\nFollowing are the", "= '\\033[95m' final = '\\033[93m' total_scanned_global=0 found_scanned_global=0 def OpenLog(log_file_name): try:", "(http://bhavyanshu.github.io) | Apache License V2.0 | Project Source (https://github.com/bhavyanshu/Shell-Finder) ------", "download the latest dictionary from github link\" exit() keywords =", "<EMAIL> Description : shellfind.py is a Python command line utility", "Email : <EMAIL> Description : shellfind.py is a Python command", "connection to site \"+website_url conn = urllib2.Request(website_url) urllib2.urlopen(website_url) print positive+\"Connected!", "tries all possibilities via dictionary match. ''' import socket import", "dir permissions.\" found_scanned_url=New_URL print positive+\"Possible shell found at \",found_scanned_url log_file.writelines(found_scanned_url+\"\\n\")", "negative+\"Not found\" total_scanned_global = total_scanned_global+1 elif hasattr(e,'code'): print negative+\"Not found", "possible shells \" print OpenLog(log_file_name) if __name__ == '__main__': main()", "except(IOError): print negative+\"Dictionary file not found_scanned_global. Please download the latest", "file not found_scanned_global. Please download the latest dictionary from github", "latest dictionary from github link\" exit() keywords = dictionary.readlines() for", "urlopen, URLError negative = '\\033[91m' positive = '\\033[32m' wait =", "Project Source (https://github.com/bhavyanshu/Shell-Finder) ------ ##\" website_url = raw_input(\"\\n\\nEnter URL to", "time as t import urllib2 from urllib2 import Request, urlopen,", "\",found_scanned_url log_file.writelines(found_scanned_url+\"\\n\") found_scanned_global=found_scanned_global+1 total_scanned_global=total_scanned_global+1 log_file.close() print \"\\nTotal tries : \",", "t import urllib2 from urllib2 import Request, urlopen, URLError negative", "Welcome to Shell Finder Utility - Developed by <NAME> (http://bhavyanshu.github.io)", "the latest dictionary from github link\" exit() keywords = dictionary.readlines()", "github link\" exit() keywords = dictionary.readlines() for keys in keywords:", "sys import httplib from urlparse import urlparse import time as", "considers all the shells available and tries all possibilities via", "file. Check dir permissions.\" found_scanned_url=New_URL print positive+\"Possible shell found at", "not exist.\" def main(): socket.setdefaulttimeout(10) print wait+\"\\n## ------ Welcome to", "replace newline with empty New_URL = website_url+\"/\"+keys print wait+\">>>> \"+New_URL", "exit() try: dictionary = open(\"dictionary\",\"r\") except(IOError): print negative+\"Dictionary file not", "total_scanned_global print positive+\"\\nPossible shells: \",found_scanned_global print final+\"\\nFollowing are the links", "= open(log_file_name, 'r') return f.read() f.close() except IOError: return \"File\"", "def main(): socket.setdefaulttimeout(10) print wait+\"\\n## ------ Welcome to Shell Finder", "import httplib from urlparse import urlparse import time as t", "directory access permissions.\" print wait+\"\\nCreating a persistent connection to site", "try: response = urlopen(req) except URLError, e: if hasattr(e,'reason'): print", "create=open(log_file_name,\"w\") except: print negative+\"\\nError generating log file. Please check directory", "global found_scanned_global try: try: create=open(log_file_name,\"w\") except: print negative+\"\\nError generating log", "| Apache License V2.0 | Project Source (https://github.com/bhavyanshu/Shell-Finder) ------ ##\"", "socket import sys import httplib from urlparse import urlparse import", "log_file.writelines(found_scanned_url+\"\\n\") found_scanned_global=found_scanned_global+1 total_scanned_global=total_scanned_global+1 log_file.close() print \"\\nTotal tries : \", total_scanned_global", "#To replace newline with empty New_URL = website_url+\"/\"+keys print wait+\">>>>", "Request, urlopen, URLError negative = '\\033[91m' positive = '\\033[32m' wait", "is a Python command line utility which lets you look", "Source (https://github.com/bhavyanshu/Shell-Finder) ------ ##\" website_url = raw_input(\"\\n\\nEnter URL to scan", "total_scanned_global = total_scanned_global+1 else: try: log_file=open(log_file_name,\"a+\") #Appending to it except(IOError):", "available and tries all possibilities via dictionary match. ''' import", "import sys import httplib from urlparse import urlparse import time", "- Developed by <NAME> (http://bhavyanshu.github.io) | Apache License V2.0 |", "to create log file. Check dir permissions.\" found_scanned_url=New_URL print positive+\"Possible", "not found_scanned_global. Please download the latest dictionary from github link\"", "the shells available and tries all possibilities via dictionary match.", "\"File\" + log_file_name + \"does not exist.\" def main(): socket.setdefaulttimeout(10)", "hacker must have uploaded. It considers all the shells available", "urllib2.urlopen(website_url) print positive+\"Connected! Begining to scan for shells..\" except (urllib2.HTTPError)", "\",found_scanned_global print final+\"\\nFollowing are the links to possible shells \"", "main(): socket.setdefaulttimeout(10) print wait+\"\\n## ------ Welcome to Shell Finder Utility", "import socket import sys import httplib from urlparse import urlparse", "import urlparse import time as t import urllib2 from urllib2", "final = '\\033[93m' total_scanned_global=0 found_scanned_global=0 def OpenLog(log_file_name): try: f =", "dictionary = open(\"dictionary\",\"r\") except(IOError): print negative+\"Dictionary file not found_scanned_global. Please", "\"LOG/\"+parse_url.netloc+\".log\" global total_scanned_global global found_scanned_global try: try: create=open(log_file_name,\"w\") except: print", "urllib2.Request(website_url) urllib2.urlopen(website_url) print positive+\"Connected! Begining to scan for shells..\" except", "log_file_name + \"does not exist.\" def main(): socket.setdefaulttimeout(10) print wait+\"\\n##", "as Exit: print negative+\"\\nEither the server is down or you", "found \" total_scanned_global = total_scanned_global+1 else: try: log_file=open(log_file_name,\"a+\") #Appending to", "check directory access permissions.\" print wait+\"\\nCreating a persistent connection to", "shells: \",found_scanned_global print final+\"\\nFollowing are the links to possible shells", "urlopen(req) except URLError, e: if hasattr(e,'reason'): print negative+\"Not found\" total_scanned_global", ": shellfind.py is a Python command line utility which lets", "dictionary match. ''' import socket import sys import httplib from", "= \"LOG/\"+parse_url.netloc+\".log\" global total_scanned_global global found_scanned_global try: try: create=open(log_file_name,\"w\") except:", "exit() keywords = dictionary.readlines() for keys in keywords: keys=keys.replace(\"\\n\",\"\") #To", "keys=keys.replace(\"\\n\",\"\") #To replace newline with empty New_URL = website_url+\"/\"+keys print", "access permissions.\" print wait+\"\\nCreating a persistent connection to site \"+website_url", "file. Please check directory access permissions.\" print wait+\"\\nCreating a persistent", "= total_scanned_global+1 elif hasattr(e,'code'): print negative+\"Not found \" total_scanned_global =", "website_url = raw_input(\"\\n\\nEnter URL to scan ([eg, http://sitename.com or https://sitename.com/subdir", "negative = '\\033[91m' positive = '\\033[32m' wait = '\\033[95m' final", "as t import urllib2 from urllib2 import Request, urlopen, URLError", "'r') return f.read() f.close() except IOError: return \"File\" + log_file_name", "Please download the latest dictionary from github link\" exit() keywords", "log_file_name = \"LOG/\"+parse_url.netloc+\".log\" global total_scanned_global global found_scanned_global try: try: create=open(log_file_name,\"w\")", "print positive+\"\\nPossible shells: \",found_scanned_global print final+\"\\nFollowing are the links to", "= total_scanned_global+1 else: try: log_file=open(log_file_name,\"a+\") #Appending to it except(IOError): print", "urlparse import time as t import urllib2 from urllib2 import", "Python command line utility which lets you look for shells", "total_scanned_global=0 found_scanned_global=0 def OpenLog(log_file_name): try: f = open(log_file_name, 'r') return", "| Project Source (https://github.com/bhavyanshu/Shell-Finder) ------ ##\" website_url = raw_input(\"\\n\\nEnter URL", "#!/usr/bin/env python ''' Author : <NAME> Email : <EMAIL> Description", "URL to scan ([eg, http://sitename.com or https://sitename.com/subdir ] | Do", "a Python command line utility which lets you look for", "connected to the internet.\" exit() try: dictionary = open(\"dictionary\",\"r\") except(IOError):", "Please check directory access permissions.\" print wait+\"\\nCreating a persistent connection", "persistent connection to site \"+website_url conn = urllib2.Request(website_url) urllib2.urlopen(website_url) print", "------ Welcome to Shell Finder Utility - Developed by <NAME>", "via dictionary match. ''' import socket import sys import httplib", ": <NAME> Email : <EMAIL> Description : shellfind.py is a", "hasattr(e,'code'): print negative+\"Not found \" total_scanned_global = total_scanned_global+1 else: try:", "parse_url=urlparse(website_url) log_file_name = \"LOG/\"+parse_url.netloc+\".log\" global total_scanned_global global found_scanned_global try: try:", "Utility - Developed by <NAME> (http://bhavyanshu.github.io) | Apache License V2.0", "website_url+\"/\"+keys print wait+\">>>> \"+New_URL req=Request(New_URL) try: response = urlopen(req) except", "''' Author : <NAME> Email : <EMAIL> Description : shellfind.py", "slash at the end of URL) : \") parse_url=urlparse(website_url) log_file_name", "which lets you look for shells on a site that", "print negative+\"Not found\" total_scanned_global = total_scanned_global+1 elif hasattr(e,'code'): print negative+\"Not", "total_scanned_global+1 else: try: log_file=open(log_file_name,\"a+\") #Appending to it except(IOError): print negative+\"Failed", "to the internet.\" exit() try: dictionary = open(\"dictionary\",\"r\") except(IOError): print", "total_scanned_global global found_scanned_global try: try: create=open(log_file_name,\"w\") except: print negative+\"\\nError generating", "total_scanned_global = total_scanned_global+1 elif hasattr(e,'code'): print negative+\"Not found \" total_scanned_global", "Check dir permissions.\" found_scanned_url=New_URL print positive+\"Possible shell found at \",found_scanned_url", "found_scanned_global=0 def OpenLog(log_file_name): try: f = open(log_file_name, 'r') return f.read()", "to it except(IOError): print negative+\"Failed to create log file. Check", "wait = '\\033[95m' final = '\\033[93m' total_scanned_global=0 found_scanned_global=0 def OpenLog(log_file_name):", "to Shell Finder Utility - Developed by <NAME> (http://bhavyanshu.github.io) |", ": \") parse_url=urlparse(website_url) log_file_name = \"LOG/\"+parse_url.netloc+\".log\" global total_scanned_global global found_scanned_global", "URLError, e: if hasattr(e,'reason'): print negative+\"Not found\" total_scanned_global = total_scanned_global+1", "= dictionary.readlines() for keys in keywords: keys=keys.replace(\"\\n\",\"\") #To replace newline", "dictionary.readlines() for keys in keywords: keys=keys.replace(\"\\n\",\"\") #To replace newline with", "try: create=open(log_file_name,\"w\") except: print negative+\"\\nError generating log file. Please check", "possibilities via dictionary match. ''' import socket import sys import", "f = open(log_file_name, 'r') return f.read() f.close() except IOError: return", "= urllib2.Request(website_url) urllib2.urlopen(website_url) print positive+\"Connected! Begining to scan for shells..\"", "found_scanned_global try: try: create=open(log_file_name,\"w\") except: print negative+\"\\nError generating log file.", "by <NAME> (http://bhavyanshu.github.io) | Apache License V2.0 | Project Source", "import time as t import urllib2 from urllib2 import Request,", "generating log file. Please check directory access permissions.\" print wait+\"\\nCreating", "New_URL = website_url+\"/\"+keys print wait+\">>>> \"+New_URL req=Request(New_URL) try: response =", "<NAME> (http://bhavyanshu.github.io) | Apache License V2.0 | Project Source (https://github.com/bhavyanshu/Shell-Finder)", "negative+\"Failed to create log file. Check dir permissions.\" found_scanned_url=New_URL print", "a persistent connection to site \"+website_url conn = urllib2.Request(website_url) urllib2.urlopen(website_url)", "except IOError: return \"File\" + log_file_name + \"does not exist.\"", "print negative+\"Not found \" total_scanned_global = total_scanned_global+1 else: try: log_file=open(log_file_name,\"a+\")", "] | Do not add slash at the end of", "utility which lets you look for shells on a site", "to scan for shells..\" except (urllib2.HTTPError) as Exit: print negative+\"\\nEither", "(https://github.com/bhavyanshu/Shell-Finder) ------ ##\" website_url = raw_input(\"\\n\\nEnter URL to scan ([eg,", "scan for shells..\" except (urllib2.HTTPError) as Exit: print negative+\"\\nEither the", "or you are not connected to the internet.\" exit() try:", "Finder Utility - Developed by <NAME> (http://bhavyanshu.github.io) | Apache License", "positive+\"\\nPossible shells: \",found_scanned_global print final+\"\\nFollowing are the links to possible", "\" total_scanned_global = total_scanned_global+1 else: try: log_file=open(log_file_name,\"a+\") #Appending to it", "all the shells available and tries all possibilities via dictionary", "'\\033[93m' total_scanned_global=0 found_scanned_global=0 def OpenLog(log_file_name): try: f = open(log_file_name, 'r')", "you look for shells on a site that the hacker", "not add slash at the end of URL) : \")", "negative+\"Not found \" total_scanned_global = total_scanned_global+1 else: try: log_file=open(log_file_name,\"a+\") #Appending", "at the end of URL) : \") parse_url=urlparse(website_url) log_file_name =", "\") parse_url=urlparse(website_url) log_file_name = \"LOG/\"+parse_url.netloc+\".log\" global total_scanned_global global found_scanned_global try:", "V2.0 | Project Source (https://github.com/bhavyanshu/Shell-Finder) ------ ##\" website_url = raw_input(\"\\n\\nEnter", "to possible shells \" print OpenLog(log_file_name) if __name__ == '__main__':", "req=Request(New_URL) try: response = urlopen(req) except URLError, e: if hasattr(e,'reason'):", "site \"+website_url conn = urllib2.Request(website_url) urllib2.urlopen(website_url) print positive+\"Connected! Begining to", "print wait+\">>>> \"+New_URL req=Request(New_URL) try: response = urlopen(req) except URLError,", "print final+\"\\nFollowing are the links to possible shells \" print", "return f.read() f.close() except IOError: return \"File\" + log_file_name +", "(urllib2.HTTPError) as Exit: print negative+\"\\nEither the server is down or", "a site that the hacker must have uploaded. It considers", "is down or you are not connected to the internet.\"", "socket.setdefaulttimeout(10) print wait+\"\\n## ------ Welcome to Shell Finder Utility -", "for shells on a site that the hacker must have", "negative+\"\\nError generating log file. Please check directory access permissions.\" print", "= '\\033[91m' positive = '\\033[32m' wait = '\\033[95m' final =", "f.read() f.close() except IOError: return \"File\" + log_file_name + \"does", "Description : shellfind.py is a Python command line utility which", "hasattr(e,'reason'): print negative+\"Not found\" total_scanned_global = total_scanned_global+1 elif hasattr(e,'code'): print", "total_scanned_global=total_scanned_global+1 log_file.close() print \"\\nTotal tries : \", total_scanned_global print positive+\"\\nPossible", "keys in keywords: keys=keys.replace(\"\\n\",\"\") #To replace newline with empty New_URL", "scan ([eg, http://sitename.com or https://sitename.com/subdir ] | Do not add", "print wait+\"\\nCreating a persistent connection to site \"+website_url conn =", "site that the hacker must have uploaded. It considers all", "permissions.\" found_scanned_url=New_URL print positive+\"Possible shell found at \",found_scanned_url log_file.writelines(found_scanned_url+\"\\n\") found_scanned_global=found_scanned_global+1", "= '\\033[32m' wait = '\\033[95m' final = '\\033[93m' total_scanned_global=0 found_scanned_global=0", "Apache License V2.0 | Project Source (https://github.com/bhavyanshu/Shell-Finder) ------ ##\" website_url", "uploaded. It considers all the shells available and tries all", "match. ''' import socket import sys import httplib from urlparse", "= '\\033[93m' total_scanned_global=0 found_scanned_global=0 def OpenLog(log_file_name): try: f = open(log_file_name,", "if hasattr(e,'reason'): print negative+\"Not found\" total_scanned_global = total_scanned_global+1 elif hasattr(e,'code'):", "print negative+\"Failed to create log file. Check dir permissions.\" found_scanned_url=New_URL", "except: print negative+\"\\nError generating log file. Please check directory access", "= raw_input(\"\\n\\nEnter URL to scan ([eg, http://sitename.com or https://sitename.com/subdir ]", "to site \"+website_url conn = urllib2.Request(website_url) urllib2.urlopen(website_url) print positive+\"Connected! Begining", "final+\"\\nFollowing are the links to possible shells \" print OpenLog(log_file_name)", "print negative+\"\\nError generating log file. Please check directory access permissions.\"", "shellfind.py is a Python command line utility which lets you", "Shell Finder Utility - Developed by <NAME> (http://bhavyanshu.github.io) | Apache", "are not connected to the internet.\" exit() try: dictionary =", "for shells..\" except (urllib2.HTTPError) as Exit: print negative+\"\\nEither the server", "log_file.close() print \"\\nTotal tries : \", total_scanned_global print positive+\"\\nPossible shells:", "log file. Check dir permissions.\" found_scanned_url=New_URL print positive+\"Possible shell found", "create log file. Check dir permissions.\" found_scanned_url=New_URL print positive+\"Possible shell", "<NAME> Email : <EMAIL> Description : shellfind.py is a Python", "down or you are not connected to the internet.\" exit()", "found\" total_scanned_global = total_scanned_global+1 elif hasattr(e,'code'): print negative+\"Not found \"", "global total_scanned_global global found_scanned_global try: try: create=open(log_file_name,\"w\") except: print negative+\"\\nError", "positive+\"Connected! Begining to scan for shells..\" except (urllib2.HTTPError) as Exit:", "'\\033[32m' wait = '\\033[95m' final = '\\033[93m' total_scanned_global=0 found_scanned_global=0 def", "have uploaded. It considers all the shells available and tries", "found_scanned_global. Please download the latest dictionary from github link\" exit()", "print wait+\"\\n## ------ Welcome to Shell Finder Utility - Developed", "elif hasattr(e,'code'): print negative+\"Not found \" total_scanned_global = total_scanned_global+1 else:", "response = urlopen(req) except URLError, e: if hasattr(e,'reason'): print negative+\"Not", "Developed by <NAME> (http://bhavyanshu.github.io) | Apache License V2.0 | Project", "| Do not add slash at the end of URL)", "wait+\">>>> \"+New_URL req=Request(New_URL) try: response = urlopen(req) except URLError, e:", "must have uploaded. It considers all the shells available and", "f.close() except IOError: return \"File\" + log_file_name + \"does not", "from urlparse import urlparse import time as t import urllib2", "the end of URL) : \") parse_url=urlparse(website_url) log_file_name = \"LOG/\"+parse_url.netloc+\".log\"", "try: dictionary = open(\"dictionary\",\"r\") except(IOError): print negative+\"Dictionary file not found_scanned_global.", "wait+\"\\n## ------ Welcome to Shell Finder Utility - Developed by", "''' import socket import sys import httplib from urlparse import", "shells on a site that the hacker must have uploaded." ]
[ "return \"Invalid input\" elif (bracket != collector.pop()): return False return", "and W are properly nested strings. # For example, the", "if(not isinstance(s, str)): return \"Invalid input\" collector = [] for", "worst-case space complexity is O(N) (not counting the storage required", "but \"([)()]\" is not. # Write a function: # int", "\")\". Complexity: # expected worst-case time complexity is O(N); #", "= dict(zip('({[', ')}]')) if(not isinstance(s, str)): return \"Invalid input\" collector", "required for input arguments). def solution(s): sets = dict(zip('({[', ')}]'))", "in(sets.values()): return \"Invalid input\" elif (bracket != collector.pop()): return False", "range [0..200,000]; # string S consists only of the following", "the following characters: \"(\", \"{\", \"[\", \"]\", \"}\" and/or \")\".", "is true: # S is empty; # S has the", "has the form \"VW\" where V and W are properly", "explained above. # Assume that: # N is an integer", "return 0, as explained above. # Assume that: # N", "not. # Write a function: # int solution(char *S); #", "consists only of the following characters: \"(\", \"{\", \"[\", \"]\",", "<gh_stars>1-10 # A string S consisting of N characters is", "function should return 1 and given S = \"([)()]\", the", "is O(N) (not counting the storage required for input arguments).", "the form \"VW\" where V and W are properly nested", "the function should return 1 and given S = \"([)()]\",", "sets): collector.append(sets[bracket]) elif bracket not in(sets.values()): return \"Invalid input\" elif", "solution(s): sets = dict(zip('({[', ')}]')) if(not isinstance(s, str)): return \"Invalid", "# N is an integer within the range [0..200,000]; #", "elif bracket not in(sets.values()): return \"Invalid input\" elif (bracket !=", "not in(sets.values()): return \"Invalid input\" elif (bracket != collector.pop()): return", "\"([)()]\", the function should return 0, as explained above. #", "Complexity: # expected worst-case time complexity is O(N); # expected", "any of the following conditions is true: # S is", "complexity is O(N) (not counting the storage required for input", "# Assume that: # N is an integer within the", "within the range [0..200,000]; # string S consists only of", "a properly nested string; S has the form \"VW\" where", "Write a function: # int solution(char *S); # that, given", "and 0 otherwise. # For example, given S = \"{[()()]}\",", "# string S consists only of the following characters: \"(\",", "1 and given S = \"([)()]\", the function should return", "properly nested string; S has the form \"VW\" where V", "\"]\", \"}\" and/or \")\". Complexity: # expected worst-case time complexity", "A string S consisting of N characters is considered to", "that: # N is an integer within the range [0..200,000];", "considered to be properly nested if any of the following", "= [] for bracket in s: if(bracket in sets): collector.append(sets[bracket])", "the form \"(U)\" or \"[U]\" or \"{U}\" where U is", "')}]')) if(not isinstance(s, str)): return \"Invalid input\" collector = []", "\"Invalid input\" collector = [] for bracket in s: if(bracket", "integer within the range [0..200,000]; # string S consists only", "s: if(bracket in sets): collector.append(sets[bracket]) elif bracket not in(sets.values()): return", "in sets): collector.append(sets[bracket]) elif bracket not in(sets.values()): return \"Invalid input\"", "[0..200,000]; # string S consists only of the following characters:", "is properly nested but \"([)()]\" is not. # Write a", "function: # int solution(char *S); # that, given a string", "W are properly nested strings. # For example, the string", "of N characters, returns 1 if S is properly nested", "bracket not in(sets.values()): return \"Invalid input\" elif (bracket != collector.pop()):", "if S is properly nested and 0 otherwise. # For", "the function should return 0, as explained above. # Assume", "given a string S consisting of N characters, returns 1", "# that, given a string S consisting of N characters,", "expected worst-case space complexity is O(N) (not counting the storage", "def solution(s): sets = dict(zip('({[', ')}]')) if(not isinstance(s, str)): return", "input\" collector = [] for bracket in s: if(bracket in", "V and W are properly nested strings. # For example,", "given S = \"{[()()]}\", the function should return 1 and", "O(N) (not counting the storage required for input arguments). def", "# For example, the string \"{[()()]}\" is properly nested but", "sets = dict(zip('({[', ')}]')) if(not isinstance(s, str)): return \"Invalid input\"", "S = \"([)()]\", the function should return 0, as explained", "For example, given S = \"{[()()]}\", the function should return", "a function: # int solution(char *S); # that, given a", "where U is a properly nested string; S has the", "consisting of N characters, returns 1 if S is properly", "S has the form \"(U)\" or \"[U]\" or \"{U}\" where", "the storage required for input arguments). def solution(s): sets =", "\"(\", \"{\", \"[\", \"]\", \"}\" and/or \")\". Complexity: # expected", "characters, returns 1 if S is properly nested and 0", "of the following conditions is true: # S is empty;", "= \"{[()()]}\", the function should return 1 and given S", "be properly nested if any of the following conditions is", "following conditions is true: # S is empty; # S", "S = \"{[()()]}\", the function should return 1 and given", "are properly nested strings. # For example, the string \"{[()()]}\"", "nested and 0 otherwise. # For example, given S =", "empty; # S has the form \"(U)\" or \"[U]\" or", "return \"Invalid input\" collector = [] for bracket in s:", "# expected worst-case space complexity is O(N) (not counting the", "for bracket in s: if(bracket in sets): collector.append(sets[bracket]) elif bracket", "S consists only of the following characters: \"(\", \"{\", \"[\",", "*S); # that, given a string S consisting of N", "as explained above. # Assume that: # N is an", "\"{\", \"[\", \"]\", \"}\" and/or \")\". Complexity: # expected worst-case", "worst-case time complexity is O(N); # expected worst-case space complexity", "return 1 and given S = \"([)()]\", the function should", "\"[U]\" or \"{U}\" where U is a properly nested string;", "properly nested strings. # For example, the string \"{[()()]}\" is", "U is a properly nested string; S has the form", "counting the storage required for input arguments). def solution(s): sets", "input arguments). def solution(s): sets = dict(zip('({[', ')}]')) if(not isinstance(s,", "\"{U}\" where U is a properly nested string; S has", "otherwise. # For example, given S = \"{[()()]}\", the function", "collector = [] for bracket in s: if(bracket in sets):", "# For example, given S = \"{[()()]}\", the function should", "input\" elif (bracket != collector.pop()): return False return not collector", "elif (bracket != collector.pop()): return False return not collector print(solution(\"()[]{}\"))", "S is properly nested and 0 otherwise. # For example,", "expected worst-case time complexity is O(N); # expected worst-case space", "collector.append(sets[bracket]) elif bracket not in(sets.values()): return \"Invalid input\" elif (bracket", "arguments). def solution(s): sets = dict(zip('({[', ')}]')) if(not isinstance(s, str)):", "is empty; # S has the form \"(U)\" or \"[U]\"", "conditions is true: # S is empty; # S has", "string; S has the form \"VW\" where V and W", "S is empty; # S has the form \"(U)\" or", "that, given a string S consisting of N characters, returns", "0 otherwise. # For example, given S = \"{[()()]}\", the", "and given S = \"([)()]\", the function should return 0,", "is considered to be properly nested if any of the", "0, as explained above. # Assume that: # N is", "space complexity is O(N) (not counting the storage required for", "# int solution(char *S); # that, given a string S", "bracket in s: if(bracket in sets): collector.append(sets[bracket]) elif bracket not", "a string S consisting of N characters, returns 1 if", "strings. # For example, the string \"{[()()]}\" is properly nested", "# S is empty; # S has the form \"(U)\"", "string S consisting of N characters, returns 1 if S", "only of the following characters: \"(\", \"{\", \"[\", \"]\", \"}\"", "where V and W are properly nested strings. # For", "function should return 0, as explained above. # Assume that:", "int solution(char *S); # that, given a string S consisting", "Assume that: # N is an integer within the range", "string S consists only of the following characters: \"(\", \"{\",", "example, the string \"{[()()]}\" is properly nested but \"([)()]\" is", "time complexity is O(N); # expected worst-case space complexity is", "if(bracket in sets): collector.append(sets[bracket]) elif bracket not in(sets.values()): return \"Invalid", "is not. # Write a function: # int solution(char *S);", "if any of the following conditions is true: # S", "# Write a function: # int solution(char *S); # that,", "\"{[()()]}\" is properly nested but \"([)()]\" is not. # Write", "\"}\" and/or \")\". Complexity: # expected worst-case time complexity is", "isinstance(s, str)): return \"Invalid input\" collector = [] for bracket", "properly nested and 0 otherwise. # For example, given S", "following characters: \"(\", \"{\", \"[\", \"]\", \"}\" and/or \")\". Complexity:", "\"(U)\" or \"[U]\" or \"{U}\" where U is a properly", "should return 0, as explained above. # Assume that: #", "an integer within the range [0..200,000]; # string S consists", "str)): return \"Invalid input\" collector = [] for bracket in", "is O(N); # expected worst-case space complexity is O(N) (not", "\"Invalid input\" elif (bracket != collector.pop()): return False return not", "returns 1 if S is properly nested and 0 otherwise.", "[] for bracket in s: if(bracket in sets): collector.append(sets[bracket]) elif", "to be properly nested if any of the following conditions", "has the form \"(U)\" or \"[U]\" or \"{U}\" where U", "string S consisting of N characters is considered to be", "of N characters is considered to be properly nested if", "nested strings. # For example, the string \"{[()()]}\" is properly", "S consisting of N characters, returns 1 if S is", "nested but \"([)()]\" is not. # Write a function: #", "N is an integer within the range [0..200,000]; # string", "characters is considered to be properly nested if any of", "the range [0..200,000]; # string S consists only of the", "is properly nested and 0 otherwise. # For example, given", "or \"{U}\" where U is a properly nested string; S", "is a properly nested string; S has the form \"VW\"", "O(N); # expected worst-case space complexity is O(N) (not counting", "\"([)()]\" is not. # Write a function: # int solution(char", "\"{[()()]}\", the function should return 1 and given S =", "and/or \")\". Complexity: # expected worst-case time complexity is O(N);", "N characters is considered to be properly nested if any", "properly nested if any of the following conditions is true:", "S consisting of N characters is considered to be properly", "form \"VW\" where V and W are properly nested strings.", "is an integer within the range [0..200,000]; # string S", "# A string S consisting of N characters is considered", "string \"{[()()]}\" is properly nested but \"([)()]\" is not. #", "form \"(U)\" or \"[U]\" or \"{U}\" where U is a", "For example, the string \"{[()()]}\" is properly nested but \"([)()]\"", "the string \"{[()()]}\" is properly nested but \"([)()]\" is not.", "the following conditions is true: # S is empty; #", "1 if S is properly nested and 0 otherwise. #", "should return 1 and given S = \"([)()]\", the function", "(not counting the storage required for input arguments). def solution(s):", "storage required for input arguments). def solution(s): sets = dict(zip('({[',", "consisting of N characters is considered to be properly nested", "complexity is O(N); # expected worst-case space complexity is O(N)", "example, given S = \"{[()()]}\", the function should return 1", "in s: if(bracket in sets): collector.append(sets[bracket]) elif bracket not in(sets.values()):", "solution(char *S); # that, given a string S consisting of", "N characters, returns 1 if S is properly nested and", "# expected worst-case time complexity is O(N); # expected worst-case", "# S has the form \"(U)\" or \"[U]\" or \"{U}\"", "nested if any of the following conditions is true: #", "\"VW\" where V and W are properly nested strings. #", "of the following characters: \"(\", \"{\", \"[\", \"]\", \"}\" and/or", "characters: \"(\", \"{\", \"[\", \"]\", \"}\" and/or \")\". Complexity: #", "\"[\", \"]\", \"}\" and/or \")\". Complexity: # expected worst-case time", "for input arguments). def solution(s): sets = dict(zip('({[', ')}]')) if(not", "S has the form \"VW\" where V and W are", "given S = \"([)()]\", the function should return 0, as", "properly nested but \"([)()]\" is not. # Write a function:", "= \"([)()]\", the function should return 0, as explained above.", "or \"[U]\" or \"{U}\" where U is a properly nested", "true: # S is empty; # S has the form", "nested string; S has the form \"VW\" where V and", "dict(zip('({[', ')}]')) if(not isinstance(s, str)): return \"Invalid input\" collector =", "above. # Assume that: # N is an integer within" ]
[ "iter.product(range(-1,2), repeat = 3): if z == y == x", "8) and pos in spielfeld)} def scale_rotate(ob, scale, rot, fr):", "break for zelle in new | dead: if zelle not", "from collections import Counter import itertools as iter feld_von, feld_bis", "dead = spielfeld - spielfeld2 new = spielfeld2 - spielfeld", "- spielfeld spielfeld = spielfeld2 if not new and not", "= 3): o = bpy.data.objects.new(n, m) o.location = (x, y,", "nächsteGeneration(spielfeld): nachb = Counter([p for pos in spielfeld for p", "(i-1)*animate_frame) scale_rotate(ob, 750, 3.141/2, i * animate_frame) else: scale_rotate(ob, 750,", "pos[2]+z def nächsteGeneration(spielfeld): nachb = Counter([p for pos in spielfeld", "x,y,z in iter.product(range(-1,2), repeat = 3): if z == y", "6 or (anz in (5, 6, 7, 8) and pos", "pos[0]+x, pos[1]+y, pos[2]+z def nächsteGeneration(spielfeld): nachb = Counter([p for pos", "anz == 6 or (anz in (5, 6, 7, 8)", "if z == y == x == 0: continue yield", "(x, y, z) cubes[x, y, z] = o bpy.context.collection.objects.link(o) o.select_set(False)", "z) cubes[x, y, z] = o bpy.context.collection.objects.link(o) o.select_set(False) for i", "-3.141/2, (i-1)*animate_frame) scale_rotate(ob, 750, 3.141/2, i * animate_frame) else: scale_rotate(ob,", "bpy.ops.mesh.primitive_cube_add(size=0.001, location=(0, 0, 0)) orig_cube = bpy.context.active_object n = \"cube\"", "rnd.randint(feld_von, feld_bis)) for _ in range(anz)} animate_frame = 8 def", "animate_frame = 8 def nachbarn(pos): for x,y,z in iter.product(range(-1,2), repeat", "return {pos for pos, anz in nachb.items() if anz ==", "= spielfeld2 - spielfeld spielfeld = spielfeld2 if not new", "== 0: continue yield pos[0]+x, pos[1]+y, pos[2]+z def nächsteGeneration(spielfeld): nachb", "for x,y,z in iter.product(range(spielfeld_von,spielfeld_bis), repeat = 3): o = bpy.data.objects.new(n,", "if zelle not in cubes: continue ob = cubes[zelle] if", "o bpy.context.collection.objects.link(o) o.select_set(False) for i in range(200): print(f'Durchlauf No. {i},", "750, 3.141/2, i * animate_frame) else: scale_rotate(ob, 750, 3.141/2, (i-1)", "def nachbarn(pos): for x,y,z in iter.product(range(-1,2), repeat = 3): if", "nachb = Counter([p for pos in spielfeld for p in", "= orig_cube.data.copy() cubes = {} for x,y,z in iter.product(range(spielfeld_von,spielfeld_bis), repeat", "feld_bis = -4, 4 spielfeld_von, spielfeld_bis = feld_von-6, feld_bis+6 anz", "z] = o bpy.context.collection.objects.link(o) o.select_set(False) for i in range(200): print(f'Durchlauf", "scale_rotate(ob, 0.001, -3.141/2, i * animate_frame) if not spielfeld: break", "nachbarn(pos): for x,y,z in iter.product(range(-1,2), repeat = 3): if z", "\"cube\" m = orig_cube.data.copy() cubes = {} for x,y,z in", "spielfeld = {(rnd.randint(feld_von, feld_bis), rnd.randint( feld_von, feld_bis), rnd.randint(feld_von, feld_bis)) for", "spielfeld_bis = feld_von-6, feld_bis+6 anz = int((feld_bis-feld_von)**3*.3) spielfeld = {(rnd.randint(feld_von,", "location=(0, 0, 0)) orig_cube = bpy.context.active_object n = \"cube\" m", "def nächsteGeneration(spielfeld): nachb = Counter([p for pos in spielfeld for", "= cubes[zelle] if zelle in new: scale_rotate(ob, 0.001, -3.141/2, (i-1)*animate_frame)", "i * animate_frame) else: scale_rotate(ob, 750, 3.141/2, (i-1) * animate_frame)", "0.001, -3.141/2, i * animate_frame) if not spielfeld: break bpy.context.scene.frame_current", "in nachb.items() if anz == 6 or (anz in (5,", "import Counter import itertools as iter feld_von, feld_bis = -4,", "(5, 6, 7, 8) and pos in spielfeld)} def scale_rotate(ob,", "bpy import random as rnd from collections import Counter import", "pos, anz in nachb.items() if anz == 6 or (anz", "if zelle in new: scale_rotate(ob, 0.001, -3.141/2, (i-1)*animate_frame) scale_rotate(ob, 750,", "rot) ob.keyframe_insert(data_path='rotation_euler', frame=fr) ob.keyframe_insert(data_path='scale', frame=fr) bpy.ops.mesh.primitive_cube_add(size=0.001, location=(0, 0, 0)) orig_cube", "* animate_frame) else: scale_rotate(ob, 750, 3.141/2, (i-1) * animate_frame) scale_rotate(ob,", "3): o = bpy.data.objects.new(n, m) o.location = (x, y, z)", "frame=fr) ob.keyframe_insert(data_path='scale', frame=fr) bpy.ops.mesh.primitive_cube_add(size=0.001, location=(0, 0, 0)) orig_cube = bpy.context.active_object", "= o bpy.context.collection.objects.link(o) o.select_set(False) for i in range(200): print(f'Durchlauf No.", "for pos in spielfeld for p in nachbarn(pos)]) return {pos", "{pos for pos, anz in nachb.items() if anz == 6", "continue yield pos[0]+x, pos[1]+y, pos[2]+z def nächsteGeneration(spielfeld): nachb = Counter([p", "Anz. Zellen = {len(spielfeld)}') spielfeld2 = nächsteGeneration(spielfeld) dead = spielfeld", "x == 0: continue yield pos[0]+x, pos[1]+y, pos[2]+z def nächsteGeneration(spielfeld):", "spielfeld2 if not new and not dead: break for zelle", "ob = cubes[zelle] if zelle in new: scale_rotate(ob, 0.001, -3.141/2,", "range(anz)} animate_frame = 8 def nachbarn(pos): for x,y,z in iter.product(range(-1,2),", "scale) ob.rotation_euler.rotate_axis(\"Z\", rot) ob.keyframe_insert(data_path='rotation_euler', frame=fr) ob.keyframe_insert(data_path='scale', frame=fr) bpy.ops.mesh.primitive_cube_add(size=0.001, location=(0, 0,", "in range(200): print(f'Durchlauf No. {i}, Anz. Zellen = {len(spielfeld)}') spielfeld2", "= (scale, scale, scale) ob.rotation_euler.rotate_axis(\"Z\", rot) ob.keyframe_insert(data_path='rotation_euler', frame=fr) ob.keyframe_insert(data_path='scale', frame=fr)", "= bpy.data.objects.new(n, m) o.location = (x, y, z) cubes[x, y,", "animate_frame) else: scale_rotate(ob, 750, 3.141/2, (i-1) * animate_frame) scale_rotate(ob, 0.001,", "and pos in spielfeld)} def scale_rotate(ob, scale, rot, fr): ob.scale", "{(rnd.randint(feld_von, feld_bis), rnd.randint( feld_von, feld_bis), rnd.randint(feld_von, feld_bis)) for _ in", "o.location = (x, y, z) cubes[x, y, z] = o", "import itertools as iter feld_von, feld_bis = -4, 4 spielfeld_von,", "itertools as iter feld_von, feld_bis = -4, 4 spielfeld_von, spielfeld_bis", "{} for x,y,z in iter.product(range(spielfeld_von,spielfeld_bis), repeat = 3): o =", "scale_rotate(ob, 750, 3.141/2, i * animate_frame) else: scale_rotate(ob, 750, 3.141/2,", "else: scale_rotate(ob, 750, 3.141/2, (i-1) * animate_frame) scale_rotate(ob, 0.001, -3.141/2,", "spielfeld2 new = spielfeld2 - spielfeld spielfeld = spielfeld2 if", "in new | dead: if zelle not in cubes: continue", "spielfeld spielfeld = spielfeld2 if not new and not dead:", "x,y,z in iter.product(range(spielfeld_von,spielfeld_bis), repeat = 3): o = bpy.data.objects.new(n, m)", "= {len(spielfeld)}') spielfeld2 = nächsteGeneration(spielfeld) dead = spielfeld - spielfeld2", "in iter.product(range(-1,2), repeat = 3): if z == y ==", "scale, rot, fr): ob.scale = (scale, scale, scale) ob.rotation_euler.rotate_axis(\"Z\", rot)", "= nächsteGeneration(spielfeld) dead = spielfeld - spielfeld2 new = spielfeld2", "spielfeld for p in nachbarn(pos)]) return {pos for pos, anz", "= 8 def nachbarn(pos): for x,y,z in iter.product(range(-1,2), repeat =", "Zellen = {len(spielfeld)}') spielfeld2 = nächsteGeneration(spielfeld) dead = spielfeld -", "if not new and not dead: break for zelle in", "bpy.data.objects.new(n, m) o.location = (x, y, z) cubes[x, y, z]", "spielfeld2 = nächsteGeneration(spielfeld) dead = spielfeld - spielfeld2 new =", "= (x, y, z) cubes[x, y, z] = o bpy.context.collection.objects.link(o)", "{len(spielfeld)}') spielfeld2 = nächsteGeneration(spielfeld) dead = spielfeld - spielfeld2 new", "collections import Counter import itertools as iter feld_von, feld_bis =", "repeat = 3): if z == y == x ==", "7, 8) and pos in spielfeld)} def scale_rotate(ob, scale, rot,", "0, 0)) orig_cube = bpy.context.active_object n = \"cube\" m =", "in new: scale_rotate(ob, 0.001, -3.141/2, (i-1)*animate_frame) scale_rotate(ob, 750, 3.141/2, i", "spielfeld = spielfeld2 if not new and not dead: break", "random as rnd from collections import Counter import itertools as", "feld_von-6, feld_bis+6 anz = int((feld_bis-feld_von)**3*.3) spielfeld = {(rnd.randint(feld_von, feld_bis), rnd.randint(", "bpy.context.active_object n = \"cube\" m = orig_cube.data.copy() cubes = {}", "anz = int((feld_bis-feld_von)**3*.3) spielfeld = {(rnd.randint(feld_von, feld_bis), rnd.randint( feld_von, feld_bis),", "spielfeld - spielfeld2 new = spielfeld2 - spielfeld spielfeld =", "as iter feld_von, feld_bis = -4, 4 spielfeld_von, spielfeld_bis =", "anz in nachb.items() if anz == 6 or (anz in", "not dead: break for zelle in new | dead: if", "nächsteGeneration(spielfeld) dead = spielfeld - spielfeld2 new = spielfeld2 -", "scale_rotate(ob, 750, 3.141/2, (i-1) * animate_frame) scale_rotate(ob, 0.001, -3.141/2, i", "4 spielfeld_von, spielfeld_bis = feld_von-6, feld_bis+6 anz = int((feld_bis-feld_von)**3*.3) spielfeld", "rot, fr): ob.scale = (scale, scale, scale) ob.rotation_euler.rotate_axis(\"Z\", rot) ob.keyframe_insert(data_path='rotation_euler',", "in nachbarn(pos)]) return {pos for pos, anz in nachb.items() if", "for x,y,z in iter.product(range(-1,2), repeat = 3): if z ==", "feld_bis), rnd.randint(feld_von, feld_bis)) for _ in range(anz)} animate_frame = 8", "y, z] = o bpy.context.collection.objects.link(o) o.select_set(False) for i in range(200):", "yield pos[0]+x, pos[1]+y, pos[2]+z def nächsteGeneration(spielfeld): nachb = Counter([p for", "feld_bis)) for _ in range(anz)} animate_frame = 8 def nachbarn(pos):", "= -4, 4 spielfeld_von, spielfeld_bis = feld_von-6, feld_bis+6 anz =", "0: continue yield pos[0]+x, pos[1]+y, pos[2]+z def nächsteGeneration(spielfeld): nachb =", "rnd from collections import Counter import itertools as iter feld_von,", "import random as rnd from collections import Counter import itertools", "not new and not dead: break for zelle in new", "cubes[zelle] if zelle in new: scale_rotate(ob, 0.001, -3.141/2, (i-1)*animate_frame) scale_rotate(ob,", "import bpy import random as rnd from collections import Counter", "spielfeld)} def scale_rotate(ob, scale, rot, fr): ob.scale = (scale, scale,", "= bpy.context.active_object n = \"cube\" m = orig_cube.data.copy() cubes =", "animate_frame) scale_rotate(ob, 0.001, -3.141/2, i * animate_frame) if not spielfeld:", "new and not dead: break for zelle in new |", "for _ in range(anz)} animate_frame = 8 def nachbarn(pos): for", "bpy.context.collection.objects.link(o) o.select_set(False) for i in range(200): print(f'Durchlauf No. {i}, Anz.", "range(200): print(f'Durchlauf No. {i}, Anz. Zellen = {len(spielfeld)}') spielfeld2 =", "== y == x == 0: continue yield pos[0]+x, pos[1]+y,", "= spielfeld - spielfeld2 new = spielfeld2 - spielfeld spielfeld", "-4, 4 spielfeld_von, spielfeld_bis = feld_von-6, feld_bis+6 anz = int((feld_bis-feld_von)**3*.3)", "pos in spielfeld for p in nachbarn(pos)]) return {pos for", "in range(anz)} animate_frame = 8 def nachbarn(pos): for x,y,z in", "i in range(200): print(f'Durchlauf No. {i}, Anz. Zellen = {len(spielfeld)}')", "o = bpy.data.objects.new(n, m) o.location = (x, y, z) cubes[x,", "dead: break for zelle in new | dead: if zelle", "print(f'Durchlauf No. {i}, Anz. Zellen = {len(spielfeld)}') spielfeld2 = nächsteGeneration(spielfeld)", "for p in nachbarn(pos)]) return {pos for pos, anz in", "zelle in new | dead: if zelle not in cubes:", "= {} for x,y,z in iter.product(range(spielfeld_von,spielfeld_bis), repeat = 3): o", "or (anz in (5, 6, 7, 8) and pos in", "ob.keyframe_insert(data_path='scale', frame=fr) bpy.ops.mesh.primitive_cube_add(size=0.001, location=(0, 0, 0)) orig_cube = bpy.context.active_object n", "as rnd from collections import Counter import itertools as iter", "y == x == 0: continue yield pos[0]+x, pos[1]+y, pos[2]+z", "int((feld_bis-feld_von)**3*.3) spielfeld = {(rnd.randint(feld_von, feld_bis), rnd.randint( feld_von, feld_bis), rnd.randint(feld_von, feld_bis))", "ob.rotation_euler.rotate_axis(\"Z\", rot) ob.keyframe_insert(data_path='rotation_euler', frame=fr) ob.keyframe_insert(data_path='scale', frame=fr) bpy.ops.mesh.primitive_cube_add(size=0.001, location=(0, 0, 0))", "ob.scale = (scale, scale, scale) ob.rotation_euler.rotate_axis(\"Z\", rot) ob.keyframe_insert(data_path='rotation_euler', frame=fr) ob.keyframe_insert(data_path='scale',", "{i}, Anz. Zellen = {len(spielfeld)}') spielfeld2 = nächsteGeneration(spielfeld) dead =", "orig_cube.data.copy() cubes = {} for x,y,z in iter.product(range(spielfeld_von,spielfeld_bis), repeat =", "cubes: continue ob = cubes[zelle] if zelle in new: scale_rotate(ob,", "== x == 0: continue yield pos[0]+x, pos[1]+y, pos[2]+z def", "cubes = {} for x,y,z in iter.product(range(spielfeld_von,spielfeld_bis), repeat = 3):", "feld_bis+6 anz = int((feld_bis-feld_von)**3*.3) spielfeld = {(rnd.randint(feld_von, feld_bis), rnd.randint( feld_von,", "scale, scale) ob.rotation_euler.rotate_axis(\"Z\", rot) ob.keyframe_insert(data_path='rotation_euler', frame=fr) ob.keyframe_insert(data_path='scale', frame=fr) bpy.ops.mesh.primitive_cube_add(size=0.001, location=(0,", "repeat = 3): o = bpy.data.objects.new(n, m) o.location = (x,", "continue ob = cubes[zelle] if zelle in new: scale_rotate(ob, 0.001,", "o.select_set(False) for i in range(200): print(f'Durchlauf No. {i}, Anz. Zellen", "in spielfeld for p in nachbarn(pos)]) return {pos for pos,", "spielfeld2 - spielfeld spielfeld = spielfeld2 if not new and", "= spielfeld2 if not new and not dead: break for", "feld_von, feld_bis = -4, 4 spielfeld_von, spielfeld_bis = feld_von-6, feld_bis+6", "spielfeld_von, spielfeld_bis = feld_von-6, feld_bis+6 anz = int((feld_bis-feld_von)**3*.3) spielfeld =", "pos[1]+y, pos[2]+z def nächsteGeneration(spielfeld): nachb = Counter([p for pos in", "== 6 or (anz in (5, 6, 7, 8) and", "and not dead: break for zelle in new | dead:", "3.141/2, i * animate_frame) else: scale_rotate(ob, 750, 3.141/2, (i-1) *", "iter.product(range(spielfeld_von,spielfeld_bis), repeat = 3): o = bpy.data.objects.new(n, m) o.location =", "feld_von, feld_bis), rnd.randint(feld_von, feld_bis)) for _ in range(anz)} animate_frame =", "not in cubes: continue ob = cubes[zelle] if zelle in", "| dead: if zelle not in cubes: continue ob =", "= 3): if z == y == x == 0:", "frame=fr) bpy.ops.mesh.primitive_cube_add(size=0.001, location=(0, 0, 0)) orig_cube = bpy.context.active_object n =", "cubes[x, y, z] = o bpy.context.collection.objects.link(o) o.select_set(False) for i in", "_ in range(anz)} animate_frame = 8 def nachbarn(pos): for x,y,z", "for pos, anz in nachb.items() if anz == 6 or", "750, 3.141/2, (i-1) * animate_frame) scale_rotate(ob, 0.001, -3.141/2, i *", "new | dead: if zelle not in cubes: continue ob", "new = spielfeld2 - spielfeld spielfeld = spielfeld2 if not", "if anz == 6 or (anz in (5, 6, 7,", "ob.keyframe_insert(data_path='rotation_euler', frame=fr) ob.keyframe_insert(data_path='scale', frame=fr) bpy.ops.mesh.primitive_cube_add(size=0.001, location=(0, 0, 0)) orig_cube =", "def scale_rotate(ob, scale, rot, fr): ob.scale = (scale, scale, scale)", "m) o.location = (x, y, z) cubes[x, y, z] =", "(scale, scale, scale) ob.rotation_euler.rotate_axis(\"Z\", rot) ob.keyframe_insert(data_path='rotation_euler', frame=fr) ob.keyframe_insert(data_path='scale', frame=fr) bpy.ops.mesh.primitive_cube_add(size=0.001,", "= \"cube\" m = orig_cube.data.copy() cubes = {} for x,y,z", "feld_bis), rnd.randint( feld_von, feld_bis), rnd.randint(feld_von, feld_bis)) for _ in range(anz)}", "pos in spielfeld)} def scale_rotate(ob, scale, rot, fr): ob.scale =", "for i in range(200): print(f'Durchlauf No. {i}, Anz. Zellen =", "iter feld_von, feld_bis = -4, 4 spielfeld_von, spielfeld_bis = feld_von-6,", "nachbarn(pos)]) return {pos for pos, anz in nachb.items() if anz", "m = orig_cube.data.copy() cubes = {} for x,y,z in iter.product(range(spielfeld_von,spielfeld_bis),", "= Counter([p for pos in spielfeld for p in nachbarn(pos)])", "dead: if zelle not in cubes: continue ob = cubes[zelle]", "z == y == x == 0: continue yield pos[0]+x,", "scale_rotate(ob, scale, rot, fr): ob.scale = (scale, scale, scale) ob.rotation_euler.rotate_axis(\"Z\",", "3): if z == y == x == 0: continue", "scale_rotate(ob, 0.001, -3.141/2, (i-1)*animate_frame) scale_rotate(ob, 750, 3.141/2, i * animate_frame)", "= {(rnd.randint(feld_von, feld_bis), rnd.randint( feld_von, feld_bis), rnd.randint(feld_von, feld_bis)) for _", "in iter.product(range(spielfeld_von,spielfeld_bis), repeat = 3): o = bpy.data.objects.new(n, m) o.location", "new: scale_rotate(ob, 0.001, -3.141/2, (i-1)*animate_frame) scale_rotate(ob, 750, 3.141/2, i *", "0)) orig_cube = bpy.context.active_object n = \"cube\" m = orig_cube.data.copy()", "zelle in new: scale_rotate(ob, 0.001, -3.141/2, (i-1)*animate_frame) scale_rotate(ob, 750, 3.141/2,", "* animate_frame) scale_rotate(ob, 0.001, -3.141/2, i * animate_frame) if not", "Counter([p for pos in spielfeld for p in nachbarn(pos)]) return", "fr): ob.scale = (scale, scale, scale) ob.rotation_euler.rotate_axis(\"Z\", rot) ob.keyframe_insert(data_path='rotation_euler', frame=fr)", "= int((feld_bis-feld_von)**3*.3) spielfeld = {(rnd.randint(feld_von, feld_bis), rnd.randint( feld_von, feld_bis), rnd.randint(feld_von,", "6, 7, 8) and pos in spielfeld)} def scale_rotate(ob, scale,", "rnd.randint( feld_von, feld_bis), rnd.randint(feld_von, feld_bis)) for _ in range(anz)} animate_frame", "(i-1) * animate_frame) scale_rotate(ob, 0.001, -3.141/2, i * animate_frame) if", "p in nachbarn(pos)]) return {pos for pos, anz in nachb.items()", "8 def nachbarn(pos): for x,y,z in iter.product(range(-1,2), repeat = 3):", "for zelle in new | dead: if zelle not in", "in cubes: continue ob = cubes[zelle] if zelle in new:", "3.141/2, (i-1) * animate_frame) scale_rotate(ob, 0.001, -3.141/2, i * animate_frame)", "i * animate_frame) if not spielfeld: break bpy.context.scene.frame_current = 1", "0.001, -3.141/2, (i-1)*animate_frame) scale_rotate(ob, 750, 3.141/2, i * animate_frame) else:", "in (5, 6, 7, 8) and pos in spielfeld)} def", "orig_cube = bpy.context.active_object n = \"cube\" m = orig_cube.data.copy() cubes", "No. {i}, Anz. Zellen = {len(spielfeld)}') spielfeld2 = nächsteGeneration(spielfeld) dead", "-3.141/2, i * animate_frame) if not spielfeld: break bpy.context.scene.frame_current =", "Counter import itertools as iter feld_von, feld_bis = -4, 4", "n = \"cube\" m = orig_cube.data.copy() cubes = {} for", "= feld_von-6, feld_bis+6 anz = int((feld_bis-feld_von)**3*.3) spielfeld = {(rnd.randint(feld_von, feld_bis),", "zelle not in cubes: continue ob = cubes[zelle] if zelle", "nachb.items() if anz == 6 or (anz in (5, 6,", "(anz in (5, 6, 7, 8) and pos in spielfeld)}", "in spielfeld)} def scale_rotate(ob, scale, rot, fr): ob.scale = (scale,", "- spielfeld2 new = spielfeld2 - spielfeld spielfeld = spielfeld2", "y, z) cubes[x, y, z] = o bpy.context.collection.objects.link(o) o.select_set(False) for" ]
[ "example. If there are less PV systems available than requested,", "as an xr_batch_processor so it can run after SelectPVSystemsNearCenterOfImage. \"\"\"", "PV systems available than requested, then randomly sample with duplicates", "systems than requested PV systems. replace = len(all_indicies) < self.requested_num_pv_systems", "import PV from power_perceiver.load_prepared_batches.data_sources.prepared_data_source import XarrayBatch @dataclass class ReduceNumPVSystems: \"\"\"Reduce", "np.random.default_rng() # Seeded by seed_rngs worker_init_function def __call__(self, xr_batch: XarrayBatch)", "XarrayBatch: pv_batch = xr_batch[PV] num_examples = len(pv_batch.example) selection = np.zeros(shape=(num_examples,", "by seed_rngs worker_init_function def __call__(self, xr_batch: XarrayBatch) -> XarrayBatch: pv_batch", "be chosen multiple times for this example if there are", "times for this example if there are # less available", "SelectPVSystemsNearCenterOfImage. \"\"\" requested_num_pv_systems: int def __post_init__(self): self.rng = np.random.default_rng() #", "= np.random.default_rng() # Seeded by seed_rngs worker_init_function def __call__(self, xr_batch:", "chosen_indicies = self.rng.choice( all_indicies, size=self.requested_num_pv_systems, replace=replace ) selection[example_i] = chosen_indicies", "there are less PV systems available than requested, then randomly", "xr from power_perceiver.load_prepared_batches.data_sources import PV from power_perceiver.load_prepared_batches.data_sources.prepared_data_source import XarrayBatch @dataclass", "example to `requested_num_pv_systems`. Randomly select PV systems for each example.", "system to be chosen multiple times for this example if", ") selection[example_i] = chosen_indicies selection = xr.DataArray(selection, dims=(\"example\", \"pv_system\")) pv_batch", "PV systems for each example. If there are less PV", "from power_perceiver.load_prepared_batches.data_sources.prepared_data_source import XarrayBatch @dataclass class ReduceNumPVSystems: \"\"\"Reduce the number", "= len(pv_batch.example) selection = np.zeros(shape=(num_examples, self.requested_num_pv_systems), dtype=np.int32) for example_i in", "pv_mask_for_example = pv_batch.pv_mask.isel(example=example_i).values all_indicies = np.nonzero(pv_mask_for_example)[0] # Only allow a", "than requested, then randomly sample with duplicates allowed. This is", "systems. replace = len(all_indicies) < self.requested_num_pv_systems chosen_indicies = self.rng.choice( all_indicies,", "dataclass import numpy as np import xarray as xr from", "replace=replace ) selection[example_i] = chosen_indicies selection = xr.DataArray(selection, dims=(\"example\", \"pv_system\"))", "\"\"\" requested_num_pv_systems: int def __post_init__(self): self.rng = np.random.default_rng() # Seeded", "Randomly select PV systems for each example. If there are", "than requested PV systems. replace = len(all_indicies) < self.requested_num_pv_systems chosen_indicies", "example_i in range(num_examples): pv_mask_for_example = pv_batch.pv_mask.isel(example=example_i).values all_indicies = np.nonzero(pv_mask_for_example)[0] #", "for this example if there are # less available PV", "run after SelectPVSystemsNearCenterOfImage. \"\"\" requested_num_pv_systems: int def __post_init__(self): self.rng =", "__post_init__(self): self.rng = np.random.default_rng() # Seeded by seed_rngs worker_init_function def", "less available PV systems than requested PV systems. replace =", "number of PV systems per example to `requested_num_pv_systems`. Randomly select", "xarray as xr from power_perceiver.load_prepared_batches.data_sources import PV from power_perceiver.load_prepared_batches.data_sources.prepared_data_source import", "available PV systems than requested PV systems. replace = len(all_indicies)", "it can run after SelectPVSystemsNearCenterOfImage. \"\"\" requested_num_pv_systems: int def __post_init__(self):", "systems for each example. If there are less PV systems", "PV from power_perceiver.load_prepared_batches.data_sources.prepared_data_source import XarrayBatch @dataclass class ReduceNumPVSystems: \"\"\"Reduce the", "selection = xr.DataArray(selection, dims=(\"example\", \"pv_system\")) pv_batch = pv_batch.isel(pv_system=selection) xr_batch[PV] =", "requested, then randomly sample with duplicates allowed. This is implemented", "from dataclasses import dataclass import numpy as np import xarray", "are # less available PV systems than requested PV systems.", "randomly sample with duplicates allowed. This is implemented as an", "chosen multiple times for this example if there are #", "dataclasses import dataclass import numpy as np import xarray as", "self.requested_num_pv_systems), dtype=np.int32) for example_i in range(num_examples): pv_mask_for_example = pv_batch.pv_mask.isel(example=example_i).values all_indicies", "allow a PV system to be chosen multiple times for", "= len(all_indicies) < self.requested_num_pv_systems chosen_indicies = self.rng.choice( all_indicies, size=self.requested_num_pv_systems, replace=replace", "dtype=np.int32) for example_i in range(num_examples): pv_mask_for_example = pv_batch.pv_mask.isel(example=example_i).values all_indicies =", "for each example. If there are less PV systems available", "= chosen_indicies selection = xr.DataArray(selection, dims=(\"example\", \"pv_system\")) pv_batch = pv_batch.isel(pv_system=selection)", "numpy as np import xarray as xr from power_perceiver.load_prepared_batches.data_sources import", "duplicates allowed. This is implemented as an xr_batch_processor so it", "= xr.DataArray(selection, dims=(\"example\", \"pv_system\")) pv_batch = pv_batch.isel(pv_system=selection) xr_batch[PV] = pv_batch", "xr_batch_processor so it can run after SelectPVSystemsNearCenterOfImage. \"\"\" requested_num_pv_systems: int", "per example to `requested_num_pv_systems`. Randomly select PV systems for each", "np.nonzero(pv_mask_for_example)[0] # Only allow a PV system to be chosen", "all_indicies = np.nonzero(pv_mask_for_example)[0] # Only allow a PV system to", "int def __post_init__(self): self.rng = np.random.default_rng() # Seeded by seed_rngs", "XarrayBatch) -> XarrayBatch: pv_batch = xr_batch[PV] num_examples = len(pv_batch.example) selection", "selection = np.zeros(shape=(num_examples, self.requested_num_pv_systems), dtype=np.int32) for example_i in range(num_examples): pv_mask_for_example", "PV systems. replace = len(all_indicies) < self.requested_num_pv_systems chosen_indicies = self.rng.choice(", "xr.DataArray(selection, dims=(\"example\", \"pv_system\")) pv_batch = pv_batch.isel(pv_system=selection) xr_batch[PV] = pv_batch return", "power_perceiver.load_prepared_batches.data_sources.prepared_data_source import XarrayBatch @dataclass class ReduceNumPVSystems: \"\"\"Reduce the number of", "requested_num_pv_systems: int def __post_init__(self): self.rng = np.random.default_rng() # Seeded by", "xr_batch[PV] num_examples = len(pv_batch.example) selection = np.zeros(shape=(num_examples, self.requested_num_pv_systems), dtype=np.int32) for", "systems per example to `requested_num_pv_systems`. Randomly select PV systems for", "PV systems than requested PV systems. replace = len(all_indicies) <", "there are # less available PV systems than requested PV", "less PV systems available than requested, then randomly sample with", "to `requested_num_pv_systems`. Randomly select PV systems for each example. If", "all_indicies, size=self.requested_num_pv_systems, replace=replace ) selection[example_i] = chosen_indicies selection = xr.DataArray(selection,", "class ReduceNumPVSystems: \"\"\"Reduce the number of PV systems per example", "worker_init_function def __call__(self, xr_batch: XarrayBatch) -> XarrayBatch: pv_batch = xr_batch[PV]", "from power_perceiver.load_prepared_batches.data_sources import PV from power_perceiver.load_prepared_batches.data_sources.prepared_data_source import XarrayBatch @dataclass class", "sample with duplicates allowed. This is implemented as an xr_batch_processor", "-> XarrayBatch: pv_batch = xr_batch[PV] num_examples = len(pv_batch.example) selection =", "Seeded by seed_rngs worker_init_function def __call__(self, xr_batch: XarrayBatch) -> XarrayBatch:", "If there are less PV systems available than requested, then", "in range(num_examples): pv_mask_for_example = pv_batch.pv_mask.isel(example=example_i).values all_indicies = np.nonzero(pv_mask_for_example)[0] # Only", "num_examples = len(pv_batch.example) selection = np.zeros(shape=(num_examples, self.requested_num_pv_systems), dtype=np.int32) for example_i", "xr_batch: XarrayBatch) -> XarrayBatch: pv_batch = xr_batch[PV] num_examples = len(pv_batch.example)", "__call__(self, xr_batch: XarrayBatch) -> XarrayBatch: pv_batch = xr_batch[PV] num_examples =", "# less available PV systems than requested PV systems. replace", "dims=(\"example\", \"pv_system\")) pv_batch = pv_batch.isel(pv_system=selection) xr_batch[PV] = pv_batch return xr_batch", "def __call__(self, xr_batch: XarrayBatch) -> XarrayBatch: pv_batch = xr_batch[PV] num_examples", "def __post_init__(self): self.rng = np.random.default_rng() # Seeded by seed_rngs worker_init_function", "multiple times for this example if there are # less", "range(num_examples): pv_mask_for_example = pv_batch.pv_mask.isel(example=example_i).values all_indicies = np.nonzero(pv_mask_for_example)[0] # Only allow", "< self.requested_num_pv_systems chosen_indicies = self.rng.choice( all_indicies, size=self.requested_num_pv_systems, replace=replace ) selection[example_i]", "power_perceiver.load_prepared_batches.data_sources import PV from power_perceiver.load_prepared_batches.data_sources.prepared_data_source import XarrayBatch @dataclass class ReduceNumPVSystems:", "example if there are # less available PV systems than", "import xarray as xr from power_perceiver.load_prepared_batches.data_sources import PV from power_perceiver.load_prepared_batches.data_sources.prepared_data_source", "# Only allow a PV system to be chosen multiple", "= self.rng.choice( all_indicies, size=self.requested_num_pv_systems, replace=replace ) selection[example_i] = chosen_indicies selection", "this example if there are # less available PV systems", "seed_rngs worker_init_function def __call__(self, xr_batch: XarrayBatch) -> XarrayBatch: pv_batch =", "Only allow a PV system to be chosen multiple times", "a PV system to be chosen multiple times for this", "PV system to be chosen multiple times for this example", "implemented as an xr_batch_processor so it can run after SelectPVSystemsNearCenterOfImage.", "requested PV systems. replace = len(all_indicies) < self.requested_num_pv_systems chosen_indicies =", "selection[example_i] = chosen_indicies selection = xr.DataArray(selection, dims=(\"example\", \"pv_system\")) pv_batch =", "can run after SelectPVSystemsNearCenterOfImage. \"\"\" requested_num_pv_systems: int def __post_init__(self): self.rng", "self.rng = np.random.default_rng() # Seeded by seed_rngs worker_init_function def __call__(self,", "pv_batch.pv_mask.isel(example=example_i).values all_indicies = np.nonzero(pv_mask_for_example)[0] # Only allow a PV system", "are less PV systems available than requested, then randomly sample", "import XarrayBatch @dataclass class ReduceNumPVSystems: \"\"\"Reduce the number of PV", "to be chosen multiple times for this example if there", "available than requested, then randomly sample with duplicates allowed. This", "size=self.requested_num_pv_systems, replace=replace ) selection[example_i] = chosen_indicies selection = xr.DataArray(selection, dims=(\"example\",", "an xr_batch_processor so it can run after SelectPVSystemsNearCenterOfImage. \"\"\" requested_num_pv_systems:", "= np.zeros(shape=(num_examples, self.requested_num_pv_systems), dtype=np.int32) for example_i in range(num_examples): pv_mask_for_example =", "import dataclass import numpy as np import xarray as xr", "the number of PV systems per example to `requested_num_pv_systems`. Randomly", "after SelectPVSystemsNearCenterOfImage. \"\"\" requested_num_pv_systems: int def __post_init__(self): self.rng = np.random.default_rng()", "= xr_batch[PV] num_examples = len(pv_batch.example) selection = np.zeros(shape=(num_examples, self.requested_num_pv_systems), dtype=np.int32)", "chosen_indicies selection = xr.DataArray(selection, dims=(\"example\", \"pv_system\")) pv_batch = pv_batch.isel(pv_system=selection) xr_batch[PV]", "then randomly sample with duplicates allowed. This is implemented as", "= pv_batch.pv_mask.isel(example=example_i).values all_indicies = np.nonzero(pv_mask_for_example)[0] # Only allow a PV", "so it can run after SelectPVSystemsNearCenterOfImage. \"\"\" requested_num_pv_systems: int def", "# Seeded by seed_rngs worker_init_function def __call__(self, xr_batch: XarrayBatch) ->", "as xr from power_perceiver.load_prepared_batches.data_sources import PV from power_perceiver.load_prepared_batches.data_sources.prepared_data_source import XarrayBatch", "with duplicates allowed. This is implemented as an xr_batch_processor so", "= np.nonzero(pv_mask_for_example)[0] # Only allow a PV system to be", "PV systems per example to `requested_num_pv_systems`. Randomly select PV systems", "pv_batch = xr_batch[PV] num_examples = len(pv_batch.example) selection = np.zeros(shape=(num_examples, self.requested_num_pv_systems),", "is implemented as an xr_batch_processor so it can run after", "each example. If there are less PV systems available than", "np import xarray as xr from power_perceiver.load_prepared_batches.data_sources import PV from", "`requested_num_pv_systems`. Randomly select PV systems for each example. If there", "for example_i in range(num_examples): pv_mask_for_example = pv_batch.pv_mask.isel(example=example_i).values all_indicies = np.nonzero(pv_mask_for_example)[0]", "@dataclass class ReduceNumPVSystems: \"\"\"Reduce the number of PV systems per", "\"\"\"Reduce the number of PV systems per example to `requested_num_pv_systems`.", "len(pv_batch.example) selection = np.zeros(shape=(num_examples, self.requested_num_pv_systems), dtype=np.int32) for example_i in range(num_examples):", "if there are # less available PV systems than requested", "systems available than requested, then randomly sample with duplicates allowed.", "ReduceNumPVSystems: \"\"\"Reduce the number of PV systems per example to", "len(all_indicies) < self.requested_num_pv_systems chosen_indicies = self.rng.choice( all_indicies, size=self.requested_num_pv_systems, replace=replace )", "of PV systems per example to `requested_num_pv_systems`. Randomly select PV", "select PV systems for each example. If there are less", "as np import xarray as xr from power_perceiver.load_prepared_batches.data_sources import PV", "self.rng.choice( all_indicies, size=self.requested_num_pv_systems, replace=replace ) selection[example_i] = chosen_indicies selection =", "This is implemented as an xr_batch_processor so it can run", "replace = len(all_indicies) < self.requested_num_pv_systems chosen_indicies = self.rng.choice( all_indicies, size=self.requested_num_pv_systems,", "np.zeros(shape=(num_examples, self.requested_num_pv_systems), dtype=np.int32) for example_i in range(num_examples): pv_mask_for_example = pv_batch.pv_mask.isel(example=example_i).values", "self.requested_num_pv_systems chosen_indicies = self.rng.choice( all_indicies, size=self.requested_num_pv_systems, replace=replace ) selection[example_i] =", "allowed. This is implemented as an xr_batch_processor so it can", "import numpy as np import xarray as xr from power_perceiver.load_prepared_batches.data_sources", "XarrayBatch @dataclass class ReduceNumPVSystems: \"\"\"Reduce the number of PV systems" ]
[ "#encoding=utf8 # 按天生成文件 import logging import time from logging.handlers import", "\"timed_test.log\" logger = logging.getLogger(\"YouLoggerName\") logger.setLevel(logging.INFO) handler = TimedRotatingFileHandler(logFilePath, when=\"d\", interval=1,", "when=\"d\", interval=1, backupCount=7) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s", "import TimedRotatingFileHandler #---------------------------------------------------------------------- if __name__ == \"__main__\": logFilePath = \"timed_test.log\"", "range(6): logger.info(\"This is a info!\") logger.debug(\"This is a debug!\") #", "for i in range(6): logger.info(\"This is a info!\") logger.debug(\"This is", "按天生成文件 import logging import time from logging.handlers import TimedRotatingFileHandler #----------------------------------------------------------------------", "%(levelname)s - %(message)s') handler.setFormatter(formatter) handler.setLevel(logging.INFO) logger.addHandler(handler) for i in range(6):", "__name__ == \"__main__\": logFilePath = \"timed_test.log\" logger = logging.getLogger(\"YouLoggerName\") logger.setLevel(logging.INFO)", "# 按天生成文件 import logging import time from logging.handlers import TimedRotatingFileHandler", "formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter)", "%(message)s') handler.setFormatter(formatter) handler.setLevel(logging.INFO) logger.addHandler(handler) for i in range(6): logger.info(\"This is", "- %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) handler.setLevel(logging.INFO) logger.addHandler(handler) for", "handler.setFormatter(formatter) handler.setLevel(logging.INFO) logger.addHandler(handler) for i in range(6): logger.info(\"This is a", "logging.handlers import TimedRotatingFileHandler #---------------------------------------------------------------------- if __name__ == \"__main__\": logFilePath =", "%(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) handler.setLevel(logging.INFO) logger.addHandler(handler) for i", "from logging.handlers import TimedRotatingFileHandler #---------------------------------------------------------------------- if __name__ == \"__main__\": logFilePath", "backupCount=7) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')", "time from logging.handlers import TimedRotatingFileHandler #---------------------------------------------------------------------- if __name__ == \"__main__\":", "logging import time from logging.handlers import TimedRotatingFileHandler #---------------------------------------------------------------------- if __name__", "handler.setLevel(logging.INFO) logger.addHandler(handler) for i in range(6): logger.info(\"This is a info!\")", "logger = logging.getLogger(\"YouLoggerName\") logger.setLevel(logging.INFO) handler = TimedRotatingFileHandler(logFilePath, when=\"d\", interval=1, backupCount=7)", "interval=1, backupCount=7) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s -", "in range(6): logger.info(\"This is a info!\") logger.debug(\"This is a debug!\")", "import logging import time from logging.handlers import TimedRotatingFileHandler #---------------------------------------------------------------------- if", "= \"timed_test.log\" logger = logging.getLogger(\"YouLoggerName\") logger.setLevel(logging.INFO) handler = TimedRotatingFileHandler(logFilePath, when=\"d\",", "- %(levelname)s - %(message)s') handler.setFormatter(formatter) handler.setLevel(logging.INFO) logger.addHandler(handler) for i in", "logger.setLevel(logging.INFO) handler = TimedRotatingFileHandler(logFilePath, when=\"d\", interval=1, backupCount=7) formatter = logging.Formatter('%(asctime)s", "TimedRotatingFileHandler(logFilePath, when=\"d\", interval=1, backupCount=7) formatter = logging.Formatter('%(asctime)s - %(name)s -", "= logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) handler.setLevel(logging.INFO)", "i in range(6): logger.info(\"This is a info!\") logger.debug(\"This is a", "logger.addHandler(handler) for i in range(6): logger.info(\"This is a info!\") logger.debug(\"This", "logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) handler.setLevel(logging.INFO) logger.addHandler(handler)", "TimedRotatingFileHandler #---------------------------------------------------------------------- if __name__ == \"__main__\": logFilePath = \"timed_test.log\" logger", "\"__main__\": logFilePath = \"timed_test.log\" logger = logging.getLogger(\"YouLoggerName\") logger.setLevel(logging.INFO) handler =", "handler = TimedRotatingFileHandler(logFilePath, when=\"d\", interval=1, backupCount=7) formatter = logging.Formatter('%(asctime)s -", "= logging.getLogger(\"YouLoggerName\") logger.setLevel(logging.INFO) handler = TimedRotatingFileHandler(logFilePath, when=\"d\", interval=1, backupCount=7) formatter", "logFilePath = \"timed_test.log\" logger = logging.getLogger(\"YouLoggerName\") logger.setLevel(logging.INFO) handler = TimedRotatingFileHandler(logFilePath,", "import time from logging.handlers import TimedRotatingFileHandler #---------------------------------------------------------------------- if __name__ ==", "= TimedRotatingFileHandler(logFilePath, when=\"d\", interval=1, backupCount=7) formatter = logging.Formatter('%(asctime)s - %(name)s", "== \"__main__\": logFilePath = \"timed_test.log\" logger = logging.getLogger(\"YouLoggerName\") logger.setLevel(logging.INFO) handler", "logging.getLogger(\"YouLoggerName\") logger.setLevel(logging.INFO) handler = TimedRotatingFileHandler(logFilePath, when=\"d\", interval=1, backupCount=7) formatter =", "if __name__ == \"__main__\": logFilePath = \"timed_test.log\" logger = logging.getLogger(\"YouLoggerName\")", "- %(message)s') handler.setFormatter(formatter) handler.setLevel(logging.INFO) logger.addHandler(handler) for i in range(6): logger.info(\"This", "logger.info(\"This is a info!\") logger.debug(\"This is a debug!\") # time.sleep(61)", "#---------------------------------------------------------------------- if __name__ == \"__main__\": logFilePath = \"timed_test.log\" logger =" ]
[ "this class usable as a # dictionary key: def __hash__(self):", "know about his/her order\") PersonAction.angry = PersonAction(\"person is pissed off\")", "action def __str__(self): return self.action def __eq__(self, other): return eq(self.action,", "hash(self.action) # Static fields; an enumeration of instances: PersonAction.compliment =", "when __cmp__ or __eq__ is defined # in order to", "def __eq__(self, other): return eq(self.action, other.action) # Necessary when __cmp__", "eq(self.action, other.action) # Necessary when __cmp__ or __eq__ is defined", "def __hash__(self): return hash(self.action) # Static fields; an enumeration of", "of instances: PersonAction.compliment = PersonAction(\"person compliments\") PersonAction.informing = PersonAction(\"person gives", "order\") PersonAction.query = PersonAction(\"person wants to know about his/her order\")", "self.action = action def __str__(self): return self.action def __eq__(self, other):", "# Necessary when __cmp__ or __eq__ is defined # in", "PersonAction.compliment = PersonAction(\"person compliments\") PersonAction.informing = PersonAction(\"person gives information about", "instances: PersonAction.compliment = PersonAction(\"person compliments\") PersonAction.informing = PersonAction(\"person gives information", "operator import eq class PersonAction: def __init__(self, action): self.action =", "an enumeration of instances: PersonAction.compliment = PersonAction(\"person compliments\") PersonAction.informing =", "PersonAction.informing = PersonAction(\"person gives information about the service order\") PersonAction.query", "class usable as a # dictionary key: def __hash__(self): return", "Necessary when __cmp__ or __eq__ is defined # in order", "is defined # in order to make this class usable", "service order\") PersonAction.query = PersonAction(\"person wants to know about his/her", "wants to know about his/her order\") PersonAction.angry = PersonAction(\"person is", "a # dictionary key: def __hash__(self): return hash(self.action) # Static", "__eq__(self, other): return eq(self.action, other.action) # Necessary when __cmp__ or", "as a # dictionary key: def __hash__(self): return hash(self.action) #", "return hash(self.action) # Static fields; an enumeration of instances: PersonAction.compliment", "action): self.action = action def __str__(self): return self.action def __eq__(self,", "or __eq__ is defined # in order to make this", "make this class usable as a # dictionary key: def", "to know about his/her order\") PersonAction.angry = PersonAction(\"person is pissed", "= PersonAction(\"person compliments\") PersonAction.informing = PersonAction(\"person gives information about the", "eq class PersonAction: def __init__(self, action): self.action = action def", "import eq class PersonAction: def __init__(self, action): self.action = action", "return eq(self.action, other.action) # Necessary when __cmp__ or __eq__ is", "other.action) # Necessary when __cmp__ or __eq__ is defined #", "fields; an enumeration of instances: PersonAction.compliment = PersonAction(\"person compliments\") PersonAction.informing", "# in order to make this class usable as a", "= PersonAction(\"person gives information about the service order\") PersonAction.query =", "information about the service order\") PersonAction.query = PersonAction(\"person wants to", "# Static fields; an enumeration of instances: PersonAction.compliment = PersonAction(\"person", "compliments\") PersonAction.informing = PersonAction(\"person gives information about the service order\")", "return self.action def __eq__(self, other): return eq(self.action, other.action) # Necessary", "gives information about the service order\") PersonAction.query = PersonAction(\"person wants", "PersonAction(\"person gives information about the service order\") PersonAction.query = PersonAction(\"person", "enumeration of instances: PersonAction.compliment = PersonAction(\"person compliments\") PersonAction.informing = PersonAction(\"person", "PersonAction(\"person compliments\") PersonAction.informing = PersonAction(\"person gives information about the service", "the service order\") PersonAction.query = PersonAction(\"person wants to know about", "PersonAction(\"person wants to know about his/her order\") PersonAction.angry = PersonAction(\"person", "key: def __hash__(self): return hash(self.action) # Static fields; an enumeration", "to make this class usable as a # dictionary key:", "__eq__ is defined # in order to make this class", "= action def __str__(self): return self.action def __eq__(self, other): return", "__hash__(self): return hash(self.action) # Static fields; an enumeration of instances:", "PersonAction: def __init__(self, action): self.action = action def __str__(self): return", "__cmp__ or __eq__ is defined # in order to make", "PersonAction.query = PersonAction(\"person wants to know about his/her order\") PersonAction.angry", "Static fields; an enumeration of instances: PersonAction.compliment = PersonAction(\"person compliments\")", "dictionary key: def __hash__(self): return hash(self.action) # Static fields; an", "order to make this class usable as a # dictionary", "class PersonAction: def __init__(self, action): self.action = action def __str__(self):", "self.action def __eq__(self, other): return eq(self.action, other.action) # Necessary when", "in order to make this class usable as a #", "__init__(self, action): self.action = action def __str__(self): return self.action def", "def __str__(self): return self.action def __eq__(self, other): return eq(self.action, other.action)", "# dictionary key: def __hash__(self): return hash(self.action) # Static fields;", "from operator import eq class PersonAction: def __init__(self, action): self.action", "about the service order\") PersonAction.query = PersonAction(\"person wants to know", "def __init__(self, action): self.action = action def __str__(self): return self.action", "defined # in order to make this class usable as", "__str__(self): return self.action def __eq__(self, other): return eq(self.action, other.action) #", "usable as a # dictionary key: def __hash__(self): return hash(self.action)", "= PersonAction(\"person wants to know about his/her order\") PersonAction.angry =", "other): return eq(self.action, other.action) # Necessary when __cmp__ or __eq__" ]
[ "system==\"ubuntu\": os.system(\"sudo python3 core/host.py \"+sys.argv[2]+\" \"+sys.argv[3]+\" \"+sys.argv[4]) else: os.system(\"python3 core/host.py", "--help for more information\") elif sys.argv[1]==\"update\": if system==\"ubuntu\": os.system(\"sudo python3", "print (\"error : invalid arguments !!\") print (\"use : myserver", "to start default localhost server.\") print (\" -s -ng <hostname>", "!!\") print (\"use : myserver --help for more information\") sys.exit()", "print (\"use : myserver --help for more information\") elif len(sys.argv)==6:", "elif sys.argv[1]==\"-db\": if len(sys.argv)==3: if sys.argv[2]==\"start\": if system==\"ubuntu\": os.system(\"sudo python3", "localhost server.\") print (\" -s -ng <hostname> <port> <path> to", "\"+sys.argv[4]+\" \"+sys.argv[5]) else: os.system(\"python3 core/server.py -ng \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) else:", "os.system(\"sudo python3 core/un.py\") else: os.system(\"python3 core/un.py\") else: print (\"error :", "sys.argv[2]==\"-t\": if system==\"ubuntu\": os.system(\"sudo python3 core/un.py\") else: os.system(\"python3 core/un.py\") else:", "(\"use : myserver --help for more information\") else: print (\"error", "core/host.py \"+sys.argv[2]+\" \"+sys.argv[3]+\" \"+sys.argv[4]) else: os.system(\"python3 core/host.py \"+sys.argv[2]+\" \"+sys.argv[3]+\" \"+sys.argv[4])", "--help for more information\") elif len(sys.argv)==6: if sys.argv[2]==\"-php\": if system==\"ubuntu\":", "Date :- 13/11/2018 - 9/11/2019 # Powered By :- H1ckPro", ".MyServer.py\") elif sys.argv[1]==\"--help\" or sys.argv[1]==\"-help\" or sys.argv[1]==\"help\": print (\"\") print", "if len(sys.argv)==3: if sys.argv[2]==\"start\": if system==\"ubuntu\": os.system(\"sudo python3 core/mysql.py \"+sys.argv[2])", "sys.argv[1]==\"-db\": if len(sys.argv)==3: if sys.argv[2]==\"start\": if system==\"ubuntu\": os.system(\"sudo python3 core/mysql.py", "--help for more information\") elif sys.argv[1]==\"rm\": if len(sys.argv)==3: if sys.argv[2]==\"-T\"", "(\" -s -py <hostname> <port> <path> to start python localhost", "information\") elif sys.argv[1]==\"rm\": if len(sys.argv)==3: if sys.argv[2]==\"-T\" or sys.argv[2]==\"-t\": if", "start/stop MySQL database server.\") print (\" -s apache to start", "LordReaper # Date :- 13/11/2018 - 9/11/2019 # Powered By", "else: print (\"error : invalid arguments\") print (\"use : myserver", "\"+sys.argv[2]+\" \"+sys.argv[3]+\" \"+sys.argv[4]) else: print (\"error : invalid arguments !!\")", ": invalid arguments\") print (\"use : myserver --help for more", "time import sleep from core.system import * if len(sys.argv)>1: pass", "- 9/11/2019 # Powered By :- H1ckPro Software's import sys", "python3 core/server.py -py \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) else: os.system(\"python3 core/server.py -py", "(\" Commands:\") print (\" -s <hostname> <port> <path> to start", "By :- H1ckPro Software's import sys import os from time", "core/upd.py\") elif sys.argv[1]==\"start\": if system==\"ubuntu\": os.system(\"sudo python3 .MyServer.py\") else: os.system(\"python3", "\"+sys.argv[3]+\" \"+sys.argv[4]) else: os.system(\"python3 core/host.py \"+sys.argv[2]+\" \"+sys.argv[3]+\" \"+sys.argv[4]) else: print", "core/upd.py\") else: os.system(\"python3 core/upd.py\") elif sys.argv[1]==\"start\": if system==\"ubuntu\": os.system(\"sudo python3", "\"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) else: os.system(\"python3 core/server.py -ng \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5])", "for more information\") elif len(sys.argv)==5: if system==\"ubuntu\": os.system(\"sudo python3 core/server.py", "\"+sys.argv[4]) else: os.system(\"python3 core/host.py \"+sys.argv[2]+\" \"+sys.argv[3]+\" \"+sys.argv[4]) else: print (\"error", "sys.argv[1]==\"update\": if system==\"ubuntu\": os.system(\"sudo python3 core/upd.py\") else: os.system(\"python3 core/upd.py\") elif", "(\" -s <hostname> <port> <path> to start default localhost server.\")", "(\" start start MyServer menu.\") print (\"\") else: print (\"error", "if system==\"ubuntu\": os.system(\"sudo python3 core/mysql.py \"+sys.argv[2]) else: os.system(\"python3 core/mysql.py \"+sys.argv[2])", "Author :- LordReaper # Date :- 13/11/2018 - 9/11/2019 #", "if system==\"ubuntu\": os.system(\"sudo python3 core/upd.py\") else: os.system(\"python3 core/upd.py\") elif sys.argv[1]==\"start\":", "os.system(\"python3 core/server.py -php \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) elif sys.argv[2]==\"-py\": if system==\"ubuntu\":", "php localhost server.\") print (\" -s -php <hostname> <port> <path>", "core/s.py \"+sys.argv[1]) elif len(sys.argv)==3: if sys.argv[2]==\"apache\": if system==\"ubuntu\": os.system(\"sudo python3", "--help for more information\") else: print (\"error : invalid arguments\")", "apache web server.\") print (\" update update MyServer.\") print (\"", "os.system(\"sudo python3 core/server.py -apa\") else: os.system(\"python3 core/server.py -apa\") else: print", "\"+sys.argv[4]) else: print (\"error : invalid arguments\") print (\"use :", "\"+sys.argv[4]+\" \"+sys.argv[5]) else: os.system(\"python3 core/server.py -php \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) elif", "<hostname> <localhost_port> <port> to access localhost server on internet.\") print", "localhost server.\") print (\" -h <hostname> <localhost_port> <port> to access", "9/11/2019 # Powered By :- H1ckPro Software's import sys import", "-apa\") else: print (\"error : invalid arguments !!\") print (\"use", "start default localhost server.\") print (\" -s -ng <hostname> <port>", "localhost server.\") print (\" -s -py <hostname> <port> <path> to", "sys.argv[2]==\"apache\": if system==\"ubuntu\": os.system(\"sudo python3 core/server.py -apa\") else: os.system(\"python3 core/server.py", "python3 core/mysql.py \"+sys.argv[2]) else: os.system(\"python3 core/mysql.py \"+sys.argv[2]) elif sys.argv[2]==\"stop\": if", "uninstall MyServer.\") print (\" start start MyServer menu.\") print (\"\")", "information\") elif len(sys.argv)==6: if sys.argv[2]==\"-php\": if system==\"ubuntu\": os.system(\"sudo python3 core/server.py", "system==\"ubuntu\": os.system(\"sudo python3 core/server.py -d \"+sys.argv[2]+\" \"+sys.argv[3]+\" \"+sys.argv[4]) else: os.system(\"python3", "update MyServer.\") print (\" rm -t uninstall MyServer.\") print (\"", "arguments !!\") print (\"use : myserver --help for more information\")", "# Tool Name :- MyServer # Author :- LordReaper #", "os.system(\"sudo python3 core/mysql.py \"+sys.argv[2]) else: os.system(\"python3 core/mysql.py \"+sys.argv[2]) else: print", "system==\"ubuntu\": os.system(\"sudo python3 core/server.py -ng \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) else: os.system(\"python3", "print (\"\") print (\"Usage: myserver [command]... [arguments]...\") print (\"\") print", "elif len(sys.argv)==5: if system==\"ubuntu\": os.system(\"sudo python3 core/host.py \"+sys.argv[2]+\" \"+sys.argv[3]+\" \"+sys.argv[4])", "(\"\") print (\"Usage: myserver [command]... [arguments]...\") print (\"\") print (\"", "(\"use : myserver --help for more information\") elif len(sys.argv)==6: if", "\"+sys.argv[5]) elif sys.argv[2]==\"-py\": if system==\"ubuntu\": os.system(\"sudo python3 core/server.py -py \"+sys.argv[3]+\"", "if sys.argv[2]==\"-T\" or sys.argv[2]==\"-t\": if system==\"ubuntu\": os.system(\"sudo python3 core/un.py\") else:", "-db [start/stop] to start/stop MySQL database server.\") print (\" -s", "core/mysql.py \"+sys.argv[2]) else: os.system(\"python3 core/mysql.py \"+sys.argv[2]) elif sys.argv[2]==\"stop\": if system==\"ubuntu\":", "for more information\") else: print (\"error : invalid arguments\") print", "sys.argv[2]==\"-ng\": if system==\"ubuntu\": os.system(\"sudo python3 core/server.py -ng \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5])", "myserver --help for more information\") elif sys.argv[1]==\"-db\": if len(sys.argv)==3: if", "elif sys.argv[1]==\"start\": if system==\"ubuntu\": os.system(\"sudo python3 .MyServer.py\") else: os.system(\"python3 .MyServer.py\")", "--help for more information\") elif sys.argv[1]==\"-db\": if len(sys.argv)==3: if sys.argv[2]==\"start\":", "server.\") print (\" -s -php <hostname> <port> <path> to start", "menu.\") print (\"\") else: print (\"error : invalid arguments !!\")", "(\"error : invalid arguments !!\") print (\"use : myserver --help", ":- H1ckPro Software's import sys import os from time import", "else: os.system(\"python3 core/host.py \"+sys.argv[2]+\" \"+sys.argv[3]+\" \"+sys.argv[4]) else: print (\"error :", "for more information\") elif sys.argv[1]==\"rm\": if len(sys.argv)==3: if sys.argv[2]==\"-T\" or", "elif len(sys.argv)==5: if system==\"ubuntu\": os.system(\"sudo python3 core/server.py -d \"+sys.argv[2]+\" \"+sys.argv[3]+\"", "core/mysql.py \"+sys.argv[2]) elif sys.argv[2]==\"stop\": if system==\"ubuntu\": os.system(\"sudo python3 core/mysql.py \"+sys.argv[2])", "<port> <path> to start default localhost server.\") print (\" -s", "more information\") elif len(sys.argv)==6: if sys.argv[2]==\"-php\": if system==\"ubuntu\": os.system(\"sudo python3", "os.system(\"python3 core/s.py \"+sys.argv[1]) elif len(sys.argv)==3: if sys.argv[2]==\"apache\": if system==\"ubuntu\": os.system(\"sudo", "\"+sys.argv[5]) elif sys.argv[2]==\"-ng\": if system==\"ubuntu\": os.system(\"sudo python3 core/server.py -ng \"+sys.argv[3]+\"", "-ng <hostname> <port> <path> to start php localhost server.\") print", "(\"\") print (\" Commands:\") print (\" -s <hostname> <port> <path>", "print (\" -s -php <hostname> <port> <path> to start php", "Software's import sys import os from time import sleep from", "<path> to start php localhost server.\") print (\" -s -py", "print (\"use : myserver --help for more information\") elif sys.argv[1]==\"rm\":", ": invalid arguments !!\") print (\"use : myserver --help for", "else: os.system(\"python3 core/server.py -apa\") else: print (\"error : invalid arguments", "os.system(\"sudo python3 core/server.py -py \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) else: os.system(\"python3 core/server.py", "more information\") sys.exit() if sys.argv[1]==\"-s\": if len(sys.argv)==2: if system==\"ubuntu\": os.system(\"sudo", "\"+sys.argv[5]) else: os.system(\"python3 core/server.py -php \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) elif sys.argv[2]==\"-py\":", "\"+sys.argv[4]) else: os.system(\"python3 core/server.py -d \"+sys.argv[2]+\" \"+sys.argv[3]+\" \"+sys.argv[4]) else: print", "else: os.system(\"python3 core/s.py \"+sys.argv[1]) elif len(sys.argv)==3: if sys.argv[2]==\"apache\": if system==\"ubuntu\":", "core/s.py \"+sys.argv[1]) elif len(sys.argv)==5: if system==\"ubuntu\": os.system(\"sudo python3 core/host.py \"+sys.argv[2]+\"", "from time import sleep from core.system import * if len(sys.argv)>1:", "print (\"\") else: print (\"error : invalid arguments !!\") print", "if system==\"ubuntu\": os.system(\"sudo python3 core/server.py -php \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) else:", "os.system(\"python3 core/mysql.py \"+sys.argv[2]) else: print (\"error : invalid arguments !!\")", ": myserver --help for more information\") elif len(sys.argv)==5: if system==\"ubuntu\":", "\"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) elif sys.argv[2]==\"-py\": if system==\"ubuntu\": os.system(\"sudo python3 core/server.py", "server.\") print (\" update update MyServer.\") print (\" rm -t", "import sleep from core.system import * if len(sys.argv)>1: pass else:", "sys.argv[1]==\"rm\": if len(sys.argv)==3: if sys.argv[2]==\"-T\" or sys.argv[2]==\"-t\": if system==\"ubuntu\": os.system(\"sudo", "<localhost_port> <port> to access localhost server on internet.\") print (\"", "\"+sys.argv[4]+\" \"+sys.argv[5]) else: os.system(\"python3 core/server.py -py \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) elif", "python3 .MyServer.py\") else: os.system(\"python3 .MyServer.py\") elif sys.argv[1]==\"--help\" or sys.argv[1]==\"-help\" or", "invalid arguments\") print (\"use : myserver --help for more information\")", "system==\"ubuntu\": os.system(\"sudo python3 core/server.py -apa\") else: os.system(\"python3 core/server.py -apa\") else:", "(\"use : myserver --help for more information\") elif sys.argv[1]==\"-db\": if", "\"+sys.argv[2]) else: os.system(\"python3 core/mysql.py \"+sys.argv[2]) else: print (\"error : invalid", "to start php localhost server.\") print (\" -s -py <hostname>", "<port> to access localhost server on internet.\") print (\" -db", "arguments\") print (\"use : myserver --help for more information\") elif", "Tool Name :- MyServer # Author :- LordReaper # Date", "\"+sys.argv[1]) elif len(sys.argv)==3: if sys.argv[2]==\"apache\": if system==\"ubuntu\": os.system(\"sudo python3 core/server.py", "core/un.py\") else: os.system(\"python3 core/un.py\") else: print (\"error : invalid arguments\")", "server.\") print (\" -s -py <hostname> <port> <path> to start", "core/mysql.py \"+sys.argv[2]) else: os.system(\"python3 core/mysql.py \"+sys.argv[2]) else: print (\"error :", "(\" -s apache to start apache web server.\") print (\"", "python3 core/server.py -d \"+sys.argv[2]+\" \"+sys.argv[3]+\" \"+sys.argv[4]) else: os.system(\"python3 core/server.py -d", "print (\"Usage: myserver [command]... [arguments]...\") print (\"\") print (\" Commands:\")", "sys.argv[1]==\"help\": print (\"\") print (\"Usage: myserver [command]... [arguments]...\") print (\"\")", "(\" -s -php <hostname> <port> <path> to start php localhost", "--help for more information\") else: print (\"error : invalid arguments", "sys.exit() if sys.argv[1]==\"-s\": if len(sys.argv)==2: if system==\"ubuntu\": os.system(\"sudo python3 core/s.py", "* if len(sys.argv)>1: pass else: print (\"error : invalid arguments", "print (\" Commands:\") print (\" -s <hostname> <port> <path> to", ": myserver --help for more information\") else: print (\"error :", "# Powered By :- H1ckPro Software's import sys import os", "if system==\"ubuntu\": os.system(\"sudo python3 core/un.py\") else: os.system(\"python3 core/un.py\") else: print", "python3 core/server.py -apa\") else: os.system(\"python3 core/server.py -apa\") else: print (\"error", "len(sys.argv)==5: if system==\"ubuntu\": os.system(\"sudo python3 core/server.py -d \"+sys.argv[2]+\" \"+sys.argv[3]+\" \"+sys.argv[4])", "len(sys.argv)==6: if sys.argv[2]==\"-php\": if system==\"ubuntu\": os.system(\"sudo python3 core/server.py -php \"+sys.argv[3]+\"", "else: os.system(\"python3 core/s.py \"+sys.argv[1]) elif len(sys.argv)==5: if system==\"ubuntu\": os.system(\"sudo python3", "-php \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) else: os.system(\"python3 core/server.py -php \"+sys.argv[3]+\" \"+sys.argv[4]+\"", "print (\"use : myserver --help for more information\") elif sys.argv[1]==\"update\":", "else: os.system(\"python3 core/mysql.py \"+sys.argv[2]) else: print (\"error : invalid arguments", "else: os.system(\"python3 core/un.py\") else: print (\"error : invalid arguments\") print", "sys.argv[1]==\"-help\" or sys.argv[1]==\"help\": print (\"\") print (\"Usage: myserver [command]... [arguments]...\")", "arguments\") print (\"use : myserver --help for more information\") else:", "python3 core/s.py \"+sys.argv[1]) else: os.system(\"python3 core/s.py \"+sys.argv[1]) elif len(sys.argv)==5: if", "to access localhost server on internet.\") print (\" -db [start/stop]", "sys.argv[2]==\"-php\": if system==\"ubuntu\": os.system(\"sudo python3 core/server.py -php \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5])", "<hostname> <port> <path> to start python localhost server.\") print (\"", "\"+sys.argv[3]+\" \"+sys.argv[4]) else: print (\"error : invalid arguments !!\") print", "more information\") else: print (\"error : invalid arguments\") print (\"use", "to start python localhost server.\") print (\" -h <hostname> <localhost_port>", "elif sys.argv[2]==\"-py\": if system==\"ubuntu\": os.system(\"sudo python3 core/server.py -py \"+sys.argv[3]+\" \"+sys.argv[4]+\"", "-ng \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) else: os.system(\"python3 core/server.py -ng \"+sys.argv[3]+\" \"+sys.argv[4]+\"", "-apa\") else: os.system(\"python3 core/server.py -apa\") else: print (\"error : invalid", "sys.argv[1]==\"-h\": if len(sys.argv)==2: if system==\"ubuntu\": os.system(\"sudo python3 core/s.py \"+sys.argv[1]) else:", "(\" update update MyServer.\") print (\" rm -t uninstall MyServer.\")", "sys.argv[2]==\"stop\": if system==\"ubuntu\": os.system(\"sudo python3 core/mysql.py \"+sys.argv[2]) else: os.system(\"python3 core/mysql.py", "\"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) elif sys.argv[2]==\"-ng\": if system==\"ubuntu\": os.system(\"sudo python3 core/server.py", "\"+sys.argv[1]) elif len(sys.argv)==5: if system==\"ubuntu\": os.system(\"sudo python3 core/host.py \"+sys.argv[2]+\" \"+sys.argv[3]+\"", "MySQL database server.\") print (\" -s apache to start apache", "\"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) else: os.system(\"python3 core/server.py -php \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5])", "os.system(\"python3 core/un.py\") else: print (\"error : invalid arguments\") print (\"use", "<path> to start php localhost server.\") print (\" -s -php", ":- LordReaper # Date :- 13/11/2018 - 9/11/2019 # Powered", "for more information\") elif len(sys.argv)==6: if sys.argv[2]==\"-php\": if system==\"ubuntu\": os.system(\"sudo", "elif sys.argv[2]==\"-ng\": if system==\"ubuntu\": os.system(\"sudo python3 core/server.py -ng \"+sys.argv[3]+\" \"+sys.argv[4]+\"", "print (\" -db [start/stop] to start/stop MySQL database server.\") print", "os.system(\"sudo python3 core/s.py \"+sys.argv[1]) else: os.system(\"python3 core/s.py \"+sys.argv[1]) elif len(sys.argv)==3:", "update update MyServer.\") print (\" rm -t uninstall MyServer.\") print", "sys.argv[1]==\"--help\" or sys.argv[1]==\"-help\" or sys.argv[1]==\"help\": print (\"\") print (\"Usage: myserver", "information\") elif sys.argv[1]==\"-db\": if len(sys.argv)==3: if sys.argv[2]==\"start\": if system==\"ubuntu\": os.system(\"sudo", "elif sys.argv[1]==\"--help\" or sys.argv[1]==\"-help\" or sys.argv[1]==\"help\": print (\"\") print (\"Usage:", "(\" -db [start/stop] to start/stop MySQL database server.\") print (\"", "!!\") print (\"use : myserver --help for more information\") else:", "information\") elif sys.argv[1]==\"-h\": if len(sys.argv)==2: if system==\"ubuntu\": os.system(\"sudo python3 core/s.py", ": myserver --help for more information\") elif len(sys.argv)==6: if sys.argv[2]==\"-php\":", "os.system(\"python3 core/upd.py\") elif sys.argv[1]==\"start\": if system==\"ubuntu\": os.system(\"sudo python3 .MyServer.py\") else:", "access localhost server on internet.\") print (\" -db [start/stop] to", "sys.argv[2]==\"-T\" or sys.argv[2]==\"-t\": if system==\"ubuntu\": os.system(\"sudo python3 core/un.py\") else: os.system(\"python3", "system==\"ubuntu\": os.system(\"sudo python3 core/upd.py\") else: os.system(\"python3 core/upd.py\") elif sys.argv[1]==\"start\": if", "(\"Usage: myserver [command]... [arguments]...\") print (\"\") print (\" Commands:\") print", "database server.\") print (\" -s apache to start apache web", "MyServer.\") print (\" rm -t uninstall MyServer.\") print (\" start", "start python localhost server.\") print (\" -h <hostname> <localhost_port> <port>", "core/server.py -apa\") else: print (\"error : invalid arguments !!\") print", "system==\"ubuntu\": os.system(\"sudo python3 core/server.py -py \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) else: os.system(\"python3", "if sys.argv[2]==\"start\": if system==\"ubuntu\": os.system(\"sudo python3 core/mysql.py \"+sys.argv[2]) else: os.system(\"python3", "-d \"+sys.argv[2]+\" \"+sys.argv[3]+\" \"+sys.argv[4]) else: print (\"error : invalid arguments", ": myserver --help for more information\") elif sys.argv[1]==\"-h\": if len(sys.argv)==2:", "myserver [command]... [arguments]...\") print (\"\") print (\" Commands:\") print (\"", "to start php localhost server.\") print (\" -s -php <hostname>", "os.system(\"sudo python3 core/server.py -d \"+sys.argv[2]+\" \"+sys.argv[3]+\" \"+sys.argv[4]) else: os.system(\"python3 core/server.py", "web server.\") print (\" update update MyServer.\") print (\" rm", "myserver --help for more information\") elif len(sys.argv)==5: if system==\"ubuntu\": os.system(\"sudo", "core/mysql.py \"+sys.argv[2]) else: print (\"error : invalid arguments !!\") print", "from core.system import * if len(sys.argv)>1: pass else: print (\"error", "-ng \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) else: print (\"error : invalid arguments", "# Date :- 13/11/2018 - 9/11/2019 # Powered By :-", "<port> <path> to start python localhost server.\") print (\" -h", "len(sys.argv)==2: if system==\"ubuntu\": os.system(\"sudo python3 core/s.py \"+sys.argv[1]) else: os.system(\"python3 core/s.py", "if system==\"ubuntu\": os.system(\"sudo python3 .MyServer.py\") else: os.system(\"python3 .MyServer.py\") elif sys.argv[1]==\"--help\"", "--help for more information\") sys.exit() if sys.argv[1]==\"-s\": if len(sys.argv)==2: if", "elif len(sys.argv)==3: if sys.argv[2]==\"apache\": if system==\"ubuntu\": os.system(\"sudo python3 core/server.py -apa\")", "os.system(\"sudo python3 .MyServer.py\") else: os.system(\"python3 .MyServer.py\") elif sys.argv[1]==\"--help\" or sys.argv[1]==\"-help\"", "localhost server.\") print (\" -s -php <hostname> <port> <path> to", "\"+sys.argv[2]+\" \"+sys.argv[3]+\" \"+sys.argv[4]) else: print (\"error : invalid arguments\") print", "[command]... [arguments]...\") print (\"\") print (\" Commands:\") print (\" -s", "elif sys.argv[2]==\"stop\": if system==\"ubuntu\": os.system(\"sudo python3 core/mysql.py \"+sys.argv[2]) else: os.system(\"python3", "(\"\") else: print (\"error : invalid arguments !!\") print (\"use", "server on internet.\") print (\" -db [start/stop] to start/stop MySQL", "if sys.argv[2]==\"-php\": if system==\"ubuntu\": os.system(\"sudo python3 core/server.py -php \"+sys.argv[3]+\" \"+sys.argv[4]+\"", "for more information\") sys.exit() if sys.argv[1]==\"-s\": if len(sys.argv)==2: if system==\"ubuntu\":", "apache to start apache web server.\") print (\" update update", "if system==\"ubuntu\": os.system(\"sudo python3 core/server.py -ng \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) else:", "print (\"use : myserver --help for more information\") elif sys.argv[1]==\"-h\":", "python3 core/s.py \"+sys.argv[1]) else: os.system(\"python3 core/s.py \"+sys.argv[1]) elif len(sys.argv)==3: if", "os.system(\"python3 core/s.py \"+sys.argv[1]) elif len(sys.argv)==5: if system==\"ubuntu\": os.system(\"sudo python3 core/host.py", "print (\" -s <hostname> <port> <path> to start default localhost", ": myserver --help for more information\") sys.exit() if sys.argv[1]==\"-s\": if", "MyServer.\") print (\" start start MyServer menu.\") print (\"\") else:", "start start MyServer menu.\") print (\"\") else: print (\"error :", "Commands:\") print (\" -s <hostname> <port> <path> to start default", "<hostname> <port> <path> to start default localhost server.\") print (\"", ":- 13/11/2018 - 9/11/2019 # Powered By :- H1ckPro Software's", "import os from time import sleep from core.system import *", "os.system(\"sudo python3 core/mysql.py \"+sys.argv[2]) else: os.system(\"python3 core/mysql.py \"+sys.argv[2]) elif sys.argv[2]==\"stop\":", "len(sys.argv)==3: if sys.argv[2]==\"start\": if system==\"ubuntu\": os.system(\"sudo python3 core/mysql.py \"+sys.argv[2]) else:", ".MyServer.py\") else: os.system(\"python3 .MyServer.py\") elif sys.argv[1]==\"--help\" or sys.argv[1]==\"-help\" or sys.argv[1]==\"help\":", "Powered By :- H1ckPro Software's import sys import os from", "core/server.py -php \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) else: os.system(\"python3 core/server.py -php \"+sys.argv[3]+\"", "<path> to start default localhost server.\") print (\" -s -ng", "Name :- MyServer # Author :- LordReaper # Date :-", "print (\"error : invalid arguments\") print (\"use : myserver --help", "\"+sys.argv[5]) else: os.system(\"python3 core/server.py -py \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) elif sys.argv[2]==\"-ng\":", "(\"use : myserver --help for more information\") elif len(sys.argv)==5: if", "sys.argv[2]==\"-py\": if system==\"ubuntu\": os.system(\"sudo python3 core/server.py -py \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5])", "len(sys.argv)==5: if system==\"ubuntu\": os.system(\"sudo python3 core/host.py \"+sys.argv[2]+\" \"+sys.argv[3]+\" \"+sys.argv[4]) else:", "-s <hostname> <port> <path> to start default localhost server.\") print", "\"+sys.argv[5]) else: print (\"error : invalid arguments !!\") print (\"use", "-h <hostname> <localhost_port> <port> to access localhost server on internet.\")", "if len(sys.argv)==2: if system==\"ubuntu\": os.system(\"sudo python3 core/s.py \"+sys.argv[1]) else: os.system(\"python3", ": myserver --help for more information\") elif sys.argv[1]==\"-db\": if len(sys.argv)==3:", "[start/stop] to start/stop MySQL database server.\") print (\" -s apache", "\"+sys.argv[2]) elif sys.argv[2]==\"stop\": if system==\"ubuntu\": os.system(\"sudo python3 core/mysql.py \"+sys.argv[2]) else:", "core.system import * if len(sys.argv)>1: pass else: print (\"error :", "os.system(\"python3 core/server.py -ng \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) else: print (\"error :", "-d \"+sys.argv[2]+\" \"+sys.argv[3]+\" \"+sys.argv[4]) else: os.system(\"python3 core/server.py -d \"+sys.argv[2]+\" \"+sys.argv[3]+\"", "for more information\") else: print (\"error : invalid arguments !!\")", "-php <hostname> <port> <path> to start php localhost server.\") print", "or sys.argv[1]==\"-help\" or sys.argv[1]==\"help\": print (\"\") print (\"Usage: myserver [command]...", "myserver --help for more information\") elif sys.argv[1]==\"rm\": if len(sys.argv)==3: if", "if len(sys.argv)>1: pass else: print (\"error : invalid arguments !!\")", "python3 core/server.py -ng \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) else: os.system(\"python3 core/server.py -ng", "if system==\"ubuntu\": os.system(\"sudo python3 core/server.py -apa\") else: os.system(\"python3 core/server.py -apa\")", "--help for more information\") elif len(sys.argv)==5: if system==\"ubuntu\": os.system(\"sudo python3", "sleep from core.system import * if len(sys.argv)>1: pass else: print", "else: os.system(\"python3 .MyServer.py\") elif sys.argv[1]==\"--help\" or sys.argv[1]==\"-help\" or sys.argv[1]==\"help\": print", "\"+sys.argv[2]+\" \"+sys.argv[3]+\" \"+sys.argv[4]) else: os.system(\"python3 core/host.py \"+sys.argv[2]+\" \"+sys.argv[3]+\" \"+sys.argv[4]) else:", "\"+sys.argv[2]) else: print (\"error : invalid arguments !!\") print (\"use", "(\"use : myserver --help for more information\") elif sys.argv[1]==\"-h\": if", "<hostname> <port> <path> to start php localhost server.\") print (\"", "python3 core/mysql.py \"+sys.argv[2]) else: os.system(\"python3 core/mysql.py \"+sys.argv[2]) else: print (\"error", "\"+sys.argv[3]+\" \"+sys.argv[4]) else: print (\"error : invalid arguments\") print (\"use", "python3 core/upd.py\") else: os.system(\"python3 core/upd.py\") elif sys.argv[1]==\"start\": if system==\"ubuntu\": os.system(\"sudo", "start MyServer menu.\") print (\"\") else: print (\"error : invalid", "os from time import sleep from core.system import * if", "if sys.argv[1]==\"-s\": if len(sys.argv)==2: if system==\"ubuntu\": os.system(\"sudo python3 core/s.py \"+sys.argv[1])", "print (\"\") print (\" Commands:\") print (\" -s <hostname> <port>", "else: os.system(\"python3 core/server.py -py \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) elif sys.argv[2]==\"-ng\": if", "invalid arguments !!\") print (\"use : myserver --help for more", "information\") else: print (\"error : invalid arguments\") print (\"use :", "len(sys.argv)>1: pass else: print (\"error : invalid arguments !!\") print", "print (\" -s -ng <hostname> <port> <path> to start php", "information\") sys.exit() if sys.argv[1]==\"-s\": if len(sys.argv)==2: if system==\"ubuntu\": os.system(\"sudo python3", "myserver --help for more information\") elif len(sys.argv)==6: if sys.argv[2]==\"-php\": if", "os.system(\"sudo python3 core/upd.py\") else: os.system(\"python3 core/upd.py\") elif sys.argv[1]==\"start\": if system==\"ubuntu\":", "(\" -s -ng <hostname> <port> <path> to start php localhost", "-t uninstall MyServer.\") print (\" start start MyServer menu.\") print", "print (\" -s apache to start apache web server.\") print", "sys.argv[1]==\"start\": if system==\"ubuntu\": os.system(\"sudo python3 .MyServer.py\") else: os.system(\"python3 .MyServer.py\") elif", "MyServer # Author :- LordReaper # Date :- 13/11/2018 -", "elif sys.argv[1]==\"rm\": if len(sys.argv)==3: if sys.argv[2]==\"-T\" or sys.argv[2]==\"-t\": if system==\"ubuntu\":", "myserver --help for more information\") else: print (\"error : invalid", "information\") else: print (\"error : invalid arguments !!\") print (\"use", "core/s.py \"+sys.argv[1]) else: os.system(\"python3 core/s.py \"+sys.argv[1]) elif len(sys.argv)==5: if system==\"ubuntu\":", "elif len(sys.argv)==6: if sys.argv[2]==\"-php\": if system==\"ubuntu\": os.system(\"sudo python3 core/server.py -php", "information\") elif len(sys.argv)==5: if system==\"ubuntu\": os.system(\"sudo python3 core/server.py -d \"+sys.argv[2]+\"", "more information\") elif len(sys.argv)==5: if system==\"ubuntu\": os.system(\"sudo python3 core/server.py -d", "-s -php <hostname> <port> <path> to start php localhost server.\")", "core/s.py \"+sys.argv[1]) else: os.system(\"python3 core/s.py \"+sys.argv[1]) elif len(sys.argv)==3: if sys.argv[2]==\"apache\":", "else: os.system(\"python3 core/upd.py\") elif sys.argv[1]==\"start\": if system==\"ubuntu\": os.system(\"sudo python3 .MyServer.py\")", "core/server.py -py \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) else: os.system(\"python3 core/server.py -py \"+sys.argv[3]+\"", "system==\"ubuntu\": os.system(\"sudo python3 core/un.py\") else: os.system(\"python3 core/un.py\") else: print (\"error", "<port> <path> to start php localhost server.\") print (\" -s", "-php \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) elif sys.argv[2]==\"-py\": if system==\"ubuntu\": os.system(\"sudo python3", "elif sys.argv[1]==\"update\": if system==\"ubuntu\": os.system(\"sudo python3 core/upd.py\") else: os.system(\"python3 core/upd.py\")", "core/server.py -php \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) elif sys.argv[2]==\"-py\": if system==\"ubuntu\": os.system(\"sudo", "or sys.argv[2]==\"-t\": if system==\"ubuntu\": os.system(\"sudo python3 core/un.py\") else: os.system(\"python3 core/un.py\")", "\"+sys.argv[4]) else: print (\"error : invalid arguments !!\") print (\"use", "more information\") elif sys.argv[1]==\"rm\": if len(sys.argv)==3: if sys.argv[2]==\"-T\" or sys.argv[2]==\"-t\":", "default localhost server.\") print (\" -s -ng <hostname> <port> <path>", "information\") elif sys.argv[1]==\"update\": if system==\"ubuntu\": os.system(\"sudo python3 core/upd.py\") else: os.system(\"python3", "-py <hostname> <port> <path> to start python localhost server.\") print", "server.\") print (\" -s apache to start apache web server.\")", "os.system(\"python3 core/host.py \"+sys.argv[2]+\" \"+sys.argv[3]+\" \"+sys.argv[4]) else: print (\"error : invalid", "more information\") else: print (\"error : invalid arguments !!\") print", "print (\" -h <hostname> <localhost_port> <port> to access localhost server", "(\" rm -t uninstall MyServer.\") print (\" start start MyServer", "system==\"ubuntu\": os.system(\"sudo python3 core/mysql.py \"+sys.argv[2]) else: os.system(\"python3 core/mysql.py \"+sys.argv[2]) elif", "system==\"ubuntu\": os.system(\"sudo python3 .MyServer.py\") else: os.system(\"python3 .MyServer.py\") elif sys.argv[1]==\"--help\" or", "else: os.system(\"python3 core/server.py -php \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) elif sys.argv[2]==\"-py\": if", "or sys.argv[1]==\"help\": print (\"\") print (\"Usage: myserver [command]... [arguments]...\") print", "elif sys.argv[1]==\"-h\": if len(sys.argv)==2: if system==\"ubuntu\": os.system(\"sudo python3 core/s.py \"+sys.argv[1])", "!!\") print (\"use : myserver --help for more information\") elif", "\"+sys.argv[2]) else: os.system(\"python3 core/mysql.py \"+sys.argv[2]) elif sys.argv[2]==\"stop\": if system==\"ubuntu\": os.system(\"sudo", "start php localhost server.\") print (\" -s -py <hostname> <port>", "core/server.py -apa\") else: os.system(\"python3 core/server.py -apa\") else: print (\"error :", "# Author :- LordReaper # Date :- 13/11/2018 - 9/11/2019", "\"+sys.argv[5]) else: os.system(\"python3 core/server.py -ng \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) else: print", "-py \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) elif sys.argv[2]==\"-ng\": if system==\"ubuntu\": os.system(\"sudo python3", "start apache web server.\") print (\" update update MyServer.\") print", "for more information\") elif sys.argv[1]==\"-h\": if len(sys.argv)==2: if system==\"ubuntu\": os.system(\"sudo", "core/server.py -py \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) elif sys.argv[2]==\"-ng\": if system==\"ubuntu\": os.system(\"sudo", "core/server.py -d \"+sys.argv[2]+\" \"+sys.argv[3]+\" \"+sys.argv[4]) else: print (\"error : invalid", "import sys import os from time import sleep from core.system", "-s -ng <hostname> <port> <path> to start php localhost server.\")", "MyServer menu.\") print (\"\") else: print (\"error : invalid arguments", "if system==\"ubuntu\": os.system(\"sudo python3 core/server.py -d \"+sys.argv[2]+\" \"+sys.argv[3]+\" \"+sys.argv[4]) else:", "os.system(\"python3 core/mysql.py \"+sys.argv[2]) elif sys.argv[2]==\"stop\": if system==\"ubuntu\": os.system(\"sudo python3 core/mysql.py", "sys import os from time import sleep from core.system import", "\"+sys.argv[1]) else: os.system(\"python3 core/s.py \"+sys.argv[1]) elif len(sys.argv)==3: if sys.argv[2]==\"apache\": if", "print (\" update update MyServer.\") print (\" rm -t uninstall", "import * if len(sys.argv)>1: pass else: print (\"error : invalid", "print (\"use : myserver --help for more information\") elif len(sys.argv)==5:", "server.\") print (\" -s -ng <hostname> <port> <path> to start", "if sys.argv[2]==\"apache\": if system==\"ubuntu\": os.system(\"sudo python3 core/server.py -apa\") else: os.system(\"python3", "len(sys.argv)==3: if sys.argv[2]==\"apache\": if system==\"ubuntu\": os.system(\"sudo python3 core/server.py -apa\") else:", "system==\"ubuntu\": os.system(\"sudo python3 core/server.py -php \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) else: os.system(\"python3", "python3 core/host.py \"+sys.argv[2]+\" \"+sys.argv[3]+\" \"+sys.argv[4]) else: os.system(\"python3 core/host.py \"+sys.argv[2]+\" \"+sys.argv[3]+\"", "sys.argv[1]==\"-s\": if len(sys.argv)==2: if system==\"ubuntu\": os.system(\"sudo python3 core/s.py \"+sys.argv[1]) else:", "os.system(\"python3 .MyServer.py\") elif sys.argv[1]==\"--help\" or sys.argv[1]==\"-help\" or sys.argv[1]==\"help\": print (\"\")", "\"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) else: os.system(\"python3 core/server.py -py \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5])", "print (\"use : myserver --help for more information\") elif sys.argv[1]==\"-db\":", "\"+sys.argv[3]+\" \"+sys.argv[4]) else: os.system(\"python3 core/server.py -d \"+sys.argv[2]+\" \"+sys.argv[3]+\" \"+sys.argv[4]) else:", "core/server.py -ng \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) else: os.system(\"python3 core/server.py -ng \"+sys.argv[3]+\"", "myserver --help for more information\") elif sys.argv[1]==\"update\": if system==\"ubuntu\": os.system(\"sudo", "if system==\"ubuntu\": os.system(\"sudo python3 core/server.py -py \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) else:", "os.system(\"python3 core/server.py -py \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) elif sys.argv[2]==\"-ng\": if system==\"ubuntu\":", "python3 core/un.py\") else: os.system(\"python3 core/un.py\") else: print (\"error : invalid", "if system==\"ubuntu\": os.system(\"sudo python3 core/s.py \"+sys.argv[1]) else: os.system(\"python3 core/s.py \"+sys.argv[1])", "\"+sys.argv[1]) else: os.system(\"python3 core/s.py \"+sys.argv[1]) elif len(sys.argv)==5: if system==\"ubuntu\": os.system(\"sudo", "os.system(\"sudo python3 core/server.py -ng \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) else: os.system(\"python3 core/server.py", "print (\" start start MyServer menu.\") print (\"\") else: print", "-s -py <hostname> <port> <path> to start python localhost server.\")", "os.system(\"sudo python3 core/server.py -php \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) else: os.system(\"python3 core/server.py", "internet.\") print (\" -db [start/stop] to start/stop MySQL database server.\")", "13/11/2018 - 9/11/2019 # Powered By :- H1ckPro Software's import", "\"+sys.argv[4]+\" \"+sys.argv[5]) else: print (\"error : invalid arguments !!\") print", "os.system(\"python3 core/server.py -apa\") else: print (\"error : invalid arguments !!\")", "os.system(\"python3 core/server.py -d \"+sys.argv[2]+\" \"+sys.argv[3]+\" \"+sys.argv[4]) else: print (\"error :", "more information\") elif sys.argv[1]==\"-h\": if len(sys.argv)==2: if system==\"ubuntu\": os.system(\"sudo python3", "more information\") elif sys.argv[1]==\"update\": if system==\"ubuntu\": os.system(\"sudo python3 core/upd.py\") else:", "myserver --help for more information\") elif sys.argv[1]==\"-h\": if len(sys.argv)==2: if", "start php localhost server.\") print (\" -s -php <hostname> <port>", "if system==\"ubuntu\": os.system(\"sudo python3 core/host.py \"+sys.argv[2]+\" \"+sys.argv[3]+\" \"+sys.argv[4]) else: os.system(\"python3", "for more information\") elif sys.argv[1]==\"-db\": if len(sys.argv)==3: if sys.argv[2]==\"start\": if", "(\"use : myserver --help for more information\") elif sys.argv[1]==\"rm\": if", "len(sys.argv)==3: if sys.argv[2]==\"-T\" or sys.argv[2]==\"-t\": if system==\"ubuntu\": os.system(\"sudo python3 core/un.py\")", "[arguments]...\") print (\"\") print (\" Commands:\") print (\" -s <hostname>", "\"+sys.argv[4]+\" \"+sys.argv[5]) elif sys.argv[2]==\"-ng\": if system==\"ubuntu\": os.system(\"sudo python3 core/server.py -ng", "print (\"use : myserver --help for more information\") sys.exit() if", "more information\") elif sys.argv[1]==\"-db\": if len(sys.argv)==3: if sys.argv[2]==\"start\": if system==\"ubuntu\":", ": myserver --help for more information\") elif sys.argv[1]==\"update\": if system==\"ubuntu\":", "\"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) else: print (\"error : invalid arguments !!\")", "php localhost server.\") print (\" -s -py <hostname> <port> <path>", "core/un.py\") else: print (\"error : invalid arguments\") print (\"use :", "\"+sys.argv[4]+\" \"+sys.argv[5]) elif sys.argv[2]==\"-py\": if system==\"ubuntu\": os.system(\"sudo python3 core/server.py -py", "core/server.py -d \"+sys.argv[2]+\" \"+sys.argv[3]+\" \"+sys.argv[4]) else: os.system(\"python3 core/server.py -d \"+sys.argv[2]+\"", "-py \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) else: os.system(\"python3 core/server.py -py \"+sys.argv[3]+\" \"+sys.argv[4]+\"", "to start/stop MySQL database server.\") print (\" -s apache to", "core/server.py -ng \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) else: print (\"error : invalid", ":- MyServer # Author :- LordReaper # Date :- 13/11/2018", "(\"error : invalid arguments\") print (\"use : myserver --help for", "pass else: print (\"error : invalid arguments !!\") print (\"use", "for more information\") elif sys.argv[1]==\"update\": if system==\"ubuntu\": os.system(\"sudo python3 core/upd.py\")", "localhost server on internet.\") print (\" -db [start/stop] to start/stop", ": myserver --help for more information\") elif sys.argv[1]==\"rm\": if len(sys.argv)==3:", "python localhost server.\") print (\" -h <hostname> <localhost_port> <port> to", "(\"use : myserver --help for more information\") sys.exit() if sys.argv[1]==\"-s\":", "to start apache web server.\") print (\" update update MyServer.\")", "print (\" -s -py <hostname> <port> <path> to start python", "--help for more information\") elif sys.argv[1]==\"-h\": if len(sys.argv)==2: if system==\"ubuntu\":", "else: print (\"error : invalid arguments !!\") print (\"use :", "os.system(\"sudo python3 core/host.py \"+sys.argv[2]+\" \"+sys.argv[3]+\" \"+sys.argv[4]) else: os.system(\"python3 core/host.py \"+sys.argv[2]+\"", "if len(sys.argv)==3: if sys.argv[2]==\"-T\" or sys.argv[2]==\"-t\": if system==\"ubuntu\": os.system(\"sudo python3", "(\" -h <hostname> <localhost_port> <port> to access localhost server on", "else: os.system(\"python3 core/server.py -d \"+sys.argv[2]+\" \"+sys.argv[3]+\" \"+sys.argv[4]) else: print (\"error", "server.\") print (\" -h <hostname> <localhost_port> <port> to access localhost", "sys.argv[2]==\"start\": if system==\"ubuntu\": os.system(\"sudo python3 core/mysql.py \"+sys.argv[2]) else: os.system(\"python3 core/mysql.py", "else: os.system(\"python3 core/mysql.py \"+sys.argv[2]) elif sys.argv[2]==\"stop\": if system==\"ubuntu\": os.system(\"sudo python3", "(\"use : myserver --help for more information\") elif sys.argv[1]==\"update\": if", "system==\"ubuntu\": os.system(\"sudo python3 core/s.py \"+sys.argv[1]) else: os.system(\"python3 core/s.py \"+sys.argv[1]) elif", "system==\"ubuntu\": os.system(\"sudo python3 core/mysql.py \"+sys.argv[2]) else: os.system(\"python3 core/mysql.py \"+sys.argv[2]) else:", "H1ckPro Software's import sys import os from time import sleep", "print (\" rm -t uninstall MyServer.\") print (\" start start", "else: os.system(\"python3 core/server.py -ng \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) else: print (\"error", "rm -t uninstall MyServer.\") print (\" start start MyServer menu.\")", "myserver --help for more information\") sys.exit() if sys.argv[1]==\"-s\": if len(sys.argv)==2:", "os.system(\"sudo python3 core/s.py \"+sys.argv[1]) else: os.system(\"python3 core/s.py \"+sys.argv[1]) elif len(sys.argv)==5:", "on internet.\") print (\" -db [start/stop] to start/stop MySQL database", "\"+sys.argv[2]+\" \"+sys.argv[3]+\" \"+sys.argv[4]) else: os.system(\"python3 core/server.py -d \"+sys.argv[2]+\" \"+sys.argv[3]+\" \"+sys.argv[4])", "<path> to start python localhost server.\") print (\" -h <hostname>", "python3 core/server.py -php \"+sys.argv[3]+\" \"+sys.argv[4]+\" \"+sys.argv[5]) else: os.system(\"python3 core/server.py -php", "core/host.py \"+sys.argv[2]+\" \"+sys.argv[3]+\" \"+sys.argv[4]) else: print (\"error : invalid arguments\")", "print (\"use : myserver --help for more information\") else: print", "-s apache to start apache web server.\") print (\" update" ]
[ "pathlib import Path infile = r\"tests\\2.tmx\" stem = Path(infile).absolute().stem outfile", "= Path(infile).absolute().stem outfile = f\"{Path(infile).absolute().parent / stem}.epub\" assert gen_epub(infile, debug=True)", "test_gen_epub2. \"\"\" from pathlib import Path infile = r\"tests\\2.tmx\" stem", "\"\"\" test_gen_epub2. \"\"\" from pathlib import Path infile = r\"tests\\2.tmx\"", "from tmx2epub.gen_epub import gen_epub def test_gen_epub2(): \"\"\" test_gen_epub2. \"\"\" from", "\"\"\" test gen_epub. \"\"\" from tmx2epub.gen_epub import gen_epub def test_gen_epub2():", "def test_gen_epub2(): \"\"\" test_gen_epub2. \"\"\" from pathlib import Path infile", "import gen_epub def test_gen_epub2(): \"\"\" test_gen_epub2. \"\"\" from pathlib import", "test_gen_epub2(): \"\"\" test_gen_epub2. \"\"\" from pathlib import Path infile =", "from pathlib import Path infile = r\"tests\\2.tmx\" stem = Path(infile).absolute().stem", "test gen_epub. \"\"\" from tmx2epub.gen_epub import gen_epub def test_gen_epub2(): \"\"\"", "= f\"{Path(infile).absolute().parent / stem}.epub\" assert gen_epub(infile, debug=True) == outfile #", "Path infile = r\"tests\\2.tmx\" stem = Path(infile).absolute().stem outfile = f\"{Path(infile).absolute().parent", "outfile = f\"{Path(infile).absolute().parent / stem}.epub\" assert gen_epub(infile, debug=True) == outfile", "= r\"tests\\2.tmx\" stem = Path(infile).absolute().stem outfile = f\"{Path(infile).absolute().parent / stem}.epub\"", "/ stem}.epub\" assert gen_epub(infile, debug=True) == outfile # assert 0", "\"\"\" from pathlib import Path infile = r\"tests\\2.tmx\" stem =", "tmx2epub.gen_epub import gen_epub def test_gen_epub2(): \"\"\" test_gen_epub2. \"\"\" from pathlib", "stem = Path(infile).absolute().stem outfile = f\"{Path(infile).absolute().parent / stem}.epub\" assert gen_epub(infile,", "r\"tests\\2.tmx\" stem = Path(infile).absolute().stem outfile = f\"{Path(infile).absolute().parent / stem}.epub\" assert", "infile = r\"tests\\2.tmx\" stem = Path(infile).absolute().stem outfile = f\"{Path(infile).absolute().parent /", "f\"{Path(infile).absolute().parent / stem}.epub\" assert gen_epub(infile, debug=True) == outfile # assert", "\"\"\" from tmx2epub.gen_epub import gen_epub def test_gen_epub2(): \"\"\" test_gen_epub2. \"\"\"", "import Path infile = r\"tests\\2.tmx\" stem = Path(infile).absolute().stem outfile =", "Path(infile).absolute().stem outfile = f\"{Path(infile).absolute().parent / stem}.epub\" assert gen_epub(infile, debug=True) ==", "gen_epub def test_gen_epub2(): \"\"\" test_gen_epub2. \"\"\" from pathlib import Path", "gen_epub. \"\"\" from tmx2epub.gen_epub import gen_epub def test_gen_epub2(): \"\"\" test_gen_epub2." ]
[ "logging import requests import os logging.basicConfig(level=logging.INFO) base_url = os.getenv('BASE_URL', 'http://localhost')", "= {'orderId': i} # Publish an event/message using Dapr PubSub", "result = requests.post( url='%s/v1.0/publish/%s/%s' % (base_url, PUBSUB_NAME, TOPIC), json=order )", "range(1, 10): order = {'orderId': i} # Publish an event/message", "json import time import random import logging import requests import", "= os.getenv('BASE_URL', 'http://localhost') + ':' + os.getenv( 'DAPR_HTTP_PORT', '3500') PUBSUB_NAME", "'http://localhost') + ':' + os.getenv( 'DAPR_HTTP_PORT', '3500') PUBSUB_NAME = 'order_pub_sub'", "Pubsub Name: %s, Topic: %s' % ( base_url, PUBSUB_NAME, TOPIC))", "%s' % ( base_url, PUBSUB_NAME, TOPIC)) for i in range(1,", "os.getenv( 'DAPR_HTTP_PORT', '3500') PUBSUB_NAME = 'order_pub_sub' TOPIC = 'orders' logging.info('Publishing", "% (base_url, PUBSUB_NAME, TOPIC), json=order ) logging.info('Published data: ' +", "'order_pub_sub' TOPIC = 'orders' logging.info('Publishing to baseURL: %s, Pubsub Name:", "import json import time import random import logging import requests", "random import logging import requests import os logging.basicConfig(level=logging.INFO) base_url =", "= 'order_pub_sub' TOPIC = 'orders' logging.info('Publishing to baseURL: %s, Pubsub", "PUBSUB_NAME, TOPIC)) for i in range(1, 10): order = {'orderId':", "an event/message using Dapr PubSub via HTTP Post result =", "Dapr PubSub via HTTP Post result = requests.post( url='%s/v1.0/publish/%s/%s' %", "{'orderId': i} # Publish an event/message using Dapr PubSub via", "to baseURL: %s, Pubsub Name: %s, Topic: %s' % (", "PUBSUB_NAME = 'order_pub_sub' TOPIC = 'orders' logging.info('Publishing to baseURL: %s,", "logging.info('Publishing to baseURL: %s, Pubsub Name: %s, Topic: %s' %", "(base_url, PUBSUB_NAME, TOPIC), json=order ) logging.info('Published data: ' + json.dumps(order))", "import time import random import logging import requests import os", "HTTP Post result = requests.post( url='%s/v1.0/publish/%s/%s' % (base_url, PUBSUB_NAME, TOPIC),", "= requests.post( url='%s/v1.0/publish/%s/%s' % (base_url, PUBSUB_NAME, TOPIC), json=order ) logging.info('Published", "os logging.basicConfig(level=logging.INFO) base_url = os.getenv('BASE_URL', 'http://localhost') + ':' + os.getenv(", "Publish an event/message using Dapr PubSub via HTTP Post result", "import os logging.basicConfig(level=logging.INFO) base_url = os.getenv('BASE_URL', 'http://localhost') + ':' +", "PubSub via HTTP Post result = requests.post( url='%s/v1.0/publish/%s/%s' % (base_url,", "import requests import os logging.basicConfig(level=logging.INFO) base_url = os.getenv('BASE_URL', 'http://localhost') +", "baseURL: %s, Pubsub Name: %s, Topic: %s' % ( base_url,", "for i in range(1, 10): order = {'orderId': i} #", "logging.basicConfig(level=logging.INFO) base_url = os.getenv('BASE_URL', 'http://localhost') + ':' + os.getenv( 'DAPR_HTTP_PORT',", "using Dapr PubSub via HTTP Post result = requests.post( url='%s/v1.0/publish/%s/%s'", "base_url = os.getenv('BASE_URL', 'http://localhost') + ':' + os.getenv( 'DAPR_HTTP_PORT', '3500')", "= 'orders' logging.info('Publishing to baseURL: %s, Pubsub Name: %s, Topic:", "'orders' logging.info('Publishing to baseURL: %s, Pubsub Name: %s, Topic: %s'", "base_url, PUBSUB_NAME, TOPIC)) for i in range(1, 10): order =", "TOPIC)) for i in range(1, 10): order = {'orderId': i}", "in range(1, 10): order = {'orderId': i} # Publish an", "10): order = {'orderId': i} # Publish an event/message using", "i in range(1, 10): order = {'orderId': i} # Publish", "Topic: %s' % ( base_url, PUBSUB_NAME, TOPIC)) for i in", "'3500') PUBSUB_NAME = 'order_pub_sub' TOPIC = 'orders' logging.info('Publishing to baseURL:", "i} # Publish an event/message using Dapr PubSub via HTTP", "# Publish an event/message using Dapr PubSub via HTTP Post", "url='%s/v1.0/publish/%s/%s' % (base_url, PUBSUB_NAME, TOPIC), json=order ) logging.info('Published data: '", "PUBSUB_NAME, TOPIC), json=order ) logging.info('Published data: ' + json.dumps(order)) time.sleep(1)", "requests import os logging.basicConfig(level=logging.INFO) base_url = os.getenv('BASE_URL', 'http://localhost') + ':'", "'DAPR_HTTP_PORT', '3500') PUBSUB_NAME = 'order_pub_sub' TOPIC = 'orders' logging.info('Publishing to", "%s, Topic: %s' % ( base_url, PUBSUB_NAME, TOPIC)) for i", "time import random import logging import requests import os logging.basicConfig(level=logging.INFO)", "( base_url, PUBSUB_NAME, TOPIC)) for i in range(1, 10): order", "os.getenv('BASE_URL', 'http://localhost') + ':' + os.getenv( 'DAPR_HTTP_PORT', '3500') PUBSUB_NAME =", "import random import logging import requests import os logging.basicConfig(level=logging.INFO) base_url", "via HTTP Post result = requests.post( url='%s/v1.0/publish/%s/%s' % (base_url, PUBSUB_NAME,", "% ( base_url, PUBSUB_NAME, TOPIC)) for i in range(1, 10):", "event/message using Dapr PubSub via HTTP Post result = requests.post(", "+ os.getenv( 'DAPR_HTTP_PORT', '3500') PUBSUB_NAME = 'order_pub_sub' TOPIC = 'orders'", "':' + os.getenv( 'DAPR_HTTP_PORT', '3500') PUBSUB_NAME = 'order_pub_sub' TOPIC =", "Name: %s, Topic: %s' % ( base_url, PUBSUB_NAME, TOPIC)) for", "Post result = requests.post( url='%s/v1.0/publish/%s/%s' % (base_url, PUBSUB_NAME, TOPIC), json=order", "import logging import requests import os logging.basicConfig(level=logging.INFO) base_url = os.getenv('BASE_URL',", "requests.post( url='%s/v1.0/publish/%s/%s' % (base_url, PUBSUB_NAME, TOPIC), json=order ) logging.info('Published data:", "order = {'orderId': i} # Publish an event/message using Dapr", "%s, Pubsub Name: %s, Topic: %s' % ( base_url, PUBSUB_NAME,", "TOPIC = 'orders' logging.info('Publishing to baseURL: %s, Pubsub Name: %s,", "+ ':' + os.getenv( 'DAPR_HTTP_PORT', '3500') PUBSUB_NAME = 'order_pub_sub' TOPIC" ]
[ "Age : {}\".format(str(data[\"data\"][\"usia\"])) ret_ += \"\\n╠ Birthday : {}\".format(str(data[\"data\"][\"ultah\"])) ret_", "= cl.reissueGroupTicket(to) cl.sendMessage(to, \"[ Group Ticket ]\\nhttps://cl.me/R/ti/g/{}\".format(str(ticket))) else: cl.sendMessage(to, \"Grouplink未開啟", "+ cl.getContact(ls).pictureStatus cl.sendImageWithURL(msg.to, str(path)) for ls in lists: path =", "inkey =MENTION['MENTIONEES'][0]['M'] admin.append(str(inkey)) cl.sendMessage(to,\"已新增權限\") elif text.lower() == 'demin ': MENTION", "cl.sendMessage(to, \"開啟成功\") elif text.lower() == 'groupinfo': group = cl.getGroup(to) try:", "msg.contentMetadata = {'mid': target} settings[\"copy\"] = False break #==============================================================================# if", "elif text.lower() == 'groupname': gid = cl.getGroup(to) cl.sendMessage(to, \"[群組名稱 :", "if msg.to not in read['readPoint']: cl.sendMessage(msg.to,\"偵測點已取消\") else: try: del read['readPoint'][msg.to]", "]\" cl.sendMessage(to, str(ret_)) except Exception as e: cl.sendMessage(msg.to, str(e)) elif", "in admin: mc += \"\\n╠ \"+cl.getContact(mi_d).displayName cl.sendMessage(to,mc + \"\\n╚══[ Finish", "<gh_stars>1-10 # -*- coding: utf-8 -*- from linepy import *", "point:\\n\" + readTime) elif text.lower() == 'resetread': tz = pytz.timezone(\"Asia/Jakarta\")", "= datetime.now() with open(\"errorLog.txt\",\"a\") as error: error.write(\"\\n[%s] %s\" % (str(time),", "= False break #==============================================================================# if op.type == 26: print (\"[", "STICKER ID : {}\".format(stk_id) ret_ += \"\\n╠ STICKER PACKAGES ID", "*sys.argv) def backupData(): try: backup = settings f = codecs.open('temp.json','w','utf-8')", "True cl.updateGroup(group) cl.sendMessage(to, \"開啟成功\") elif text.lower() == 'groupinfo': group =", "] BOT RESETTED\") backupData() python = sys.executable os.execl(python, python, *sys.argv)", "\"\", \"statusMessage\": \"\", \"pictureStatus\": \"\" } msg_dict = {} bl", "+= \"\\n╠ \"+mi_d cl.sendMessage(to,mc + \"\\n╚══[ Finish ]\") #==============================================================================# elif", "= cl.getContact(ls) mi_d = contact.mid cl.sendContact(msg.to, mi_d) elif msg.text.lower().startswith(\"mid \"):", "text.lower() == 'link off': if msg.toType == 2: group =", "s in groups.members: if _name in s.displayName: print (\"[Target] Copy\")", "'autoadd on': settings[\"autoAdd\"] = True cl.sendMessage(to, \"Auto Add on success\")", ": \" + str(cl.authToken)) channelToken = cl.getChannelResult() cl.log(\"Channel Token :", "gs = cl.getGroup(msg.to) cl.sendMessage(msg.to,\"Sorry guys\") targets = [] for g", "in msg.text): if msg.toType == 2: X = cl.getGroup(msg.to) X.name", "\"Auto Add off success\") elif text.lower() == 'autojoin on': settings[\"autoJoin\"]", "u'' s=0 b=[] for i in group.members[a*100 : (a+1)*100]: b.append({\"S\":str(s),", "19 ] KICK ALL MEMBER\") _name = msg.text.replace(\"Byeall\",\"\") gs =", "cl.getBlockedContactIds() ret_ = \"╔══[ 關於使用者 ]\" ret_ += \"\\n╠ 使用者名稱", "elif text.lower() == 'cleanban': settings[\"blacklist\"] == {ok} for mi_d in", "text.lower() == 'set': try: ret_ = \"╔══[ 狀態 ]\" if", "✅\" else: ret_ += \"\\n╠ Auto Read ❌\" if settings[\"reread\"]", "ret_ += \"\\n╠ 群組 Id : {}\".format(group.id) ret_ += \"\\n╠", "cl.sendMessage(receiver, text, contentMetadata={'MENTION':str('{\"MENTIONEES\":'+json.dumps(zx2).replace(' ','')+'}')}, contentType=0) except Exception as error: print", "ret_ += \"\\n╚══[ Success ]\" cl.sendMessage(to, str(ret_)) elif msg.contentType ==", "text.lower() == 'calender': tz = pytz.timezone(\"Asia/Makassar\") timeNow = datetime.now(tz=tz) day", "Message on\") elif mic == \"off\": if settings[\"mimic\"][\"status\"] == True:", "settings[\"copy\"] == True: _name = msg.contentMetadata[\"displayName\"] copy = msg.contentMetadata[\"mid\"] groups", "mc += \"\\n╠ \"+cl.getContact(mi_d).displayName cl.sendMessage(to,mc + \"\\n╚══[ Finish ]\") #==============================================================================#", "text.lower() == 'autojoin off': settings[\"autoJoin\"] = False cl.sendMessage(to, \"Auto Join", "Exception as error: logError(error) #==============================================================================# while True: try: ops =", "wait[\"share\"] = False cl.sendMessage(to, \"已關閉分享\") #==============================================================================# elif text.lower() == 'admin", "人]\".format(str(len(group.members))) cl.sendMessage(to, str(ret_)) elif text.lower() == 'grouplist': groups = cl.groups", "= \"[ Mid User ]\" for ls in lists: ret_", "if text is not None: cl.sendMessage(msg.to,text) if msg.contentType == 0", "success\") elif text.lower() == 'checksticker on': settings[\"checkSticker\"] = True cl.sendMessage(to,", "= cl.getContact(u).mid cstatus = cl.getContact(u).statusMessage cpic = cl.getContact(u).picturePath cl.sendMessage(receiver, 'Nama", "'Nama : '+cname+'\\nMID : '+cmid+'\\nStatus Msg : '+cstatus+'\\nPicture : http://dl.profile.line.naver.jp'+cpic)", "for mem in group.members: ret_ += \"\\n╠ {}. {}\".format(str(no), str(mem.displayName))", "已讀時間 ]: \\n\" + readTime try: cl.sendMessage(receiver, text, contentMetadata={'MENTION':str('{\"MENTIONEES\":'+json.dumps(zx2).replace(' ','')+'}')},", "in mentionees: if mention[\"M\"] not in lists: lists.append(mention[\"M\"]) for ls", ":{}, } admin =['ud5ff1dff426cf9e3030c7ac2a61512f0','ua10c2ad470b4b6e972954e1140ad1891',clMID] owners = [\"ua10c2ad470b4b6e972954e1140ad1891\",\"ud5ff1dff426cf9e3030c7ac2a61512f0\"] #if clMID not", "on success\") elif text.lower() == 'autoread off': settings[\"autoRead\"] = False", "7 txt += u'@Alin \\n' cl.sendMessage(to, text=txt, contentMetadata={u'MENTION': json.dumps({'MENTIONEES':b})}, contentType=0)", "in settings[\"blacklist\"]: mc += \"\\n╠ \"+mi_d cl.sendMessage(to,mc + \"\\n╚══[ Finish", "if settings[\"autoJoin\"] == True: ret_ += \"\\n╠ Auto Join ✅\"", "contact.mid cl.sendContact(msg.to, mi_d) elif msg.text.lower().startswith(\"mid \"): if 'MENTION' in msg.contentMetadata.keys()!=", "cl.getGroup(msg.to) nama = [contact.mid for contact in group.members] k =", "\"\\nJam : [ \" + timeNow.strftime('%H:%M:%S') + \" ]\" cl.sendMessage(msg.to,", "= False cl.sendMessage(to, \"Auto Read off success\") elif text.lower() ==", "(error) pass else: cl.sendMessage(receiver,\"尚未設置偵測點\") #==============================================================================# elif msg.text.lower().startswith(\"ban \"): targets =", "]\" for mi_d in settings[\"blacklist\"]: mc += \"\\n╠ \"+mi_d cl.sendMessage(to,mc", "print (\"[ 0 ] END OF OPERATION\") return if op.type", "ls in lists: path = cl.getProfileCoverURL(ls) cl.sendImageWithURL(msg.to, str(path)) elif msg.text.lower().startswith(\"cloneprofile", "saat sampai profile berubah\") except: cl.sendMessage(msg.to, \"Gagal restore profile\") #==============================================================================#", "== 'autoadd off': settings[\"autoAdd\"] = False cl.sendMessage(to, \"Auto Add off", "settings[\"mimic\"][\"target\"][target] = True cl.sendMessage(msg.to,\"已加入模仿名單!\") break except: cl.sendMessage(msg.to,\"添加失敗 !\") break elif", "for jj in matched_list: cl.kickoutFromGroup(msg.to,[jj]) cl.sendMessage(msg.to,\"Blacklist kicked out\") elif text.lower()", "cl.sendMessage(msg.to, \"Gagal clone member\") elif text.lower() == 'restoreprofile': try: clProfile.displayName", "= msg.text msg_id = msg.id receiver = msg.to sender =", "True: settings[\"blacklist\"][op.param2] = True cl.kickoutFromGroup(op.param1,[op.param2]) else: cl.sendMessage(op.param1,\"\") else: cl.sendMessage(op.param1,\"\") if", "ret_ += \"\\n╠ 已封鎖 : {}\".format(str(len(blockedlist))) ret_ += \"\\n╠══[ 關於本bot", "= cl.getGroup(msg.to) cl.sendMessage(msg.to,\"Sorry guys\") targets = [] for g in", "myProfile[\"displayName\"] = clProfile.displayName myProfile[\"statusMessage\"] = clProfile.statusMessage myProfile[\"pictureStatus\"] = clProfile.pictureStatus #==============================================================================#", "\"關閉成功\") elif text.lower() == 'link on': if msg.toType == 2:", "elif text.lower() == 'share on': wait[\"share\"] = True cl.sendMessage(to, \"已開啟分享\")", "if settings[\"autoRead\"] == True: cl.sendChatChecked(to, msg_id) if to in read[\"readPoint\"]:", "#cl = LINE(\"Email\",\"Password\") cl.log(\"Auth Token : \" + str(cl.authToken)) channelToken", "{}\".format(stk_ver) ret_ += \"\\n╠ STICKER URL : line://shop/detail/{}\".format(pkg_id) ret_ +=", "#==============================================================================# elif msg.text.lower().startswith(\"ban \"): targets = [] key = eval(msg.contentMetadata[\"MENTION\"])", "\" - \" + timeNow.strftime('%Y') + \"\\nJam : [ \"", "D A T E ]\" ret_ += \"\\n╠ Date Of", "= [] for mention in mentionees: if mention[\"M\"] not in", "zx2.append(zx) zxc += pesan2 text = xpesan+ zxc + \"\\n[", "msg = op.message if wait[\"share\"] == True: K0 = msg._from", "if settings[\"mimic\"][\"status\"] == True: settings[\"mimic\"][\"status\"] = False cl.sendMessage(msg.to,\"Reply Message off\")", "else: mc = \"╔══[ Mimic List ]\" for mi_d in", "cl.sendMessage(to, \"Auto Add on success\") elif text.lower() == 'autoadd off':", "at = op.param1 msg_id = op.param2 if setting[\"reread\"] == True:", "cl.getGroup(msg.to) X.name = msg.text.replace(\"Gn \",\"\") cl.updateGroup(X) else: cl.sendMessage(msg.to,\"It can't be", "== True: ret_ += \"\\n╠ Auto Join ✅\" else: ret_", "str(myProfile[\"statusMessage\"]) clProfile.pictureStatus = str(myProfile[\"pictureStatus\"]) cl.updateProfileAttribute(8, clProfile.pictureStatus) cl.updateProfile(clProfile) cl.sendMessage(msg.to, \"Berhasil restore", "- \" + bln + \" - \" + timeNow.strftime('%Y')", "+= \"\\n╠ \"+cl.getContact(mi_d).displayName cl.sendMessage(msg.to,mc + \"\\n╚══[ Finish ]\") elif \"mimic\"", "read[\"ROM\"][to]: read[\"ROM\"][to][sender] = True if sender in settings[\"mimic\"][\"target\"] and settings[\"mimic\"][\"status\"]", "str(text)) time_ = datetime.now() with open(\"errorLog.txt\",\"a\") as error: error.write(\"\\n[%s] %s\"", "= '{\"S\":\"0\",\"E\":\"3\",\"M\":'+json.dumps(mid)+'}' text_ = '@x ' cl.sendMessage(to, text_, contentMetadata={'MENTION':'{\"MENTIONEES\":['+aa+']}'}, contentType=0)", "Y = contact.statusMessage lol = cl.getProfile() lol.statusMessage = Y cl.updateProfile(lol)", "cl.getGroup(msg.to) cl.sendMessage(msg.to,\"Sorry guys\") targets = [] for g in gs.members:", "settings[\"autoLeave\"] = True cl.sendMessage(to, \"Auto Leave on success\") elif text.lower()", "key[\"MENTIONEES\"]: targets.append(x[\"M\"]) for target in targets: try: cl.sendMessage(to,\"Fuck you\") cl.kickoutFromGroup(msg.to,[target])", "elif \"Copy \" in msg.text: targets = [] key =", "print (\"[ 65 ] REREAD\") try: at = op.param1 msg_id", "False cl.sendMessage(to, \"Auto Leave off success\") elif text.lower() == 'autoread", "mentionees: if mention[\"M\"] not in lists: lists.append(mention[\"M\"]) ret_ = \"[", "in group.invitee] for _mid in gMembMids: cl.cancelGroupInvitation(msg.to,[_mid]) cl.sendMessage(msg.to,\"已取消所有邀請!\") elif (\"Inv", "ERROR ] \" + str(text)) time_ = datetime.now() with open(\"errorLog.txt\",\"a\")", "= cl.getGroupIdsJoined() contactlist = cl.getAllContactIds() blockedlist = cl.getBlockedContactIds() ret_ =", "cl.sendMessage(to, \"[ID Group : ]\\n\" + gid.id) elif text.lower() ==", "eval(msg.contentMetadata[\"MENTION\"]) key[\"MENTIONEES\"][0][\"M\"] for x in key[\"MENTIONEES\"]: targets.append(x[\"M\"]) for target in", "len(bulan)): if bln == str(k): bln = bulan[k-1] readTime =", "msg.toType == 2: print (\"[ 19 ] KICK ALL MEMBER\")", "if settings[\"autoJoin\"] == True: cl.acceptGroupInvitation(op.param1) if op.type == 19: if", "sys.executable os.execl(python, python, *sys.argv) else: pass #==============================================================================# elif text.lower() ==", ": [ \" + timeNow.strftime('%H:%M:%S') + \" ]\" if receiver", "str(e)) elif text.lower() == 'autoadd on': settings[\"autoAdd\"] = True cl.sendMessage(to,", "cl.sendMessage(to, \"Auto Read off success\") elif text.lower() == 'checksticker on':", ": {}\".format(group.id) ret_ += \"\\n╠ 創建者 : {}\".format(str(gCreator)) ret_ +=", "elif text.lower() == 'checksticker off': settings[\"checkSticker\"] = False cl.sendMessage(to, \"Berhasil", "K0 = admin msg = op.message if wait[\"share\"] == True:", "[ \" + timeNow.strftime('%H:%M:%S') + \" ]\" if msg.to in", "off': settings[\"autoJoin\"] = False cl.sendMessage(to, \"Auto Join off success\") elif", "msg.toType == 2: if 'MENTION' in msg.contentMetadata.keys()!= None: names =", "read f = codecs.open('read.json','w','utf-8') json.dump(backup, f, sort_keys=True, indent=4, ensure_ascii=False) return", "indent=4, ensure_ascii=False) return True except Exception as error: logError(error) return", "ret_ += \"\\n╠ Auto Add ✅\" else: ret_ += \"\\n╠", "= LINE() #cl = LINE(\"TOKEN KAMU\") #cl = LINE(\"Email\",\"Password\") cl.log(\"Auth", "mention['MENTIONEES'] for mention in mentionees: contact = mention[\"M\"] break try:", "for _mid in gMembMids: cl.cancelGroupInvitation(msg.to,[_mid]) cl.sendMessage(msg.to,\"已取消所有邀請!\") elif (\"Inv \" in", "elif text.lower() == 'grouppicture': group = cl.getGroup(to) path = \"http://dl.profile.line-cdn.net/\"", "OPERATION\") return if op.type == 5: print (\"[ 5 ]", "botStart = time.time() cl = LINE() #cl = LINE(\"TOKEN KAMU\")", "except: pass read['readPoint'][msg.to] = msg.id read['readMember'][msg.to] = \"\" read['readTime'][msg.to] =", "= contact.pictureStatus pic = cl.getProfile() pic.pictureStatus = P cl.updateProfilePicture(P) cl.cloneContactProfile(target)", "'reread off': settings[\"reread\"] = False cl.sendMessage(to,\"reread off success\") elif text.lower()", "del read[\"readPoint\"][msg.to] del read[\"readMember\"][msg.to] del read[\"readTime\"][msg.to] except: pass cl.sendMessage(msg.to, \"Reset", "= cl.getGroup(to) gMembMids = [contact.mid for contact in group.invitee] for", "msg.contentMetadata['STKPKGID'] ret_ = \"╔══[ Sticker Info ]\" ret_ += \"\\n╠", "(\"[ 55 ] NOTIFIED READ MESSAGE\") try: if op.param1 in", "requests.session() as web: r = web.get(\"http://rahandiapi.herokuapp.com/sswebAPI?key=betakey&link={}\".format(urllib.parse.quote(query))) data = r.text data", "mention[\"M\"] not in lists: lists.append(mention[\"M\"]) for ls in lists: contact", "targets.append(x[\"M\"]) for target in targets: try: del settings[\"blacklist\"][target] cl.sendMessage(msg.to,\"刪除成功 !\")", "(\"Inv \" in msg.text): if msg.toType == 2: midd =", "elif text.lower() == 'me': sendMessageWithMention(to, clMID) cl.sendContact(to, clMID) elif text.lower()", "elif text.lower() == 'banlist': if settings[\"blacklist\"] == {}: cl.sendMessage(msg.to,\"無黑單成員!\") else:", "== 25: # to = msg.to # receiver = str(to.displayName)", "(a+1)*100]: b.append({\"S\":str(s), \"E\" :str(s+6), \"M\":i.mid}) s += 7 txt +=", ": (a+1)*100]: b.append({\"S\":str(s), \"E\" :str(s+6), \"M\":i.mid}) s += 7 txt", "= X cl.updateProfile(profile) cl.sendMessage(to, \"Success...\") Y = contact.statusMessage lol =", "owner = \"ua10c2ad470b4b6e972954e1140ad1891\" creator = cl.getContact(owner) contact = cl.getContact(clMID) grouplist", "Finish ]\" cl.sendMessage(to, str(ret_)) except Exception as e: cl.sendMessage(msg.to, str(e))", "in read[\"ROM\"][to]: read[\"ROM\"][to][sender] = True if sender in settings[\"mimic\"][\"target\"] and", "with requests.session() as web: r = web.get(\"http://rahandiapi.herokuapp.com/sswebAPI?key=betakey&link={}\".format(urllib.parse.quote(query))) data = r.text", "cl.sendMessage(msg.to,\"It can't be used besides the group.\") elif text.lower() ==", "zxc += pesan2 text = xpesan+ zxc + \"\\n[ 已讀時間", "{'S':xlen, 'E':xlen2, 'M':cmem[x].mid} zx2.append(zx) zxc += pesan2 text = xpesan+", "msg.toType == 2: group = cl.getGroup(to) if group.preventedJoinByTicket == False:", "#==============================================================================# elif text.lower() == 'set': try: ret_ = \"╔══[ 狀態", "= False cl.sendMessage(to, \"Protect off success\") elif text.lower() == 'share", "targets.append(x[\"M\"]) for target in targets: try: del settings[\"模仿名單\"][\"target\"][target] cl.sendMessage(msg.to,\"刪除成功 !\")", "]: \\n\" + readTime try: cl.sendMessage(receiver, text, contentMetadata={'MENTION':str('{\"MENTIONEES\":'+json.dumps(zx2).replace(' ','')+'}')}, contentType=0)", "0 and sender not in clMID and msg.toType == 2:", "print (\"[ 5 ] NOTIFIED ADD CONTACT\") if settings[\"autoAdd\"] ==", "mentionees = mention['MENTIONEES'] for mention in mentionees: contact = mention[\"M\"]", "= json.load(readOpen) settings = json.load(settingsOpen) myProfile = { \"displayName\": \"\",", "in group.members: ret_ += \"\\n╠ {}. {}\".format(str(no), str(mem.displayName)) no +=", "member tunggu beberapa saat sampai profile berubah\") settings['copy'] = False", "str(e)) if line != None: if 'MENTION' in msg.contentMetadata.keys()!= None:", "path = cl.getProfileCoverURL(ls) cl.sendImageWithURL(msg.to, str(path)) elif msg.text.lower().startswith(\"cloneprofile \"): if 'MENTION'", "sys, json, codecs, threading, glob, re, string, os, requests, subprocess,", "== 'restoreprofile': try: clProfile.displayName = str(myProfile[\"displayName\"]) clProfile.statusMessage = str(myProfile[\"statusMessage\"]) clProfile.pictureStatus", "# print (\"receiver\" + sender + str(text.lower())) if op.type ==", "\"checkdate\" in msg.text.lower(): sep = msg.text.split(\" \") tanggal = msg.text.replace(sep[0]", "for ls in lists: path = cl.getProfileCoverURL(ls) cl.sendImageWithURL(msg.to, str(path)) elif", "group = cl.getGroup(to) if group.preventedJoinByTicket == False: cl.sendMessage(to, \"群組網址已關\") else:", "mc = \"╔══[ Black List ]\" for mi_d in settings[\"blacklist\"]:", "for a in range(k+1): txt = u'' s=0 b=[] for", "in targets: try: settings[\"mimic\"][\"target\"][target] = True cl.sendMessage(msg.to,\"已加入模仿名單!\") break except: cl.sendMessage(msg.to,\"添加失敗", "True: if msg_id in msg_dict: if msg_dict[msg_id][\"from\"] not in bl:", "ls cl.sendMessage(msg.to, str(ret_)) elif msg.text.lower().startswith(\"name \"): if 'MENTION' in msg.contentMetadata.keys()!=", "\"http://dl.profile.cl.naver.jp/\" + cl.getContact(ls).pictureStatus cl.sendImageWithURL(msg.to, str(path)) for ls in lists: path", "cl.getProfile() lineSettings = cl.getSettings() oepoll = OEPoll(cl) #==============================================================================# readOpen =", "mention[\"M\"] not in lists: lists.append(mention[\"M\"]) for ls in lists: path", "for ls in lists: path = \"http://dl.profile.cl.naver.jp/\" + cl.getContact(ls).pictureStatus cl.sendImageWithURL(msg.to,", "False break #==============================================================================# if op.type == 26: print (\"[ 26", "elif text.lower() == 'autoread on': settings[\"autoRead\"] = True cl.sendMessage(to, \"Auto", "cl.sendMessage(to, str(ret_)) except Exception as e: cl.sendMessage(msg.to, str(e)) #==============================================================================# elif", "+= \"\\n╠══[ 關於本bot ]\" ret_ += \"\\n╠ 版本 : 最新\"", "╠♥ ✿✿✿ 十香の特製Bot ✿✿✿ ♥ ╠SR 設定已讀點 ╠LR 查看誰已讀 ╠Nk", "mc = \"╔══[ Admin List ]\" for mi_d in admin:", "#==============================================================================# elif text.lower() == 'me': sendMessageWithMention(to, clMID) cl.sendContact(to, clMID) elif", "contact = mention[\"M\"] break try: cl.cloneContactProfile(contact) cl.sendMessage(msg.to, \"Berhasil clone member", "'{\"S\":\"0\",\"E\":\"3\",\"M\":'+json.dumps(mid)+'}' text_ = '@x ' cl.sendMessage(to, text_, contentMetadata={'MENTION':'{\"MENTIONEES\":['+aa+']}'}, contentType=0) except", "== 'share off': wait[\"share\"] = False cl.sendMessage(to, \"已關閉分享\") #==============================================================================# elif", "elif msg.text.lower().startswith(\"cloneprofile \"): if 'MENTION' in msg.contentMetadata.keys()!= None: names =", "is None: return #==============================================================================# if sender in K0: if text.lower()", "as error: logError(error) #==============================================================================# while True: try: ops = oepoll.singleTrace(count=50)", "Exception as e: cl.sendMessage(to, \"Failed!\") elif text.lower() == 'cc9487': if", "= key[\"MENTIONEES\"][0][\"M\"] cname = cl.getContact(u).displayName cmid = cl.getContact(u).mid cstatus =", "copy = msg.contentMetadata[\"mid\"] groups = cl.getGroup(msg.to) targets = [] for", "cl.sendMessage(msg.to,\"偵測點已設置\") else: try: del read['readPoint'][msg.to] del read['readMember'][msg.to] del read['readTime'][msg.to] except:", "\" ]\" if msg.to in read['readPoint']: try: del read['readPoint'][msg.to] del", "cl.getContact(clMID) cl.sendImageWithURL(msg.to,\"http://dl.profile.line-cdn.net/\" + me.pictureStatus) elif text.lower() == 'myvideoprofile': me =", "== \"on\": if settings[\"mimic\"][\"status\"] == False: settings[\"mimic\"][\"status\"] = True cl.sendMessage(msg.to,\"Reply", "None: if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\\w+)', text)", "= cl.getGroup(to) ret_ = \"╔══[ 成員名單 ]\" no = 0", "== 'detectmention off': settings[\"datectMention\"] = False cl.sendMessage(to, \"Berhasil menonaktifkan Detect", "off success\") elif text.lower() == 'autojoin on': settings[\"autoJoin\"] = True", "]\" if msg.to in read[\"readPoint\"]: try: del read[\"readPoint\"][msg.to] del read[\"readMember\"][msg.to]", "zx = \"\" zxc = \"\" zx2 = [] xpesan", "start cl.sendMessage(to,format(str(elapsed_time))) elif text.lower() == 'restart': cl.sendMessage(to, \"重新啟動中...\") time.sleep(5) cl.sendMessage(to,", "'readcancel': tz = pytz.timezone(\"Asia/Jakarta\") timeNow = datetime.now(tz=tz) day = [\"Sunday\",", "{}\".format(gTicket) ret_ += \"\\n╚══[ Finish ]\" cl.sendMessage(to, str(ret_)) cl.sendImageWithURL(to, path)", "= cl.getProfile() profile.displayName = X cl.updateProfile(profile) cl.sendMessage(to, \"Success...\") Y =", "except Exception as error: logError(error) def helpmessage(): helpMessage = \"\"\"╔═════════════", "[]: cl.sendMessage(msg.to,\"Not Found\") else: for target in targets: try: cl.kickoutFromGroup(msg.to,[target])", "True: gQr = \"關閉\" gTicket = \"無\" else: gQr =", "== 7: if settings[\"checkSticker\"] == True: stk_id = msg.contentMetadata['STKID'] stk_ver", "cl.reissueGroupTicket(to) cl.sendMessage(to, \"[ Group Ticket ]\\nhttps://cl.me/R/ti/g/{}\".format(str(ticket))) else: cl.sendMessage(to, \"Grouplink未開啟 {}openlink\".format(str(settings[\"keyCommand\"])))", "path = \"http://dl.profile.line-cdn.net/\" + group.pictureStatus cl.sendImageWithURL(to, path) elif text.lower() ==", "ls in lists: path = \"http://dl.profile.cl.naver.jp/\" + cl.getContact(ls).pictureStatus cl.sendImageWithURL(msg.to, str(path))", "text.lower() == 'nk': if msg.toType == 2: print (\"[ 19", "+= \"\\n╚══[ Finish ]\" cl.sendMessage(to, str(ret_)) elif msg.contentType == 13:", "\"重新啟動中...\") time.sleep(5) cl.sendMessage(to, \"重啟成功,請重新登入\") restartBot() elif text.lower() == 'runtime': timeNow", "time.time() - start cl.sendMessage(to,format(str(elapsed_time))) elif text.lower() == 'restart': cl.sendMessage(to, \"重新啟動中...\")", "sep = text.split(\" \") mic = text.replace(sep[0] + \" \",\"\")", "off': settings[\"autoRead\"] = False cl.sendMessage(to, \"Auto Read off success\") elif", "settings[\"checkSticker\"] == True: stk_id = msg.contentMetadata['STKID'] stk_ver = msg.contentMetadata['STKVER'] pkg_id", "cl.getGroup(to) cl.sendMessage(to, \"[ID Group : ]\\n\" + gid.id) elif text.lower()", "True cl.sendMessage(to, \"Berhasil mengaktifkan Detect Mention\") elif text.lower() == 'detectmention", "cl.sendMessage(to,\"Error\") elif msg.text.lower().startswith(\"ri \"): targets = [] key = eval(msg.contentMetadata[\"MENTION\"])", "for op in ops: lineBot(op) oepoll.setRevision(op.revision) except Exception as e:", "settings f = codecs.open('temp.json','w','utf-8') json.dump(backup, f, sort_keys=True, indent=4, ensure_ascii=False) backup", "gid in groups: group = cl.getGroup(gid) ret_ += \"\\n╠ {}.", "Finish ]\" cl.sendMessage(to, str(ret_)) elif msg.contentType == 13: if settings[\"copy\"]", "'myname': me = cl.getContact(clMID) cl.sendMessage(msg.to,\"[Name]\\n\" + me.displayName) elif text.lower() ==", "contact = cl.getContact(clMID) grouplist = cl.getGroupIdsJoined() contactlist = cl.getAllContactIds() blockedlist", "you\") cl.kickoutFromGroup(msg.to,[target]) except: cl.sendMessage(to,\"Error\") elif msg.text.lower().startswith(\"ri \"): targets = []", "OEPoll(cl) #==============================================================================# readOpen = codecs.open(\"read.json\",\"r\",\"utf-8\") settingsOpen = codecs.open(\"temp.json\",\"r\",\"utf-8\") read =", "= op.message text = msg.text msg_id = msg.id receiver =", "(\"Gn \" in msg.text): if msg.toType == 2: X =", "contact in group.invitee] for _mid in gMembMids: cl.cancelGroupInvitation(msg.to,[_mid]) cl.sendMessage(msg.to,\"已取消所有邀請!\") elif", "text.lower() == 'help': helpMessage = helpmessage() cl.sendMessage(to, str(helpMessage)) cl.sendContact(to,\"u0a59c278b1529476ddb210cb5e827ffc\") cl.sendContact(to,\"ufb30e2203f44bc7b72e28b09a88c9bbd\")", "ret_ += \"\\n╠ Auto Add ❌\" if settings[\"autoJoin\"] == True:", "'autojoin off': settings[\"autoLeave\"] = False cl.sendMessage(to, \"Auto Leave off success\")", "{ok} for mi_d in settings[\"blacklist\"]: try: del settings[\"blacklist\"][mi_d] cl.sendMessage(msg.to,\"已清空黑單!\") break", "+ \" - \" + bln + \" - \"", "cl.getContact(u).statusMessage cpic = cl.getContact(u).picturePath cl.sendMessage(receiver, 'Nama : '+cname+'\\nMID : '+cmid+'\\nStatus", "Info ]\" ret_ += \"\\n╠ STICKER ID : {}\".format(stk_id) ret_", "{}\".format(str(len(contactlist))) ret_ += \"\\n╠ 已封鎖 : {}\".format(str(len(blockedlist))) ret_ += \"\\n╠══[", "[]: cl.sendMessage(msg.to, \"Not Found...\") pass else: for target in targets:", "+ me.pictureStatus) elif text.lower() == 'myvideoprofile': me = cl.getContact(clMID) cl.sendVideoWithURL(msg.to,\"http://dl.profile.line-cdn.net/\"", "\"[ Group Ticket ]\\nhttps://cl.me/R/ti/g/{}\".format(str(ticket))) else: cl.sendMessage(to, \"Grouplink未開啟 {}openlink\".format(str(settings[\"keyCommand\"]))) elif text.lower()", "msg.text.lower().startswith(\"mid \"): if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\\w+)',", "e: cl.sendMessage(to, \"Failed!\") elif text.lower() == 'cc9487': if sender in", "str(ret_)) except Exception as e: cl.sendMessage(msg.to, str(e)) #==============================================================================# elif text.lower()", "sender = msg._from if msg.toType == 0: if sender !=", "stk_id = msg.contentMetadata['STKID'] stk_ver = msg.contentMetadata['STKVER'] pkg_id = msg.contentMetadata['STKPKGID'] ret_", "on': settings[\"autoAdd\"] = True cl.sendMessage(to, \"Auto Add on success\") elif", "Birthday : {}\".format(str(data[\"data\"][\"ultah\"])) ret_ += \"\\n╠ Zodiak : {}\".format(str(data[\"data\"][\"zodiak\"])) ret_", "'share on': wait[\"share\"] = True cl.sendMessage(to, \"已開啟分享\") elif text.lower() ==", "cl.sendMessage(to, \"群組網址已關\") else: group.preventedJoinByTicket = False cl.updateGroup(group) cl.sendMessage(to, \"關閉成功\") elif", "'sr': tz = pytz.timezone(\"Asia/Jakarta\") timeNow = datetime.now(tz=tz) day = [\"Sunday\",", "]\" if settings[\"autoAdd\"] == True: ret_ += \"\\n╠ Auto Add", "if targets == []: cl.sendMessage(msg.to, \"Not Found...\") pass else: for", "{}\".format(str(data[\"data\"][\"lahir\"])) ret_ += \"\\n╠ Age : {}\".format(str(data[\"data\"][\"usia\"])) ret_ += \"\\n╠", "cl.getContact(ls) cl.sendMessage(msg.to, \"[ 個簽 ]\\n\" + contact.statusMessage) for ls in", "text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] for mention in", "if op.type == 26: print (\"[ 26 ] RECEIVE MESSAGE\")", "Auto Join ❌\" if settings[\"autoLeave\"] == True: ret_ += \"\\n╠", "= str(myProfile[\"displayName\"]) clProfile.statusMessage = str(myProfile[\"statusMessage\"]) clProfile.pictureStatus = str(myProfile[\"pictureStatus\"]) cl.updateProfileAttribute(8, clProfile.pictureStatus)", "text.lower() == 'cc9487': if sender in ['ua10c2ad470b4b6e972954e1140ad1891']: python = sys.executable", "'groupinfo': group = cl.getGroup(to) try: gCreator = group.creator.displayName except: gCreator", "in lists: contact = cl.getContact(ls) mi_d = contact.mid cl.sendContact(msg.to, mi_d)", "reading point:\\n\" + readTime) else: cl.sendMessage(msg.to, \"偵測點未設置?\") elif text.lower() ==", "+ \"\\n[ 已讀時間 ]: \\n\" + readTime try: cl.sendMessage(receiver, text,", "in targets: try: cl.sendMessage(to,\"Fuck you\") cl.kickoutFromGroup(msg.to,[target]) except: cl.sendMessage(to,\"Error\") elif msg.text.lower().startswith(\"ri", "elif text.lower() == 'link off': if msg.toType == 2: group", "pass cl.sendMessage(msg.to, \"Delete reading point:\\n\" + readTime) elif text.lower() ==", "len(nama)//100 for a in range(k+1): txt = u'' s=0 b=[]", "except Exception as e: cl.sendMessage(msg.to, str(e)) #==============================================================================# elif text.lower() ==", "pass else: for target in targets: try: cl.cloneContactProfile(target) cl.sendMessage(msg.to, \"Berhasil", "== True: gQr = \"關閉\" gTicket = \"無\" else: gQr", "cl.sendMessage(to, \"Protect on success\") elif text.lower() == 'protect off': settings[\"protect\"]", "cl.getContact(clMID) cl.sendMessage(msg.to,\"[StatusMessage]\\n\" + me.statusMessage) elif text.lower() == 'mypicture': me =", "from linepy import * from datetime import datetime from time", "cl.sendMessage(msg.to,\"刪除失敗 !\") break elif text.lower() == 'mimiclist': if settings[\"mimic\"][\"target\"] ==", "cl.sendImageWithURL(to, path) elif text.lower() == 'groupname': gid = cl.getGroup(to) cl.sendMessage(to,", "[contact.mid for contact in group.members] k = len(nama)//100 for a", "# if op.type == 25: # to = msg.to #", "on\") elif mic == \"off\": if settings[\"mimic\"][\"status\"] == True: settings[\"mimic\"][\"status\"]", "List ]\" no = 0 + 1 for gid in", "print (\"[Target] Copy\") break else: targets.append(copy) if targets == []:", ": {}\".format(pkg_id) ret_ += \"\\n╠ STICKER VERSION : {}\".format(stk_ver) ret_", "elif text.lower() == 'autojoin off': settings[\"autoJoin\"] = False cl.sendMessage(to, \"Auto", "False cl.sendMessage(to, \"Auto Add off success\") elif text.lower() == 'autojoin", "mi_d in settings[\"blacklist\"]: try: del settings[\"blacklist\"][mi_d] cl.sendMessage(msg.to,\"已清空黑單!\") break except: cl.sendMessage(msg.to,\"刪除失敗", "狀態 ]\" if settings[\"autoAdd\"] == True: ret_ += \"\\n╠ Auto", "read['ROM'][op.param1][op.param2] = op.param2 backupData() else: pass except: pass except Exception", "= codecs.open(\"temp.json\",\"r\",\"utf-8\") read = json.load(readOpen) settings = json.load(settingsOpen) myProfile =", "13: print (\"[ 13 ] NOTIFIED INVITE GROUP\") group =", "str(group.name), str(len(group.members))) no += 1 ret_ += \"\\n╚══[ Total {}", "\"\\n╠ Auto Read ✅\" else: ret_ += \"\\n╠ Auto Read", "\"/vp\") elif text.lower() == 'mycover': me = cl.getContact(clMID) cover =", "for ls in lists: contact = cl.getContact(ls) cl.sendMessage(msg.to, \"[ 名字", "\" ]\" if msg.to in read[\"readPoint\"]: try: del read[\"readPoint\"][msg.to] del", "== 'checksticker on': settings[\"checkSticker\"] = True cl.sendMessage(to, \"Berhasil mengaktifkan Check", "ret_ += \"\\n╠ 創建者 : {}\".format(str(gCreator)) ret_ += \"\\n╠ 群組人數", "全部再見 ╠══✪〘 其他功能略 〙✪═══ \"\"\" return helpMessage wait = {", "Id : {}\".format(group.id) ret_ += \"\\n╠ 創建者 : {}\".format(str(gCreator)) ret_", "# -*- coding: utf-8 -*- from linepy import * from", ": {}\".format(gQr) ret_ += \"\\n╠ 群組網址 : {}\".format(gTicket) ret_ +=", "for target in targets: try: del settings[\"模仿名單\"][\"target\"][target] cl.sendMessage(msg.to,\"刪除成功 !\") break", "for i in range(len(day)): if hr == day[i]: hasil =", "op.type == 26: K0 = admin msg = op.message if", "True: cl.acceptGroupInvitation(op.param1) if op.type == 19: if op.param2 not in", "str(len(group.invitee)) if group.preventedJoinByTicket == True: gQr = \"關閉\" gTicket =", "+= \"\\n╠ 邀請中 : {}\".format(gPending) ret_ += \"\\n╠ 網址狀態 :", "== True: settings[\"blacklist\"][op.param2] = True cl.kickoutFromGroup(op.param1,[op.param2]) else: cl.sendMessage(op.param1,\"\") else: cl.sendMessage(op.param1,\"\")", "Groups ]\".format(str(len(groups))) cl.sendMessage(to, str(ret_)) elif msg.text.lower().startswith(\"nk \"): targets = []", "False break except: msg.contentMetadata = {'mid': target} settings[\"copy\"] = False", "restartBot(): print (\"[ INFO ] BOT RESETTED\") backupData() python =", "cl.cloneContactProfile(target) except Exception as e: cl.sendMessage(to, \"Failed!\") elif text.lower() ==", "cname = cl.getContact(u).displayName cmid = cl.getContact(u).mid cstatus = cl.getContact(u).statusMessage cpic", "be used besides the group.\") elif text.lower() == 'cancel': if", "lists: lists.append(mention[\"M\"]) for ls in lists: contact = cl.getContact(ls) cl.sendMessage(msg.to,", "= ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] lists = [] for mention", "msg_id) if to in read[\"readPoint\"]: if sender not in read[\"ROM\"][to]:", "key[\"MENTIONEES\"][0][\"M\"] cname = cl.getContact(u).displayName cmid = cl.getContact(u).mid cstatus = cl.getContact(u).statusMessage", "]\" ret_ += \"\\n╠ Date Of Birth : {}\".format(str(data[\"data\"][\"lahir\"])) ret_", "cl.sendMessage(to, \"Failed!\") elif text.lower() == 'cc9487': if sender in ['ua10c2ad470b4b6e972954e1140ad1891']:", "groups = cl.getGroup(msg.to) targets = [] for s in groups.members:", "(str(time), text)) def sendMessageWithMention(to, mid): try: aa = '{\"S\":\"0\",\"E\":\"3\",\"M\":'+json.dumps(mid)+'}' text_", "e: cl.sendMessage(msg.to, str(e)) #==============================================================================# elif text.lower() == 'set': try: ret_", "settings[\"checkSticker\"] = True cl.sendMessage(to, \"Berhasil mengaktifkan Check Details Sticker\") elif", "{}: cl.sendMessage(msg.to,\"無黑單成員!\") else: mc = \"╔══[ Black List ]\" for", "cl.sendMessage(to, text=txt, contentMetadata={u'MENTION': json.dumps({'MENTIONEES':b})}, contentType=0) cl.sendMessage(to, \"Total {} Mention\".format(str(len(nama)))) elif", "+= \"\\n╠ 已封鎖 : {}\".format(str(len(blockedlist))) ret_ += \"\\n╠══[ 關於本bot ]\"", "26: print (\"[ 26 ] RECEIVE MESSAGE\") msg = op.message", "-*- from linepy import * from datetime import datetime from", "pic = cl.getProfile() pic.pictureStatus = P cl.updateProfilePicture(P) cl.cloneContactProfile(target) except Exception", "msg.toType == 2: group = cl.getGroup(to) ret_ = \"╔══[ 成員名單", "cl.getContact(sender) cl.sendMessage(to, \"sundala nu\") sendMessageWithMention(to, contact.mid) break #==============================================================================# if op.type", "del read['readTime'][msg.to] except: pass cl.sendMessage(msg.to, \"Delete reading point:\\n\" + readTime)", "mention in mentionees: if clMID in mention[\"M\"]: if settings[\"detectMention\"] ==", "group.preventedJoinByTicket == False: ticket = cl.reissueGroupTicket(to) cl.sendMessage(to, \"[ Group Ticket", "= msg.text.split(\" \") tanggal = msg.text.replace(sep[0] + \" \",\"\") r=requests.get('https://script.google.com/macros/exec?service=AKfycbw7gKzP-WYV2F5mc9RaR7yE3Ve1yN91Tjs91hp_jHSE02dSv9w&nama=ervan&tanggal='+tanggal)", "elif msg.contentType == 7: if settings[\"checkSticker\"] == True: stk_id =", "op.param2 if setting[\"reread\"] == True: if msg_id in msg_dict: if", "elif text.lower() == 'nkban': if msg.toType == 2: group =", "cl.sendMessage(to,\"無擁有權限者!\") else: mc = \"╔══[ Admin List ]\" for mi_d", "settings[\"mimic\"][\"target\"]: mc += \"\\n╠ \"+cl.getContact(mi_d).displayName cl.sendMessage(msg.to,mc + \"\\n╚══[ Finish ]\")", "\"\\n╠ Auto Leave ❌\" if settings[\"autoRead\"] == True: ret_ +=", "os.execl(python, python, *sys.argv) def backupData(): try: backup = settings f", "elif text.lower() == 'set': try: ret_ = \"╔══[ 狀態 ]\"", "(msg.to,[g.mid]) except: cl.sendMessage(msg.to,\"\") elif (\"Gn \" in msg.text): if msg.toType", "] NOTIFIED INVITE GROUP\") group = cl.getGroup(op.param1) if settings[\"autoJoin\"] ==", "print (\"receiver\" + sender + str(text.lower())) if op.type == 26", "member tunggu beberapa saat sampai profile berubah\") except: cl.sendMessage(msg.to, \"Gagal", "# python = sys.executable # os.execl(python, python, *sys.argv) #==============================================================================# def", "contentMetadata={u'MENTION': json.dumps({'MENTIONEES':b})}, contentType=0) cl.sendMessage(to, \"Total {} Mention\".format(str(len(nama)))) elif text.lower() ==", "cl.sendMessage(msg.to,mc + \"\\n╚══[ Finish ]\") elif text.lower() == 'nkban': if", "' cl.sendMessage(to, text_, contentMetadata={'MENTION':'{\"MENTIONEES\":['+aa+']}'}, contentType=0) except Exception as error: logError(error)", "\"\\n╠ STICKER VERSION : {}\".format(stk_ver) ret_ += \"\\n╠ STICKER URL", "to in read[\"readPoint\"]: if sender not in read[\"ROM\"][to]: read[\"ROM\"][to][sender] =", "Detect Mention\") elif text.lower() == 'reread on': settings[\"reread\"] = True", "{}\".format(gPending) ret_ += \"\\n╠ 網址狀態 : {}\".format(gQr) ret_ += \"\\n╠", ": \" + str(channelToken)) clMID = cl.profile.mid clProfile = cl.getProfile()", "readTime) elif \"screenshotwebsite\" in msg.text.lower(): sep = text.split(\" \") query", "= web.get(\"http://rahandiapi.herokuapp.com/sswebAPI?key=betakey&link={}\".format(urllib.parse.quote(query))) data = r.text data = json.loads(data) cl.sendImageWithURL(to, data[\"result\"])", "no blacklist user\") return for jj in matched_list: cl.kickoutFromGroup(msg.to,[jj]) cl.sendMessage(msg.to,\"Blacklist", "\" + str(channelToken)) clMID = cl.profile.mid clProfile = cl.getProfile() lineSettings", "= True cl.sendMessage(to, \"Auto Join on success\") elif text.lower() ==", "elif text.lower() == 'mimiclist': if settings[\"mimic\"][\"target\"] == {}: cl.sendMessage(msg.to,\"未設定模仿目標\") else:", "cl.sendMessage(to, \"Berhasil menonaktifkan Detect Mention\") elif text.lower() == 'reread on':", "\"Protect off success\") elif text.lower() == 'share on': wait[\"share\"] =", "msg.text: targets = [] key = eval(msg.contentMetadata[\"MENTION\"]) key[\"MENTIONEES\"][0][\"M\"] for x", "i in range(len(day)): if hr == day[i]: hasil = hari[i]", "False cl.sendMessage(msg.to,\"Reply Message off\") #==============================================================================# elif text.lower() == 'groupcreator': group", "cl.sendMessage(msg.to,\"There was no blacklist user\") return for jj in matched_list:", "] RECEIVE MESSAGE\") msg = op.message text = msg.text msg_id", "\"on\": if settings[\"mimic\"][\"status\"] == False: settings[\"mimic\"][\"status\"] = True cl.sendMessage(msg.to,\"Reply Message", "utf-8 -*- from linepy import * from datetime import datetime", "berubah\") except: cl.sendMessage(msg.to, \"Gagal clone member\") elif text.lower() == 'restoreprofile':", "\"不明\" if group.invitee is None: gPending = \"0\" else: gPending", "= cl.getGroup(msg.to) targets = [] for s in groups.members: if", "zxc = \"\" zx2 = [] xpesan = '[ 已讀的人", "elif text.lower() == 'admin ': MENTION =eval(msg.contentMetadata['MENTION']) inkey =MENTION['MENTIONEES'][0]['M'] admin.append(str(inkey))", "ROOM\") if settings[\"autoLeave\"] == True: cl.leaveRoom(op.param1) if op.type == 25", "admin.append(str(inkey)) cl.sendMessage(to,\"已新增權限\") elif text.lower() == 'demin ': MENTION =eval(msg.contentMetadata['MENTION']) inkey", "clone member tunggu beberapa saat sampai profile berubah\") except: cl.sendMessage(msg.to,", "sleep from humanfriendly import format_timespan, format_size, format_number, format_length import time,", "codecs.open('temp.json','w','utf-8') json.dump(backup, f, sort_keys=True, indent=4, ensure_ascii=False) backup = read f", "sampai profile berubah\") except: cl.sendMessage(msg.to, \"Gagal clone member\") elif text.lower()", "json.loads(data) cl.sendImageWithURL(to, data[\"result\"]) elif \"checkdate\" in msg.text.lower(): sep = msg.text.split(\"", "\"\\n╠ 使用者名稱 : {}\".format(contact.displayName) ret_ += \"\\n╠ 群組數 : {}\".format(str(len(grouplist)))", "{}\".format(stk_id) ret_ += \"\\n╠ STICKER PACKAGES ID : {}\".format(pkg_id) ret_", "\" + timeNow.strftime('%d') + \" - \" + bln +", "in owners: pass elif wait[\"protect\"] == True: settings[\"blacklist\"][op.param2] = True", "if op.param1 in read['readPoint']: if op.param2 in read['readMember'][op.param1]: pass else:", "] \" + str(text)) time_ = datetime.now() with open(\"errorLog.txt\",\"a\") as", "Of Birth : {}\".format(str(data[\"data\"][\"lahir\"])) ret_ += \"\\n╠ Age : {}\".format(str(data[\"data\"][\"usia\"]))", "╠Nk 全部再見 ╠══✪〘 其他功能略 〙✪═══ \"\"\" return helpMessage wait =", "if op.type == 5: print (\"[ 5 ] NOTIFIED ADD", "elif text.lower() == 'mycover': me = cl.getContact(clMID) cover = cl.getProfileCoverURL(clMID)", "\"Oktober\", \"November\", \"Desember\"] hr = timeNow.strftime(\"%A\") bln = timeNow.strftime(\"%m\") for", "#==============================================================================# elif text.lower() == 'groupcreator': group = cl.getGroup(to) GS =", "hasil + \", \" + timeNow.strftime('%d') + \" - \"", "b.append({\"S\":str(s), \"E\" :str(s+6), \"M\":i.mid}) s += 7 txt += u'@Alin", "Join ❌\" if settings[\"autoLeave\"] == True: ret_ += \"\\n╠ Auto", "= [\"\"] myProfile[\"displayName\"] = clProfile.displayName myProfile[\"statusMessage\"] = clProfile.statusMessage myProfile[\"pictureStatus\"] =", "ensure_ascii=False) backup = read f = codecs.open('read.json','w','utf-8') json.dump(backup, f, sort_keys=True,", "cl.getGroupIdsJoined() contactlist = cl.getAllContactIds() blockedlist = cl.getBlockedContactIds() ret_ = \"╔══[", "try: ret_ = \"╔══[ 狀態 ]\" if settings[\"autoAdd\"] == True:", "guys\") targets = [] for g in gs.members: if _name", "Black List ]\" for mi_d in settings[\"blacklist\"]: mc += \"\\n╠", "'detectmention off': settings[\"datectMention\"] = False cl.sendMessage(to, \"Berhasil menonaktifkan Detect Mention\")", "except Exception as e: cl.sendMessage(receiver, str(e)) if line != None:", "for rom in read[\"ROM\"][receiver].items(): chiya.append(rom[1]) cmem = cl.getContacts(chiya) zx =", "'me': sendMessageWithMention(to, clMID) cl.sendContact(to, clMID) elif text.lower() == 'mymid': cl.sendMessage(msg.to,\"[MID]\\n\"", "[ \" + timeNow.strftime('%H:%M:%S') + \" ]\" if msg.to not", "= bulan[k-1] readTime = hasil + \", \" + timeNow.strftime('%d')", "cl.updateProfilePicture(P) cl.cloneContactProfile(target) except Exception as e: cl.sendMessage(to, \"Failed!\") elif text.lower()", "print (\"send\" + receiver + str(text.lower())) # if op.type ==", "break except: msg.contentMetadata = {'mid': target} settings[\"copy\"] = False break", "if _name in s.displayName: print (\"[Target] Copy\") break else: targets.append(copy)", "]\" cl.sendMessage(msg.to, readTime) elif \"screenshotwebsite\" in msg.text.lower(): sep = text.split(\"", "2: group = cl.getGroup(to) if group.preventedJoinByTicket == False: ticket =", "x in range(len(cmem)): xname = str(cmem[x].displayName) pesan = '' pesan2", "'restart': cl.sendMessage(to, \"重新啟動中...\") time.sleep(5) cl.sendMessage(to, \"重啟成功,請重新登入\") restartBot() elif text.lower() ==", "key[\"MENTIONEES\"]: targets.append(x[\"M\"]) for target in targets: try: del settings[\"模仿名單\"][\"target\"][target] cl.sendMessage(msg.to,\"刪除成功", "== True: if msg_id in msg_dict: if msg_dict[msg_id][\"from\"] not in", "pass except Exception as e: print (e) #==============================================================================# if op.type", "clProfile.pictureStatus #==============================================================================# def restartBot(): print (\"[ INFO ] BOT RESETTED\")", "]\") elif \"mimic\" in msg.text.lower(): sep = text.split(\" \") mic", "text.lower() == 'lr': tz = pytz.timezone(\"Asia/Jakarta\") timeNow = datetime.now(tz=tz) day", "aa = '{\"S\":\"0\",\"E\":\"3\",\"M\":'+json.dumps(mid)+'}' text_ = '@x ' cl.sendMessage(to, text_, contentMetadata={'MENTION':'{\"MENTIONEES\":['+aa+']}'},", "text.lower() == 'resetread': tz = pytz.timezone(\"Asia/Jakarta\") timeNow = datetime.now(tz=tz) day", "elif msg.text.lower().startswith(\"unban \"): targets = [] key = eval(msg.contentMetadata[\"MENTION\"]) key[\"MENTIONEES\"][0][\"M\"]", "== 'checksticker off': settings[\"checkSticker\"] = False cl.sendMessage(to, \"Berhasil menonaktifkan Check", "text.lower() == 'cancel': if msg.toType == 2: group = cl.getGroup(to)", "= \"╔══[ Admin List ]\" for mi_d in admin: mc", "group = cl.getGroup(to) GS = group.creator.mid cl.sendContact(to, GS) elif text.lower()", "cl.sendImageWithURL(msg.to, cover) elif msg.text.lower().startswith(\"contact \"): if 'MENTION' in msg.contentMetadata.keys()!= None:", "def logError(text): cl.log(\"[ ERROR ] \" + str(text)) time_ =", "timeNow.strftime(\"%A\") bln = timeNow.strftime(\"%m\") for i in range(len(day)): if hr", "[] key = eval(msg.contentMetadata[\"MENTION\"]) key[\"MENTIONEES\"][0][\"M\"] for x in key[\"MENTIONEES\"]: targets.append(x[\"M\"])", "elif msg.text.lower().startswith(\"ban \"): targets = [] key = eval(msg.contentMetadata[\"MENTION\"]) key[\"MENTIONEES\"][0][\"M\"]", "mc = \"╔══[ Mimic List ]\" for mi_d in settings[\"mimic\"][\"target\"]:", "cl.getChannelResult() cl.log(\"Channel Token : \" + str(channelToken)) clMID = cl.profile.mid", "str(cmem[x].displayName) pesan = '' pesan2 = pesan+\"@c\\n\" xlen = str(len(zxc)+len(xpesan))", "♥ ╠SR 設定已讀點 ╠LR 查看誰已讀 ╠Nk @ 標註踢人 ╠Nk 全部再見", "True: K0 = msg._from else: K0 = admin # if", ": '+cmid+'\\nStatus Msg : '+cstatus+'\\nPicture : http://dl.profile.line.naver.jp'+cpic) cl.sendMessage(receiver, None, contentMetadata={'mid':", "else: cl.sendMessage(msg.to,\"It can't be used besides the group.\") elif text.lower()", "cl.sendMessage(to, \"Auto Read on success\") elif text.lower() == 'autoread off':", "for target in targets: try: cl.kickoutFromGroup(msg.to,[target]) print (msg.to,[g.mid]) except: cl.sendMessage(msg.to,\"\")", "if op.type == 24: print (\"[ 24 ] NOTIFIED LEAVE", "= False cl.sendMessage(to, \"已關閉分享\") #==============================================================================# elif text.lower() == 'admin ':", "if msg.to in read[\"readPoint\"]: try: del read[\"readPoint\"][msg.to] del read[\"readMember\"][msg.to] del", "targets: try: del settings[\"blacklist\"][target] cl.sendMessage(msg.to,\"刪除成功 !\") break except: cl.sendMessage(msg.to,\"刪除失敗 !\")", "settings[\"autoJoin\"] == True: ret_ += \"\\n╠ Auto Join ✅\" else:", "cl.sendMessage(msg.to, \"Reset reading point:\\n\" + readTime) else: cl.sendMessage(msg.to, \"偵測點未設置?\") elif", "hari = [\"Minggu\", \"Senin\", \"Selasa\", \"Rabu\", \"Kamis\", \"Jumat\", \"Sabtu\"] bulan", "for ls in lists: contact = cl.getContact(ls) mi_d = contact.mid", "elif \"screenshotwebsite\" in msg.text.lower(): sep = text.split(\" \") query =", ": {}\".format(str(gCreator)) ret_ += \"\\n╠ 群組人數 : {}\".format(str(len(group.members))) ret_ +=", "群組名稱 : {}\".format(str(group.name)) ret_ += \"\\n╠ 群組 Id : {}\".format(group.id)", "'mypicture': me = cl.getContact(clMID) cl.sendImageWithURL(msg.to,\"http://dl.profile.line-cdn.net/\" + me.pictureStatus) elif text.lower() ==", "== 0: if text is None: return #==============================================================================# if sender", "Auto Add ✅\" else: ret_ += \"\\n╠ Auto Add ❌\"", "cl.sendMessage(receiver,\"尚未設置偵測點\") #==============================================================================# elif msg.text.lower().startswith(\"ban \"): targets = [] key =", "cl.sendMessage(msg.to, str(e)) elif text.lower() == 'autoadd on': settings[\"autoAdd\"] = True", "on': wait[\"share\"] = True cl.sendMessage(to, \"已開啟分享\") elif text.lower() == 'share", "\"\\n╠ 製作者 : {}\".format(creator.displayName) ret_ += \"\\n╚══[ 感謝您的使用 ]\" cl.sendMessage(to,", "group.\") elif text.lower() == 'cancel': if msg.toType == 2: group", "clone member\") elif text.lower() == 'restoreprofile': try: clProfile.displayName = str(myProfile[\"displayName\"])", "cl.getGroup(to) GS = group.creator.mid cl.sendContact(to, GS) elif text.lower() == 'groupid':", "except: msg.contentMetadata = {'mid': target} settings[\"copy\"] = False break #==============================================================================#", "elapsed_time = time.time() - start cl.sendMessage(to,format(str(elapsed_time))) elif text.lower() == 'restart':", "== 2: if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\\w+)',", "'myvideoprofile': me = cl.getContact(clMID) cl.sendVideoWithURL(msg.to,\"http://dl.profile.line-cdn.net/\" + me.pictureStatus + \"/vp\") elif", "e: cl.sendMessage(receiver, str(e)) if line != None: if 'MENTION' in", "point:\\n\" + readTime) else: cl.sendMessage(msg.to, \"偵測點未設置?\") elif text.lower() == 'lr':", "in targets: try: contact = cl.getContact(target) X = contact.displayName profile", "== 2: group = cl.getGroup(to) ret_ = \"╔══[ 成員名單 ]\"", "cl.sendMessage(msg.to,\"偵測點已取消\") else: try: del read['readPoint'][msg.to] del read['readMember'][msg.to] del read['readTime'][msg.to] except:", "print (\"[ 13 ] NOTIFIED INVITE GROUP\") group = cl.getGroup(op.param1)", "+ bln + \" - \" + timeNow.strftime('%Y') + \"\\nJam", "chiya.append(rom[1]) cmem = cl.getContacts(chiya) zx = \"\" zxc = \"\"", "cl.sendMessage(to,mc + \"\\n╚══[ Finish ]\") #==============================================================================# elif \"Copy \" in", "myProfile = { \"displayName\": \"\", \"statusMessage\": \"\", \"pictureStatus\": \"\" }", "+ str(text.lower())) if op.type == 26 or op.type == 25:", "cl.getGroup(to) ret_ = \"╔══[ 成員名單 ]\" no = 0 +", "admin: mc += \"\\n╠ \"+cl.getContact(mi_d).displayName cl.sendMessage(to,mc + \"\\n╚══[ Finish ]\")", "print (e) #==============================================================================# if op.type == 55: print (\"[ 55", "\",\"\") if mic == \"on\": if settings[\"mimic\"][\"status\"] == False: settings[\"mimic\"][\"status\"]", "\"[ Mid User ]\" for ls in lists: ret_ +=", "try: gCreator = group.creator.displayName except: gCreator = \"不明\" if group.invitee", "print (\"[ 55 ] NOTIFIED READ MESSAGE\") try: if op.param1", "✿✿✿ ♥ ╠SR 設定已讀點 ╠LR 查看誰已讀 ╠Nk @ 標註踢人 ╠Nk", "settings[\"protect\"] = False cl.sendMessage(to, \"Protect off success\") elif text.lower() ==", "+= pesan2 text = xpesan+ zxc + \"\\n[ 已讀時間 ]:", "_mid in gMembMids: cl.cancelGroupInvitation(msg.to,[_mid]) cl.sendMessage(msg.to,\"已取消所有邀請!\") elif (\"Inv \" in msg.text):", "backupData(): try: backup = settings f = codecs.open('temp.json','w','utf-8') json.dump(backup, f,", "= pytz.timezone(\"Asia/Jakarta\") timeNow = datetime.now(tz=tz) day = [\"Sunday\", \"Monday\", \"Tuesday\",", "2: X = cl.getGroup(msg.to) X.name = msg.text.replace(\"Gn \",\"\") cl.updateGroup(X) else:", "msg.contentMetadata['STKVER'] pkg_id = msg.contentMetadata['STKPKGID'] ret_ = \"╔══[ Sticker Info ]\"", "\"╔══[ D A T E ]\" ret_ += \"\\n╠ Date", "+ contact.statusMessage) for ls in lists: path = \"http://dl.profile.cl.naver.jp/\" +", "= 0 + 1 for mem in group.members: ret_ +=", "cl.sendMessage(msg.to, \"[ 個簽 ]\\n\" + contact.statusMessage) for ls in lists:", "\"\\n╚══[ Finish ]\" cl.sendMessage(to, str(ret_)) cl.sendImageWithURL(to, path) elif text.lower() ==", "sender != cl.profile.mid: to = sender else: to = receiver", "if sender not in read[\"ROM\"][to]: read[\"ROM\"][to][sender] = True if sender", "op.param1 in read['readPoint']: if op.param2 in read['readMember'][op.param1]: pass else: read['readMember'][op.param1]", "\\n\" + readTime try: cl.sendMessage(receiver, text, contentMetadata={'MENTION':str('{\"MENTIONEES\":'+json.dumps(zx2).replace(' ','')+'}')}, contentType=0) except", "'detectmention on': settings[\"datectMention\"] = True cl.sendMessage(to, \"Berhasil mengaktifkan Detect Mention\")", "break except: cl.sendMessage(msg.to,\"添加失敗 !\") break elif msg.text.lower().startswith(\"mimicdel \"): targets =", "elif text.lower() == 'autojoin off': settings[\"autoLeave\"] = False cl.sendMessage(to, \"Auto", "lol.statusMessage = Y cl.updateProfile(lol) P = contact.pictureStatus pic = cl.getProfile()", "標註踢人 ╠Nk 全部再見 ╠══✪〘 其他功能略 〙✪═══ \"\"\" return helpMessage wait", "+ cl.getContact(ls).pictureStatus cl.sendImageWithURL(msg.to, path) try: key = eval(msg.contentMetadata[\"MENTION\"]) u =", "'autoleave on': settings[\"autoLeave\"] = True cl.sendMessage(to, \"Auto Leave on success\")", "[] for s in groups.members: if _name in s.displayName: print", "cl.sendMessage(to,\"已停止權限\") elif text.lower() == 'adminlist': if admin == []: cl.sendMessage(to,\"無擁有權限者!\")", "= False cl.sendMessage(msg.to,\"Reply Message off\") #==============================================================================# elif text.lower() == 'groupcreator':", "ast, pytz, urllib, urllib.parse #==============================================================================# botStart = time.time() cl =", "= cl.getContact(clMID) cl.sendMessage(msg.to,\"[Name]\\n\" + me.displayName) elif text.lower() == 'mytoken': me", "cl.getGroup(to) try: gCreator = group.creator.displayName except: gCreator = \"不明\" if", "read['ROM'][msg.to] = {} with open('read.json', 'w') as fp: json.dump(read, fp,", "in settings[\"blacklist\"]: mc += \"\\n╠ \"+cl.getContact(mi_d).displayName cl.sendMessage(msg.to,mc + \"\\n╚══[ Finish", "restartBot() elif text.lower() == 'runtime': timeNow = time.time() runtime =", "matched_list+=filter(lambda str: str == tag, gMembMids) if matched_list == []:", "pass else: read['readMember'][op.param1] += op.param2 read['ROM'][op.param1][op.param2] = op.param2 backupData() else:", "= cl.getGroup(to) if group.preventedJoinByTicket == False: ticket = cl.reissueGroupTicket(to) cl.sendMessage(to,", "in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\\w+)', text) mention = ast.literal_eval(msg.contentMetadata['MENTION'])", "+ str(channelToken)) clMID = cl.profile.mid clProfile = cl.getProfile() lineSettings =", "try: del settings[\"blacklist\"][target] cl.sendMessage(msg.to,\"刪除成功 !\") break except: cl.sendMessage(msg.to,\"刪除失敗 !\") break", "True: settings[\"mimic\"][\"status\"] = False cl.sendMessage(msg.to,\"Reply Message off\") #==============================================================================# elif text.lower()", "as error: error.write(\"\\n[%s] %s\" % (str(time), text)) def sendMessageWithMention(to, mid):", "]\\n\" + contact.displayName) for ls in lists: contact = cl.getContact(ls)", "saat sampai profile berubah\") except: cl.sendMessage(msg.to, \"Gagal clone member\") elif", "cl.sendMessage(msg.to, \"Berhasil restore profile tunggu beberapa saat sampai profile berubah\")", "if op.type == 26 or op.type == 25: print (\"[", "+ gid.id) elif text.lower() == 'grouppicture': group = cl.getGroup(to) path", "mem in group.members: ret_ += \"\\n╠ {}. {}\".format(str(no), str(mem.displayName)) no", "{}openlink\".format(str(settings[\"keyCommand\"]))) elif text.lower() == 'link off': if msg.toType == 2:", "txt += u'@Alin \\n' cl.sendMessage(to, text=txt, contentMetadata={u'MENTION': json.dumps({'MENTIONEES':b})}, contentType=0) cl.sendMessage(to,", "point:\\n\" + readTime) elif text.lower() == 'readcancel': tz = pytz.timezone(\"Asia/Jakarta\")", "= cl.getGroup(to) cl.sendMessage(to, \"[群組名稱 : ]\\n\" + gid.name) elif text.lower()", "group.preventedJoinByTicket == True: gQr = \"關閉\" gTicket = \"無\" else:", "\"Rabu\", \"Kamis\", \"Jumat\", \"Sabtu\"] bulan = [\"Januari\", \"Februari\", \"Maret\", \"April\",", "is None: gPending = \"0\" else: gPending = str(len(group.invitee)) if", "= op.param1 msg_id = op.param2 if setting[\"reread\"] == True: if", "cl.cancelGroupInvitation(msg.to,[_mid]) cl.sendMessage(msg.to,\"已取消所有邀請!\") elif (\"Inv \" in msg.text): if msg.toType ==", "_name in s.displayName: print (\"[Target] Copy\") break else: targets.append(copy) if", "x in key[\"MENTIONEES\"]: targets.append(x[\"M\"]) for target in targets: try: del", "= False break except: msg.contentMetadata = {'mid': target} settings[\"copy\"] =", "pass elif wait[\"protect\"] == True: settings[\"blacklist\"][op.param2] = True cl.kickoutFromGroup(op.param1,[op.param2]) else:", "text.lower() == 'admin ': MENTION =eval(msg.contentMetadata['MENTION']) inkey =MENTION['MENTIONEES'][0]['M'] admin.append(str(inkey)) cl.sendMessage(to,\"已新增權限\")", "else: group.preventedJoinByTicket = False cl.updateGroup(group) cl.sendMessage(to, \"關閉成功\") elif text.lower() ==", "[] for g in gs.members: if _name in g.displayName: targets.append(g.mid)", "+ clMID) elif text.lower() == 'myname': me = cl.getContact(clMID) cl.sendMessage(msg.to,\"[Name]\\n\"", "in settings[\"blacklist\"]: matched_list+=filter(lambda str: str == tag, gMembMids) if matched_list", "= cl.getContact(ls) cl.sendMessage(msg.to, \"[ 名字 ]\\n\" + contact.displayName) for ls", "group.preventedJoinByTicket == False: cl.sendMessage(to, \"群組網址已關\") else: group.preventedJoinByTicket = False cl.updateGroup(group)", "= msg.contentMetadata['STKID'] stk_ver = msg.contentMetadata['STKVER'] pkg_id = msg.contentMetadata['STKPKGID'] ret_ =", "for mi_d in settings[\"blacklist\"]: try: del settings[\"blacklist\"][mi_d] cl.sendMessage(msg.to,\"已清空黑單!\") break except:", "receiver + str(text.lower())) # if op.type == 26: # to", "time import sleep from humanfriendly import format_timespan, format_size, format_number, format_length", "= { \"share\":False, \"sender\" :{}, } admin =['ud5ff1dff426cf9e3030c7ac2a61512f0','ua10c2ad470b4b6e972954e1140ad1891',clMID] owners =", "elif text.lower() == 'groupid': gid = cl.getGroup(to) cl.sendMessage(to, \"[ID Group", "]\" if msg.to not in read['readPoint']: cl.sendMessage(msg.to,\"偵測點已取消\") else: try: del", "in read['readMember'][op.param1]: pass else: read['readMember'][op.param1] += op.param2 read['ROM'][op.param1][op.param2] = op.param2", "success\") elif text.lower() == 'autoread off': settings[\"autoRead\"] = False cl.sendMessage(to,", "= str(len(zxc)+len(pesan2)+len(xpesan)-1) zx = {'S':xlen, 'E':xlen2, 'M':cmem[x].mid} zx2.append(zx) zxc +=", "cl.sendMessage(to,\"reread off success\") elif text.lower() == 'protect on': settings[\"protect\"] =", "\"\\n╠ Auto Join ✅\" else: ret_ += \"\\n╠ Auto Join", "elif text.lower() == 'myvideoprofile': me = cl.getContact(clMID) cl.sendVideoWithURL(msg.to,\"http://dl.profile.line-cdn.net/\" + me.pictureStatus", "cl.sendMessage(to, \"[ Group Ticket ]\\nhttps://cl.me/R/ti/g/{}\".format(str(ticket))) else: cl.sendMessage(to, \"Grouplink未開啟 {}openlink\".format(str(settings[\"keyCommand\"]))) elif", "targets: try: cl.kickoutFromGroup(msg.to,[target]) print (msg.to,[g.mid]) except: cl.sendMessage(msg.to,\"\") elif (\"Gn \"", "read['readMember'][msg.to] = \"\" read['readTime'][msg.to] = datetime.now().strftime('%H:%M:%S') read['ROM'][msg.to] = {} with", "\" + str(text)) time_ = datetime.now() with open(\"errorLog.txt\",\"a\") as error:", "{}\".format(str(data[\"data\"][\"ultah\"])) ret_ += \"\\n╠ Zodiak : {}\".format(str(data[\"data\"][\"zodiak\"])) ret_ += \"\\n╚══[", "False cl.sendMessage(to, \"Auto Join off success\") elif text.lower() == 'autoleave", "cl.log(\"[ ERROR ] \" + str(text)) time_ = datetime.now() with", "mention['MENTIONEES'] lists = [] for mention in mentionees: if clMID", "msg_dict: if msg_dict[msg_id][\"from\"] not in bl: cl.sendMessage(at,\"[收回訊息者]\\n%s\\n[訊息內容]\\n%s\"%(cl.getContact(msg_dict[msg_id][\"from\"]).displayName,msg_dict[msg_id][\"text\"])) del msg_dict[msg_id] else:", "to = msg._from # sender = str(to.displayName) # print (\"receiver\"", "cl.sendMessage(msg.to,\"Reply Message off\") #==============================================================================# elif text.lower() == 'groupcreator': group =", "+= \"\\n╠ 群組網址 : {}\".format(gTicket) ret_ += \"\\n╚══[ Finish ]\"", "else: cl.sendMessage(op.param1,\"\") else: cl.sendMessage(op.param1,\"\") if op.type == 24: print (\"[", "Group : ]\\n\" + gid.id) elif text.lower() == 'grouppicture': group", "text.lower() == 'sr': tz = pytz.timezone(\"Asia/Jakarta\") timeNow = datetime.now(tz=tz) day", "\"\\n╠ Birthday : {}\".format(str(data[\"data\"][\"ultah\"])) ret_ += \"\\n╠ Zodiak : {}\".format(str(data[\"data\"][\"zodiak\"]))", "== 'banmidlist': if settings[\"blacklist\"] == {}: cl.sendMessage(msg.to,\"無黑單成員!\") else: mc =", "'mymid': cl.sendMessage(msg.to,\"[MID]\\n\" + clMID) elif text.lower() == 'myname': me =", "+ \"\\n╚══[ Finish ]\") #==============================================================================# elif text.lower() == 'me': sendMessageWithMention(to,", "= True if sender in settings[\"mimic\"][\"target\"] and settings[\"mimic\"][\"status\"] == True", "mentionees: if mention[\"M\"] not in lists: lists.append(mention[\"M\"]) for ls in", "List ]\" for mi_d in settings[\"blacklist\"]: mc += \"\\n╠ \"+cl.getContact(mi_d).displayName", "== 55: print (\"[ 55 ] NOTIFIED READ MESSAGE\") try:", "xlen = str(len(zxc)+len(xpesan)) xlen2 = str(len(zxc)+len(pesan2)+len(xpesan)-1) zx = {'S':xlen, 'E':xlen2,", "for ls in lists: ret_ += \"\\n\" + ls cl.sendMessage(msg.to,", "關於本bot ]\" ret_ += \"\\n╠ 版本 : 最新\" ret_ +=", "settings[\"autoJoin\"] = False cl.sendMessage(to, \"Auto Join off success\") elif text.lower()", "receiver if settings[\"autoRead\"] == True: cl.sendChatChecked(to, msg_id) if to in", "\"\\n╠ 群組網址 : {}\".format(gTicket) ret_ += \"\\n╚══[ Finish ]\" cl.sendMessage(to,", "if bln == str(k): bln = bulan[k-1] readTime = hasil", "except Exception as e: print (e) #==============================================================================# if op.type ==", "settings = json.load(settingsOpen) myProfile = { \"displayName\": \"\", \"statusMessage\": \"\",", "{}\".format(group.id) ret_ += \"\\n╠ 創建者 : {}\".format(str(gCreator)) ret_ += \"\\n╠", "== 0: print (\"[ 0 ] END OF OPERATION\") return", "with open('read.json', 'w') as fp: json.dump(read, fp, sort_keys=True, indent=4) cl.sendMessage(msg.to,", "me.statusMessage) elif text.lower() == 'mypicture': me = cl.getContact(clMID) cl.sendImageWithURL(msg.to,\"http://dl.profile.line-cdn.net/\" +", "myProfile[\"pictureStatus\"] = clProfile.pictureStatus #==============================================================================# def restartBot(): print (\"[ INFO ]", "mi_d in settings[\"mimic\"][\"target\"]: mc += \"\\n╠ \"+cl.getContact(mi_d).displayName cl.sendMessage(msg.to,mc + \"\\n╚══[", "MEMBER\") _name = msg.text.replace(\"Byeall\",\"\") gs = cl.getGroup(msg.to) cl.sendMessage(msg.to,\"Sorry guys\") targets", "== []: cl.sendMessage(msg.to, \"Not Found...\") pass else: for target in", "= True cl.sendMessage(msg.to,\"已加入黑單!\") break except: cl.sendMessage(msg.to,\"添加失敗 !\") break elif msg.text.lower().startswith(\"unban", "off success\") elif text.lower() == 'autoread on': settings[\"autoRead\"] = True", "g.displayName: targets.append(g.mid) if targets == []: cl.sendMessage(msg.to,\"Not Found\") else: for", "return if op.type == 5: print (\"[ 5 ] NOTIFIED", "blacklist user\") return for jj in matched_list: cl.kickoutFromGroup(msg.to,[jj]) cl.sendMessage(msg.to,\"Blacklist kicked", "cl.sendMessage(to, str(ret_)) elif msg.contentType == 13: if settings[\"copy\"] == True:", "\" + timeNow.strftime('%Y') + \"\\nJam : [ \" + timeNow.strftime('%H:%M:%S')", "if msg_dict[msg_id][\"from\"] not in bl: cl.sendMessage(at,\"[收回訊息者]\\n%s\\n[訊息內容]\\n%s\"%(cl.getContact(msg_dict[msg_id][\"from\"]).displayName,msg_dict[msg_id][\"text\"])) del msg_dict[msg_id] else: pass", "} msg_dict = {} bl = [\"\"] myProfile[\"displayName\"] = clProfile.displayName", "in targets: try: cl.sendMessage(to,\"來回機票一張ww\") cl.kickoutFromGroup(msg.to,[target]) cl.inviteIntoGroup(to,[target]) except: cl.sendMessage(to,\"Error\") elif text.lower()", "elif text.lower() == 'mymid': cl.sendMessage(msg.to,\"[MID]\\n\" + clMID) elif text.lower() ==", "'tagall': group = cl.getGroup(msg.to) nama = [contact.mid for contact in", "mc += \"\\n╠ \"+cl.getContact(mi_d).displayName cl.sendMessage(msg.to,mc + \"\\n╚══[ Finish ]\") elif", "+ \"/vp\") elif text.lower() == 'mycover': me = cl.getContact(clMID) cover", "ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] for mention in mentionees: contact =", "elif msg.text.lower().startswith(\"mid \"): if 'MENTION' in msg.contentMetadata.keys()!= None: names =", "= cl.getGroup(to) gMembMids = [contact.mid for contact in group.members] matched_list", "群組人數 : {}\".format(str(len(group.members))) ret_ += \"\\n╠ 邀請中 : {}\".format(gPending) ret_", "+ str(text.lower())) # if op.type == 26: # to =", "{} | {}\".format(str(no), str(group.name), str(len(group.members))) no += 1 ret_ +=", "else: to = receiver if msg.contentType == 0: if text", "= timeNow - botStart runtime = format_timespan(runtime) cl.sendMessage(to, \"系統已運作 {}\".format(str(runtime)))", "cl.getContact(clMID) cover = cl.getProfileCoverURL(clMID) cl.sendImageWithURL(msg.to, cover) elif msg.text.lower().startswith(\"contact \"): if", "text.lower() == 'me': sendMessageWithMention(to, clMID) cl.sendContact(to, clMID) elif text.lower() ==", "tz = pytz.timezone(\"Asia/Makassar\") timeNow = datetime.now(tz=tz) day = [\"Sunday\", \"Monday\",", "elif \"checkdate\" in msg.text.lower(): sep = msg.text.split(\" \") tanggal =", "try: del settings[\"模仿名單\"][\"target\"][target] cl.sendMessage(msg.to,\"刪除成功 !\") break except: cl.sendMessage(msg.to,\"刪除失敗 !\") break", "receiver else: to = receiver if settings[\"autoRead\"] == True: cl.sendChatChecked(to,", "26 or op.type == 25: print (\"[ 25 ] SEND", "== True: cl.leaveRoom(op.param1) if op.type == 25 or op.type ==", "1 ret_ += \"\\n╚══[ 全部成員共 {} 人]\".format(str(len(group.members))) cl.sendMessage(to, str(ret_)) elif", "% (str(time), text)) def sendMessageWithMention(to, mid): try: aa = '{\"S\":\"0\",\"E\":\"3\",\"M\":'+json.dumps(mid)+'}'", "+ group.pictureStatus ret_ = \"╔══[ Group Info ]\" ret_ +=", "targets: try: cl.sendMessage(to,\"Fuck you\") cl.kickoutFromGroup(msg.to,[target]) except: cl.sendMessage(to,\"Error\") elif msg.text.lower().startswith(\"ri \"):", "in lists: contact = cl.getContact(ls) cl.sendMessage(msg.to, \"[ 個簽 ]\\n\" +", "= cl.getContact(u).statusMessage cpic = cl.getContact(u).picturePath cl.sendMessage(receiver, 'Nama : '+cname+'\\nMID :", "cstatus = cl.getContact(u).statusMessage cpic = cl.getContact(u).picturePath cl.sendMessage(receiver, 'Nama : '+cname+'\\nMID", "text.lower() == 'reread off': settings[\"reread\"] = False cl.sendMessage(to,\"reread off success\")", "True cl.sendMessage(to, \"已開啟分享\") elif text.lower() == 'share off': wait[\"share\"] =", "cover = cl.getProfileCoverURL(clMID) cl.sendImageWithURL(msg.to, cover) elif msg.text.lower().startswith(\"contact \"): if 'MENTION'", "Y cl.updateProfile(lol) P = contact.pictureStatus pic = cl.getProfile() pic.pictureStatus =", "targets.append(x[\"M\"]) for target in targets: try: cl.sendMessage(to,\"來回機票一張ww\") cl.kickoutFromGroup(msg.to,[target]) cl.inviteIntoGroup(to,[target]) except:", "settings[\"autoLeave\"] == True: ret_ += \"\\n╠ Auto Leave ✅\" else:", "if settings[\"autoLeave\"] == True: cl.leaveRoom(op.param1) if op.type == 25 or", "NOTIFIED LEAVE ROOM\") if settings[\"autoLeave\"] == True: cl.leaveRoom(op.param1) if op.type", "not None: for op in ops: lineBot(op) oepoll.setRevision(op.revision) except Exception", "{}: cl.sendMessage(msg.to,\"未設定模仿目標\") else: mc = \"╔══[ Mimic List ]\" for", "settings[\"mimic\"][\"status\"] == False: settings[\"mimic\"][\"status\"] = True cl.sendMessage(msg.to,\"Reply Message on\") elif", "except: gCreator = \"不明\" if group.invitee is None: gPending =", "read[\"readPoint\"][msg.to] del read[\"readMember\"][msg.to] del read[\"readTime\"][msg.to] except: pass cl.sendMessage(msg.to, \"Reset reading", "= False cl.sendMessage(to, \"Auto Join off success\") elif text.lower() ==", "if admin == []: cl.sendMessage(to,\"無擁有權限者!\") else: mc = \"╔══[ Admin", "\"Success...\") Y = contact.statusMessage lol = cl.getProfile() lol.statusMessage = Y", "STICKER VERSION : {}\".format(stk_ver) ret_ += \"\\n╠ STICKER URL :", "BOT RESETTED\") backupData() python = sys.executable os.execl(python, python, *sys.argv) def", "{'mid': target} settings[\"copy\"] = False break #==============================================================================# if op.type ==", "op.param1 msg_id = op.param2 if setting[\"reread\"] == True: if msg_id", "= msg.to # receiver = str(to.displayName) # print (\"send\" +", "msg._from if msg.toType == 0: if sender != cl.profile.mid: to", "break except: cl.sendMessage(msg.to,\"刪除失敗 !\") break elif text.lower() == 'banlist': if", "65 ] REREAD\") try: at = op.param1 msg_id = op.param2", "for gid in groups: group = cl.getGroup(gid) ret_ += \"\\n╠", "= LINE(\"TOKEN KAMU\") #cl = LINE(\"Email\",\"Password\") cl.log(\"Auth Token : \"", "== 'restart': cl.sendMessage(to, \"重新啟動中...\") time.sleep(5) cl.sendMessage(to, \"重啟成功,請重新登入\") restartBot() elif text.lower()", "read['readMember'][op.param1] += op.param2 read['ROM'][op.param1][op.param2] = op.param2 backupData() else: pass except:", "cl.sendMessage(to, \"Berhasil mengaktifkan Detect Mention\") elif text.lower() == 'detectmention off':", "settings[\"mimic\"][\"status\"] == True: settings[\"mimic\"][\"status\"] = False cl.sendMessage(msg.to,\"Reply Message off\") #==============================================================================#", "= read f = codecs.open('read.json','w','utf-8') json.dump(backup, f, sort_keys=True, indent=4, ensure_ascii=False)", "= True cl.sendMessage(to, \"已開啟分享\") elif text.lower() == 'share off': wait[\"share\"]", "path = cl.getProfileCoverURL(ls) pmath = \"http://dl.profile.cl.naver.jp/\" + cl.getContact(ls).pictureStatus cl.sendImageWithURL(msg.to, path)", "(e) #==============================================================================# if op.type == 55: print (\"[ 55 ]", "str(k): bln = bulan[k-1] readTime = hasil + \", \"", "settings[\"mimic\"][\"target\"] and settings[\"mimic\"][\"status\"] == True and settings[\"mimic\"][\"target\"][sender] == True: text", "settings[\"autoJoin\"] = True cl.sendMessage(to, \"Auto Join on success\") elif text.lower()", "not in lists: lists.append(mention[\"M\"]) ret_ = \"[ Mid User ]\"", "25: print (\"[ 25 ] SEND MESSAGE\") msg = op.message", "'[ 已讀的人 ]:\\n' for x in range(len(cmem)): xname = str(cmem[x].displayName)", "in key[\"MENTIONEES\"]: targets.append(x[\"M\"]) for target in targets: try: contact =", "= \"\" zx2 = [] xpesan = '[ 已讀的人 ]:\\n'", "indent=4) cl.sendMessage(msg.to, \"Set reading point:\\n\" + readTime) elif text.lower() ==", "== 'protect off': settings[\"protect\"] = False cl.sendMessage(to, \"Protect off success\")", "cl.getGroup(gid) ret_ += \"\\n╠ {}. {} | {}\".format(str(no), str(group.name), str(len(group.members)))", "reading point:\\n\" + readTime) elif text.lower() == 'readcancel': tz =", "== 'share on': wait[\"share\"] = True cl.sendMessage(to, \"已開啟分享\") elif text.lower()", "msg.contentMetadata[\"mid\"] groups = cl.getGroup(msg.to) targets = [] for s in", "elif text.lower() == 'groupinfo': group = cl.getGroup(to) try: gCreator =", "{}\".format(str(len(blockedlist))) ret_ += \"\\n╠══[ 關於本bot ]\" ret_ += \"\\n╠ 版本", "in range(len(day)): if hr == day[i]: hasil = hari[i] for", "\" ]\" cl.sendMessage(msg.to, readTime) elif \"screenshotwebsite\" in msg.text.lower(): sep =", "tunggu beberapa saat sampai profile berubah\") except: cl.sendMessage(msg.to, \"Gagal clone", "False cl.sendMessage(to, \"Berhasil menonaktifkan Detect Mention\") elif text.lower() == 'reread", "cl.sendMessage(to, str(ret_)) elif msg.contentType == 7: if settings[\"checkSticker\"] == True:", "+ sender + str(text.lower())) if op.type == 26 or op.type", "except: cl.sendMessage(msg.to,\"添加失敗 !\") break elif msg.text.lower().startswith(\"mimicdel \"): targets = []", "in key[\"MENTIONEES\"]: targets.append(x[\"M\"]) for target in targets: try: del settings[\"blacklist\"][target]", "not in clMID and msg.toType == 2: if 'MENTION' in", "{}\".format(str(data[\"data\"][\"usia\"])) ret_ += \"\\n╠ Birthday : {}\".format(str(data[\"data\"][\"ultah\"])) ret_ += \"\\n╠", "True cl.sendMessage(msg.to,\"已加入黑單!\") break except: cl.sendMessage(msg.to,\"添加失敗 !\") break elif msg.text.lower().startswith(\"unban \"):", "elif text.lower() == 'link on': if msg.toType == 2: group", "sys.executable os.execl(python, python, *sys.argv) def backupData(): try: backup = settings", "else: to = receiver if settings[\"autoRead\"] == True: cl.sendChatChecked(to, msg_id)", "Exception as error: logError(error) def helpmessage(): helpMessage = \"\"\"╔═════════════ ╠♥", "== 2: print (\"[ 19 ] KICK ALL MEMBER\") _name", "+= \"\\n╠ {}. {}\".format(str(no), str(mem.displayName)) no += 1 ret_ +=", "stk_ver = msg.contentMetadata['STKVER'] pkg_id = msg.contentMetadata['STKPKGID'] ret_ = \"╔══[ Sticker", "= hasil + \", \" + timeNow.strftime('%d') + \" -", "off': settings[\"checkSticker\"] = False cl.sendMessage(to, \"Berhasil menonaktifkan Check Details Sticker\")", "cl.getContact(u).displayName cmid = cl.getContact(u).mid cstatus = cl.getContact(u).statusMessage cpic = cl.getContact(u).picturePath", "== 'autojoin off': settings[\"autoJoin\"] = False cl.sendMessage(to, \"Auto Join off", "\"+cl.getContact(mi_d).displayName cl.sendMessage(to,mc + \"\\n╚══[ Finish ]\") #==============================================================================# elif text.lower() ==", "= eval(msg.contentMetadata[\"MENTION\"]) key[\"MENTIONEES\"][0][\"M\"] for x in key[\"MENTIONEES\"]: targets.append(x[\"M\"]) for target", "Group Info ]\" ret_ += \"\\n╠ 群組名稱 : {}\".format(str(group.name)) ret_", "*sys.argv) else: pass #==============================================================================# elif text.lower() == 'calender': tz =", "+ \" - \" + timeNow.strftime('%Y') + \"\\nJam : [", "python, *sys.argv) #==============================================================================# def lineBot(op): try: if op.type == 0:", "#if clMID not in owners: # python = sys.executable #", "if msg.toType == 2: group = cl.getGroup(to) ret_ = \"╔══[", "success\") elif text.lower() == 'autoread on': settings[\"autoRead\"] = True cl.sendMessage(to,", "Check Details Sticker\") elif text.lower() == 'detectmention on': settings[\"datectMention\"] =", "True: try: ops = oepoll.singleTrace(count=50) if ops is not None:", "- start cl.sendMessage(to,format(str(elapsed_time))) elif text.lower() == 'restart': cl.sendMessage(to, \"重新啟動中...\") time.sleep(5)", "\"Februari\", \"Maret\", \"April\", \"Mei\", \"Juni\", \"Juli\", \"Agustus\", \"September\", \"Oktober\", \"November\",", "= sys.executable # os.execl(python, python, *sys.argv) #==============================================================================# def lineBot(op): try:", "settings[\"blacklist\"][target] cl.sendMessage(msg.to,\"刪除成功 !\") break except: cl.sendMessage(msg.to,\"刪除失敗 !\") break elif text.lower()", "[] for mention in mentionees: if clMID in mention[\"M\"]: if", "elif text.lower() == 'groupmemberlist': if msg.toType == 2: group =", "ret_ += \"\\n╠ Auto Read ❌\" if settings[\"reread\"] ==True: ret_+=\"\\n╠", "k = len(nama)//100 for a in range(k+1): txt = u''", "contact in group.members] matched_list = [] for tag in settings[\"blacklist\"]:", "settings[\"mimic\"][\"target\"] == {}: cl.sendMessage(msg.to,\"未設定模仿目標\") else: mc = \"╔══[ Mimic List", "+= \"\\n╠ Auto Add ❌\" if settings[\"autoJoin\"] == True: ret_", "查看誰已讀 ╠Nk @ 標註踢人 ╠Nk 全部再見 ╠══✪〘 其他功能略 〙✪═══ \"\"\"", "'autoadd off': settings[\"autoAdd\"] = False cl.sendMessage(to, \"Auto Add off success\")", "settings[\"autoRead\"] = True cl.sendMessage(to, \"Auto Read on success\") elif text.lower()", "del read['readTime'][msg.to] except: pass read['readPoint'][msg.to] = msg.id read['readMember'][msg.to] = \"\"", "if line != None: if 'MENTION' in msg.contentMetadata.keys()!= None: names", "'cc9487': if sender in ['ua10c2ad470b4b6e972954e1140ad1891']: python = sys.executable os.execl(python, python,", "berubah\") settings['copy'] = False break except: msg.contentMetadata = {'mid': target}", "55: print (\"[ 55 ] NOTIFIED READ MESSAGE\") try: if", "mic = text.replace(sep[0] + \" \",\"\") if mic == \"on\":", "ops is not None: for op in ops: lineBot(op) oepoll.setRevision(op.revision)", "ret_+=\"\\n╠ Reread ✅\" else: ret_ += \"\\n╠ Reread ❌\" ret_", "pmath = \"http://dl.profile.cl.naver.jp/\" + cl.getContact(ls).pictureStatus cl.sendImageWithURL(msg.to, path) try: key =", "\"+cl.getContact(mi_d).displayName cl.sendMessage(msg.to,mc + \"\\n╚══[ Finish ]\") elif text.lower() == 'nkban':", "= text.split(\" \") mic = text.replace(sep[0] + \" \",\"\") if", "i in group.members[a*100 : (a+1)*100]: b.append({\"S\":str(s), \"E\" :str(s+6), \"M\":i.mid}) s", "Auto Read ✅\" else: ret_ += \"\\n╠ Auto Read ❌\"", "cl.getSettings() oepoll = OEPoll(cl) #==============================================================================# readOpen = codecs.open(\"read.json\",\"r\",\"utf-8\") settingsOpen =", "text.lower() == 'mimiclist': if settings[\"mimic\"][\"target\"] == {}: cl.sendMessage(msg.to,\"未設定模仿目標\") else: mc", "try: at = op.param1 msg_id = op.param2 if setting[\"reread\"] ==", "cl.sendMessage(msg.to,\"Reply Message on\") elif mic == \"off\": if settings[\"mimic\"][\"status\"] ==", "+= \"\\n╠ STICKER VERSION : {}\".format(stk_ver) ret_ += \"\\n╠ STICKER", "eval(msg.contentMetadata[\"MENTION\"]) u = key[\"MENTIONEES\"][0][\"M\"] cname = cl.getContact(u).displayName cmid = cl.getContact(u).mid", "str == tag, gMembMids) if matched_list == []: cl.sendMessage(msg.to,\"There was", "x in key[\"MENTIONEES\"]: targets.append(x[\"M\"]) for target in targets: try: cl.sendMessage(to,\"來回機票一張ww\")", "\"\\n╠ 群組名稱 : {}\".format(str(group.name)) ret_ += \"\\n╠ 群組 Id :", "= \"http://dl.profile.line-cdn.net/\" + group.pictureStatus cl.sendImageWithURL(to, path) elif text.lower() == 'groupname':", "xname = str(cmem[x].displayName) pesan = '' pesan2 = pesan+\"@c\\n\" xlen", "sender in K0: if text.lower() == 'help': helpMessage = helpmessage()", "sendMessageWithMention(to, clMID) cl.sendContact(to, clMID) elif text.lower() == 'mymid': cl.sendMessage(msg.to,\"[MID]\\n\" +", "ret_ += \"\\n╠ 群組網址 : {}\".format(gTicket) ret_ += \"\\n╚══[ Finish", "cl.sendMessage(msg.to, readTime) elif \"screenshotwebsite\" in msg.text.lower(): sep = text.split(\" \")", "mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] for mention in mentionees:", "cl.sendMessage(msg.to,mc + \"\\n╚══[ Finish ]\") elif \"mimic\" in msg.text.lower(): sep", "\"Senin\", \"Selasa\", \"Rabu\", \"Kamis\", \"Jumat\", \"Sabtu\"] bulan = [\"Januari\", \"Februari\",", "\"Saturday\"] hari = [\"Minggu\", \"Senin\", \"Selasa\", \"Rabu\", \"Kamis\", \"Jumat\", \"Sabtu\"]", "backup = read f = codecs.open('read.json','w','utf-8') json.dump(backup, f, sort_keys=True, indent=4,", "= cl.getContact(clMID) cl.sendVideoWithURL(msg.to,\"http://dl.profile.line-cdn.net/\" + me.pictureStatus + \"/vp\") elif text.lower() ==", "for mi_d in settings[\"mimic\"][\"target\"]: mc += \"\\n╠ \"+cl.getContact(mi_d).displayName cl.sendMessage(msg.to,mc +", "2: midd = msg.text.replace(\"Inv \",\"\") cl.findAndAddContactsByMid(midd) cl.inviteIntoGroup(to,[midd]) #==============================================================================# elif text.lower()", "targets: try: settings[\"blacklist\"][target] = True cl.sendMessage(msg.to,\"已加入黑單!\") break except: cl.sendMessage(msg.to,\"添加失敗 !\")", "ls in lists: contact = cl.getContact(ls) mi_d = contact.mid cl.sendContact(msg.to,", "sendMessageWithMention(to, mid): try: aa = '{\"S\":\"0\",\"E\":\"3\",\"M\":'+json.dumps(mid)+'}' text_ = '@x '", "STICKER PACKAGES ID : {}\".format(pkg_id) ret_ += \"\\n╠ STICKER VERSION", "cl.updateProfile(profile) cl.sendMessage(to, \"Success...\") Y = contact.statusMessage lol = cl.getProfile() lol.statusMessage", "try: cl.sendMessage(to,\"來回機票一張ww\") cl.kickoutFromGroup(msg.to,[target]) cl.inviteIntoGroup(to,[target]) except: cl.sendMessage(to,\"Error\") elif text.lower() == 'nk':", "elif text.lower() == 'share off': wait[\"share\"] = False cl.sendMessage(to, \"已關閉分享\")", "elif msg.text.lower().startswith(\"mimicdel \"): targets = [] key = eval(msg.contentMetadata[\"MENTION\"]) key[\"MENTIONEES\"][0][\"M\"]", "admin == []: cl.sendMessage(to,\"無擁有權限者!\") else: mc = \"╔══[ Admin List", "\"\\n╠ {}. {} | {}\".format(str(no), str(group.name), str(len(group.members))) no += 1", "] NOTIFIED LEAVE ROOM\") if settings[\"autoLeave\"] == True: cl.leaveRoom(op.param1) if", "zx2 = [] xpesan = '[ 已讀的人 ]:\\n' for x", "except: pass except Exception as error: logError(error) #==============================================================================# while True:", "+ receiver + str(text.lower())) # if op.type == 26: #", "try: settings[\"mimic\"][\"target\"][target] = True cl.sendMessage(msg.to,\"已加入模仿名單!\") break except: cl.sendMessage(msg.to,\"添加失敗 !\") break", "= json.loads(data) cl.sendImageWithURL(to, data[\"result\"]) elif \"checkdate\" in msg.text.lower(): sep =", "+ \", \" + timeNow.strftime('%d') + \" - \" +", "msg.text.split(\" \") tanggal = msg.text.replace(sep[0] + \" \",\"\") r=requests.get('https://script.google.com/macros/exec?service=AKfycbw7gKzP-WYV2F5mc9RaR7yE3Ve1yN91Tjs91hp_jHSE02dSv9w&nama=ervan&tanggal='+tanggal) data=r.text", "key = eval(msg.contentMetadata[\"MENTION\"]) u = key[\"MENTIONEES\"][0][\"M\"] cname = cl.getContact(u).displayName cmid", "elif text.lower() == 'nk': if msg.toType == 2: print (\"[", "= '[ 已讀的人 ]:\\n' for x in range(len(cmem)): xname =", "╠LR 查看誰已讀 ╠Nk @ 標註踢人 ╠Nk 全部再見 ╠══✪〘 其他功能略 〙✪═══", "\", \" + timeNow.strftime('%d') + \" - \" + bln", "b=[] for i in group.members[a*100 : (a+1)*100]: b.append({\"S\":str(s), \"E\" :str(s+6),", "GS) elif text.lower() == 'groupid': gid = cl.getGroup(to) cl.sendMessage(to, \"[ID", "contentMetadata={'MENTION':'{\"MENTIONEES\":['+aa+']}'}, contentType=0) except Exception as error: logError(error) def helpmessage(): helpMessage", "for mention in mentionees: if clMID in mention[\"M\"]: if settings[\"detectMention\"]", "Mention\") elif text.lower() == 'detectmention off': settings[\"datectMention\"] = False cl.sendMessage(to,", "== True: ret_ += \"\\n╠ Auto Read ✅\" else: ret_", "break elif text.lower() == 'banmidlist': if settings[\"blacklist\"] == {}: cl.sendMessage(msg.to,\"無黑單成員!\")", "msg.text.lower().startswith(\"name \"): if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\\w+)',", "= False cl.sendMessage(to, \"Berhasil menonaktifkan Detect Mention\") elif text.lower() ==", "Total {} Groups ]\".format(str(len(groups))) cl.sendMessage(to, str(ret_)) elif msg.text.lower().startswith(\"nk \"): targets", "bulan[k-1] readTime = hasil + \", \" + timeNow.strftime('%d') +", "in range(len(cmem)): xname = str(cmem[x].displayName) pesan = '' pesan2 =", "off success\") elif text.lower() == 'autoleave on': settings[\"autoLeave\"] = True", "\",\"\") cl.findAndAddContactsByMid(midd) cl.inviteIntoGroup(to,[midd]) #==============================================================================# elif text.lower() == 'tagall': group =", "else: cl.sendMessage(msg.to, \"偵測點未設置?\") elif text.lower() == 'lr': tz = pytz.timezone(\"Asia/Jakarta\")", "in targets: try: settings[\"blacklist\"][target] = True cl.sendMessage(msg.to,\"已加入黑單!\") break except: cl.sendMessage(msg.to,\"添加失敗", "#==============================================================================# elif text.lower() == 'tagall': group = cl.getGroup(msg.to) nama =", "\") mic = text.replace(sep[0] + \" \",\"\") if mic ==", "not in bl: cl.sendMessage(at,\"[收回訊息者]\\n%s\\n[訊息內容]\\n%s\"%(cl.getContact(msg_dict[msg_id][\"from\"]).displayName,msg_dict[msg_id][\"text\"])) del msg_dict[msg_id] else: pass except Exception", "# to = msg._from # sender = str(to.displayName) # print", "for mention in mentionees: contact = mention[\"M\"] break try: cl.cloneContactProfile(contact)", "jj in matched_list: cl.kickoutFromGroup(msg.to,[jj]) cl.sendMessage(msg.to,\"Blacklist kicked out\") elif text.lower() ==", "['ua10c2ad470b4b6e972954e1140ad1891']: python = sys.executable os.execl(python, python, *sys.argv) else: pass #==============================================================================#", "format_timespan, format_size, format_number, format_length import time, random, sys, json, codecs,", "#==============================================================================# readOpen = codecs.open(\"read.json\",\"r\",\"utf-8\") settingsOpen = codecs.open(\"temp.json\",\"r\",\"utf-8\") read = json.load(readOpen)", "cl.sendMessage(to,mc + \"\\n╚══[ Finish ]\") #==============================================================================# elif text.lower() == 'me':", "text.lower() == 'reread on': settings[\"reread\"] = True cl.sendMessage(to,\"reread on success\")", "oepoll.singleTrace(count=50) if ops is not None: for op in ops:", "linepy import * from datetime import datetime from time import", "== 'groupid': gid = cl.getGroup(to) cl.sendMessage(to, \"[ID Group : ]\\n\"", "+= \"\\n╠ Auto Add ✅\" else: ret_ += \"\\n╠ Auto", "'groupname': gid = cl.getGroup(to) cl.sendMessage(to, \"[群組名稱 : ]\\n\" + gid.name)", "op.type == 26 or op.type == 25: print (\"[ 25", ": {}\".format(str(len(group.members))) ret_ += \"\\n╠ 邀請中 : {}\".format(gPending) ret_ +=", "clProfile.statusMessage myProfile[\"pictureStatus\"] = clProfile.pictureStatus #==============================================================================# def restartBot(): print (\"[ INFO", "timeNow - botStart runtime = format_timespan(runtime) cl.sendMessage(to, \"系統已運作 {}\".format(str(runtime))) elif", "]\") #==============================================================================# elif text.lower() == 'me': sendMessageWithMention(to, clMID) cl.sendContact(to, clMID)", "]\" for ls in lists: ret_ += \"\\n\" + ls", "text.lower() == 'groupmemberlist': if msg.toType == 2: group = cl.getGroup(to)", "for target in targets: try: contact = cl.getContact(target) X =", "success\") elif text.lower() == 'autoleave on': settings[\"autoLeave\"] = True cl.sendMessage(to,", "text_ = '@x ' cl.sendMessage(to, text_, contentMetadata={'MENTION':'{\"MENTIONEES\":['+aa+']}'}, contentType=0) except Exception", "else: to = receiver else: to = receiver if msg.contentType", "text = msg.text msg_id = msg.id receiver = msg.to sender", "mi_d in settings[\"blacklist\"]: mc += \"\\n╠ \"+cl.getContact(mi_d).displayName cl.sendMessage(msg.to,mc + \"\\n╚══[", "+= \"\\n╠ 群組名稱 : {}\".format(str(group.name)) ret_ += \"\\n╠ 群組 Id", "ret_ += \"\\n╠ STICKER VERSION : {}\".format(stk_ver) ret_ += \"\\n╠", "cl.getGroup(to) if group.preventedJoinByTicket == True: cl.sendMessage(to, \"群組網址已開\") else: group.preventedJoinByTicket =", "read['readPoint']: try: del read['readPoint'][msg.to] del read['readMember'][msg.to] del read['readTime'][msg.to] except: pass", "msg.text msg_id = msg.id receiver = msg.to sender = msg._from", "lists: contact = cl.getContact(ls) cl.sendMessage(msg.to, \"[ 個簽 ]\\n\" + contact.statusMessage)", "= clProfile.statusMessage myProfile[\"pictureStatus\"] = clProfile.pictureStatus #==============================================================================# def restartBot(): print (\"[", "= cl.getAllContactIds() blockedlist = cl.getBlockedContactIds() ret_ = \"╔══[ 關於使用者 ]\"", "in msg_dict: if msg_dict[msg_id][\"from\"] not in bl: cl.sendMessage(at,\"[收回訊息者]\\n%s\\n[訊息內容]\\n%s\"%(cl.getContact(msg_dict[msg_id][\"from\"]).displayName,msg_dict[msg_id][\"text\"])) del msg_dict[msg_id]", "== 'runtime': timeNow = time.time() runtime = timeNow - botStart", "json.dump(read, fp, sort_keys=True, indent=4) cl.sendMessage(msg.to, \"Set reading point:\\n\" + readTime)", "elif text.lower() == 'groupcreator': group = cl.getGroup(to) GS = group.creator.mid", "hr == day[i]: hasil = hari[i] for k in range(0,", "== 2: group = cl.getGroup(to) if group.preventedJoinByTicket == False: ticket", ": line://shop/detail/{}\".format(pkg_id) ret_ += \"\\n╚══[ Finish ]\" cl.sendMessage(to, str(ret_)) elif", "pesan2 text = xpesan+ zxc + \"\\n[ 已讀時間 ]: \\n\"", "try: if op.type == 0: print (\"[ 0 ] END", "return #==============================================================================# if sender in K0: if text.lower() == 'help':", ": '+cname+'\\nMID : '+cmid+'\\nStatus Msg : '+cstatus+'\\nPicture : http://dl.profile.line.naver.jp'+cpic) cl.sendMessage(receiver,", "lists.append(mention[\"M\"]) for ls in lists: path = cl.getProfileCoverURL(ls) cl.sendImageWithURL(msg.to, str(path))", "beberapa saat sampai profile berubah\") settings['copy'] = False break except:", "saat sampai profile berubah\") settings['copy'] = False break except: msg.contentMetadata", "= \"http://dl.profile.line-cdn.net/\" + group.pictureStatus ret_ = \"╔══[ Group Info ]\"", "\"\\n╚══[ Total {} Groups ]\".format(str(len(groups))) cl.sendMessage(to, str(ret_)) elif msg.text.lower().startswith(\"nk \"):", "read['readPoint']: cl.sendMessage(msg.to,\"偵測點已取消\") else: try: del read['readPoint'][msg.to] del read['readMember'][msg.to] del read['readTime'][msg.to]", "else: ret_ += \"\\n╠ Auto Add ❌\" if settings[\"autoJoin\"] ==", ": {}\".format(stk_ver) ret_ += \"\\n╠ STICKER URL : line://shop/detail/{}\".format(pkg_id) ret_", "cl.updateProfileAttribute(8, clProfile.pictureStatus) cl.updateProfile(clProfile) cl.sendMessage(msg.to, \"Berhasil restore profile tunggu beberapa saat", "clMID) elif text.lower() == 'myname': me = cl.getContact(clMID) cl.sendMessage(msg.to,\"[Name]\\n\" +", "elif text.lower() == 'autoadd on': settings[\"autoAdd\"] = True cl.sendMessage(to, \"Auto", "== 'link on': if msg.toType == 2: group = cl.getGroup(to)", "{}\".format(gQr) ret_ += \"\\n╠ 群組網址 : {}\".format(gTicket) ret_ += \"\\n╚══[", "targets.append(x[\"M\"]) for target in targets: try: contact = cl.getContact(target) X", "= contact.statusMessage lol = cl.getProfile() lol.statusMessage = Y cl.updateProfile(lol) P", ": {}\".format(str(data[\"data\"][\"usia\"])) ret_ += \"\\n╠ Birthday : {}\".format(str(data[\"data\"][\"ultah\"])) ret_ +=", "\"╔══[ Group List ]\" no = 0 + 1 for", "cl.getGroup(to) cl.sendMessage(to, \"[群組名稱 : ]\\n\" + gid.name) elif text.lower() ==", "'nk': if msg.toType == 2: print (\"[ 19 ] KICK", "== 'autoread off': settings[\"autoRead\"] = False cl.sendMessage(to, \"Auto Read off", "+ timeNow.strftime('%H:%M:%S') + \" ]\" if msg.to in read[\"readPoint\"]: try:", "if settings[\"autoRead\"] == True: ret_ += \"\\n╠ Auto Read ✅\"", "nama = [contact.mid for contact in group.members] k = len(nama)//100", "if settings[\"mimic\"][\"target\"] == {}: cl.sendMessage(msg.to,\"未設定模仿目標\") else: mc = \"╔══[ Mimic", "= True cl.updateGroup(group) cl.sendMessage(to, \"開啟成功\") elif text.lower() == 'groupinfo': group", "else: for target in targets: try: cl.kickoutFromGroup(msg.to,[target]) print (msg.to,[g.mid]) except:", "elif text.lower() == 'restart': cl.sendMessage(to, \"重新啟動中...\") time.sleep(5) cl.sendMessage(to, \"重啟成功,請重新登入\") restartBot()", "+ me.displayName) elif text.lower() == 'mytoken': me = cl.getContact(clMID) cl.sendMessage(msg.to,\"[StatusMessage]\\n\"", "string, os, requests, subprocess, six, ast, pytz, urllib, urllib.parse #==============================================================================#", "def restartBot(): print (\"[ INFO ] BOT RESETTED\") backupData() python", "elif text.lower() == 'cancel': if msg.toType == 2: group =", "\"Agustus\", \"September\", \"Oktober\", \"November\", \"Desember\"] hr = timeNow.strftime(\"%A\") bln =", "to = msg.to # receiver = str(to.displayName) # print (\"send\"", "2: if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\\w+)', text)", "if group.preventedJoinByTicket == False: cl.sendMessage(to, \"群組網址已關\") else: group.preventedJoinByTicket = False", "\"Wednesday\", \"Thursday\",\"Friday\", \"Saturday\"] hari = [\"Minggu\", \"Senin\", \"Selasa\", \"Rabu\", \"Kamis\",", "感謝您的使用 ]\" cl.sendMessage(to, str(ret_)) except Exception as e: cl.sendMessage(msg.to, str(e))", "if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\\w+)', text) mention", "False cl.updateGroup(group) cl.sendMessage(to, \"關閉成功\") elif text.lower() == 'link on': if", "\"Auto Leave off success\") elif text.lower() == 'autoread on': settings[\"autoRead\"]", "text.lower() == 'protect on': settings[\"protect\"] = True cl.sendMessage(to, \"Protect on", "'demin ': MENTION =eval(msg.contentMetadata['MENTION']) inkey =MENTION['MENTIONEES'][0]['M'] admin.remove(str(inkey)) cl.sendMessage(to,\"已停止權限\") elif text.lower()", "\"Total {} Mention\".format(str(len(nama)))) elif text.lower() == 'sr': tz = pytz.timezone(\"Asia/Jakarta\")", "\"Delete reading point:\\n\" + readTime) elif text.lower() == 'resetread': tz", "✅\" else: ret_ += \"\\n╠ Auto Add ❌\" if settings[\"autoJoin\"]", "(\"[ 19 ] KICK ALL MEMBER\") _name = msg.text.replace(\"Byeall\",\"\") gs", "try: clProfile.displayName = str(myProfile[\"displayName\"]) clProfile.statusMessage = str(myProfile[\"statusMessage\"]) clProfile.pictureStatus = str(myProfile[\"pictureStatus\"])", "contentType=0) except Exception as error: logError(error) def helpmessage(): helpMessage =", "return False def logError(text): cl.log(\"[ ERROR ] \" + str(text))", "owners = [\"ua10c2ad470b4b6e972954e1140ad1891\",\"ud5ff1dff426cf9e3030c7ac2a61512f0\"] #if clMID not in owners: # python", "in read['readPoint']: if read[\"ROM\"][receiver].items() == []: cl.sendMessage(receiver,\"[ 已讀的人 ]:\\nNone\") else:", "else: ret_ += \"\\n╠ Reread ❌\" ret_ += \"\\n╚══[ Finish", "on success\") elif text.lower() == 'autoadd off': settings[\"autoAdd\"] = False", "= cl.getProfileCoverURL(clMID) cl.sendImageWithURL(msg.to, cover) elif msg.text.lower().startswith(\"contact \"): if 'MENTION' in", "# to = msg.to # receiver = str(to.displayName) # print", "cl.sendMessage(msg.to,\"添加失敗 !\") break elif msg.text.lower().startswith(\"mimicdel \"): targets = [] key", "sort_keys=True, indent=4, ensure_ascii=False) return True except Exception as error: logError(error)", "== 'banlist': if settings[\"blacklist\"] == {}: cl.sendMessage(msg.to,\"無黑單成員!\") else: mc =", "K0 = msg._from else: K0 = admin # if op.type", "ALL MEMBER\") _name = msg.text.replace(\"Byeall\",\"\") gs = cl.getGroup(msg.to) cl.sendMessage(msg.to,\"Sorry guys\")", "group = cl.getGroup(gid) ret_ += \"\\n╠ {}. {} | {}\".format(str(no),", "群組網址 : {}\".format(gTicket) ret_ += \"\\n╚══[ Finish ]\" cl.sendMessage(to, str(ret_))", "= str(to.displayName) # print (\"send\" + receiver + str(text.lower())) #", "group.preventedJoinByTicket = False cl.updateGroup(group) cl.sendMessage(to, \"關閉成功\") elif text.lower() == 'link", "mic == \"off\": if settings[\"mimic\"][\"status\"] == True: settings[\"mimic\"][\"status\"] = False", "on': settings[\"reread\"] = True cl.sendMessage(to,\"reread on success\") elif text.lower() ==", "in bl: cl.sendMessage(at,\"[收回訊息者]\\n%s\\n[訊息內容]\\n%s\"%(cl.getContact(msg_dict[msg_id][\"from\"]).displayName,msg_dict[msg_id][\"text\"])) del msg_dict[msg_id] else: pass except Exception as", "berubah\") except: cl.sendMessage(msg.to, \"Gagal restore profile\") #==============================================================================# elif msg.text.lower().startswith(\"mimicadd \"):", "datetime.now(tz=tz) day = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\"Friday\", \"Saturday\"] hari", "== 'grouplist': groups = cl.groups ret_ = \"╔══[ Group List", "json.dumps({'MENTIONEES':b})}, contentType=0) cl.sendMessage(to, \"Total {} Mention\".format(str(len(nama)))) elif text.lower() == 'sr':", "text.lower() == 'share off': wait[\"share\"] = False cl.sendMessage(to, \"已關閉分享\") #==============================================================================#", "try: arr = [] owner = \"ua10c2ad470b4b6e972954e1140ad1891\" creator = cl.getContact(owner)", "xpesan = '[ 已讀的人 ]:\\n' for x in range(len(cmem)): xname", "Join off success\") elif text.lower() == 'autoleave on': settings[\"autoLeave\"] =", "\"Thursday\",\"Friday\", \"Saturday\"] hari = [\"Minggu\", \"Senin\", \"Selasa\", \"Rabu\", \"Kamis\", \"Jumat\",", "timeNow.strftime('%H:%M:%S') + \" ]\" if receiver in read['readPoint']: if read[\"ROM\"][receiver].items()", "in lists: lists.append(mention[\"M\"]) for ls in lists: contact = cl.getContact(ls)", "] END OF OPERATION\") return if op.type == 5: print", "settings[\"autoJoin\"] == True: cl.acceptGroupInvitation(op.param1) if op.type == 19: if op.param2", "import sleep from humanfriendly import format_timespan, format_size, format_number, format_length import", "msg.text.lower(): sep = msg.text.split(\" \") tanggal = msg.text.replace(sep[0] + \"", "del msg_dict[msg_id] else: pass except Exception as e: print (e)", "# if op.type == 26: # to = msg._from #", "mengaktifkan Check Details Sticker\") elif text.lower() == 'checksticker off': settings[\"checkSticker\"]", "= cl.getGroup(msg.to) nama = [contact.mid for contact in group.members] k", "settings[\"autoAdd\"] = False cl.sendMessage(to, \"Auto Add off success\") elif text.lower()", "error: logError(error) return False def logError(text): cl.log(\"[ ERROR ] \"", "text.lower() == 'grouplist': groups = cl.groups ret_ = \"╔══[ Group", "VERSION : {}\".format(stk_ver) ret_ += \"\\n╠ STICKER URL : line://shop/detail/{}\".format(pkg_id)", "gPending = \"0\" else: gPending = str(len(group.invitee)) if group.preventedJoinByTicket ==", "if sender != cl.profile.mid: to = sender else: to =", "== 'nkban': if msg.toType == 2: group = cl.getGroup(to) gMembMids", "'+cmid+'\\nStatus Msg : '+cstatus+'\\nPicture : http://dl.profile.line.naver.jp'+cpic) cl.sendMessage(receiver, None, contentMetadata={'mid': cmid},", "elif msg.contentType == 13: if settings[\"copy\"] == True: _name =", "\" ]\" if msg.to not in read['readPoint']: cl.sendMessage(msg.to,\"偵測點已取消\") else: try:", "== 2: group = cl.getGroup(to) if group.preventedJoinByTicket == True: cl.sendMessage(to,", "Found\") else: for target in targets: try: cl.kickoutFromGroup(msg.to,[target]) print (msg.to,[g.mid])", "True: ret_ += \"\\n╠ Auto Add ✅\" else: ret_ +=", "\"Desember\"] hr = timeNow.strftime(\"%A\") bln = timeNow.strftime(\"%m\") for i in", "readTime) elif text.lower() == 'readcancel': tz = pytz.timezone(\"Asia/Jakarta\") timeNow =", "target in targets: try: cl.sendMessage(to,\"Fuck you\") cl.kickoutFromGroup(msg.to,[target]) except: cl.sendMessage(to,\"Error\") elif", "\"\\n╚══[ Finish ]\") elif text.lower() == 'nkban': if msg.toType ==", "2: group = cl.getGroup(to) gMembMids = [contact.mid for contact in", "time.time() cl.sendMessage(to, \"計算中...\") elapsed_time = time.time() - start cl.sendMessage(to,format(str(elapsed_time))) elif", "== 'autoread on': settings[\"autoRead\"] = True cl.sendMessage(to, \"Auto Read on", "elif text.lower() == 'adminlist': if admin == []: cl.sendMessage(to,\"無擁有權限者!\") else:", "= [] for rom in read[\"ROM\"][receiver].items(): chiya.append(rom[1]) cmem = cl.getContacts(chiya)", "PACKAGES ID : {}\".format(pkg_id) ret_ += \"\\n╠ STICKER VERSION :", "if ops is not None: for op in ops: lineBot(op)", "None: return #==============================================================================# if sender in K0: if text.lower() ==", "timeNow = time.time() runtime = timeNow - botStart runtime =", "{ \"displayName\": \"\", \"statusMessage\": \"\", \"pictureStatus\": \"\" } msg_dict =", "1 ret_ += \"\\n╚══[ Total {} Groups ]\".format(str(len(groups))) cl.sendMessage(to, str(ret_))", "else: ret_ += \"\\n╠ Auto Join ❌\" if settings[\"autoLeave\"] ==", "cl.getContact(ls) cl.sendMessage(msg.to, \"[ 名字 ]\\n\" + contact.displayName) for ls in", "[contact.mid for contact in group.members] matched_list = [] for tag", "else: chiya = [] for rom in read[\"ROM\"][receiver].items(): chiya.append(rom[1]) cmem", "True cl.sendMessage(to, \"Berhasil mengaktifkan Check Details Sticker\") elif text.lower() ==", "1 for mem in group.members: ret_ += \"\\n╠ {}. {}\".format(str(no),", "(\"[ 24 ] NOTIFIED LEAVE ROOM\") if settings[\"autoLeave\"] == True:", "24: print (\"[ 24 ] NOTIFIED LEAVE ROOM\") if settings[\"autoLeave\"]", "[\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\"Friday\", \"Saturday\"] hari = [\"Minggu\", \"Senin\",", "to = receiver else: to = receiver if msg.contentType ==", "Leave ✅\" else: ret_ += \"\\n╠ Auto Leave ❌\" if", "cl.log(\"Channel Token : \" + str(channelToken)) clMID = cl.profile.mid clProfile", "me = cl.getContact(clMID) cl.sendImageWithURL(msg.to,\"http://dl.profile.line-cdn.net/\" + me.pictureStatus) elif text.lower() == 'myvideoprofile':", "cl.sendImageWithURL(msg.to, str(path)) elif msg.text.lower().startswith(\"cloneprofile \"): if 'MENTION' in msg.contentMetadata.keys()!= None:", "cl.getContact(u).picturePath cl.sendMessage(receiver, 'Nama : '+cname+'\\nMID : '+cmid+'\\nStatus Msg : '+cstatus+'\\nPicture", "cl.sendContact(to, GS) elif text.lower() == 'groupid': gid = cl.getGroup(to) cl.sendMessage(to,", "gQr = \"開啟\" gTicket = \"https://cl.me/R/ti/g/{}\".format(str(cl.reissueGroupTicket(group.id))) path = \"http://dl.profile.line-cdn.net/\" +", "settings[\"autoLeave\"] == True: cl.leaveRoom(op.param1) if op.type == 25 or op.type", "elif text.lower() == 'speed': start = time.time() cl.sendMessage(to, \"計算中...\") elapsed_time", "ret_ = \"╔══[ 狀態 ]\" if settings[\"autoAdd\"] == True: ret_", "off success\") elif text.lower() == 'protect on': settings[\"protect\"] = True", "== 2: X = cl.getGroup(msg.to) X.name = msg.text.replace(\"Gn \",\"\") cl.updateGroup(X)", "out\") elif text.lower() == 'cleanban': settings[\"blacklist\"] == {ok} for mi_d", "query = text.replace(sep[0] + \" \",\"\") with requests.session() as web:", "]\" cl.sendMessage(to, str(ret_)) elif msg.contentType == 13: if settings[\"copy\"] ==", "elif text.lower() == 'autoread off': settings[\"autoRead\"] = False cl.sendMessage(to, \"Auto", "26: K0 = admin msg = op.message if wait[\"share\"] ==", "'+cstatus+'\\nPicture : http://dl.profile.line.naver.jp'+cpic) cl.sendMessage(receiver, None, contentMetadata={'mid': cmid}, contentType=13) if cl.getContact(u).videoProfile", "msg.text.lower().startswith(\"ri \"): targets = [] key = eval(msg.contentMetadata[\"MENTION\"]) key[\"MENTIONEES\"][0][\"M\"] for", "+= \"\\n╠ 好友數 : {}\".format(str(len(contactlist))) ret_ += \"\\n╠ 已封鎖 :", "+= 1 ret_ += \"\\n╚══[ 全部成員共 {} 人]\".format(str(len(group.members))) cl.sendMessage(to, str(ret_))", "elif text.lower() == 'restoreprofile': try: clProfile.displayName = str(myProfile[\"displayName\"]) clProfile.statusMessage =", "indent=4, ensure_ascii=False) backup = read f = codecs.open('read.json','w','utf-8') json.dump(backup, f,", "cover) elif msg.text.lower().startswith(\"contact \"): if 'MENTION' in msg.contentMetadata.keys()!= None: names", "break else: targets.append(copy) if targets == []: cl.sendMessage(msg.to, \"Not Found...\")", "\"╔══[ 狀態 ]\" if settings[\"autoAdd\"] == True: ret_ += \"\\n╠", "False cl.sendMessage(to, \"Berhasil menonaktifkan Check Details Sticker\") elif text.lower() ==", "\" in msg.text): if msg.toType == 2: X = cl.getGroup(msg.to)", "= {} with open('read.json', 'w') as fp: json.dump(read, fp, sort_keys=True,", "Read ✅\" else: ret_ += \"\\n╠ Auto Read ❌\" if", "K0 = admin # if op.type == 25: # to", "cl.getContact(ls) mi_d = contact.mid cl.sendContact(msg.to, mi_d) elif msg.text.lower().startswith(\"mid \"): if", "pytz, urllib, urllib.parse #==============================================================================# botStart = time.time() cl = LINE()", "cl.sendMessage(msg.to,\"刪除成功 !\") break except: cl.sendMessage(msg.to,\"刪除失敗 !\") break elif text.lower() ==", "cmid = cl.getContact(u).mid cstatus = cl.getContact(u).statusMessage cpic = cl.getContact(u).picturePath cl.sendMessage(receiver,", "#cl = LINE(\"TOKEN KAMU\") #cl = LINE(\"Email\",\"Password\") cl.log(\"Auth Token :", "break #==============================================================================# if op.type == 65: print (\"[ 65 ]", "lineBot(op): try: if op.type == 0: print (\"[ 0 ]", "cl.sendImageWithURL(msg.to,\"http://dl.profile.line-cdn.net/\" + me.pictureStatus) elif text.lower() == 'myvideoprofile': me = cl.getContact(clMID)", "msg_dict = {} bl = [\"\"] myProfile[\"displayName\"] = clProfile.displayName myProfile[\"statusMessage\"]", "cl.sendMessage(op.param1,\"\") if op.type == 24: print (\"[ 24 ] NOTIFIED", "off': wait[\"share\"] = False cl.sendMessage(to, \"已關閉分享\") #==============================================================================# elif text.lower() ==", "cl.sendMessage(to, \"Total {} Mention\".format(str(len(nama)))) elif text.lower() == 'sr': tz =", "[] for mention in mentionees: if mention[\"M\"] not in lists:", "== 65: print (\"[ 65 ] REREAD\") try: at =", "datetime from time import sleep from humanfriendly import format_timespan, format_size,", "mention in mentionees: if mention[\"M\"] not in lists: lists.append(mention[\"M\"]) for", "= [contact.mid for contact in group.members] matched_list = [] for", "helpMessage = helpmessage() cl.sendMessage(to, str(helpMessage)) cl.sendContact(to,\"u0a59c278b1529476ddb210cb5e827ffc\") cl.sendContact(to,\"ufb30e2203f44bc7b72e28b09a88c9bbd\") #==============================================================================# elif text.lower()", "5 ] NOTIFIED ADD CONTACT\") if settings[\"autoAdd\"] == True: cl.sendMessage(op.param1,", "\"\\n╚══[ Finish ]\") #==============================================================================# elif \"Copy \" in msg.text: targets", ": {}\".format(str(data[\"data\"][\"ultah\"])) ret_ += \"\\n╠ Zodiak : {}\".format(str(data[\"data\"][\"zodiak\"])) ret_ +=", "gMembMids: cl.cancelGroupInvitation(msg.to,[_mid]) cl.sendMessage(msg.to,\"已取消所有邀請!\") elif (\"Inv \" in msg.text): if msg.toType", "@ 標註踢人 ╠Nk 全部再見 ╠══✪〘 其他功能略 〙✪═══ \"\"\" return helpMessage", "\"Tuesday\", \"Wednesday\", \"Thursday\",\"Friday\", \"Saturday\"] hari = [\"Minggu\", \"Senin\", \"Selasa\", \"Rabu\",", "\"\\n╠ STICKER PACKAGES ID : {}\".format(pkg_id) ret_ += \"\\n╠ STICKER", "wait[\"protect\"] == True: settings[\"blacklist\"][op.param2] = True cl.kickoutFromGroup(op.param1,[op.param2]) else: cl.sendMessage(op.param1,\"\") else:", "Detect Mention\") elif text.lower() == 'detectmention off': settings[\"datectMention\"] = False", "return for jj in matched_list: cl.kickoutFromGroup(msg.to,[jj]) cl.sendMessage(msg.to,\"Blacklist kicked out\") elif", "{}\".format(creator.displayName) ret_ += \"\\n╚══[ 感謝您的使用 ]\" cl.sendMessage(to, str(ret_)) except Exception", "+ \" ]\" cl.sendMessage(msg.to, readTime) elif \"screenshotwebsite\" in msg.text.lower(): sep", "\" + bln + \" - \" + timeNow.strftime('%Y') +", "URL : line://shop/detail/{}\".format(pkg_id) ret_ += \"\\n╚══[ Finish ]\" cl.sendMessage(to, str(ret_))", "as e: cl.sendMessage(to, \"Failed!\") elif text.lower() == 'cc9487': if sender", "cl.sendMessage(to, \"Auto Join on success\") elif text.lower() == 'autojoin off':", "group.preventedJoinByTicket == True: cl.sendMessage(to, \"群組網址已開\") else: group.preventedJoinByTicket = True cl.updateGroup(group)", "True: contact = cl.getContact(sender) cl.sendMessage(to, \"sundala nu\") sendMessageWithMention(to, contact.mid) break", "= len(nama)//100 for a in range(k+1): txt = u'' s=0", "\"Juni\", \"Juli\", \"Agustus\", \"September\", \"Oktober\", \"November\", \"Desember\"] hr = timeNow.strftime(\"%A\")", "sort_keys=True, indent=4) cl.sendMessage(msg.to, \"Set reading point:\\n\" + readTime) elif text.lower()", "= \"\" read['readTime'][msg.to] = datetime.now().strftime('%H:%M:%S') read['ROM'][msg.to] = {} with open('read.json',", "clProfile.statusMessage = str(myProfile[\"statusMessage\"]) clProfile.pictureStatus = str(myProfile[\"pictureStatus\"]) cl.updateProfileAttribute(8, clProfile.pictureStatus) cl.updateProfile(clProfile) cl.sendMessage(msg.to,", "sender else: to = receiver else: to = receiver if", "Date Of Birth : {}\".format(str(data[\"data\"][\"lahir\"])) ret_ += \"\\n╠ Age :", "{}. {}\".format(str(no), str(mem.displayName)) no += 1 ret_ += \"\\n╚══[ 全部成員共", "\\n' cl.sendMessage(to, text=txt, contentMetadata={u'MENTION': json.dumps({'MENTIONEES':b})}, contentType=0) cl.sendMessage(to, \"Total {} Mention\".format(str(len(nama))))", "pass except: pass except Exception as error: logError(error) #==============================================================================# while", "=['ud5ff1dff426cf9e3030c7ac2a61512f0','ua10c2ad470b4b6e972954e1140ad1891',clMID] owners = [\"ua10c2ad470b4b6e972954e1140ad1891\",\"ud5ff1dff426cf9e3030c7ac2a61512f0\"] #if clMID not in owners: #", "= datetime.now(tz=tz) day = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\"Friday\", \"Saturday\"]", "off': settings[\"protect\"] = False cl.sendMessage(to, \"Protect off success\") elif text.lower()", "\"Selasa\", \"Rabu\", \"Kamis\", \"Jumat\", \"Sabtu\"] bulan = [\"Januari\", \"Februari\", \"Maret\",", "ret_ += \"\\n╚══[ Finish ]\" cl.sendMessage(to, str(ret_)) except Exception as", "(\"[ 26 ] RECEIVE MESSAGE\") msg = op.message text =", "group = cl.getGroup(msg.to) nama = [contact.mid for contact in group.members]", "if op.type == 0: print (\"[ 0 ] END OF", "text.lower() == 'restoreprofile': try: clProfile.displayName = str(myProfile[\"displayName\"]) clProfile.statusMessage = str(myProfile[\"statusMessage\"])", "text.lower() == 'grouppicture': group = cl.getGroup(to) path = \"http://dl.profile.line-cdn.net/\" +", "str(ret_)) elif msg.text.lower().startswith(\"name \"): if 'MENTION' in msg.contentMetadata.keys()!= None: names", "True cl.kickoutFromGroup(op.param1,[op.param2]) else: cl.sendMessage(op.param1,\"\") else: cl.sendMessage(op.param1,\"\") if op.type == 24:", "cl.updateGroup(group) cl.sendMessage(to, \"開啟成功\") elif text.lower() == 'groupinfo': group = cl.getGroup(to)", "ret_ += \"\\n╠ {}. {} | {}\".format(str(no), str(group.name), str(len(group.members))) no", "cl.sendMessage(msg.to,\"無黑單成員!\") else: mc = \"╔══[ Black List ]\" for mi_d", "ID : {}\".format(stk_id) ret_ += \"\\n╠ STICKER PACKAGES ID :", "= cl.getGroup(to) cl.sendMessage(to, \"[ID Group : ]\\n\" + gid.id) elif", "targets == []: cl.sendMessage(msg.to,\"Not Found\") else: for target in targets:", "網址狀態 : {}\".format(gQr) ret_ += \"\\n╠ 群組網址 : {}\".format(gTicket) ret_", "'cleanban': settings[\"blacklist\"] == {ok} for mi_d in settings[\"blacklist\"]: try: del", "\"Copy \" in msg.text: targets = [] key = eval(msg.contentMetadata[\"MENTION\"])", "json.dump(read, fp, sort_keys=True, indent=4) cl.sendMessage(msg.to,\"偵測點已設置\") else: try: del read['readPoint'][msg.to] del", "pic.pictureStatus = P cl.updateProfilePicture(P) cl.cloneContactProfile(target) except Exception as e: cl.sendMessage(to,", ": {}\".format(str(data[\"data\"][\"lahir\"])) ret_ += \"\\n╠ Age : {}\".format(str(data[\"data\"][\"usia\"])) ret_ +=", "settings[\"blacklist\"]: mc += \"\\n╠ \"+cl.getContact(mi_d).displayName cl.sendMessage(msg.to,mc + \"\\n╚══[ Finish ]\")", "cl.sendMessage(to, \"Berhasil menonaktifkan Check Details Sticker\") elif text.lower() == 'detectmention", "\"Berhasil mengaktifkan Check Details Sticker\") elif text.lower() == 'checksticker off':", "{} Mention\".format(str(len(nama)))) elif text.lower() == 'sr': tz = pytz.timezone(\"Asia/Jakarta\") timeNow", "Join ✅\" else: ret_ += \"\\n╠ Auto Join ❌\" if", "text_, contentMetadata={'MENTION':'{\"MENTIONEES\":['+aa+']}'}, contentType=0) except Exception as error: logError(error) def helpmessage():", "= time.time() runtime = timeNow - botStart runtime = format_timespan(runtime)", "[]: cl.sendMessage(msg.to,\"There was no blacklist user\") return for jj in", "= datetime.now().strftime('%H:%M:%S') read['ROM'][msg.to] = {} with open('read.json', 'w') as fp:", "no += 1 ret_ += \"\\n╚══[ Total {} Groups ]\".format(str(len(groups)))", "me.pictureStatus) elif text.lower() == 'myvideoprofile': me = cl.getContact(clMID) cl.sendVideoWithURL(msg.to,\"http://dl.profile.line-cdn.net/\" +", "25 or op.type == 26: K0 = admin msg =", "import format_timespan, format_size, format_number, format_length import time, random, sys, json,", "if msg.contentType == 0 and sender not in clMID and", "'adminlist': if admin == []: cl.sendMessage(to,\"無擁有權限者!\") else: mc = \"╔══[", "try: cl.cloneContactProfile(target) cl.sendMessage(msg.to, \"Berhasil clone member tunggu beberapa saat sampai", "\"\\nJam : [ \" + timeNow.strftime('%H:%M:%S') + \" ]\" if", "= ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] for mention in mentionees: contact", "+= \"\\n╠ {}. {} | {}\".format(str(no), str(group.name), str(len(group.members))) no +=", "ls in lists: ret_ += \"\\n\" + ls cl.sendMessage(msg.to, str(ret_))", "[ \" + timeNow.strftime('%H:%M:%S') + \" ]\" cl.sendMessage(msg.to, readTime) elif", "NOTIFIED READ MESSAGE\") try: if op.param1 in read['readPoint']: if op.param2", "text.lower() == 'speed': start = time.time() cl.sendMessage(to, \"計算中...\") elapsed_time =", "\"\\n╠ Auto Leave ✅\" else: ret_ += \"\\n╠ Auto Leave", "True cl.sendMessage(msg.to,\"Reply Message on\") elif mic == \"off\": if settings[\"mimic\"][\"status\"]", "msg_dict[msg_id] else: pass except Exception as e: print (e) #==============================================================================#", "ret_ += \"\\n╚══[ 感謝您的使用 ]\" cl.sendMessage(to, str(ret_)) except Exception as", "text.lower() == 'protect off': settings[\"protect\"] = False cl.sendMessage(to, \"Protect off", "名字 ]\\n\" + contact.displayName) for ls in lists: contact =", "msg.toType == 2: group = cl.getGroup(to) if group.preventedJoinByTicket == True:", "\"\\n╠ 群組人數 : {}\".format(str(len(group.members))) ret_ += \"\\n╠ 邀請中 : {}\".format(gPending)", "cl.sendMessage(receiver, 'Nama : '+cname+'\\nMID : '+cmid+'\\nStatus Msg : '+cstatus+'\\nPicture :", "Mimic List ]\" for mi_d in settings[\"mimic\"][\"target\"]: mc += \"\\n╠", "= clProfile.pictureStatus #==============================================================================# def restartBot(): print (\"[ INFO ] BOT", "msg.text.lower().startswith(\"mimicadd \"): targets = [] key = eval(msg.contentMetadata[\"MENTION\"]) key[\"MENTIONEES\"][0][\"M\"] for", "msg.text.lower().startswith(\"contact \"): if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\\w+)',", "MENTION =eval(msg.contentMetadata['MENTION']) inkey =MENTION['MENTIONEES'][0]['M'] admin.append(str(inkey)) cl.sendMessage(to,\"已新增權限\") elif text.lower() == 'demin", "read[\"ROM\"][receiver].items() == []: cl.sendMessage(receiver,\"[ 已讀的人 ]:\\nNone\") else: chiya = []", "key[\"MENTIONEES\"]: targets.append(x[\"M\"]) for target in targets: try: contact = cl.getContact(target)", "used besides the group.\") elif text.lower() == 'cancel': if msg.toType", "== 13: print (\"[ 13 ] NOTIFIED INVITE GROUP\") group", "sampai profile berubah\") settings['copy'] = False break except: msg.contentMetadata =", "me = cl.getContact(clMID) cl.sendMessage(msg.to,\"[Name]\\n\" + me.displayName) elif text.lower() == 'mytoken':", "25 ] SEND MESSAGE\") msg = op.message text = msg.text", "me.pictureStatus + \"/vp\") elif text.lower() == 'mycover': me = cl.getContact(clMID)", "try: del read['readPoint'][msg.to] del read['readMember'][msg.to] del read['readTime'][msg.to] except: pass read['readPoint'][msg.to]", "if to in read[\"readPoint\"]: if sender not in read[\"ROM\"][to]: read[\"ROM\"][to][sender]", "settings[\"autoLeave\"] = False cl.sendMessage(to, \"Auto Leave off success\") elif text.lower()", "#==============================================================================# if sender in K0: if text.lower() == 'help': helpMessage", "mention in mentionees: contact = mention[\"M\"] break try: cl.cloneContactProfile(contact) cl.sendMessage(msg.to,", "\"Auto Leave on success\") elif text.lower() == 'autojoin off': settings[\"autoLeave\"]", "cl.getGroup(msg.to) targets = [] for s in groups.members: if _name", "REREAD\") try: at = op.param1 msg_id = op.param2 if setting[\"reread\"]", "= {'mid': target} settings[\"copy\"] = False break #==============================================================================# if op.type", "\"\"\"╔═════════════ ╠♥ ✿✿✿ 十香の特製Bot ✿✿✿ ♥ ╠SR 設定已讀點 ╠LR 查看誰已讀", "fp, sort_keys=True, indent=4) cl.sendMessage(msg.to, \"Set reading point:\\n\" + readTime) elif", "= msg.text.replace(\"Gn \",\"\") cl.updateGroup(X) else: cl.sendMessage(msg.to,\"It can't be used besides", "web.get(\"http://rahandiapi.herokuapp.com/sswebAPI?key=betakey&link={}\".format(urllib.parse.quote(query))) data = r.text data = json.loads(data) cl.sendImageWithURL(to, data[\"result\"]) elif", "十香の特製Bot ✿✿✿ ♥ ╠SR 設定已讀點 ╠LR 查看誰已讀 ╠Nk @ 標註踢人", "+ \" ]\" if msg.to in read['readPoint']: try: del read['readPoint'][msg.to]", "MENTION =eval(msg.contentMetadata['MENTION']) inkey =MENTION['MENTIONEES'][0]['M'] admin.remove(str(inkey)) cl.sendMessage(to,\"已停止權限\") elif text.lower() == 'adminlist':", "cl.getGroup(to) if group.preventedJoinByTicket == False: cl.sendMessage(to, \"群組網址已關\") else: group.preventedJoinByTicket =", "cl.sendMessage(receiver,\"[ 已讀的人 ]:\\nNone\") else: chiya = [] for rom in", "bln = bulan[k-1] readTime = hasil + \", \" +", "\") tanggal = msg.text.replace(sep[0] + \" \",\"\") r=requests.get('https://script.google.com/macros/exec?service=AKfycbw7gKzP-WYV2F5mc9RaR7yE3Ve1yN91Tjs91hp_jHSE02dSv9w&nama=ervan&tanggal='+tanggal) data=r.text data=json.loads(data)", "[] for tag in settings[\"blacklist\"]: matched_list+=filter(lambda str: str == tag,", "text.lower() == 'groupid': gid = cl.getGroup(to) cl.sendMessage(to, \"[ID Group :", "+ timeNow.strftime('%H:%M:%S') + \" ]\" cl.sendMessage(msg.to, readTime) elif \"screenshotwebsite\" in", "for contact in group.members] k = len(nama)//100 for a in", "except: cl.sendMessage(msg.to, \"Gagal restore profile\") #==============================================================================# elif msg.text.lower().startswith(\"mimicadd \"): targets", "+ \" ]\" if receiver in read['readPoint']: if read[\"ROM\"][receiver].items() ==", "try: del read[\"readPoint\"][msg.to] del read[\"readMember\"][msg.to] del read[\"readTime\"][msg.to] except: pass cl.sendMessage(msg.to,", "in msg.text): if msg.toType == 2: midd = msg.text.replace(\"Inv \",\"\")", "== 'cleanban': settings[\"blacklist\"] == {ok} for mi_d in settings[\"blacklist\"]: try:", "settings[\"mimic\"][\"status\"] = True cl.sendMessage(msg.to,\"Reply Message on\") elif mic == \"off\":", "if _name in g.displayName: targets.append(g.mid) if targets == []: cl.sendMessage(msg.to,\"Not", "cl.getContact(clMID) cl.sendVideoWithURL(msg.to,\"http://dl.profile.line-cdn.net/\" + me.pictureStatus + \"/vp\") elif text.lower() == 'mycover':", "\"Mei\", \"Juni\", \"Juli\", \"Agustus\", \"September\", \"Oktober\", \"November\", \"Desember\"] hr =", "targets.append(x[\"M\"]) for target in targets: try: cl.sendMessage(to,\"Fuck you\") cl.kickoutFromGroup(msg.to,[target]) except:", "mi_d in settings[\"blacklist\"]: mc += \"\\n╠ \"+mi_d cl.sendMessage(to,mc + \"\\n╚══[", "on': settings[\"autoLeave\"] = True cl.sendMessage(to, \"Auto Leave on success\") elif", "bulan = [\"Januari\", \"Februari\", \"Maret\", \"April\", \"Mei\", \"Juni\", \"Juli\", \"Agustus\",", "e: print (e) #==============================================================================# if op.type == 55: print (\"[", "= \"ua10c2ad470b4b6e972954e1140ad1891\" creator = cl.getContact(owner) contact = cl.getContact(clMID) grouplist =", "GS = group.creator.mid cl.sendContact(to, GS) elif text.lower() == 'groupid': gid", "cl.getContact(clMID) cl.sendMessage(msg.to,\"[Name]\\n\" + me.displayName) elif text.lower() == 'mytoken': me =", "+= \"\\n╠ STICKER ID : {}\".format(stk_id) ret_ += \"\\n╠ STICKER", "contentMetadata={'MENTION':str('{\"MENTIONEES\":'+json.dumps(zx2).replace(' ','')+'}')}, contentType=0) except Exception as error: print (error) pass", "= msg._from else: K0 = admin # if op.type ==", "cl.sendMessage(receiver, str(e)) if line != None: if 'MENTION' in msg.contentMetadata.keys()!=", "List ]\" for mi_d in settings[\"mimic\"][\"target\"]: mc += \"\\n╠ \"+cl.getContact(mi_d).displayName", "'nkban': if msg.toType == 2: group = cl.getGroup(to) gMembMids =", "== True: _name = msg.contentMetadata[\"displayName\"] copy = msg.contentMetadata[\"mid\"] groups =", "group = cl.getGroup(to) path = \"http://dl.profile.line-cdn.net/\" + group.pictureStatus cl.sendImageWithURL(to, path)", "tanggal = msg.text.replace(sep[0] + \" \",\"\") r=requests.get('https://script.google.com/macros/exec?service=AKfycbw7gKzP-WYV2F5mc9RaR7yE3Ve1yN91Tjs91hp_jHSE02dSv9w&nama=ervan&tanggal='+tanggal) data=r.text data=json.loads(data) ret_", "if sender in settings[\"mimic\"][\"target\"] and settings[\"mimic\"][\"status\"] == True and settings[\"mimic\"][\"target\"][sender]", "+ 1 for mem in group.members: ret_ += \"\\n╠ {}.", "targets: try: cl.cloneContactProfile(target) cl.sendMessage(msg.to, \"Berhasil clone member tunggu beberapa saat", "settings[\"blacklist\"]: try: del settings[\"blacklist\"][mi_d] cl.sendMessage(msg.to,\"已清空黑單!\") break except: cl.sendMessage(msg.to,\"刪除失敗 !\") break", "cl.sendMessage(msg.to,\"添加失敗 !\") break elif msg.text.lower().startswith(\"unban \"): targets = [] key", "group.preventedJoinByTicket = True cl.updateGroup(group) cl.sendMessage(to, \"開啟成功\") elif text.lower() == 'groupinfo':", "except Exception as e: cl.sendMessage(to, \"Failed!\") elif text.lower() == 'cc9487':", "','')+'}')}, contentType=0) except Exception as error: print (error) pass else:", "'grouppicture': group = cl.getGroup(to) path = \"http://dl.profile.line-cdn.net/\" + group.pictureStatus cl.sendImageWithURL(to,", "me = cl.getContact(clMID) cl.sendMessage(msg.to,\"[StatusMessage]\\n\" + me.statusMessage) elif text.lower() == 'mypicture':", "\"\\n╠ Age : {}\".format(str(data[\"data\"][\"usia\"])) ret_ += \"\\n╠ Birthday : {}\".format(str(data[\"data\"][\"ultah\"]))", "elif text.lower() == 'resetread': tz = pytz.timezone(\"Asia/Jakarta\") timeNow = datetime.now(tz=tz)", "{} with open('read.json', 'w') as fp: json.dump(read, fp, sort_keys=True, indent=4)", "'w') as fp: json.dump(read, fp, sort_keys=True, indent=4) cl.sendMessage(msg.to,\"偵測點已設置\") else: try:", "not in read['readPoint']: cl.sendMessage(msg.to,\"偵測點已取消\") else: try: del read['readPoint'][msg.to] del read['readMember'][msg.to]", "text.lower() == 'adminlist': if admin == []: cl.sendMessage(to,\"無擁有權限者!\") else: mc", ": {}\".format(gPending) ret_ += \"\\n╠ 網址狀態 : {}\".format(gQr) ret_ +=", "group.members] k = len(nama)//100 for a in range(k+1): txt =", "text.lower() == 'myname': me = cl.getContact(clMID) cl.sendMessage(msg.to,\"[Name]\\n\" + me.displayName) elif", "fp: json.dump(read, fp, sort_keys=True, indent=4) cl.sendMessage(msg.to, \"Set reading point:\\n\" +", "group = cl.getGroup(to) gMembMids = [contact.mid for contact in group.invitee]", "else: mc = \"╔══[ Black List ]\" for mi_d in", "END OF OPERATION\") return if op.type == 5: print (\"[", "\"Berhasil menonaktifkan Check Details Sticker\") elif text.lower() == 'detectmention on':", "OF OPERATION\") return if op.type == 5: print (\"[ 5", "2: group = cl.getGroup(to) if group.preventedJoinByTicket == True: cl.sendMessage(to, \"群組網址已開\")", "\"0\" else: gPending = str(len(group.invitee)) if group.preventedJoinByTicket == True: gQr", "ret_ += \"\\n╠ {}. {}\".format(str(no), str(mem.displayName)) no += 1 ret_", "hasil = hari[i] for k in range(0, len(bulan)): if bln", "[ \" + timeNow.strftime('%H:%M:%S') + \" ]\" if receiver in", "pesan2 = pesan+\"@c\\n\" xlen = str(len(zxc)+len(xpesan)) xlen2 = str(len(zxc)+len(pesan2)+len(xpesan)-1) zx", "arr = [] owner = \"ua10c2ad470b4b6e972954e1140ad1891\" creator = cl.getContact(owner) contact", "targets = [] for g in gs.members: if _name in", "print (\"[ 26 ] RECEIVE MESSAGE\") msg = op.message text", "= msg.contentMetadata['STKPKGID'] ret_ = \"╔══[ Sticker Info ]\" ret_ +=", "cl.groups ret_ = \"╔══[ Group List ]\" no = 0", "2: print (\"[ 19 ] KICK ALL MEMBER\") _name =", "+= \"\\n╠ \"+cl.getContact(mi_d).displayName cl.sendMessage(to,mc + \"\\n╚══[ Finish ]\") #==============================================================================# elif", "group.invitee] for _mid in gMembMids: cl.cancelGroupInvitation(msg.to,[_mid]) cl.sendMessage(msg.to,\"已取消所有邀請!\") elif (\"Inv \"", "clMID) elif text.lower() == 'mymid': cl.sendMessage(msg.to,\"[MID]\\n\" + clMID) elif text.lower()", "key = eval(msg.contentMetadata[\"MENTION\"]) key[\"MENTIONEES\"][0][\"M\"] for x in key[\"MENTIONEES\"]: targets.append(x[\"M\"]) for", "success\") elif text.lower() == 'autojoin off': settings[\"autoLeave\"] = False cl.sendMessage(to,", "targets: try: contact = cl.getContact(target) X = contact.displayName profile =", "key[\"MENTIONEES\"]: targets.append(x[\"M\"]) for target in targets: try: cl.sendMessage(to,\"來回機票一張ww\") cl.kickoutFromGroup(msg.to,[target]) cl.inviteIntoGroup(to,[target])", "wait[\"share\"] = True cl.sendMessage(to, \"已開啟分享\") elif text.lower() == 'share off':", "]\" ret_ += \"\\n╠ 群組名稱 : {}\".format(str(group.name)) ret_ += \"\\n╠", "= msg.id receiver = msg.to sender = msg._from if msg.toType", "+= \"\\n╚══[ 感謝您的使用 ]\" cl.sendMessage(to, str(ret_)) except Exception as e:", "\" + timeNow.strftime('%H:%M:%S') + \" ]\" if msg.to not in", "is not None: for op in ops: lineBot(op) oepoll.setRevision(op.revision) except", "cl.sendMessage(to, str(ret_)) cl.sendImageWithURL(to, path) elif text.lower() == 'groupmemberlist': if msg.toType", "msg_dict[msg_id][\"from\"] not in bl: cl.sendMessage(at,\"[收回訊息者]\\n%s\\n[訊息內容]\\n%s\"%(cl.getContact(msg_dict[msg_id][\"from\"]).displayName,msg_dict[msg_id][\"text\"])) del msg_dict[msg_id] else: pass except", "= hari[i] for k in range(0, len(bulan)): if bln ==", "== 'help': helpMessage = helpmessage() cl.sendMessage(to, str(helpMessage)) cl.sendContact(to,\"u0a59c278b1529476ddb210cb5e827ffc\") cl.sendContact(to,\"ufb30e2203f44bc7b72e28b09a88c9bbd\") #==============================================================================#", "targets.append(x[\"M\"]) for target in targets: try: settings[\"mimic\"][\"target\"][target] = True cl.sendMessage(msg.to,\"已加入模仿名單!\")", "+ readTime) elif text.lower() == 'readcancel': tz = pytz.timezone(\"Asia/Jakarta\") timeNow", "ls in lists: contact = cl.getContact(ls) cl.sendMessage(msg.to, \"[ 名字 ]\\n\"", "❌\" if settings[\"autoLeave\"] == True: ret_ += \"\\n╠ Auto Leave", "sender not in clMID and msg.toType == 2: if 'MENTION'", "success\") elif text.lower() == 'autoadd off': settings[\"autoAdd\"] = False cl.sendMessage(to,", "\"): if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\\w+)', text)", "#==============================================================================# if op.type == 55: print (\"[ 55 ] NOTIFIED", "bln + \" - \" + timeNow.strftime('%Y') + \"\\nJam :", "pytz.timezone(\"Asia/Jakarta\") timeNow = datetime.now(tz=tz) day = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",", "cl.sendMessage(msg.to,\"[StatusMessage]\\n\" + me.statusMessage) elif text.lower() == 'mypicture': me = cl.getContact(clMID)", "success\") elif text.lower() == 'protect off': settings[\"protect\"] = False cl.sendMessage(to,", "[contact.mid for contact in group.invitee] for _mid in gMembMids: cl.cancelGroupInvitation(msg.to,[_mid])", "\"November\", \"Desember\"] hr = timeNow.strftime(\"%A\") bln = timeNow.strftime(\"%m\") for i", "read['readPoint'][msg.to] del read['readMember'][msg.to] del read['readTime'][msg.to] except: pass read['readPoint'][msg.to] = msg.id", "in lists: lists.append(mention[\"M\"]) ret_ = \"[ Mid User ]\" for", "MESSAGE\") msg = op.message text = msg.text msg_id = msg.id", "]:\\n' for x in range(len(cmem)): xname = str(cmem[x].displayName) pesan =", "True except Exception as error: logError(error) return False def logError(text):", "oepoll = OEPoll(cl) #==============================================================================# readOpen = codecs.open(\"read.json\",\"r\",\"utf-8\") settingsOpen = codecs.open(\"temp.json\",\"r\",\"utf-8\")", "+= \"\\n╠ 版本 : 最新\" ret_ += \"\\n╠ 製作者 :", "group.pictureStatus ret_ = \"╔══[ Group Info ]\" ret_ += \"\\n╠", "0: print (\"[ 0 ] END OF OPERATION\") return if", "lists: lists.append(mention[\"M\"]) for ls in lists: contact = cl.getContact(ls) mi_d", "= [] key = eval(msg.contentMetadata[\"MENTION\"]) key[\"MENTIONEES\"][0][\"M\"] for x in key[\"MENTIONEES\"]:", "\"[群組名稱 : ]\\n\" + gid.name) elif text.lower() == 'grouplink': if", "\"Failed!\") elif text.lower() == 'cc9487': if sender in ['ua10c2ad470b4b6e972954e1140ad1891']: python", "= mention[\"M\"] break try: cl.cloneContactProfile(contact) cl.sendMessage(msg.to, \"Berhasil clone member tunggu", "ret_ += \"\\n╠ Zodiak : {}\".format(str(data[\"data\"][\"zodiak\"])) ret_ += \"\\n╚══[ Success", "cl.sendMessage(to, \"關閉成功\") elif text.lower() == 'link on': if msg.toType ==", "msg.id receiver = msg.to sender = msg._from if msg.toType ==", "contactlist = cl.getAllContactIds() blockedlist = cl.getBlockedContactIds() ret_ = \"╔══[ 關於使用者", "LINE(\"Email\",\"Password\") cl.log(\"Auth Token : \" + str(cl.authToken)) channelToken = cl.getChannelResult()", "f = codecs.open('read.json','w','utf-8') json.dump(backup, f, sort_keys=True, indent=4, ensure_ascii=False) return True", "elif text.lower() == 'autoadd off': settings[\"autoAdd\"] = False cl.sendMessage(to, \"Auto", "+ \"\\n╚══[ Finish ]\") elif \"mimic\" in msg.text.lower(): sep =", "try: del settings[\"blacklist\"][mi_d] cl.sendMessage(msg.to,\"已清空黑單!\") break except: cl.sendMessage(msg.to,\"刪除失敗 !\") break elif", "+= \"\\n╠ Age : {}\".format(str(data[\"data\"][\"usia\"])) ret_ += \"\\n╠ Birthday :", "= False cl.sendMessage(to,\"reread off success\") elif text.lower() == 'protect on':", "= msg.text if text is not None: cl.sendMessage(msg.to,text) if msg.contentType", "\"Maret\", \"April\", \"Mei\", \"Juni\", \"Juli\", \"Agustus\", \"September\", \"Oktober\", \"November\", \"Desember\"]", "ret_ += \"\\n╠ STICKER ID : {}\".format(stk_id) ret_ += \"\\n╠", "+ ls cl.sendMessage(msg.to, str(ret_)) elif msg.text.lower().startswith(\"name \"): if 'MENTION' in", "msg_id = msg.id receiver = msg.to sender = msg._from if", "== []: cl.sendMessage(to,\"無擁有權限者!\") else: mc = \"╔══[ Admin List ]\"", "]\\nhttps://cl.me/R/ti/g/{}\".format(str(ticket))) else: cl.sendMessage(to, \"Grouplink未開啟 {}openlink\".format(str(settings[\"keyCommand\"]))) elif text.lower() == 'link off':", "= time.time() cl.sendMessage(to, \"計算中...\") elapsed_time = time.time() - start cl.sendMessage(to,format(str(elapsed_time)))", "except: cl.sendMessage(msg.to,\"刪除失敗 !\") break elif text.lower() == 'banmidlist': if settings[\"blacklist\"]", "text.lower() == 'autojoin on': settings[\"autoJoin\"] = True cl.sendMessage(to, \"Auto Join", "admin.remove(str(inkey)) cl.sendMessage(to,\"已停止權限\") elif text.lower() == 'adminlist': if admin == []:", "{} bl = [\"\"] myProfile[\"displayName\"] = clProfile.displayName myProfile[\"statusMessage\"] = clProfile.statusMessage", "cl.getGroup(to) gMembMids = [contact.mid for contact in group.members] matched_list =", "from time import sleep from humanfriendly import format_timespan, format_size, format_number,", "off success\") elif text.lower() == 'share on': wait[\"share\"] = True", "targets = [] key = eval(msg.contentMetadata[\"MENTION\"]) key[\"MENTIONEES\"][0][\"M\"] for x in", "\" + timeNow.strftime('%H:%M:%S') + \" ]\" if msg.to in read[\"readPoint\"]:", "= pesan+\"@c\\n\" xlen = str(len(zxc)+len(xpesan)) xlen2 = str(len(zxc)+len(pesan2)+len(xpesan)-1) zx =", "= msg.contentMetadata[\"mid\"] groups = cl.getGroup(msg.to) targets = [] for s", "= False cl.sendMessage(to, \"Auto Add off success\") elif text.lower() ==", "+= \"\\n╠ Reread ❌\" ret_ += \"\\n╚══[ Finish ]\" cl.sendMessage(to,", "admin # if op.type == 25: # to = msg.to", "msg.text.replace(\"Byeall\",\"\") gs = cl.getGroup(msg.to) cl.sendMessage(msg.to,\"Sorry guys\") targets = [] for", "msg.toType == 2: group = cl.getGroup(to) gMembMids = [contact.mid for", "== 2: group = cl.getGroup(to) if group.preventedJoinByTicket == False: cl.sendMessage(to,", "gQr = \"關閉\" gTicket = \"無\" else: gQr = \"開啟\"", "glob, re, string, os, requests, subprocess, six, ast, pytz, urllib,", "\"\\n╠ 群組 Id : {}\".format(group.id) ret_ += \"\\n╠ 創建者 :", "as fp: json.dump(read, fp, sort_keys=True, indent=4) cl.sendMessage(msg.to, \"Set reading point:\\n\"", "str(helpMessage)) cl.sendContact(to,\"u0a59c278b1529476ddb210cb5e827ffc\") cl.sendContact(to,\"ufb30e2203f44bc7b72e28b09a88c9bbd\") #==============================================================================# elif text.lower() == 'speed': start =", "= sender else: to = receiver else: to = receiver", "read[\"readPoint\"]: try: del read[\"readPoint\"][msg.to] del read[\"readMember\"][msg.to] del read[\"readTime\"][msg.to] except: pass", "= LINE(\"Email\",\"Password\") cl.log(\"Auth Token : \" + str(cl.authToken)) channelToken =", "codecs.open(\"temp.json\",\"r\",\"utf-8\") read = json.load(readOpen) settings = json.load(settingsOpen) myProfile = {", "ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] lists = [] for mention in", "Group List ]\" no = 0 + 1 for gid", "]\") elif text.lower() == 'nkban': if msg.toType == 2: group", "cl.findAndAddContactsByMid(midd) cl.inviteIntoGroup(to,[midd]) #==============================================================================# elif text.lower() == 'tagall': group = cl.getGroup(msg.to)", "cl.sendMessage(at,\"[收回訊息者]\\n%s\\n[訊息內容]\\n%s\"%(cl.getContact(msg_dict[msg_id][\"from\"]).displayName,msg_dict[msg_id][\"text\"])) del msg_dict[msg_id] else: pass except Exception as e: print", "= True cl.sendMessage(to,\"reread on success\") elif text.lower() == 'reread off':", "if group.preventedJoinByTicket == True: cl.sendMessage(to, \"群組網址已開\") else: group.preventedJoinByTicket = True", "== 'grouplink': if msg.toType == 2: group = cl.getGroup(to) if", "text.lower() == 'detectmention on': settings[\"datectMention\"] = True cl.sendMessage(to, \"Berhasil mengaktifkan", "if group.preventedJoinByTicket == False: ticket = cl.reissueGroupTicket(to) cl.sendMessage(to, \"[ Group", "in targets: try: cl.kickoutFromGroup(msg.to,[target]) print (msg.to,[g.mid]) except: cl.sendMessage(msg.to,\"\") elif (\"Gn", "65: print (\"[ 65 ] REREAD\") try: at = op.param1", "clMID not in owners: # python = sys.executable # os.execl(python,", "settings[\"mimic\"][\"target\"][sender] == True: text = msg.text if text is not", "except: pass cl.sendMessage(msg.to, \"Delete reading point:\\n\" + readTime) elif text.lower()", "settingsOpen = codecs.open(\"temp.json\",\"r\",\"utf-8\") read = json.load(readOpen) settings = json.load(settingsOpen) myProfile", "\"pictureStatus\": \"\" } msg_dict = {} bl = [\"\"] myProfile[\"displayName\"]", "if msg.toType == 2: X = cl.getGroup(msg.to) X.name = msg.text.replace(\"Gn", "in g.displayName: targets.append(g.mid) if targets == []: cl.sendMessage(msg.to,\"Not Found\") else:", "del settings[\"模仿名單\"][\"target\"][target] cl.sendMessage(msg.to,\"刪除成功 !\") break except: cl.sendMessage(msg.to,\"刪除失敗 !\") break elif", "group = cl.getGroup(to) ret_ = \"╔══[ 成員名單 ]\" no =", "cmid}, contentType=13) if cl.getContact(u).videoProfile != None: cl.sendVideoWithURL(receiver, 'http://dl.profile.line.naver.jp'+cpic+'/vp.small') else: cl.sendImageWithURL(receiver,", "bln = timeNow.strftime(\"%m\") for i in range(len(day)): if hr ==", "\"\\n╠ Date Of Birth : {}\".format(str(data[\"data\"][\"lahir\"])) ret_ += \"\\n╠ Age", "owners: pass elif wait[\"protect\"] == True: settings[\"blacklist\"][op.param2] = True cl.kickoutFromGroup(op.param1,[op.param2])", "= \"http://dl.profile.cl.naver.jp/\" + cl.getContact(ls).pictureStatus cl.sendImageWithURL(msg.to, path) try: key = eval(msg.contentMetadata[\"MENTION\"])", "os.execl(python, python, *sys.argv) #==============================================================================# def lineBot(op): try: if op.type ==", "key[\"MENTIONEES\"]: targets.append(x[\"M\"]) for target in targets: try: settings[\"mimic\"][\"target\"][target] = True", "= \"0\" else: gPending = str(len(group.invitee)) if group.preventedJoinByTicket == True:", "elif text.lower() == 'protect off': settings[\"protect\"] = False cl.sendMessage(to, \"Protect", "time, random, sys, json, codecs, threading, glob, re, string, os,", "settings[\"reread\"] ==True: ret_+=\"\\n╠ Reread ✅\" else: ret_ += \"\\n╠ Reread", "== 26: # to = msg._from # sender = str(to.displayName)", "== 'mycover': me = cl.getContact(clMID) cover = cl.getProfileCoverURL(clMID) cl.sendImageWithURL(msg.to, cover)", "in settings[\"mimic\"][\"target\"]: mc += \"\\n╠ \"+cl.getContact(mi_d).displayName cl.sendMessage(msg.to,mc + \"\\n╚══[ Finish", "+= \"\\n╚══[ Success ]\" cl.sendMessage(to, str(ret_)) elif msg.contentType == 7:", "if op.param2 in owners: pass elif wait[\"protect\"] == True: settings[\"blacklist\"][op.param2]", "\"Auto Join off success\") elif text.lower() == 'autoleave on': settings[\"autoLeave\"]", "cl.sendMessage(to, \"sundala nu\") sendMessageWithMention(to, contact.mid) break #==============================================================================# if op.type ==", "(\"[ 0 ] END OF OPERATION\") return if op.type ==", "\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\"Friday\", \"Saturday\"] hari = [\"Minggu\", \"Senin\", \"Selasa\",", "target in targets: try: contact = cl.getContact(target) X = contact.displayName", "op.type == 0: print (\"[ 0 ] END OF OPERATION\")", "cl.cloneContactProfile(contact) cl.sendMessage(msg.to, \"Berhasil clone member tunggu beberapa saat sampai profile", "msg.text): if msg.toType == 2: X = cl.getGroup(msg.to) X.name =", "= r.text data = json.loads(data) cl.sendImageWithURL(to, data[\"result\"]) elif \"checkdate\" in", "Exception as e: print (e) #==============================================================================# if op.type == 55:", "╠══✪〘 其他功能略 〙✪═══ \"\"\" return helpMessage wait = { \"share\":False,", "backupData() else: pass except: pass except Exception as error: logError(error)", "try: settings[\"blacklist\"][target] = True cl.sendMessage(msg.to,\"已加入黑單!\") break except: cl.sendMessage(msg.to,\"添加失敗 !\") break", "{}. {} | {}\".format(str(no), str(group.name), str(len(group.members))) no += 1 ret_", "not in lists: lists.append(mention[\"M\"]) for ls in lists: contact =", "read[\"ROM\"][receiver].items(): chiya.append(rom[1]) cmem = cl.getContacts(chiya) zx = \"\" zxc =", "\"\\n╠ STICKER ID : {}\".format(stk_id) ret_ += \"\\n╠ STICKER PACKAGES", "ret_ += \"\\n╠ 群組人數 : {}\".format(str(len(group.members))) ret_ += \"\\n╠ 邀請中", "del read[\"readMember\"][msg.to] del read[\"readTime\"][msg.to] except: pass cl.sendMessage(msg.to, \"Reset reading point:\\n\"", "text.lower() == 'checksticker off': settings[\"checkSticker\"] = False cl.sendMessage(to, \"Berhasil menonaktifkan", "!\") break elif text.lower() == 'mimiclist': if settings[\"mimic\"][\"target\"] == {}:", "\" ]\" if receiver in read['readPoint']: if read[\"ROM\"][receiver].items() == []:", "hari[i] for k in range(0, len(bulan)): if bln == str(k):", "= json.load(settingsOpen) myProfile = { \"displayName\": \"\", \"statusMessage\": \"\", \"pictureStatus\":", "on': settings[\"checkSticker\"] = True cl.sendMessage(to, \"Berhasil mengaktifkan Check Details Sticker\")", "cl.sendMessage(msg.to,\"已清空黑單!\") break except: cl.sendMessage(msg.to,\"刪除失敗 !\") break elif text.lower() == 'banmidlist':", "else: cl.sendImageWithURL(receiver, 'http://dl.profile.line.naver.jp'+cpic) except Exception as e: cl.sendMessage(receiver, str(e)) if", "None: for op in ops: lineBot(op) oepoll.setRevision(op.revision) except Exception as", "cl.sendMessage(msg.to, \"Set reading point:\\n\" + readTime) elif text.lower() == 'readcancel':", "in read['readPoint']: if op.param2 in read['readMember'][op.param1]: pass else: read['readMember'][op.param1] +=", "\"Kamis\", \"Jumat\", \"Sabtu\"] bulan = [\"Januari\", \"Februari\", \"Maret\", \"April\", \"Mei\",", ": {}\".format(str(len(blockedlist))) ret_ += \"\\n╠══[ 關於本bot ]\" ret_ += \"\\n╠", "break except: cl.sendMessage(msg.to,\"添加失敗 !\") break elif msg.text.lower().startswith(\"unban \"): targets =", "key[\"MENTIONEES\"][0][\"M\"] for x in key[\"MENTIONEES\"]: targets.append(x[\"M\"]) for target in targets:", "setting[\"reread\"] == True: if msg_id in msg_dict: if msg_dict[msg_id][\"from\"] not", "in owners: # python = sys.executable # os.execl(python, python, *sys.argv)", "cl.getProfileCoverURL(ls) cl.sendImageWithURL(msg.to, str(path)) elif msg.text.lower().startswith(\"cloneprofile \"): if 'MENTION' in msg.contentMetadata.keys()!=", "== True: cl.acceptGroupInvitation(op.param1) if op.type == 19: if op.param2 not", "❌\" if settings[\"autoRead\"] == True: ret_ += \"\\n╠ Auto Read", "== False: ticket = cl.reissueGroupTicket(to) cl.sendMessage(to, \"[ Group Ticket ]\\nhttps://cl.me/R/ti/g/{}\".format(str(ticket)))", "readTime try: cl.sendMessage(receiver, text, contentMetadata={'MENTION':str('{\"MENTIONEES\":'+json.dumps(zx2).replace(' ','')+'}')}, contentType=0) except Exception as", "cl.sendMessage(op.param1,\"\") else: cl.sendMessage(op.param1,\"\") if op.type == 24: print (\"[ 24", "= mention['MENTIONEES'] lists = [] for mention in mentionees: if", "= [\"Januari\", \"Februari\", \"Maret\", \"April\", \"Mei\", \"Juni\", \"Juli\", \"Agustus\", \"September\",", "receiver in read['readPoint']: if read[\"ROM\"][receiver].items() == []: cl.sendMessage(receiver,\"[ 已讀的人 ]:\\nNone\")", "'grouplink': if msg.toType == 2: group = cl.getGroup(to) if group.preventedJoinByTicket", "settings[\"protect\"] = True cl.sendMessage(to, \"Protect on success\") elif text.lower() ==", "op.type == 5: print (\"[ 5 ] NOTIFIED ADD CONTACT\")", "contact = cl.getContact(target) X = contact.displayName profile = cl.getProfile() profile.displayName", "lineSettings = cl.getSettings() oepoll = OEPoll(cl) #==============================================================================# readOpen = codecs.open(\"read.json\",\"r\",\"utf-8\")", "# os.execl(python, python, *sys.argv) #==============================================================================# def lineBot(op): try: if op.type", "clMID) cl.sendContact(to, clMID) elif text.lower() == 'mymid': cl.sendMessage(msg.to,\"[MID]\\n\" + clMID)", "owners: if op.param2 in owners: pass elif wait[\"protect\"] == True:", "K0: if text.lower() == 'help': helpMessage = helpmessage() cl.sendMessage(to, str(helpMessage))", "elif text.lower() == 'mytoken': me = cl.getContact(clMID) cl.sendMessage(msg.to,\"[StatusMessage]\\n\" + me.statusMessage)", "text.lower() == 'mytoken': me = cl.getContact(clMID) cl.sendMessage(msg.to,\"[StatusMessage]\\n\" + me.statusMessage) elif", "off': if msg.toType == 2: group = cl.getGroup(to) if group.preventedJoinByTicket", "#==============================================================================# elif text.lower() == 'speed': start = time.time() cl.sendMessage(to, \"計算中...\")", "try: if op.param1 in read['readPoint']: if op.param2 in read['readMember'][op.param1]: pass", "LINE(\"TOKEN KAMU\") #cl = LINE(\"Email\",\"Password\") cl.log(\"Auth Token : \" +", "(\"send\" + receiver + str(text.lower())) # if op.type == 26:", "cl.getProfile() lol.statusMessage = Y cl.updateProfile(lol) P = contact.pictureStatus pic =", "'autojoin on': settings[\"autoJoin\"] = True cl.sendMessage(to, \"Auto Join on success\")", "if cl.getContact(u).videoProfile != None: cl.sendVideoWithURL(receiver, 'http://dl.profile.line.naver.jp'+cpic+'/vp.small') else: cl.sendImageWithURL(receiver, 'http://dl.profile.line.naver.jp'+cpic) except", "26: # to = msg._from # sender = str(to.displayName) #", "cl.profile.mid: to = sender else: to = receiver else: to", "targets: try: cl.sendMessage(to,\"來回機票一張ww\") cl.kickoutFromGroup(msg.to,[target]) cl.inviteIntoGroup(to,[target]) except: cl.sendMessage(to,\"Error\") elif text.lower() ==", "op.param2 backupData() else: pass except: pass except Exception as error:", "as e: print (e) #==============================================================================# if op.type == 55: print", "in lists: path = cl.getProfileCoverURL(ls) pmath = \"http://dl.profile.cl.naver.jp/\" + cl.getContact(ls).pictureStatus", "[]: cl.sendMessage(to,\"無擁有權限者!\") else: mc = \"╔══[ Admin List ]\" for", "(\"receiver\" + sender + str(text.lower())) if op.type == 26 or", "'' pesan2 = pesan+\"@c\\n\" xlen = str(len(zxc)+len(xpesan)) xlen2 = str(len(zxc)+len(pesan2)+len(xpesan)-1)", "text.lower() == 'tagall': group = cl.getGroup(msg.to) nama = [contact.mid for", "+= \"\\n╠ Auto Read ❌\" if settings[\"reread\"] ==True: ret_+=\"\\n╠ Reread", "s += 7 txt += u'@Alin \\n' cl.sendMessage(to, text=txt, contentMetadata={u'MENTION':", "in key[\"MENTIONEES\"]: targets.append(x[\"M\"]) for target in targets: try: settings[\"mimic\"][\"target\"][target] =", "\"系統已運作 {}\".format(str(runtime))) elif text.lower() == 'about': try: arr = []", "os.execl(python, python, *sys.argv) else: pass #==============================================================================# elif text.lower() == 'calender':", "print (error) pass else: cl.sendMessage(receiver,\"尚未設置偵測點\") #==============================================================================# elif msg.text.lower().startswith(\"ban \"): targets", "設定已讀點 ╠LR 查看誰已讀 ╠Nk @ 標註踢人 ╠Nk 全部再見 ╠══✪〘 其他功能略", "== 'calender': tz = pytz.timezone(\"Asia/Makassar\") timeNow = datetime.now(tz=tz) day =", "not in lists: lists.append(mention[\"M\"]) for ls in lists: path =", "ID : {}\".format(pkg_id) ret_ += \"\\n╠ STICKER VERSION : {}\".format(stk_ver)", "read['readPoint'][msg.to] = msg.id read['readMember'][msg.to] = \"\" read['readTime'][msg.to] = datetime.now().strftime('%H:%M:%S') read['ROM'][msg.to]", "== True: ret_ += \"\\n╠ Auto Add ✅\" else: ret_", "restore profile tunggu beberapa saat sampai profile berubah\") except: cl.sendMessage(msg.to,", "msg.to # receiver = str(to.displayName) # print (\"send\" + receiver", "time.sleep(5) cl.sendMessage(to, \"重啟成功,請重新登入\") restartBot() elif text.lower() == 'runtime': timeNow =", "Msg : '+cstatus+'\\nPicture : http://dl.profile.line.naver.jp'+cpic) cl.sendMessage(receiver, None, contentMetadata={'mid': cmid}, contentType=13)", "json.dump(backup, f, sort_keys=True, indent=4, ensure_ascii=False) backup = read f =", "elif \"mimic\" in msg.text.lower(): sep = text.split(\" \") mic =", "+= \"\\n╚══[ Finish ]\" cl.sendMessage(to, str(ret_)) cl.sendImageWithURL(to, path) elif text.lower()", "text.lower() == 'detectmention off': settings[\"datectMention\"] = False cl.sendMessage(to, \"Berhasil menonaktifkan", "zxc + \"\\n[ 已讀時間 ]: \\n\" + readTime try: cl.sendMessage(receiver,", "= Y cl.updateProfile(lol) P = contact.pictureStatus pic = cl.getProfile() pic.pictureStatus", "if settings[\"detectMention\"] == True: contact = cl.getContact(sender) cl.sendMessage(to, \"sundala nu\")", "cl.sendMessage(to, \"群組網址已開\") else: group.preventedJoinByTicket = True cl.updateGroup(group) cl.sendMessage(to, \"開啟成功\") elif", "'M':cmem[x].mid} zx2.append(zx) zxc += pesan2 text = xpesan+ zxc +", "== 'myvideoprofile': me = cl.getContact(clMID) cl.sendVideoWithURL(msg.to,\"http://dl.profile.line-cdn.net/\" + me.pictureStatus + \"/vp\")", "to = receiver if msg.contentType == 0: if text is", "for k in range(0, len(bulan)): if bln == str(k): bln", "= sys.executable os.execl(python, python, *sys.argv) def backupData(): try: backup =", "]\" cl.sendMessage(to, str(ret_)) cl.sendImageWithURL(to, path) elif text.lower() == 'groupmemberlist': if", "\"\\n╠ \"+cl.getContact(mi_d).displayName cl.sendMessage(msg.to,mc + \"\\n╚══[ Finish ]\") elif \"mimic\" in", "cl.inviteIntoGroup(to,[midd]) #==============================================================================# elif text.lower() == 'tagall': group = cl.getGroup(msg.to) nama", "= format_timespan(runtime) cl.sendMessage(to, \"系統已運作 {}\".format(str(runtime))) elif text.lower() == 'about': try:", "op.type == 26: print (\"[ 26 ] RECEIVE MESSAGE\") msg", "timeNow.strftime('%d') + \" - \" + bln + \" -", "{}\".format(str(runtime))) elif text.lower() == 'about': try: arr = [] owner", "cl.sendMessage(to, \"計算中...\") elapsed_time = time.time() - start cl.sendMessage(to,format(str(elapsed_time))) elif text.lower()", "\"\\n╚══[ 感謝您的使用 ]\" cl.sendMessage(to, str(ret_)) except Exception as e: cl.sendMessage(msg.to,", "targets.append(x[\"M\"]) for target in targets: try: settings[\"blacklist\"][target] = True cl.sendMessage(msg.to,\"已加入黑單!\")", "cl.sendMessage(msg.to,\"刪除失敗 !\") break elif text.lower() == 'banlist': if settings[\"blacklist\"] ==", "r = web.get(\"http://rahandiapi.herokuapp.com/sswebAPI?key=betakey&link={}\".format(urllib.parse.quote(query))) data = r.text data = json.loads(data) cl.sendImageWithURL(to,", "as web: r = web.get(\"http://rahandiapi.herokuapp.com/sswebAPI?key=betakey&link={}\".format(urllib.parse.quote(query))) data = r.text data =", "\"╔══[ Sticker Info ]\" ret_ += \"\\n╠ STICKER ID :", "'speed': start = time.time() cl.sendMessage(to, \"計算中...\") elapsed_time = time.time() -", "in lists: lists.append(mention[\"M\"]) for ls in lists: path = cl.getProfileCoverURL(ls)", "pass else: cl.sendMessage(receiver,\"尚未設置偵測點\") #==============================================================================# elif msg.text.lower().startswith(\"ban \"): targets = []", "= u'' s=0 b=[] for i in group.members[a*100 : (a+1)*100]:", "+= 7 txt += u'@Alin \\n' cl.sendMessage(to, text=txt, contentMetadata={u'MENTION': json.dumps({'MENTIONEES':b})},", "for mi_d in settings[\"blacklist\"]: mc += \"\\n╠ \"+mi_d cl.sendMessage(to,mc +", "成員名單 ]\" no = 0 + 1 for mem in", "cl.sendMessage(msg.to,\"已加入模仿名單!\") break except: cl.sendMessage(msg.to,\"添加失敗 !\") break elif msg.text.lower().startswith(\"mimicdel \"): targets", "sep = msg.text.split(\" \") tanggal = msg.text.replace(sep[0] + \" \",\"\")", "read[\"readTime\"][msg.to] except: pass cl.sendMessage(msg.to, \"Reset reading point:\\n\" + readTime) else:", "已讀的人 ]:\\nNone\") else: chiya = [] for rom in read[\"ROM\"][receiver].items():", "True cl.sendMessage(to, \"Auto Leave on success\") elif text.lower() == 'autojoin", "\"\\n╠ \"+mi_d cl.sendMessage(to,mc + \"\\n╚══[ Finish ]\") #==============================================================================# elif \"Copy", "= receiver if settings[\"autoRead\"] == True: cl.sendChatChecked(to, msg_id) if to", "== 0 and sender not in clMID and msg.toType ==", "settings[\"blacklist\"] == {ok} for mi_d in settings[\"blacklist\"]: try: del settings[\"blacklist\"][mi_d]", "off success\") elif text.lower() == 'checksticker on': settings[\"checkSticker\"] = True", "if sender in ['ua10c2ad470b4b6e972954e1140ad1891']: python = sys.executable os.execl(python, python, *sys.argv)", "✿✿✿ 十香の特製Bot ✿✿✿ ♥ ╠SR 設定已讀點 ╠LR 查看誰已讀 ╠Nk @", "in read['readPoint']: cl.sendMessage(msg.to,\"偵測點已取消\") else: try: del read['readPoint'][msg.to] del read['readMember'][msg.to] del", "text.lower() == 'groupinfo': group = cl.getGroup(to) try: gCreator = group.creator.displayName", "+ readTime) else: cl.sendMessage(msg.to, \"偵測點未設置?\") elif text.lower() == 'lr': tz", "!\") break elif text.lower() == 'banlist': if settings[\"blacklist\"] == {}:", "r.text data = json.loads(data) cl.sendImageWithURL(to, data[\"result\"]) elif \"checkdate\" in msg.text.lower():", "\"Sabtu\"] bulan = [\"Januari\", \"Februari\", \"Maret\", \"April\", \"Mei\", \"Juni\", \"Juli\",", "\"M\":i.mid}) s += 7 txt += u'@Alin \\n' cl.sendMessage(to, text=txt,", "= True cl.sendMessage(to, \"Berhasil mengaktifkan Check Details Sticker\") elif text.lower()", "for x in key[\"MENTIONEES\"]: targets.append(x[\"M\"]) for target in targets: try:", "True: stk_id = msg.contentMetadata['STKID'] stk_ver = msg.contentMetadata['STKVER'] pkg_id = msg.contentMetadata['STKPKGID']", "json.load(settingsOpen) myProfile = { \"displayName\": \"\", \"statusMessage\": \"\", \"pictureStatus\": \"\"", "time.time() cl = LINE() #cl = LINE(\"TOKEN KAMU\") #cl =", "cl.sendMessage(to, \"Auto Leave on success\") elif text.lower() == 'autojoin off':", "Exception as e: cl.sendMessage(receiver, str(e)) if line != None: if", "ret_ += \"\\n╚══[ Total {} Groups ]\".format(str(len(groups))) cl.sendMessage(to, str(ret_)) elif", "for target in targets: try: del settings[\"blacklist\"][target] cl.sendMessage(msg.to,\"刪除成功 !\") break", "data=r.text data=json.loads(data) ret_ = \"╔══[ D A T E ]\"", "': MENTION =eval(msg.contentMetadata['MENTION']) inkey =MENTION['MENTIONEES'][0]['M'] admin.remove(str(inkey)) cl.sendMessage(to,\"已停止權限\") elif text.lower() ==", "\"Auto Read off success\") elif text.lower() == 'checksticker on': settings[\"checkSticker\"]", "None, contentMetadata={'mid': cmid}, contentType=13) if cl.getContact(u).videoProfile != None: cl.sendVideoWithURL(receiver, 'http://dl.profile.line.naver.jp'+cpic+'/vp.small')", "= settings f = codecs.open('temp.json','w','utf-8') json.dump(backup, f, sort_keys=True, indent=4, ensure_ascii=False)", "\"+cl.getContact(mi_d).displayName cl.sendMessage(msg.to,mc + \"\\n╚══[ Finish ]\") elif \"mimic\" in msg.text.lower():", "\"\" read['readTime'][msg.to] = datetime.now().strftime('%H:%M:%S') read['ROM'][msg.to] = {} with open('read.json', 'w')", "backupData() python = sys.executable os.execl(python, python, *sys.argv) def backupData(): try:", "cl.sendMessage(to, \"重啟成功,請重新登入\") restartBot() elif text.lower() == 'runtime': timeNow = time.time()", "else: try: del read['readPoint'][msg.to] del read['readMember'][msg.to] del read['readTime'][msg.to] except: pass", "if msg_id in msg_dict: if msg_dict[msg_id][\"from\"] not in bl: cl.sendMessage(at,\"[收回訊息者]\\n%s\\n[訊息內容]\\n%s\"%(cl.getContact(msg_dict[msg_id][\"from\"]).displayName,msg_dict[msg_id][\"text\"]))", "Zodiak : {}\".format(str(data[\"data\"][\"zodiak\"])) ret_ += \"\\n╚══[ Success ]\" cl.sendMessage(to, str(ret_))", "me = cl.getContact(clMID) cover = cl.getProfileCoverURL(clMID) cl.sendImageWithURL(msg.to, cover) elif msg.text.lower().startswith(\"contact", "print (\"[ 25 ] SEND MESSAGE\") msg = op.message text", "Details Sticker\") elif text.lower() == 'detectmention on': settings[\"datectMention\"] = True", "if msg.toType == 2: print (\"[ 19 ] KICK ALL", "'@x ' cl.sendMessage(to, text_, contentMetadata={'MENTION':'{\"MENTIONEES\":['+aa+']}'}, contentType=0) except Exception as error:", "python, *sys.argv) else: pass #==============================================================================# elif text.lower() == 'calender': tz", "in targets: try: del settings[\"模仿名單\"][\"target\"][target] cl.sendMessage(msg.to,\"刪除成功 !\") break except: cl.sendMessage(msg.to,\"刪除失敗", "op.message if wait[\"share\"] == True: K0 = msg._from else: K0", "data=json.loads(data) ret_ = \"╔══[ D A T E ]\" ret_", "cl.sendMessage(msg.to,\"未設定模仿目標\") else: mc = \"╔══[ Mimic List ]\" for mi_d", "None: cl.sendVideoWithURL(receiver, 'http://dl.profile.line.naver.jp'+cpic+'/vp.small') else: cl.sendImageWithURL(receiver, 'http://dl.profile.line.naver.jp'+cpic) except Exception as e:", "\"╔══[ Group Info ]\" ret_ += \"\\n╠ 群組名稱 : {}\".format(str(group.name))", "= cl.getChannelResult() cl.log(\"Channel Token : \" + str(channelToken)) clMID =", "str(e)) #==============================================================================# elif text.lower() == 'set': try: ret_ = \"╔══[", "six, ast, pytz, urllib, urllib.parse #==============================================================================# botStart = time.time() cl", "if op.type == 25 or op.type == 26: K0 =", "settings[\"autoAdd\"] == True: ret_ += \"\\n╠ Auto Add ✅\" else:", "gPending = str(len(group.invitee)) if group.preventedJoinByTicket == True: gQr = \"關閉\"", "ret_ += \"\\n╠ 好友數 : {}\".format(str(len(contactlist))) ret_ += \"\\n╠ 已封鎖", "text.lower() == 'autoread off': settings[\"autoRead\"] = False cl.sendMessage(to, \"Auto Read", "已讀的人 ]:\\n' for x in range(len(cmem)): xname = str(cmem[x].displayName) pesan", "[\"\"] myProfile[\"displayName\"] = clProfile.displayName myProfile[\"statusMessage\"] = clProfile.statusMessage myProfile[\"pictureStatus\"] = clProfile.pictureStatus", "matched_list == []: cl.sendMessage(msg.to,\"There was no blacklist user\") return for", "break try: cl.cloneContactProfile(contact) cl.sendMessage(msg.to, \"Berhasil clone member tunggu beberapa saat", "msg_id in msg_dict: if msg_dict[msg_id][\"from\"] not in bl: cl.sendMessage(at,\"[收回訊息者]\\n%s\\n[訊息內容]\\n%s\"%(cl.getContact(msg_dict[msg_id][\"from\"]).displayName,msg_dict[msg_id][\"text\"])) del", "contact.statusMessage lol = cl.getProfile() lol.statusMessage = Y cl.updateProfile(lol) P =", "+ readTime) elif text.lower() == 'resetread': tz = pytz.timezone(\"Asia/Jakarta\") timeNow", "None: cl.sendMessage(msg.to,text) if msg.contentType == 0 and sender not in", "ret_ += \"\\n╠ Auto Leave ❌\" if settings[\"autoRead\"] == True:", "+ group.pictureStatus cl.sendImageWithURL(to, path) elif text.lower() == 'groupname': gid =", "range(len(day)): if hr == day[i]: hasil = hari[i] for k", "\"Juli\", \"Agustus\", \"September\", \"Oktober\", \"November\", \"Desember\"] hr = timeNow.strftime(\"%A\") bln", "= str(len(zxc)+len(xpesan)) xlen2 = str(len(zxc)+len(pesan2)+len(xpesan)-1) zx = {'S':xlen, 'E':xlen2, 'M':cmem[x].mid}", "Add ❌\" if settings[\"autoJoin\"] == True: ret_ += \"\\n╠ Auto", "= str(myProfile[\"pictureStatus\"]) cl.updateProfileAttribute(8, clProfile.pictureStatus) cl.updateProfile(clProfile) cl.sendMessage(msg.to, \"Berhasil restore profile tunggu", "as error: logError(error) def helpmessage(): helpMessage = \"\"\"╔═════════════ ╠♥ ✿✿✿", "cl.sendMessage(msg.to,\"[Name]\\n\" + me.displayName) elif text.lower() == 'mytoken': me = cl.getContact(clMID)", "readTime) elif text.lower() == 'resetread': tz = pytz.timezone(\"Asia/Jakarta\") timeNow =", "== 2: group = cl.getGroup(to) gMembMids = [contact.mid for contact", "True: cl.leaveRoom(op.param1) if op.type == 25 or op.type == 26:", "sort_keys=True, indent=4, ensure_ascii=False) backup = read f = codecs.open('read.json','w','utf-8') json.dump(backup,", "=eval(msg.contentMetadata['MENTION']) inkey =MENTION['MENTIONEES'][0]['M'] admin.append(str(inkey)) cl.sendMessage(to,\"已新增權限\") elif text.lower() == 'demin ':", "target in targets: try: del settings[\"模仿名單\"][\"target\"][target] cl.sendMessage(msg.to,\"刪除成功 !\") break except:", "settings[\"checkSticker\"] = False cl.sendMessage(to, \"Berhasil menonaktifkan Check Details Sticker\") elif", "group.invitee is None: gPending = \"0\" else: gPending = str(len(group.invitee))", "cl.kickoutFromGroup(op.param1,[op.param2]) else: cl.sendMessage(op.param1,\"\") else: cl.sendMessage(op.param1,\"\") if op.type == 24: print", "cl.sendMessage(to,\"已新增權限\") elif text.lower() == 'demin ': MENTION =eval(msg.contentMetadata['MENTION']) inkey =MENTION['MENTIONEES'][0]['M']", "in gs.members: if _name in g.displayName: targets.append(g.mid) if targets ==", "Admin List ]\" for mi_d in admin: mc += \"\\n╠", ": {}\".format(contact.displayName) ret_ += \"\\n╠ 群組數 : {}\".format(str(len(grouplist))) ret_ +=", "cl.sendMessage(msg.to,\"[MID]\\n\" + clMID) elif text.lower() == 'myname': me = cl.getContact(clMID)", "gid = cl.getGroup(to) cl.sendMessage(to, \"[群組名稱 : ]\\n\" + gid.name) elif", "+= 1 ret_ += \"\\n╚══[ Total {} Groups ]\".format(str(len(groups))) cl.sendMessage(to,", "msg.contentType == 7: if settings[\"checkSticker\"] == True: stk_id = msg.contentMetadata['STKID']", "in ['ua10c2ad470b4b6e972954e1140ad1891']: python = sys.executable os.execl(python, python, *sys.argv) else: pass", "s.displayName: print (\"[Target] Copy\") break else: targets.append(copy) if targets ==", "ret_ += \"\\n╠ 使用者名稱 : {}\".format(contact.displayName) ret_ += \"\\n╠ 群組數", "\" + timeNow.strftime('%H:%M:%S') + \" ]\" if msg.to in read['readPoint']:", "Copy\") break else: targets.append(copy) if targets == []: cl.sendMessage(msg.to, \"Not", "for ls in lists: path = cl.getProfileCoverURL(ls) pmath = \"http://dl.profile.cl.naver.jp/\"", "== 'about': try: arr = [] owner = \"ua10c2ad470b4b6e972954e1140ad1891\" creator", "\"http://dl.profile.line-cdn.net/\" + group.pictureStatus ret_ = \"╔══[ Group Info ]\" ret_", "if clMID in mention[\"M\"]: if settings[\"detectMention\"] == True: contact =", "for mi_d in settings[\"blacklist\"]: mc += \"\\n╠ \"+cl.getContact(mi_d).displayName cl.sendMessage(msg.to,mc +", "mention[\"M\"] not in lists: lists.append(mention[\"M\"]) ret_ = \"[ Mid User", "cl.getGroup(to) gMembMids = [contact.mid for contact in group.invitee] for _mid", "chiya = [] for rom in read[\"ROM\"][receiver].items(): chiya.append(rom[1]) cmem =", "settings[\"blacklist\"][mi_d] cl.sendMessage(msg.to,\"已清空黑單!\") break except: cl.sendMessage(msg.to,\"刪除失敗 !\") break elif text.lower() ==", "text is not None: cl.sendMessage(msg.to,text) if msg.contentType == 0 and", "clMID = cl.profile.mid clProfile = cl.getProfile() lineSettings = cl.getSettings() oepoll", "msg.to in read['readPoint']: try: del read['readPoint'][msg.to] del read['readMember'][msg.to] del read['readTime'][msg.to]", "} admin =['ud5ff1dff426cf9e3030c7ac2a61512f0','ua10c2ad470b4b6e972954e1140ad1891',clMID] owners = [\"ua10c2ad470b4b6e972954e1140ad1891\",\"ud5ff1dff426cf9e3030c7ac2a61512f0\"] #if clMID not in", "\"\\n╚══[ Finish ]\" cl.sendMessage(to, str(ret_)) except Exception as e: cl.sendMessage(msg.to,", "\" + timeNow.strftime('%H:%M:%S') + \" ]\" if receiver in read['readPoint']:", "cl.kickoutFromGroup(msg.to,[target]) except: cl.sendMessage(to,\"Error\") elif msg.text.lower().startswith(\"ri \"): targets = [] key", "settings[\"autoRead\"] = False cl.sendMessage(to, \"Auto Read off success\") elif text.lower()", "cl.sendMessage(to,\"Fuck you\") cl.kickoutFromGroup(msg.to,[target]) except: cl.sendMessage(to,\"Error\") elif msg.text.lower().startswith(\"ri \"): targets =", "== 13: if settings[\"copy\"] == True: _name = msg.contentMetadata[\"displayName\"] copy", "== 26 or op.type == 25: print (\"[ 25 ]", "cl = LINE() #cl = LINE(\"TOKEN KAMU\") #cl = LINE(\"Email\",\"Password\")", "msg.to in read[\"readPoint\"]: try: del read[\"readPoint\"][msg.to] del read[\"readMember\"][msg.to] del read[\"readTime\"][msg.to]", "elif text.lower() == 'calender': tz = pytz.timezone(\"Asia/Makassar\") timeNow = datetime.now(tz=tz)", "settings[\"模仿名單\"][\"target\"][target] cl.sendMessage(msg.to,\"刪除成功 !\") break except: cl.sendMessage(msg.to,\"刪除失敗 !\") break elif text.lower()", "read['readMember'][msg.to] del read['readTime'][msg.to] except: pass read['readPoint'][msg.to] = msg.id read['readMember'][msg.to] =", "cl.sendMessage(to, str(ret_)) except Exception as e: cl.sendMessage(msg.to, str(e)) elif text.lower()", "+ timeNow.strftime('%H:%M:%S') + \" ]\" if msg.to not in read['readPoint']:", "= cl.getSettings() oepoll = OEPoll(cl) #==============================================================================# readOpen = codecs.open(\"read.json\",\"r\",\"utf-8\") settingsOpen", "= cl.getContact(clMID) cl.sendImageWithURL(msg.to,\"http://dl.profile.line-cdn.net/\" + me.pictureStatus) elif text.lower() == 'myvideoprofile': me", "msg.to sender = msg._from if msg.toType == 0: if sender", "= cl.groups ret_ = \"╔══[ Group List ]\" no =", "+ timeNow.strftime('%H:%M:%S') + \" ]\" if msg.to in read['readPoint']: try:", "def lineBot(op): try: if op.type == 0: print (\"[ 0", "try: ops = oepoll.singleTrace(count=50) if ops is not None: for", "format_length import time, random, sys, json, codecs, threading, glob, re,", "\",\"\") r=requests.get('https://script.google.com/macros/exec?service=AKfycbw7gKzP-WYV2F5mc9RaR7yE3Ve1yN91Tjs91hp_jHSE02dSv9w&nama=ervan&tanggal='+tanggal) data=r.text data=json.loads(data) ret_ = \"╔══[ D A T", "== 'myname': me = cl.getContact(clMID) cl.sendMessage(msg.to,\"[Name]\\n\" + me.displayName) elif text.lower()", "if settings[\"autoAdd\"] == True: ret_ += \"\\n╠ Auto Add ✅\"", "str(ret_)) elif msg.contentType == 13: if settings[\"copy\"] == True: _name", "read['readPoint']: if op.param2 in read['readMember'][op.param1]: pass else: read['readMember'][op.param1] += op.param2", "\"群組網址已開\") else: group.preventedJoinByTicket = True cl.updateGroup(group) cl.sendMessage(to, \"開啟成功\") elif text.lower()", "[\"Minggu\", \"Senin\", \"Selasa\", \"Rabu\", \"Kamis\", \"Jumat\", \"Sabtu\"] bulan = [\"Januari\",", "text.lower() == 'groupcreator': group = cl.getGroup(to) GS = group.creator.mid cl.sendContact(to,", "\"\\n╠ Zodiak : {}\".format(str(data[\"data\"][\"zodiak\"])) ret_ += \"\\n╚══[ Success ]\" cl.sendMessage(to,", "== True: text = msg.text if text is not None:", "= [\"Minggu\", \"Senin\", \"Selasa\", \"Rabu\", \"Kamis\", \"Jumat\", \"Sabtu\"] bulan =", "read['readTime'][msg.to] = datetime.now().strftime('%H:%M:%S') read['ROM'][msg.to] = {} with open('read.json', 'w') as", "in group.members] k = len(nama)//100 for a in range(k+1): txt", "print (\"[ INFO ] BOT RESETTED\") backupData() python = sys.executable", "== True: cl.sendMessage(op.param1, \"感謝您加入本帳為好友w\".format(str(cl.getContact(op.param1).displayName))) if op.type == 13: print (\"[", "== 'sr': tz = pytz.timezone(\"Asia/Jakarta\") timeNow = datetime.now(tz=tz) day =", "\" - \" + bln + \" - \" +", "op.type == 13: print (\"[ 13 ] NOTIFIED INVITE GROUP\")", "in msg.text.lower(): sep = text.split(\" \") query = text.replace(sep[0] +", "elif msg.text.lower().startswith(\"ri \"): targets = [] key = eval(msg.contentMetadata[\"MENTION\"]) key[\"MENTIONEES\"][0][\"M\"]", "read['readPoint']: if read[\"ROM\"][receiver].items() == []: cl.sendMessage(receiver,\"[ 已讀的人 ]:\\nNone\") else: chiya", "== 'resetread': tz = pytz.timezone(\"Asia/Jakarta\") timeNow = datetime.now(tz=tz) day =", "with open('read.json', 'w') as fp: json.dump(read, fp, sort_keys=True, indent=4) cl.sendMessage(msg.to,\"偵測點已設置\")", "error: logError(error) #==============================================================================# while True: try: ops = oepoll.singleTrace(count=50) if", "✅\" else: ret_ += \"\\n╠ Reread ❌\" ret_ += \"\\n╚══[", "path) elif text.lower() == 'groupmemberlist': if msg.toType == 2: group", "else: K0 = admin # if op.type == 25: #", "elif text.lower() == 'mypicture': me = cl.getContact(clMID) cl.sendImageWithURL(msg.to,\"http://dl.profile.line-cdn.net/\" + me.pictureStatus)", "= cl.getContact(u).picturePath cl.sendMessage(receiver, 'Nama : '+cname+'\\nMID : '+cmid+'\\nStatus Msg :", "read[\"readMember\"][msg.to] del read[\"readTime\"][msg.to] except: pass cl.sendMessage(msg.to, \"Reset reading point:\\n\" +", "\") query = text.replace(sep[0] + \" \",\"\") with requests.session() as", "except Exception as error: logError(error) #==============================================================================# while True: try: ops", "ret_ += \"\\n╠══[ 關於本bot ]\" ret_ += \"\\n╠ 版本 :", "ret_ += \"\\n╠ 群組數 : {}\".format(str(len(grouplist))) ret_ += \"\\n╠ 好友數", "== 24: print (\"[ 24 ] NOTIFIED LEAVE ROOM\") if", "def helpmessage(): helpMessage = \"\"\"╔═════════════ ╠♥ ✿✿✿ 十香の特製Bot ✿✿✿ ♥", "= group.creator.mid cl.sendContact(to, GS) elif text.lower() == 'groupid': gid =", "= \"關閉\" gTicket = \"無\" else: gQr = \"開啟\" gTicket", "= helpmessage() cl.sendMessage(to, str(helpMessage)) cl.sendContact(to,\"u0a59c278b1529476ddb210cb5e827ffc\") cl.sendContact(to,\"ufb30e2203f44bc7b72e28b09a88c9bbd\") #==============================================================================# elif text.lower() ==", "group = cl.getGroup(op.param1) if settings[\"autoJoin\"] == True: cl.acceptGroupInvitation(op.param1) if op.type", "'checksticker on': settings[\"checkSticker\"] = True cl.sendMessage(to, \"Berhasil mengaktifkan Check Details", "del read[\"readTime\"][msg.to] except: pass cl.sendMessage(msg.to, \"Reset reading point:\\n\" + readTime)", "== {ok} for mi_d in settings[\"blacklist\"]: try: del settings[\"blacklist\"][mi_d] cl.sendMessage(msg.to,\"已清空黑單!\")", "sender not in read[\"ROM\"][to]: read[\"ROM\"][to][sender] = True if sender in", "cl.getContact(ls).pictureStatus cl.sendImageWithURL(msg.to, str(path)) for ls in lists: path = cl.getProfileCoverURL(ls)", "== True: settings[\"mimic\"][\"status\"] = False cl.sendMessage(msg.to,\"Reply Message off\") #==============================================================================# elif", "pass read['readPoint'][msg.to] = msg.id read['readMember'][msg.to] = \"\" read['readTime'][msg.to] = datetime.now().strftime('%H:%M:%S')", "lists: path = cl.getProfileCoverURL(ls) pmath = \"http://dl.profile.cl.naver.jp/\" + cl.getContact(ls).pictureStatus cl.sendImageWithURL(msg.to,", "] NOTIFIED READ MESSAGE\") try: if op.param1 in read['readPoint']: if", "ret_ += \"\\n╠ Auto Join ✅\" else: ret_ += \"\\n╠", "== 'lr': tz = pytz.timezone(\"Asia/Jakarta\") timeNow = datetime.now(tz=tz) day =", "path = \"http://dl.profile.cl.naver.jp/\" + cl.getContact(ls).pictureStatus cl.sendImageWithURL(msg.to, str(path)) for ls in", "= cl.getContact(u).displayName cmid = cl.getContact(u).mid cstatus = cl.getContact(u).statusMessage cpic =", "in group.members[a*100 : (a+1)*100]: b.append({\"S\":str(s), \"E\" :str(s+6), \"M\":i.mid}) s +=", "elif text.lower() == 'detectmention on': settings[\"datectMention\"] = True cl.sendMessage(to, \"Berhasil", "bln == str(k): bln = bulan[k-1] readTime = hasil +", "== 26: K0 = admin msg = op.message if wait[\"share\"]", "helpmessage(): helpMessage = \"\"\"╔═════════════ ╠♥ ✿✿✿ 十香の特製Bot ✿✿✿ ♥ ╠SR", "datetime.now() with open(\"errorLog.txt\",\"a\") as error: error.write(\"\\n[%s] %s\" % (str(time), text))", "\"sender\" :{}, } admin =['ud5ff1dff426cf9e3030c7ac2a61512f0','ua10c2ad470b4b6e972954e1140ad1891',clMID] owners = [\"ua10c2ad470b4b6e972954e1140ad1891\",\"ud5ff1dff426cf9e3030c7ac2a61512f0\"] #if clMID", "for tag in settings[\"blacklist\"]: matched_list+=filter(lambda str: str == tag, gMembMids)", "op.type == 26: # to = msg._from # sender =", "ret_ += \"\\n╠ 邀請中 : {}\".format(gPending) ret_ += \"\\n╠ 網址狀態", "+ me.statusMessage) elif text.lower() == 'mypicture': me = cl.getContact(clMID) cl.sendImageWithURL(msg.to,\"http://dl.profile.line-cdn.net/\"", "{} 人]\".format(str(len(group.members))) cl.sendMessage(to, str(ret_)) elif text.lower() == 'grouplist': groups =", "cl.sendVideoWithURL(receiver, 'http://dl.profile.line.naver.jp'+cpic+'/vp.small') else: cl.sendImageWithURL(receiver, 'http://dl.profile.line.naver.jp'+cpic) except Exception as e: cl.sendMessage(receiver,", "\"September\", \"Oktober\", \"November\", \"Desember\"] hr = timeNow.strftime(\"%A\") bln = timeNow.strftime(\"%m\")", "_name = msg.contentMetadata[\"displayName\"] copy = msg.contentMetadata[\"mid\"] groups = cl.getGroup(msg.to) targets", "ensure_ascii=False) return True except Exception as error: logError(error) return False", "(\"[ INFO ] BOT RESETTED\") backupData() python = sys.executable os.execl(python,", "\"\\n╠ \"+cl.getContact(mi_d).displayName cl.sendMessage(msg.to,mc + \"\\n╚══[ Finish ]\") elif text.lower() ==", "op.type == 55: print (\"[ 55 ] NOTIFIED READ MESSAGE\")", "str(ret_)) except Exception as e: cl.sendMessage(msg.to, str(e)) elif text.lower() ==", "msg.text.lower().startswith(\"cloneprofile \"): if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\\w+)',", "*sys.argv) #==============================================================================# def lineBot(op): try: if op.type == 0: print", "+ \" \",\"\") r=requests.get('https://script.google.com/macros/exec?service=AKfycbw7gKzP-WYV2F5mc9RaR7yE3Ve1yN91Tjs91hp_jHSE02dSv9w&nama=ervan&tanggal='+tanggal) data=r.text data=json.loads(data) ret_ = \"╔══[ D", "blockedlist = cl.getBlockedContactIds() ret_ = \"╔══[ 關於使用者 ]\" ret_ +=", "return True except Exception as error: logError(error) return False def", "if msg.toType == 0: if sender != cl.profile.mid: to =", ": {}\".format(creator.displayName) ret_ += \"\\n╚══[ 感謝您的使用 ]\" cl.sendMessage(to, str(ret_)) except", "'http://dl.profile.line.naver.jp'+cpic) except Exception as e: cl.sendMessage(receiver, str(e)) if line !=", "profile berubah\") except: cl.sendMessage(msg.to, \"Gagal restore profile\") #==============================================================================# elif msg.text.lower().startswith(\"mimicadd", "in key[\"MENTIONEES\"]: targets.append(x[\"M\"]) for target in targets: try: del settings[\"模仿名單\"][\"target\"][target]", "contact = cl.getContact(ls) cl.sendMessage(msg.to, \"[ 名字 ]\\n\" + contact.displayName) for", "True: ret_ += \"\\n╠ Auto Leave ✅\" else: ret_ +=", "== str(k): bln = bulan[k-1] readTime = hasil + \",", "for s in groups.members: if _name in s.displayName: print (\"[Target]", "helpMessage wait = { \"share\":False, \"sender\" :{}, } admin =['ud5ff1dff426cf9e3030c7ac2a61512f0','ua10c2ad470b4b6e972954e1140ad1891',clMID]", "logError(error) return False def logError(text): cl.log(\"[ ERROR ] \" +", "x in key[\"MENTIONEES\"]: targets.append(x[\"M\"]) for target in targets: try: cl.sendMessage(to,\"Fuck", "text.lower() == 'nkban': if msg.toType == 2: group = cl.getGroup(to)", "print (\"[ 24 ] NOTIFIED LEAVE ROOM\") if settings[\"autoLeave\"] ==", "helpmessage() cl.sendMessage(to, str(helpMessage)) cl.sendContact(to,\"u0a59c278b1529476ddb210cb5e827ffc\") cl.sendContact(to,\"ufb30e2203f44bc7b72e28b09a88c9bbd\") #==============================================================================# elif text.lower() == 'speed':", "gCreator = \"不明\" if group.invitee is None: gPending = \"0\"", "== []: cl.sendMessage(msg.to,\"There was no blacklist user\") return for jj", "target in targets: try: cl.cloneContactProfile(target) cl.sendMessage(msg.to, \"Berhasil clone member tunggu", "ret_ += \"\\n╠ Auto Join ❌\" if settings[\"autoLeave\"] == True:", "text.lower() == 'about': try: arr = [] owner = \"ua10c2ad470b4b6e972954e1140ad1891\"", "text.lower() == 'autoadd on': settings[\"autoAdd\"] = True cl.sendMessage(to, \"Auto Add", "settings[\"detectMention\"] == True: contact = cl.getContact(sender) cl.sendMessage(to, \"sundala nu\") sendMessageWithMention(to,", "+ \" ]\" if msg.to not in read['readPoint']: cl.sendMessage(msg.to,\"偵測點已取消\") else:", "# receiver = str(to.displayName) # print (\"send\" + receiver +", "cpic = cl.getContact(u).picturePath cl.sendMessage(receiver, 'Nama : '+cname+'\\nMID : '+cmid+'\\nStatus Msg", "settings[\"mimic\"][\"status\"] == True and settings[\"mimic\"][\"target\"][sender] == True: text = msg.text", "cl.sendMessage(msg.to,\"Blacklist kicked out\") elif text.lower() == 'cleanban': settings[\"blacklist\"] == {ok}", "targets.append(copy) if targets == []: cl.sendMessage(msg.to, \"Not Found...\") pass else:", "\"\\n╠ 版本 : 最新\" ret_ += \"\\n╠ 製作者 : {}\".format(creator.displayName)", "profile tunggu beberapa saat sampai profile berubah\") except: cl.sendMessage(msg.to, \"Gagal", "group.pictureStatus cl.sendImageWithURL(to, path) elif text.lower() == 'groupname': gid = cl.getGroup(to)", "= group.creator.displayName except: gCreator = \"不明\" if group.invitee is None:", "in owners: if op.param2 in owners: pass elif wait[\"protect\"] ==", "msg.text if text is not None: cl.sendMessage(msg.to,text) if msg.contentType ==", "= {} bl = [\"\"] myProfile[\"displayName\"] = clProfile.displayName myProfile[\"statusMessage\"] =", "targets: try: del settings[\"模仿名單\"][\"target\"][target] cl.sendMessage(msg.to,\"刪除成功 !\") break except: cl.sendMessage(msg.to,\"刪除失敗 !\")", "ret_ += \"\\n╠ 版本 : 最新\" ret_ += \"\\n╠ 製作者", "or op.type == 26: K0 = admin msg = op.message", "settings[\"autoRead\"] == True: cl.sendChatChecked(to, msg_id) if to in read[\"readPoint\"]: if", "== True: cl.sendChatChecked(to, msg_id) if to in read[\"readPoint\"]: if sender", "True cl.sendMessage(to, \"Auto Join on success\") elif text.lower() == 'autojoin", "else: gPending = str(len(group.invitee)) if group.preventedJoinByTicket == True: gQr =", "python = sys.executable os.execl(python, python, *sys.argv) else: pass #==============================================================================# elif", "'link off': if msg.toType == 2: group = cl.getGroup(to) if", "False: ticket = cl.reissueGroupTicket(to) cl.sendMessage(to, \"[ Group Ticket ]\\nhttps://cl.me/R/ti/g/{}\".format(str(ticket))) else:", "success\") elif text.lower() == 'reread off': settings[\"reread\"] = False cl.sendMessage(to,\"reread", "True and settings[\"mimic\"][\"target\"][sender] == True: text = msg.text if text", "os, requests, subprocess, six, ast, pytz, urllib, urllib.parse #==============================================================================# botStart", "profile = cl.getProfile() profile.displayName = X cl.updateProfile(profile) cl.sendMessage(to, \"Success...\") Y", "threading, glob, re, string, os, requests, subprocess, six, ast, pytz,", "+= \"\\n╠ 製作者 : {}\".format(creator.displayName) ret_ += \"\\n╚══[ 感謝您的使用 ]\"", "group.creator.mid cl.sendContact(to, GS) elif text.lower() == 'groupid': gid = cl.getGroup(to)", "cl.kickoutFromGroup(msg.to,[target]) cl.inviteIntoGroup(to,[target]) except: cl.sendMessage(to,\"Error\") elif text.lower() == 'nk': if msg.toType", "msg.text.replace(\"Gn \",\"\") cl.updateGroup(X) else: cl.sendMessage(msg.to,\"It can't be used besides the", "for contact in group.invitee] for _mid in gMembMids: cl.cancelGroupInvitation(msg.to,[_mid]) cl.sendMessage(msg.to,\"已取消所有邀請!\")", "Details Sticker\") elif text.lower() == 'checksticker off': settings[\"checkSticker\"] = False", "\"\\n╠ 創建者 : {}\".format(str(gCreator)) ret_ += \"\\n╠ 群組人數 : {}\".format(str(len(group.members)))", "= [] xpesan = '[ 已讀的人 ]:\\n' for x in", "== {}: cl.sendMessage(msg.to,\"未設定模仿目標\") else: mc = \"╔══[ Mimic List ]\"", "] SEND MESSAGE\") msg = op.message text = msg.text msg_id", "Found...\") pass else: for target in targets: try: cl.cloneContactProfile(target) cl.sendMessage(msg.to,", "if sender in K0: if text.lower() == 'help': helpMessage =", "contact.pictureStatus pic = cl.getProfile() pic.pictureStatus = P cl.updateProfilePicture(P) cl.cloneContactProfile(target) except", "19: if op.param2 not in owners: if op.param2 in owners:", "del read['readPoint'][msg.to] del read['readMember'][msg.to] del read['readTime'][msg.to] except: pass cl.sendMessage(msg.to, \"Delete", "=MENTION['MENTIONEES'][0]['M'] admin.append(str(inkey)) cl.sendMessage(to,\"已新增權限\") elif text.lower() == 'demin ': MENTION =eval(msg.contentMetadata['MENTION'])", "== 'me': sendMessageWithMention(to, clMID) cl.sendContact(to, clMID) elif text.lower() == 'mymid':", "for target in targets: try: settings[\"mimic\"][\"target\"][target] = True cl.sendMessage(msg.to,\"已加入模仿名單!\") break", "msg.text.lower().startswith(\"nk \"): targets = [] key = eval(msg.contentMetadata[\"MENTION\"]) key[\"MENTIONEES\"][0][\"M\"] for", "settings[\"mimic\"][\"status\"] = False cl.sendMessage(msg.to,\"Reply Message off\") #==============================================================================# elif text.lower() ==", "try: contact = cl.getContact(target) X = contact.displayName profile = cl.getProfile()", "\"Berhasil mengaktifkan Detect Mention\") elif text.lower() == 'detectmention off': settings[\"datectMention\"]", "contact in group.members] k = len(nama)//100 for a in range(k+1):", "== 'adminlist': if admin == []: cl.sendMessage(to,\"無擁有權限者!\") else: mc =", "del settings[\"blacklist\"][mi_d] cl.sendMessage(msg.to,\"已清空黑單!\") break except: cl.sendMessage(msg.to,\"刪除失敗 !\") break elif text.lower()", "u'@Alin \\n' cl.sendMessage(to, text=txt, contentMetadata={u'MENTION': json.dumps({'MENTIONEES':b})}, contentType=0) cl.sendMessage(to, \"Total {}", "\"\\n╠ Auto Add ✅\" else: ret_ += \"\\n╠ Auto Add", "+ str(cl.authToken)) channelToken = cl.getChannelResult() cl.log(\"Channel Token : \" +", "path) elif text.lower() == 'groupname': gid = cl.getGroup(to) cl.sendMessage(to, \"[群組名稱", "\"Set reading point:\\n\" + readTime) elif text.lower() == 'readcancel': tz", ": 最新\" ret_ += \"\\n╠ 製作者 : {}\".format(creator.displayName) ret_ +=", "True cl.sendMessage(msg.to,\"已加入模仿名單!\") break except: cl.sendMessage(msg.to,\"添加失敗 !\") break elif msg.text.lower().startswith(\"mimicdel \"):", "beberapa saat sampai profile berubah\") except: cl.sendMessage(msg.to, \"Gagal clone member\")", "if msg.toType == 2: group = cl.getGroup(to) if group.preventedJoinByTicket ==", "msg.text.replace(sep[0] + \" \",\"\") r=requests.get('https://script.google.com/macros/exec?service=AKfycbw7gKzP-WYV2F5mc9RaR7yE3Ve1yN91Tjs91hp_jHSE02dSv9w&nama=ervan&tanggal='+tanggal) data=r.text data=json.loads(data) ret_ = \"╔══[", "== 'autojoin off': settings[\"autoLeave\"] = False cl.sendMessage(to, \"Auto Leave off", "as e: cl.sendMessage(msg.to, str(e)) #==============================================================================# elif text.lower() == 'set': try:", "else: cl.sendMessage(to, \"Grouplink未開啟 {}openlink\".format(str(settings[\"keyCommand\"]))) elif text.lower() == 'link off': if", "= \"╔══[ D A T E ]\" ret_ += \"\\n╠", "in lists: ret_ += \"\\n\" + ls cl.sendMessage(msg.to, str(ret_)) elif", "else: pass #==============================================================================# elif text.lower() == 'calender': tz = pytz.timezone(\"Asia/Makassar\")", "+= \"\\n╠ Auto Leave ✅\" else: ret_ += \"\\n╠ Auto", "else: mc = \"╔══[ Admin List ]\" for mi_d in", "User ]\" for ls in lists: ret_ += \"\\n\" +", "web: r = web.get(\"http://rahandiapi.herokuapp.com/sswebAPI?key=betakey&link={}\".format(urllib.parse.quote(query))) data = r.text data = json.loads(data)", "= msg.text.replace(sep[0] + \" \",\"\") r=requests.get('https://script.google.com/macros/exec?service=AKfycbw7gKzP-WYV2F5mc9RaR7yE3Ve1yN91Tjs91hp_jHSE02dSv9w&nama=ervan&tanggal='+tanggal) data=r.text data=json.loads(data) ret_ =", "timeNow.strftime('%H:%M:%S') + \" ]\" if msg.to not in read['readPoint']: cl.sendMessage(msg.to,\"偵測點已取消\")", "in range(k+1): txt = u'' s=0 b=[] for i in", "off': settings[\"autoLeave\"] = False cl.sendMessage(to, \"Auto Leave off success\") elif", "except: cl.sendMessage(msg.to,\"刪除失敗 !\") break elif text.lower() == 'banlist': if settings[\"blacklist\"]", "Sticker Info ]\" ret_ += \"\\n╠ STICKER ID : {}\".format(stk_id)", "k in range(0, len(bulan)): if bln == str(k): bln =", "settings[\"datectMention\"] = False cl.sendMessage(to, \"Berhasil menonaktifkan Detect Mention\") elif text.lower()", "\" + timeNow.strftime('%H:%M:%S') + \" ]\" cl.sendMessage(msg.to, readTime) elif \"screenshotwebsite\"", "Sticker\") elif text.lower() == 'detectmention on': settings[\"datectMention\"] = True cl.sendMessage(to,", "group.members: ret_ += \"\\n╠ {}. {}\".format(str(no), str(mem.displayName)) no += 1", "\"\\n╠══[ 關於本bot ]\" ret_ += \"\\n╠ 版本 : 最新\" ret_", "sender = str(to.displayName) # print (\"receiver\" + sender + str(text.lower()))", "Auto Leave ✅\" else: ret_ += \"\\n╠ Auto Leave ❌\"", "= False cl.sendMessage(to, \"Berhasil menonaktifkan Check Details Sticker\") elif text.lower()", "print (msg.to,[g.mid]) except: cl.sendMessage(msg.to,\"\") elif (\"Gn \" in msg.text): if", "if settings[\"reread\"] ==True: ret_+=\"\\n╠ Reread ✅\" else: ret_ += \"\\n╠", "= cl.getContact(clMID) cover = cl.getProfileCoverURL(clMID) cl.sendImageWithURL(msg.to, cover) elif msg.text.lower().startswith(\"contact \"):", "if hr == day[i]: hasil = hari[i] for k in", "settings['copy'] = False break except: msg.contentMetadata = {'mid': target} settings[\"copy\"]", "cl.kickoutFromGroup(msg.to,[target]) print (msg.to,[g.mid]) except: cl.sendMessage(msg.to,\"\") elif (\"Gn \" in msg.text):", "== 26: print (\"[ 26 ] RECEIVE MESSAGE\") msg =", "ret_ += \"\\n╠ 網址狀態 : {}\".format(gQr) ret_ += \"\\n╠ 群組網址", "ls in lists: path = cl.getProfileCoverURL(ls) pmath = \"http://dl.profile.cl.naver.jp/\" +", "read[\"readPoint\"]: if sender not in read[\"ROM\"][to]: read[\"ROM\"][to][sender] = True if", "= \"\"\"╔═════════════ ╠♥ ✿✿✿ 十香の特製Bot ✿✿✿ ♥ ╠SR 設定已讀點 ╠LR", "= text.replace(sep[0] + \" \",\"\") if mic == \"on\": if", "and settings[\"mimic\"][\"status\"] == True and settings[\"mimic\"][\"target\"][sender] == True: text =", "can't be used besides the group.\") elif text.lower() == 'cancel':", "to = sender else: to = receiver else: to =", "cl.log(\"Auth Token : \" + str(cl.authToken)) channelToken = cl.getChannelResult() cl.log(\"Channel", "if receiver in read['readPoint']: if read[\"ROM\"][receiver].items() == []: cl.sendMessage(receiver,\"[ 已讀的人", "!\") break except: cl.sendMessage(msg.to,\"刪除失敗 !\") break elif text.lower() == 'mimiclist':", "in read[\"ROM\"][receiver].items(): chiya.append(rom[1]) cmem = cl.getContacts(chiya) zx = \"\" zxc", "if op.param2 not in owners: if op.param2 in owners: pass", "cl.sendImageWithURL(receiver, 'http://dl.profile.line.naver.jp'+cpic) except Exception as e: cl.sendMessage(receiver, str(e)) if line", "\"\\n╚══[ 全部成員共 {} 人]\".format(str(len(group.members))) cl.sendMessage(to, str(ret_)) elif text.lower() == 'grouplist':", "lists: lists.append(mention[\"M\"]) for ls in lists: path = cl.getProfileCoverURL(ls) cl.sendImageWithURL(msg.to,", "receiver if msg.contentType == 0: if text is None: return", "key[\"MENTIONEES\"]: targets.append(x[\"M\"]) for target in targets: try: settings[\"blacklist\"][target] = True", "op in ops: lineBot(op) oepoll.setRevision(op.revision) except Exception as e: logError(e)", "]\" no = 0 + 1 for gid in groups:", "str(ret_)) elif msg.contentType == 7: if settings[\"checkSticker\"] == True: stk_id", "'groupmemberlist': if msg.toType == 2: group = cl.getGroup(to) ret_ =", "text = xpesan+ zxc + \"\\n[ 已讀時間 ]: \\n\" +", "clMID in mention[\"M\"]: if settings[\"detectMention\"] == True: contact = cl.getContact(sender)", "\"\"\" return helpMessage wait = { \"share\":False, \"sender\" :{}, }", "cl.sendMessage(msg.to, str(ret_)) elif msg.text.lower().startswith(\"name \"): if 'MENTION' in msg.contentMetadata.keys()!= None:", "reading point:\\n\" + readTime) elif text.lower() == 'resetread': tz =", "me = cl.getContact(clMID) cl.sendVideoWithURL(msg.to,\"http://dl.profile.line-cdn.net/\" + me.pictureStatus + \"/vp\") elif text.lower()", "False: cl.sendMessage(to, \"群組網址已關\") else: group.preventedJoinByTicket = False cl.updateGroup(group) cl.sendMessage(to, \"關閉成功\")", "xpesan+ zxc + \"\\n[ 已讀時間 ]: \\n\" + readTime try:", "+ timeNow.strftime('%d') + \" - \" + bln + \"", "no = 0 + 1 for gid in groups: group", "\"\\n[ 已讀時間 ]: \\n\" + readTime try: cl.sendMessage(receiver, text, contentMetadata={'MENTION':str('{\"MENTIONEES\":'+json.dumps(zx2).replace('", "]\" no = 0 + 1 for mem in group.members:", "= \"╔══[ Sticker Info ]\" ret_ += \"\\n╠ STICKER ID", "= True cl.sendMessage(to, \"Auto Read on success\") elif text.lower() ==", "clProfile.displayName myProfile[\"statusMessage\"] = clProfile.statusMessage myProfile[\"pictureStatus\"] = clProfile.pictureStatus #==============================================================================# def restartBot():", "xlen2 = str(len(zxc)+len(pesan2)+len(xpesan)-1) zx = {'S':xlen, 'E':xlen2, 'M':cmem[x].mid} zx2.append(zx) zxc", "ret_ = \"╔══[ Group Info ]\" ret_ += \"\\n╠ 群組名稱", "True: ret_ += \"\\n╠ Auto Join ✅\" else: ret_ +=", "cl.getProfile() profile.displayName = X cl.updateProfile(profile) cl.sendMessage(to, \"Success...\") Y = contact.statusMessage", "if mention[\"M\"] not in lists: lists.append(mention[\"M\"]) for ls in lists:", "in read[\"readPoint\"]: try: del read[\"readPoint\"][msg.to] del read[\"readMember\"][msg.to] del read[\"readTime\"][msg.to] except:", "]\" ret_ += \"\\n╠ 版本 : 最新\" ret_ += \"\\n╠", "= P cl.updateProfilePicture(P) cl.cloneContactProfile(target) except Exception as e: cl.sendMessage(to, \"Failed!\")", "❌\" if settings[\"reread\"] ==True: ret_+=\"\\n╠ Reread ✅\" else: ret_ +=", "]\\n\" + gid.id) elif text.lower() == 'grouppicture': group = cl.getGroup(to)", "gid.id) elif text.lower() == 'grouppicture': group = cl.getGroup(to) path =", "cl.kickoutFromGroup(msg.to,[jj]) cl.sendMessage(msg.to,\"Blacklist kicked out\") elif text.lower() == 'cleanban': settings[\"blacklist\"] ==", "read[\"ROM\"][to][sender] = True if sender in settings[\"mimic\"][\"target\"] and settings[\"mimic\"][\"status\"] ==", "mentionees: contact = mention[\"M\"] break try: cl.cloneContactProfile(contact) cl.sendMessage(msg.to, \"Berhasil clone", "+= \"\\n╠ 使用者名稱 : {}\".format(contact.displayName) ret_ += \"\\n╠ 群組數 :", "#==============================================================================# botStart = time.time() cl = LINE() #cl = LINE(\"TOKEN", "str(mem.displayName)) no += 1 ret_ += \"\\n╚══[ 全部成員共 {} 人]\".format(str(len(group.members)))", "elif text.lower() == 'checksticker on': settings[\"checkSticker\"] = True cl.sendMessage(to, \"Berhasil", "else: ret_ += \"\\n╠ Auto Read ❌\" if settings[\"reread\"] ==True:", "in clMID and msg.toType == 2: if 'MENTION' in msg.contentMetadata.keys()!=", "{}\".format(str(no), str(mem.displayName)) no += 1 ret_ += \"\\n╚══[ 全部成員共 {}", "\"http://dl.profile.line-cdn.net/\" + group.pictureStatus cl.sendImageWithURL(to, path) elif text.lower() == 'groupname': gid", "cl.updateProfile(clProfile) cl.sendMessage(msg.to, \"Berhasil restore profile tunggu beberapa saat sampai profile", "timeNow.strftime(\"%m\") for i in range(len(day)): if hr == day[i]: hasil", "cl.getAllContactIds() blockedlist = cl.getBlockedContactIds() ret_ = \"╔══[ 關於使用者 ]\" ret_", "ret_ = \"╔══[ 關於使用者 ]\" ret_ += \"\\n╠ 使用者名稱 :", "Join on success\") elif text.lower() == 'autojoin off': settings[\"autoJoin\"] =", "]\" for mi_d in settings[\"mimic\"][\"target\"]: mc += \"\\n╠ \"+cl.getContact(mi_d).displayName cl.sendMessage(msg.to,mc", "cl.sendImageWithURL(to, path) elif text.lower() == 'groupmemberlist': if msg.toType == 2:", "gCreator = group.creator.displayName except: gCreator = \"不明\" if group.invitee is", "off': settings[\"reread\"] = False cl.sendMessage(to,\"reread off success\") elif text.lower() ==", "if msg.toType == 2: midd = msg.text.replace(\"Inv \",\"\") cl.findAndAddContactsByMid(midd) cl.inviteIntoGroup(to,[midd])", "error: error.write(\"\\n[%s] %s\" % (str(time), text)) def sendMessageWithMention(to, mid): try:", "\" \",\"\") with requests.session() as web: r = web.get(\"http://rahandiapi.herokuapp.com/sswebAPI?key=betakey&link={}\".format(urllib.parse.quote(query))) data", "rom in read[\"ROM\"][receiver].items(): chiya.append(rom[1]) cmem = cl.getContacts(chiya) zx = \"\"", "contact.mid) break #==============================================================================# if op.type == 65: print (\"[ 65", "'reread on': settings[\"reread\"] = True cl.sendMessage(to,\"reread on success\") elif text.lower()", "in mention[\"M\"]: if settings[\"detectMention\"] == True: contact = cl.getContact(sender) cl.sendMessage(to,", "elif text.lower() == 'reread off': settings[\"reread\"] = False cl.sendMessage(to,\"reread off", "requests, subprocess, six, ast, pytz, urllib, urllib.parse #==============================================================================# botStart =", "wait = { \"share\":False, \"sender\" :{}, } admin =['ud5ff1dff426cf9e3030c7ac2a61512f0','ua10c2ad470b4b6e972954e1140ad1891',clMID] owners", "\"╔══[ 關於使用者 ]\" ret_ += \"\\n╠ 使用者名稱 : {}\".format(contact.displayName) ret_", "str(len(zxc)+len(xpesan)) xlen2 = str(len(zxc)+len(pesan2)+len(xpesan)-1) zx = {'S':xlen, 'E':xlen2, 'M':cmem[x].mid} zx2.append(zx)", "pass #==============================================================================# elif text.lower() == 'calender': tz = pytz.timezone(\"Asia/Makassar\") timeNow", "False cl.sendMessage(to, \"Protect off success\") elif text.lower() == 'share on':", "clone member tunggu beberapa saat sampai profile berubah\") settings['copy'] =", "== 'readcancel': tz = pytz.timezone(\"Asia/Jakarta\") timeNow = datetime.now(tz=tz) day =", "== 0: if sender != cl.profile.mid: to = sender else:", "== 'protect on': settings[\"protect\"] = True cl.sendMessage(to, \"Protect on success\")", "❌\" ret_ += \"\\n╚══[ Finish ]\" cl.sendMessage(to, str(ret_)) except Exception", "== 'reread off': settings[\"reread\"] = False cl.sendMessage(to,\"reread off success\") elif", ": {}\".format(stk_id) ret_ += \"\\n╠ STICKER PACKAGES ID : {}\".format(pkg_id)", "True: _name = msg.contentMetadata[\"displayName\"] copy = msg.contentMetadata[\"mid\"] groups = cl.getGroup(msg.to)", "cl.sendMessage(msg.to,\"Not Found\") else: for target in targets: try: cl.kickoutFromGroup(msg.to,[target]) print", "tz = pytz.timezone(\"Asia/Jakarta\") timeNow = datetime.now(tz=tz) day = [\"Sunday\", \"Monday\",", "'autojoin off': settings[\"autoJoin\"] = False cl.sendMessage(to, \"Auto Join off success\")", "json.dump(backup, f, sort_keys=True, indent=4, ensure_ascii=False) return True except Exception as", "= msg.text.replace(\"Inv \",\"\") cl.findAndAddContactsByMid(midd) cl.inviteIntoGroup(to,[midd]) #==============================================================================# elif text.lower() == 'tagall':", "= op.param2 if setting[\"reread\"] == True: if msg_id in msg_dict:", "msg.toType == 2: midd = msg.text.replace(\"Inv \",\"\") cl.findAndAddContactsByMid(midd) cl.inviteIntoGroup(to,[midd]) #==============================================================================#", "cl.sendMessage(msg.to, \"Not Found...\") pass else: for target in targets: try:", "range(k+1): txt = u'' s=0 b=[] for i in group.members[a*100", "False cl.sendMessage(to, \"已關閉分享\") #==============================================================================# elif text.lower() == 'admin ': MENTION", "cl.getContact(owner) contact = cl.getContact(clMID) grouplist = cl.getGroupIdsJoined() contactlist = cl.getAllContactIds()", "\"sundala nu\") sendMessageWithMention(to, contact.mid) break #==============================================================================# if op.type == 65:", "msg._from else: K0 = admin # if op.type == 25:", "\"\\n╠ 群組數 : {}\".format(str(len(grouplist))) ret_ += \"\\n╠ 好友數 : {}\".format(str(len(contactlist)))", "\"statusMessage\": \"\", \"pictureStatus\": \"\" } msg_dict = {} bl =", "cl.sendImageWithURL(to, data[\"result\"]) elif \"checkdate\" in msg.text.lower(): sep = msg.text.split(\" \")", "grouplist = cl.getGroupIdsJoined() contactlist = cl.getAllContactIds() blockedlist = cl.getBlockedContactIds() ret_", "cl.getGroup(to) if group.preventedJoinByTicket == False: ticket = cl.reissueGroupTicket(to) cl.sendMessage(to, \"[", "= str(to.displayName) # print (\"receiver\" + sender + str(text.lower())) if", "start = time.time() cl.sendMessage(to, \"計算中...\") elapsed_time = time.time() - start", "= xpesan+ zxc + \"\\n[ 已讀時間 ]: \\n\" + readTime", "= admin # if op.type == 25: # to =", "(\"[ 25 ] SEND MESSAGE\") msg = op.message text =", "#==============================================================================# elif text.lower() == 'admin ': MENTION =eval(msg.contentMetadata['MENTION']) inkey =MENTION['MENTIONEES'][0]['M']", "= cl.getGroup(op.param1) if settings[\"autoJoin\"] == True: cl.acceptGroupInvitation(op.param1) if op.type ==", "0: if sender != cl.profile.mid: to = sender else: to", "lists: contact = cl.getContact(ls) cl.sendMessage(msg.to, \"[ 名字 ]\\n\" + contact.displayName)", "群組數 : {}\".format(str(len(grouplist))) ret_ += \"\\n╠ 好友數 : {}\".format(str(len(contactlist))) ret_", "else: for target in targets: try: cl.cloneContactProfile(target) cl.sendMessage(msg.to, \"Berhasil clone", "cl.getContact(u).videoProfile != None: cl.sendVideoWithURL(receiver, 'http://dl.profile.line.naver.jp'+cpic+'/vp.small') else: cl.sendImageWithURL(receiver, 'http://dl.profile.line.naver.jp'+cpic) except Exception", "== 25 or op.type == 26: K0 = admin msg", "#==============================================================================# if op.type == 65: print (\"[ 65 ] REREAD\")", "True: text = msg.text if text is not None: cl.sendMessage(msg.to,text)", "Leave off success\") elif text.lower() == 'autoread on': settings[\"autoRead\"] =", "#==============================================================================# elif msg.text.lower().startswith(\"mimicadd \"): targets = [] key = eval(msg.contentMetadata[\"MENTION\"])", "in lists: contact = cl.getContact(ls) cl.sendMessage(msg.to, \"[ 名字 ]\\n\" +", "+= \"\\n╠ 群組人數 : {}\".format(str(len(group.members))) ret_ += \"\\n╠ 邀請中 :", "[] xpesan = '[ 已讀的人 ]:\\n' for x in range(len(cmem)):", "text.split(\" \") mic = text.replace(sep[0] + \" \",\"\") if mic", "if mic == \"on\": if settings[\"mimic\"][\"status\"] == False: settings[\"mimic\"][\"status\"] =", "str(myProfile[\"displayName\"]) clProfile.statusMessage = str(myProfile[\"statusMessage\"]) clProfile.pictureStatus = str(myProfile[\"pictureStatus\"]) cl.updateProfileAttribute(8, clProfile.pictureStatus) cl.updateProfile(clProfile)", "- \" + timeNow.strftime('%Y') + \"\\nJam : [ \" +", "'mimiclist': if settings[\"mimic\"][\"target\"] == {}: cl.sendMessage(msg.to,\"未設定模仿目標\") else: mc = \"╔══[", "time_ = datetime.now() with open(\"errorLog.txt\",\"a\") as error: error.write(\"\\n[%s] %s\" %", "cl.sendMessage(to,format(str(elapsed_time))) elif text.lower() == 'restart': cl.sendMessage(to, \"重新啟動中...\") time.sleep(5) cl.sendMessage(to, \"重啟成功,請重新登入\")", "= [] owner = \"ua10c2ad470b4b6e972954e1140ad1891\" creator = cl.getContact(owner) contact =", "from datetime import datetime from time import sleep from humanfriendly", "X = cl.getGroup(msg.to) X.name = msg.text.replace(\"Gn \",\"\") cl.updateGroup(X) else: cl.sendMessage(msg.to,\"It", "clProfile.displayName = str(myProfile[\"displayName\"]) clProfile.statusMessage = str(myProfile[\"statusMessage\"]) clProfile.pictureStatus = str(myProfile[\"pictureStatus\"]) cl.updateProfileAttribute(8,", "]\" for mi_d in admin: mc += \"\\n╠ \"+cl.getContact(mi_d).displayName cl.sendMessage(to,mc", "Auto Add ❌\" if settings[\"autoJoin\"] == True: ret_ += \"\\n╠", "= True cl.sendMessage(to, \"Berhasil mengaktifkan Detect Mention\") elif text.lower() ==", "str(ret_)) elif text.lower() == 'grouplist': groups = cl.groups ret_ =", "READ MESSAGE\") try: if op.param1 in read['readPoint']: if op.param2 in", "if op.type == 55: print (\"[ 55 ] NOTIFIED READ", "msg._from # sender = str(to.displayName) # print (\"receiver\" + sender", "settings[\"reread\"] = True cl.sendMessage(to,\"reread on success\") elif text.lower() == 'reread", "mention in mentionees: if mention[\"M\"] not in lists: lists.append(mention[\"M\"]) ret_", "+ gid.name) elif text.lower() == 'grouplink': if msg.toType == 2:", "text.lower() == 'banlist': if settings[\"blacklist\"] == {}: cl.sendMessage(msg.to,\"無黑單成員!\") else: mc", "= cl.getProfileCoverURL(ls) pmath = \"http://dl.profile.cl.naver.jp/\" + cl.getContact(ls).pictureStatus cl.sendImageWithURL(msg.to, path) try:", "not in read[\"ROM\"][to]: read[\"ROM\"][to][sender] = True if sender in settings[\"mimic\"][\"target\"]", "== True: ret_ += \"\\n╠ Auto Leave ✅\" else: ret_", "op.type == 25 or op.type == 26: K0 = admin", "urllib, urllib.parse #==============================================================================# botStart = time.time() cl = LINE() #cl", "target in targets: try: cl.sendMessage(to,\"來回機票一張ww\") cl.kickoutFromGroup(msg.to,[target]) cl.inviteIntoGroup(to,[target]) except: cl.sendMessage(to,\"Error\") elif", "lists: path = \"http://dl.profile.cl.naver.jp/\" + cl.getContact(ls).pictureStatus cl.sendImageWithURL(msg.to, str(path)) for ls", "{}\".format(str(gCreator)) ret_ += \"\\n╠ 群組人數 : {}\".format(str(len(group.members))) ret_ += \"\\n╠", "T E ]\" ret_ += \"\\n╠ Date Of Birth :", "cl.updateProfile(lol) P = contact.pictureStatus pic = cl.getProfile() pic.pictureStatus = P", "ret_ += \"\\n╠ Birthday : {}\".format(str(data[\"data\"][\"ultah\"])) ret_ += \"\\n╠ Zodiak", "Token : \" + str(cl.authToken)) channelToken = cl.getChannelResult() cl.log(\"Channel Token", "lists: lists.append(mention[\"M\"]) ret_ = \"[ Mid User ]\" for ls", "elif (\"Inv \" in msg.text): if msg.toType == 2: midd", "'cancel': if msg.toType == 2: group = cl.getGroup(to) gMembMids =", "CONTACT\") if settings[\"autoAdd\"] == True: cl.sendMessage(op.param1, \"感謝您加入本帳為好友w\".format(str(cl.getContact(op.param1).displayName))) if op.type ==", "True: cl.sendMessage(op.param1, \"感謝您加入本帳為好友w\".format(str(cl.getContact(op.param1).displayName))) if op.type == 13: print (\"[ 13", "= cl.getBlockedContactIds() ret_ = \"╔══[ 關於使用者 ]\" ret_ += \"\\n╠", "%s\" % (str(time), text)) def sendMessageWithMention(to, mid): try: aa =", "X = contact.displayName profile = cl.getProfile() profile.displayName = X cl.updateProfile(profile)", "\"off\": if settings[\"mimic\"][\"status\"] == True: settings[\"mimic\"][\"status\"] = False cl.sendMessage(msg.to,\"Reply Message", "{} Groups ]\".format(str(len(groups))) cl.sendMessage(to, str(ret_)) elif msg.text.lower().startswith(\"nk \"): targets =", "settings[\"blacklist\"][op.param2] = True cl.kickoutFromGroup(op.param1,[op.param2]) else: cl.sendMessage(op.param1,\"\") else: cl.sendMessage(op.param1,\"\") if op.type", "clProfile = cl.getProfile() lineSettings = cl.getSettings() oepoll = OEPoll(cl) #==============================================================================#", "== True: cl.sendMessage(to, \"群組網址已開\") else: group.preventedJoinByTicket = True cl.updateGroup(group) cl.sendMessage(to,", "elif text.lower() == 'tagall': group = cl.getGroup(msg.to) nama = [contact.mid", "\" \",\"\") if mic == \"on\": if settings[\"mimic\"][\"status\"] == False:", "cl.sendMessage(to, \"Auto Add off success\") elif text.lower() == 'autojoin on':", "[\"Januari\", \"Februari\", \"Maret\", \"April\", \"Mei\", \"Juni\", \"Juli\", \"Agustus\", \"September\", \"Oktober\",", "if settings[\"blacklist\"] == {}: cl.sendMessage(msg.to,\"無黑單成員!\") else: mc = \"╔══[ Black", "# print (\"send\" + receiver + str(text.lower())) # if op.type", "in groups: group = cl.getGroup(gid) ret_ += \"\\n╠ {}. {}", "] KICK ALL MEMBER\") _name = msg.text.replace(\"Byeall\",\"\") gs = cl.getGroup(msg.to)", "str(to.displayName) # print (\"receiver\" + sender + str(text.lower())) if op.type", "False: settings[\"mimic\"][\"status\"] = True cl.sendMessage(msg.to,\"Reply Message on\") elif mic ==", "not None: cl.sendMessage(msg.to,text) if msg.contentType == 0 and sender not", "\"\" } msg_dict = {} bl = [\"\"] myProfile[\"displayName\"] =", "pkg_id = msg.contentMetadata['STKPKGID'] ret_ = \"╔══[ Sticker Info ]\" ret_", "admin =['ud5ff1dff426cf9e3030c7ac2a61512f0','ua10c2ad470b4b6e972954e1140ad1891',clMID] owners = [\"ua10c2ad470b4b6e972954e1140ad1891\",\"ud5ff1dff426cf9e3030c7ac2a61512f0\"] #if clMID not in owners:", "msg.text): if msg.toType == 2: midd = msg.text.replace(\"Inv \",\"\") cl.findAndAddContactsByMid(midd)", "read['readTime'][msg.to] except: pass cl.sendMessage(msg.to, \"Delete reading point:\\n\" + readTime) elif", "True: cl.sendMessage(to, \"群組網址已開\") else: group.preventedJoinByTicket = True cl.updateGroup(group) cl.sendMessage(to, \"開啟成功\")", "= contact.displayName profile = cl.getProfile() profile.displayName = X cl.updateProfile(profile) cl.sendMessage(to,", "None: names = re.findall(r'@(\\w+)', text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees =", "== 'grouppicture': group = cl.getGroup(to) path = \"http://dl.profile.line-cdn.net/\" + group.pictureStatus", "Exception as error: print (error) pass else: cl.sendMessage(receiver,\"尚未設置偵測點\") #==============================================================================# elif", "time.time() runtime = timeNow - botStart runtime = format_timespan(runtime) cl.sendMessage(to,", "= cl.getGroup(to) GS = group.creator.mid cl.sendContact(to, GS) elif text.lower() ==", "success\") elif text.lower() == 'autojoin on': settings[\"autoJoin\"] = True cl.sendMessage(to,", "\"\\n╠ Auto Read ❌\" if settings[\"reread\"] ==True: ret_+=\"\\n╠ Reread ✅\"", "== 19: if op.param2 not in owners: if op.param2 in", "text.lower() == 'link on': if msg.toType == 2: group =", "= str(len(group.invitee)) if group.preventedJoinByTicket == True: gQr = \"關閉\" gTicket", "\"E\" :str(s+6), \"M\":i.mid}) s += 7 txt += u'@Alin \\n'", "try: cl.sendMessage(receiver, text, contentMetadata={'MENTION':str('{\"MENTIONEES\":'+json.dumps(zx2).replace(' ','')+'}')}, contentType=0) except Exception as error:", "lists: path = cl.getProfileCoverURL(ls) cl.sendImageWithURL(msg.to, str(path)) elif msg.text.lower().startswith(\"cloneprofile \"): if", "codecs, threading, glob, re, string, os, requests, subprocess, six, ast,", "if msg.toType == 2: group = cl.getGroup(to) gMembMids = [contact.mid", "* from datetime import datetime from time import sleep from", "== 'autojoin on': settings[\"autoJoin\"] = True cl.sendMessage(to, \"Auto Join on", "= cl.getGroup(to) if group.preventedJoinByTicket == False: cl.sendMessage(to, \"群組網址已關\") else: group.preventedJoinByTicket", "bl: cl.sendMessage(at,\"[收回訊息者]\\n%s\\n[訊息內容]\\n%s\"%(cl.getContact(msg_dict[msg_id][\"from\"]).displayName,msg_dict[msg_id][\"text\"])) del msg_dict[msg_id] else: pass except Exception as e:", "= [contact.mid for contact in group.members] k = len(nama)//100 for", "= op.param2 backupData() else: pass except: pass except Exception as", "mention[\"M\"] break try: cl.cloneContactProfile(contact) cl.sendMessage(msg.to, \"Berhasil clone member tunggu beberapa", "'grouplist': groups = cl.groups ret_ = \"╔══[ Group List ]\"", "= True cl.sendMessage(msg.to,\"Reply Message on\") elif mic == \"off\": if", "runtime = timeNow - botStart runtime = format_timespan(runtime) cl.sendMessage(to, \"系統已運作", "gMembMids = [contact.mid for contact in group.members] matched_list = []", "'protect off': settings[\"protect\"] = False cl.sendMessage(to, \"Protect off success\") elif", "= \"http://dl.profile.cl.naver.jp/\" + cl.getContact(ls).pictureStatus cl.sendImageWithURL(msg.to, str(path)) for ls in lists:", "in msg.text.lower(): sep = msg.text.split(\" \") tanggal = msg.text.replace(sep[0] +", "op.type == 19: if op.param2 not in owners: if op.param2", "= \"不明\" if group.invitee is None: gPending = \"0\" else:", "= cl.getContact(ls) cl.sendMessage(msg.to, \"[ 個簽 ]\\n\" + contact.statusMessage) for ls", "!= None: cl.sendVideoWithURL(receiver, 'http://dl.profile.line.naver.jp'+cpic+'/vp.small') else: cl.sendImageWithURL(receiver, 'http://dl.profile.line.naver.jp'+cpic) except Exception as", "in settings[\"blacklist\"]: try: del settings[\"blacklist\"][mi_d] cl.sendMessage(msg.to,\"已清空黑單!\") break except: cl.sendMessage(msg.to,\"刪除失敗 !\")", "on': settings[\"autoRead\"] = True cl.sendMessage(to, \"Auto Read on success\") elif", "cl.sendVideoWithURL(msg.to,\"http://dl.profile.line-cdn.net/\" + me.pictureStatus + \"/vp\") elif text.lower() == 'mycover': me", "'mytoken': me = cl.getContact(clMID) cl.sendMessage(msg.to,\"[StatusMessage]\\n\" + me.statusMessage) elif text.lower() ==", "'link on': if msg.toType == 2: group = cl.getGroup(to) if", "in targets: try: cl.cloneContactProfile(target) cl.sendMessage(msg.to, \"Berhasil clone member tunggu beberapa", "cl.leaveRoom(op.param1) if op.type == 25 or op.type == 26: K0", "cl.sendMessage(to, text_, contentMetadata={'MENTION':'{\"MENTIONEES\":['+aa+']}'}, contentType=0) except Exception as error: logError(error) def", "if msg.to in read['readPoint']: try: del read['readPoint'][msg.to] del read['readMember'][msg.to] del", "\"\" zxc = \"\" zx2 = [] xpesan = '[", "e: cl.sendMessage(msg.to, str(e)) elif text.lower() == 'autoadd on': settings[\"autoAdd\"] =", "if op.type == 19: if op.param2 not in owners: if", "text.lower() == 'restart': cl.sendMessage(to, \"重新啟動中...\") time.sleep(5) cl.sendMessage(to, \"重啟成功,請重新登入\") restartBot() elif", "path = \"http://dl.profile.line-cdn.net/\" + group.pictureStatus ret_ = \"╔══[ Group Info", "as e: cl.sendMessage(receiver, str(e)) if line != None: if 'MENTION'", "Finish ]\") elif text.lower() == 'nkban': if msg.toType == 2:", "ret_ += \"\\n╠ 製作者 : {}\".format(creator.displayName) ret_ += \"\\n╚══[ 感謝您的使用", "for mi_d in admin: mc += \"\\n╠ \"+cl.getContact(mi_d).displayName cl.sendMessage(to,mc +", "'autoread off': settings[\"autoRead\"] = False cl.sendMessage(to, \"Auto Read off success\")", "= '@x ' cl.sendMessage(to, text_, contentMetadata={'MENTION':'{\"MENTIONEES\":['+aa+']}'}, contentType=0) except Exception as", "cl.getProfileCoverURL(ls) pmath = \"http://dl.profile.cl.naver.jp/\" + cl.getContact(ls).pictureStatus cl.sendImageWithURL(msg.to, path) try: key", "+= \"\\n╠ 群組數 : {}\".format(str(len(grouplist))) ret_ += \"\\n╠ 好友數 :", "= False cl.sendMessage(to, \"Auto Leave off success\") elif text.lower() ==", "\"Gagal clone member\") elif text.lower() == 'restoreprofile': try: clProfile.displayName =", "Finish ]\") #==============================================================================# elif \"Copy \" in msg.text: targets =", "else: read['readMember'][op.param1] += op.param2 read['ROM'][op.param1][op.param2] = op.param2 backupData() else: pass", "cl.sendMessage(to, \"Auto Join off success\") elif text.lower() == 'autoleave on':", "if wait[\"share\"] == True: K0 = msg._from else: K0 =", "op.type == 25: # to = msg.to # receiver =", "for i in group.members[a*100 : (a+1)*100]: b.append({\"S\":str(s), \"E\" :str(s+6), \"M\":i.mid})", "Token : \" + str(channelToken)) clMID = cl.profile.mid clProfile =", "cl.sendMessage(to, \"已關閉分享\") #==============================================================================# elif text.lower() == 'admin ': MENTION =eval(msg.contentMetadata['MENTION'])", "in read['readPoint']: try: del read['readPoint'][msg.to] del read['readMember'][msg.to] del read['readTime'][msg.to] except:", "= timeNow.strftime(\"%m\") for i in range(len(day)): if hr == day[i]:", "contentType=13) if cl.getContact(u).videoProfile != None: cl.sendVideoWithURL(receiver, 'http://dl.profile.line.naver.jp'+cpic+'/vp.small') else: cl.sendImageWithURL(receiver, 'http://dl.profile.line.naver.jp'+cpic)", "0: if text is None: return #==============================================================================# if sender in", "settings[\"autoAdd\"] == True: cl.sendMessage(op.param1, \"感謝您加入本帳為好友w\".format(str(cl.getContact(op.param1).displayName))) if op.type == 13: print", "pesan = '' pesan2 = pesan+\"@c\\n\" xlen = str(len(zxc)+len(xpesan)) xlen2", "= sys.executable os.execl(python, python, *sys.argv) else: pass #==============================================================================# elif text.lower()", "cl.sendMessage(msg.to, \"Berhasil clone member tunggu beberapa saat sampai profile berubah\")", "Info ]\" ret_ += \"\\n╠ 群組名稱 : {}\".format(str(group.name)) ret_ +=", "] REREAD\") try: at = op.param1 msg_id = op.param2 if", "\"Berhasil menonaktifkan Detect Mention\") elif text.lower() == 'reread on': settings[\"reread\"]", "= \"╔══[ 狀態 ]\" if settings[\"autoAdd\"] == True: ret_ +=", "str(len(group.members))) no += 1 ret_ += \"\\n╚══[ Total {} Groups", "text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] lists = []", "=eval(msg.contentMetadata['MENTION']) inkey =MENTION['MENTIONEES'][0]['M'] admin.remove(str(inkey)) cl.sendMessage(to,\"已停止權限\") elif text.lower() == 'adminlist': if", "ls in lists: contact = cl.getContact(ls) cl.sendMessage(msg.to, \"[ 個簽 ]\\n\"", "= cl.getContact(target) X = contact.displayName profile = cl.getProfile() profile.displayName =", "try: del read['readPoint'][msg.to] del read['readMember'][msg.to] del read['readTime'][msg.to] except: pass cl.sendMessage(msg.to,", "cl.sendMessage(to,\"reread on success\") elif text.lower() == 'reread off': settings[\"reread\"] =", "path) try: key = eval(msg.contentMetadata[\"MENTION\"]) u = key[\"MENTIONEES\"][0][\"M\"] cname =", "else: pass except Exception as e: print (e) #==============================================================================# if", "read['readPoint'][msg.to] del read['readMember'][msg.to] del read['readTime'][msg.to] except: pass cl.sendMessage(msg.to, \"Delete reading", "no = 0 + 1 for mem in group.members: ret_", "\"偵測點未設置?\") elif text.lower() == 'lr': tz = pytz.timezone(\"Asia/Jakarta\") timeNow =", "= [] for tag in settings[\"blacklist\"]: matched_list+=filter(lambda str: str ==", "'banmidlist': if settings[\"blacklist\"] == {}: cl.sendMessage(msg.to,\"無黑單成員!\") else: mc = \"╔══[", "clProfile.pictureStatus = str(myProfile[\"pictureStatus\"]) cl.updateProfileAttribute(8, clProfile.pictureStatus) cl.updateProfile(clProfile) cl.sendMessage(msg.to, \"Berhasil restore profile", "= cl.getContact(clMID) grouplist = cl.getGroupIdsJoined() contactlist = cl.getAllContactIds() blockedlist =", "text.lower() == 'share on': wait[\"share\"] = True cl.sendMessage(to, \"已開啟分享\") elif", "datetime import datetime from time import sleep from humanfriendly import", "True cl.sendMessage(to,\"reread on success\") elif text.lower() == 'reread off': settings[\"reread\"]", "sender + str(text.lower())) if op.type == 26 or op.type ==", "ret_ = \"╔══[ Group List ]\" no = 0 +", "backup = settings f = codecs.open('temp.json','w','utf-8') json.dump(backup, f, sort_keys=True, indent=4,", "msg.text.lower().startswith(\"mimicdel \"): targets = [] key = eval(msg.contentMetadata[\"MENTION\"]) key[\"MENTIONEES\"][0][\"M\"] for", "ret_ = \"╔══[ 成員名單 ]\" no = 0 + 1", "str(text.lower())) # if op.type == 26: # to = msg._from", "mentionees = mention['MENTIONEES'] lists = [] for mention in mentionees:", "fp: json.dump(read, fp, sort_keys=True, indent=4) cl.sendMessage(msg.to,\"偵測點已設置\") else: try: del read['readPoint'][msg.to]", "26 ] RECEIVE MESSAGE\") msg = op.message text = msg.text", "+ \" \",\"\") with requests.session() as web: r = web.get(\"http://rahandiapi.herokuapp.com/sswebAPI?key=betakey&link={}\".format(urllib.parse.quote(query)))", "\"\\n╠ STICKER URL : line://shop/detail/{}\".format(pkg_id) ret_ += \"\\n╚══[ Finish ]\"", "cl.cloneContactProfile(target) cl.sendMessage(msg.to, \"Berhasil clone member tunggu beberapa saat sampai profile", "import datetime from time import sleep from humanfriendly import format_timespan,", "ret_ += \"\\n╠ Age : {}\".format(str(data[\"data\"][\"usia\"])) ret_ += \"\\n╠ Birthday", "msg.contentMetadata[\"displayName\"] copy = msg.contentMetadata[\"mid\"] groups = cl.getGroup(msg.to) targets = []", "'E':xlen2, 'M':cmem[x].mid} zx2.append(zx) zxc += pesan2 text = xpesan+ zxc", "except: cl.sendMessage(msg.to,\"\") elif (\"Gn \" in msg.text): if msg.toType ==", "= True cl.sendMessage(msg.to,\"已加入模仿名單!\") break except: cl.sendMessage(msg.to,\"添加失敗 !\") break elif msg.text.lower().startswith(\"mimicdel", "str(channelToken)) clMID = cl.profile.mid clProfile = cl.getProfile() lineSettings = cl.getSettings()", "receiver = str(to.displayName) # print (\"send\" + receiver + str(text.lower()))", "\"Auto Read on success\") elif text.lower() == 'autoread off': settings[\"autoRead\"]", "success\") elif text.lower() == 'share on': wait[\"share\"] = True cl.sendMessage(to,", "for target in targets: try: settings[\"blacklist\"][target] = True cl.sendMessage(msg.to,\"已加入黑單!\") break", "'protect on': settings[\"protect\"] = True cl.sendMessage(to, \"Protect on success\") elif", "== 'nk': if msg.toType == 2: print (\"[ 19 ]", "del read['readMember'][msg.to] del read['readTime'][msg.to] except: pass cl.sendMessage(msg.to, \"Delete reading point:\\n\"", "{}\".format(str(data[\"data\"][\"zodiak\"])) ret_ += \"\\n╚══[ Success ]\" cl.sendMessage(to, str(ret_)) elif msg.contentType", "range(0, len(bulan)): if bln == str(k): bln = bulan[k-1] readTime", "E ]\" ret_ += \"\\n╠ Date Of Birth : {}\".format(str(data[\"data\"][\"lahir\"]))", "❌\" if settings[\"autoJoin\"] == True: ret_ += \"\\n╠ Auto Join", "55 ] NOTIFIED READ MESSAGE\") try: if op.param1 in read['readPoint']:", "bl = [\"\"] myProfile[\"displayName\"] = clProfile.displayName myProfile[\"statusMessage\"] = clProfile.statusMessage myProfile[\"pictureStatus\"]", "if settings[\"autoLeave\"] == True: ret_ += \"\\n╠ Auto Leave ✅\"", "json, codecs, threading, glob, re, string, os, requests, subprocess, six,", "\"\\n╠ 好友數 : {}\".format(str(len(contactlist))) ret_ += \"\\n╠ 已封鎖 : {}\".format(str(len(blockedlist)))", "mc += \"\\n╠ \"+mi_d cl.sendMessage(to,mc + \"\\n╚══[ Finish ]\") #==============================================================================#", "datetime.now().strftime('%H:%M:%S') read['ROM'][msg.to] = {} with open('read.json', 'w') as fp: json.dump(read,", "0 ] END OF OPERATION\") return if op.type == 5:", "if text is None: return #==============================================================================# if sender in K0:", "menonaktifkan Detect Mention\") elif text.lower() == 'reread on': settings[\"reread\"] =", "mi_d) elif msg.text.lower().startswith(\"mid \"): if 'MENTION' in msg.contentMetadata.keys()!= None: names", "'restoreprofile': try: clProfile.displayName = str(myProfile[\"displayName\"]) clProfile.statusMessage = str(myProfile[\"statusMessage\"]) clProfile.pictureStatus =", "= pytz.timezone(\"Asia/Makassar\") timeNow = datetime.now(tz=tz) day = [\"Sunday\", \"Monday\", \"Tuesday\",", "if settings[\"copy\"] == True: _name = msg.contentMetadata[\"displayName\"] copy = msg.contentMetadata[\"mid\"]", "= OEPoll(cl) #==============================================================================# readOpen = codecs.open(\"read.json\",\"r\",\"utf-8\") settingsOpen = codecs.open(\"temp.json\",\"r\",\"utf-8\") read", "RESETTED\") backupData() python = sys.executable os.execl(python, python, *sys.argv) def backupData():", "\"Auto Add on success\") elif text.lower() == 'autoadd off': settings[\"autoAdd\"]", "to = receiver else: to = receiver if settings[\"autoRead\"] ==", "\"[ID Group : ]\\n\" + gid.id) elif text.lower() == 'grouppicture':", "+= \"\\n╠ Birthday : {}\".format(str(data[\"data\"][\"ultah\"])) ret_ += \"\\n╠ Zodiak :", "elif msg.text.lower().startswith(\"mimicadd \"): targets = [] key = eval(msg.contentMetadata[\"MENTION\"]) key[\"MENTIONEES\"][0][\"M\"]", "is not None: cl.sendMessage(msg.to,text) if msg.contentType == 0 and sender", "success\") elif text.lower() == 'protect on': settings[\"protect\"] = True cl.sendMessage(to,", "\"\\n\" + ls cl.sendMessage(msg.to, str(ret_)) elif msg.text.lower().startswith(\"name \"): if 'MENTION'", "]:\\nNone\") else: chiya = [] for rom in read[\"ROM\"][receiver].items(): chiya.append(rom[1])", "day[i]: hasil = hari[i] for k in range(0, len(bulan)): if", "timeNow = datetime.now(tz=tz) day = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\"Friday\",", "elif text.lower() == 'cc9487': if sender in ['ua10c2ad470b4b6e972954e1140ad1891']: python =", "if settings[\"checkSticker\"] == True: stk_id = msg.contentMetadata['STKID'] stk_ver = msg.contentMetadata['STKVER']", "open('read.json', 'w') as fp: json.dump(read, fp, sort_keys=True, indent=4) cl.sendMessage(msg.to,\"偵測點已設置\") else:", "contact.displayName) for ls in lists: contact = cl.getContact(ls) cl.sendMessage(msg.to, \"[", "+= \"\\n╠ 網址狀態 : {}\".format(gQr) ret_ += \"\\n╠ 群組網址 :", "humanfriendly import format_timespan, format_size, format_number, format_length import time, random, sys,", "in mentionees: contact = mention[\"M\"] break try: cl.cloneContactProfile(contact) cl.sendMessage(msg.to, \"Berhasil", "mi_d = contact.mid cl.sendContact(msg.to, mi_d) elif msg.text.lower().startswith(\"mid \"): if 'MENTION'", "to = receiver if settings[\"autoRead\"] == True: cl.sendChatChecked(to, msg_id) if", "cl.sendMessage(to, str(helpMessage)) cl.sendContact(to,\"u0a59c278b1529476ddb210cb5e827ffc\") cl.sendContact(to,\"ufb30e2203f44bc7b72e28b09a88c9bbd\") #==============================================================================# elif text.lower() == 'speed': start", "cl.acceptGroupInvitation(op.param1) if op.type == 19: if op.param2 not in owners:", "]\" for mi_d in settings[\"blacklist\"]: mc += \"\\n╠ \"+cl.getContact(mi_d).displayName cl.sendMessage(msg.to,mc", "def sendMessageWithMention(to, mid): try: aa = '{\"S\":\"0\",\"E\":\"3\",\"M\":'+json.dumps(mid)+'}' text_ = '@x", "in msg.text.lower(): sep = text.split(\" \") mic = text.replace(sep[0] +", "lol = cl.getProfile() lol.statusMessage = Y cl.updateProfile(lol) P = contact.pictureStatus", "+ 1 for gid in groups: group = cl.getGroup(gid) ret_", "== tag, gMembMids) if matched_list == []: cl.sendMessage(msg.to,\"There was no", "= cl.profile.mid clProfile = cl.getProfile() lineSettings = cl.getSettings() oepoll =", "elif text.lower() == 'demin ': MENTION =eval(msg.contentMetadata['MENTION']) inkey =MENTION['MENTIONEES'][0]['M'] admin.remove(str(inkey))", "ticket = cl.reissueGroupTicket(to) cl.sendMessage(to, \"[ Group Ticket ]\\nhttps://cl.me/R/ti/g/{}\".format(str(ticket))) else: cl.sendMessage(to,", "if op.param2 in read['readMember'][op.param1]: pass else: read['readMember'][op.param1] += op.param2 read['ROM'][op.param1][op.param2]", "elif text.lower() == 'autoleave on': settings[\"autoLeave\"] = True cl.sendMessage(to, \"Auto", "mid): try: aa = '{\"S\":\"0\",\"E\":\"3\",\"M\":'+json.dumps(mid)+'}' text_ = '@x ' cl.sendMessage(to,", "str(ret_)) elif msg.text.lower().startswith(\"nk \"): targets = [] key = eval(msg.contentMetadata[\"MENTION\"])", "A T E ]\" ret_ += \"\\n╠ Date Of Birth", "好友數 : {}\".format(str(len(contactlist))) ret_ += \"\\n╠ 已封鎖 : {}\".format(str(len(blockedlist))) ret_", "op.type == 24: print (\"[ 24 ] NOTIFIED LEAVE ROOM\")", "!\") break except: cl.sendMessage(msg.to,\"刪除失敗 !\") break elif text.lower() == 'banlist':", "msg = op.message text = msg.text msg_id = msg.id receiver", "elif msg.text.lower().startswith(\"name \"): if 'MENTION' in msg.contentMetadata.keys()!= None: names =", "\"\\n╚══[ Finish ]\") elif \"mimic\" in msg.text.lower(): sep = text.split(\"", "== False: settings[\"mimic\"][\"status\"] = True cl.sendMessage(msg.to,\"Reply Message on\") elif mic", "for target in targets: try: cl.sendMessage(to,\"Fuck you\") cl.kickoutFromGroup(msg.to,[target]) except: cl.sendMessage(to,\"Error\")", "in group.members] matched_list = [] for tag in settings[\"blacklist\"]: matched_list+=filter(lambda", "Mention\".format(str(len(nama)))) elif text.lower() == 'sr': tz = pytz.timezone(\"Asia/Jakarta\") timeNow =", "cl.sendMessage(msg.to, \"偵測點未設置?\") elif text.lower() == 'lr': tz = pytz.timezone(\"Asia/Jakarta\") timeNow", "= cl.getGroup(msg.to) X.name = msg.text.replace(\"Gn \",\"\") cl.updateGroup(X) else: cl.sendMessage(msg.to,\"It can't", "pass cl.sendMessage(msg.to, \"Reset reading point:\\n\" + readTime) else: cl.sendMessage(msg.to, \"偵測點未設置?\")", "]\" cl.sendMessage(to, str(ret_)) elif msg.contentType == 7: if settings[\"checkSticker\"] ==", "+= \"\\n╠ STICKER URL : line://shop/detail/{}\".format(pkg_id) ret_ += \"\\n╚══[ Finish", "text, contentMetadata={'MENTION':str('{\"MENTIONEES\":'+json.dumps(zx2).replace(' ','')+'}')}, contentType=0) except Exception as error: print (error)", "open(\"errorLog.txt\",\"a\") as error: error.write(\"\\n[%s] %s\" % (str(time), text)) def sendMessageWithMention(to,", "+ \"\\n╚══[ Finish ]\") elif text.lower() == 'nkban': if msg.toType", "helpMessage = \"\"\"╔═════════════ ╠♥ ✿✿✿ 十香の特製Bot ✿✿✿ ♥ ╠SR 設定已讀點", "其他功能略 〙✪═══ \"\"\" return helpMessage wait = { \"share\":False, \"sender\"", "settings[\"datectMention\"] = True cl.sendMessage(to, \"Berhasil mengaktifkan Detect Mention\") elif text.lower()", "True if sender in settings[\"mimic\"][\"target\"] and settings[\"mimic\"][\"status\"] == True and", "hr = timeNow.strftime(\"%A\") bln = timeNow.strftime(\"%m\") for i in range(len(day)):", "= receiver if msg.contentType == 0: if text is None:", "ret_ += \"\\n╠ Reread ❌\" ret_ += \"\\n╚══[ Finish ]\"", "gs.members: if _name in g.displayName: targets.append(g.mid) if targets == []:", "text.split(\" \") query = text.replace(sep[0] + \" \",\"\") with requests.session()", "if op.type == 13: print (\"[ 13 ] NOTIFIED INVITE", "= \"╔══[ 關於使用者 ]\" ret_ += \"\\n╠ 使用者名稱 : {}\".format(contact.displayName)", "+ \"\\nJam : [ \" + timeNow.strftime('%H:%M:%S') + \" ]\"", "cl.sendMessage(msg.to,text) if msg.contentType == 0 and sender not in clMID", "elif mic == \"off\": if settings[\"mimic\"][\"status\"] == True: settings[\"mimic\"][\"status\"] =", "op.param2 read['ROM'][op.param1][op.param2] = op.param2 backupData() else: pass except: pass except", "range(len(cmem)): xname = str(cmem[x].displayName) pesan = '' pesan2 = pesan+\"@c\\n\"", "msg_id = op.param2 if setting[\"reread\"] == True: if msg_id in", "python = sys.executable # os.execl(python, python, *sys.argv) #==============================================================================# def lineBot(op):", "\"displayName\": \"\", \"statusMessage\": \"\", \"pictureStatus\": \"\" } msg_dict = {}", "= cl.getGroup(to) try: gCreator = group.creator.displayName except: gCreator = \"不明\"", "f, sort_keys=True, indent=4, ensure_ascii=False) return True except Exception as error:", "ret_ += \"\\n╠ STICKER PACKAGES ID : {}\".format(pkg_id) ret_ +=", "myProfile[\"statusMessage\"] = clProfile.statusMessage myProfile[\"pictureStatus\"] = clProfile.pictureStatus #==============================================================================# def restartBot(): print", "except: cl.sendMessage(msg.to,\"刪除失敗 !\") break elif text.lower() == 'mimiclist': if settings[\"mimic\"][\"target\"]", "== 'detectmention on': settings[\"datectMention\"] = True cl.sendMessage(to, \"Berhasil mengaktifkan Detect", "cl.sendContact(to, clMID) elif text.lower() == 'mymid': cl.sendMessage(msg.to,\"[MID]\\n\" + clMID) elif", "targets = [] for s in groups.members: if _name in", "or op.type == 25: print (\"[ 25 ] SEND MESSAGE\")", "group = cl.getGroup(to) if group.preventedJoinByTicket == True: cl.sendMessage(to, \"群組網址已開\") else:", "group = cl.getGroup(to) gMembMids = [contact.mid for contact in group.members]", "lists.append(mention[\"M\"]) ret_ = \"[ Mid User ]\" for ls in", "+= \"\\n╠ Date Of Birth : {}\".format(str(data[\"data\"][\"lahir\"])) ret_ += \"\\n╠", "msg.text.replace(\"Inv \",\"\") cl.findAndAddContactsByMid(midd) cl.inviteIntoGroup(to,[midd]) #==============================================================================# elif text.lower() == 'tagall': group", "True: cl.sendChatChecked(to, msg_id) if to in read[\"readPoint\"]: if sender not", "text.lower() == 'runtime': timeNow = time.time() runtime = timeNow -", "\"Jumat\", \"Sabtu\"] bulan = [\"Januari\", \"Februari\", \"Maret\", \"April\", \"Mei\", \"Juni\",", "text.lower() == 'cleanban': settings[\"blacklist\"] == {ok} for mi_d in settings[\"blacklist\"]:", "= receiver else: to = receiver if msg.contentType == 0:", "a in range(k+1): txt = u'' s=0 b=[] for i", "zx = {'S':xlen, 'E':xlen2, 'M':cmem[x].mid} zx2.append(zx) zxc += pesan2 text", "\"\\n╚══[ Finish ]\" cl.sendMessage(to, str(ret_)) elif msg.contentType == 13: if", "+= \"\\n╠ Auto Join ✅\" else: ret_ += \"\\n╠ Auto", "on success\") elif text.lower() == 'autojoin off': settings[\"autoJoin\"] = False", "== []: cl.sendMessage(msg.to,\"Not Found\") else: for target in targets: try:", "(\"[ 13 ] NOTIFIED INVITE GROUP\") group = cl.getGroup(op.param1) if", "\"\\n╠ 邀請中 : {}\".format(gPending) ret_ += \"\\n╠ 網址狀態 : {}\".format(gQr)", "target in targets: try: cl.kickoutFromGroup(msg.to,[target]) print (msg.to,[g.mid]) except: cl.sendMessage(msg.to,\"\") elif", "text.lower() == 'checksticker on': settings[\"checkSticker\"] = True cl.sendMessage(to, \"Berhasil mengaktifkan", "error: print (error) pass else: cl.sendMessage(receiver,\"尚未設置偵測點\") #==============================================================================# elif msg.text.lower().startswith(\"ban \"):", "- botStart runtime = format_timespan(runtime) cl.sendMessage(to, \"系統已運作 {}\".format(str(runtime))) elif text.lower()", "x in key[\"MENTIONEES\"]: targets.append(x[\"M\"]) for target in targets: try: contact", "and sender not in clMID and msg.toType == 2: if", "elif text.lower() == 'grouplink': if msg.toType == 2: group =", "== 'groupname': gid = cl.getGroup(to) cl.sendMessage(to, \"[群組名稱 : ]\\n\" +", "else: pass except: pass except Exception as error: logError(error) #==============================================================================#", "elif text.lower() == 'readcancel': tz = pytz.timezone(\"Asia/Jakarta\") timeNow = datetime.now(tz=tz)", "line != None: if 'MENTION' in msg.contentMetadata.keys()!= None: names =", "fp, sort_keys=True, indent=4) cl.sendMessage(msg.to,\"偵測點已設置\") else: try: del read['readPoint'][msg.to] del read['readMember'][msg.to]", "= True cl.sendMessage(to, \"Protect on success\") elif text.lower() == 'protect", "from humanfriendly import format_timespan, format_size, format_number, format_length import time, random,", "\"\\n╠ {}. {}\".format(str(no), str(mem.displayName)) no += 1 ret_ += \"\\n╚══[", "with open(\"errorLog.txt\",\"a\") as error: error.write(\"\\n[%s] %s\" % (str(time), text)) def", "+= op.param2 read['ROM'][op.param1][op.param2] = op.param2 backupData() else: pass except: pass", "data = r.text data = json.loads(data) cl.sendImageWithURL(to, data[\"result\"]) elif \"checkdate\"", "in K0: if text.lower() == 'help': helpMessage = helpmessage() cl.sendMessage(to,", "Exception as error: logError(error) return False def logError(text): cl.log(\"[ ERROR", "]\" ret_ += \"\\n╠ 使用者名稱 : {}\".format(contact.displayName) ret_ += \"\\n╠", "profile berubah\") settings['copy'] = False break except: msg.contentMetadata = {'mid':", "== []: cl.sendMessage(receiver,\"[ 已讀的人 ]:\\nNone\") else: chiya = [] for", "op.message text = msg.text msg_id = msg.id receiver = msg.to", "botStart runtime = format_timespan(runtime) cl.sendMessage(to, \"系統已運作 {}\".format(str(runtime))) elif text.lower() ==", "'mycover': me = cl.getContact(clMID) cover = cl.getProfileCoverURL(clMID) cl.sendImageWithURL(msg.to, cover) elif", "==True: ret_+=\"\\n╠ Reread ✅\" else: ret_ += \"\\n╠ Reread ❌\"", "del settings[\"blacklist\"][target] cl.sendMessage(msg.to,\"刪除成功 !\") break except: cl.sendMessage(msg.to,\"刪除失敗 !\") break elif", "(\"[Target] Copy\") break else: targets.append(copy) if targets == []: cl.sendMessage(msg.to,", "cl.getGroup(op.param1) if settings[\"autoJoin\"] == True: cl.acceptGroupInvitation(op.param1) if op.type == 19:", "ret_ += \"\\n╠ STICKER URL : line://shop/detail/{}\".format(pkg_id) ret_ += \"\\n╚══[", "text.lower() == 'autoadd off': settings[\"autoAdd\"] = False cl.sendMessage(to, \"Auto Add", "= cl.getProfile() lineSettings = cl.getSettings() oepoll = OEPoll(cl) #==============================================================================# readOpen", "cl.sendMessage(msg.to, \"Delete reading point:\\n\" + readTime) elif text.lower() == 'resetread':", ": ]\\n\" + gid.name) elif text.lower() == 'grouplink': if msg.toType", "=MENTION['MENTIONEES'][0]['M'] admin.remove(str(inkey)) cl.sendMessage(to,\"已停止權限\") elif text.lower() == 'adminlist': if admin ==", "sys.executable # os.execl(python, python, *sys.argv) #==============================================================================# def lineBot(op): try: if", "24 ] NOTIFIED LEAVE ROOM\") if settings[\"autoLeave\"] == True: cl.leaveRoom(op.param1)", "\"開啟成功\") elif text.lower() == 'groupinfo': group = cl.getGroup(to) try: gCreator", "settings[\"reread\"] = False cl.sendMessage(to,\"reread off success\") elif text.lower() == 'protect", "settings[\"blacklist\"] == {}: cl.sendMessage(msg.to,\"無黑單成員!\") else: mc = \"╔══[ Black List", "sort_keys=True, indent=4) cl.sendMessage(msg.to,\"偵測點已設置\") else: try: del read['readPoint'][msg.to] del read['readMember'][msg.to] del", "if op.type == 26: # to = msg._from # sender", "try: cl.kickoutFromGroup(msg.to,[target]) print (msg.to,[g.mid]) except: cl.sendMessage(msg.to,\"\") elif (\"Gn \" in", "msg.text.lower().startswith(\"ban \"): targets = [] key = eval(msg.contentMetadata[\"MENTION\"]) key[\"MENTIONEES\"][0][\"M\"] for", "Reread ✅\" else: ret_ += \"\\n╠ Reread ❌\" ret_ +=", "in groups.members: if _name in s.displayName: print (\"[Target] Copy\") break", "on success\") elif text.lower() == 'protect off': settings[\"protect\"] = False", "True: ret_ += \"\\n╠ Auto Read ✅\" else: ret_ +=", "Add on success\") elif text.lower() == 'autoadd off': settings[\"autoAdd\"] =", "profile\") #==============================================================================# elif msg.text.lower().startswith(\"mimicadd \"): targets = [] key =", "beberapa saat sampai profile berubah\") except: cl.sendMessage(msg.to, \"Gagal restore profile\")", "= \"╔══[ Group Info ]\" ret_ += \"\\n╠ 群組名稱 :", "wait[\"share\"] == True: K0 = msg._from else: K0 = admin", "cl.sendMessage(to, \"Berhasil mengaktifkan Check Details Sticker\") elif text.lower() == 'checksticker", "else: gQr = \"開啟\" gTicket = \"https://cl.me/R/ti/g/{}\".format(str(cl.reissueGroupTicket(group.id))) path = \"http://dl.profile.line-cdn.net/\"", "day = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\"Friday\", \"Saturday\"] hari =", "elif (\"Gn \" in msg.text): if msg.toType == 2: X", "\"╔══[ 成員名單 ]\" no = 0 + 1 for mem", "kicked out\") elif text.lower() == 'cleanban': settings[\"blacklist\"] == {ok} for", "Auto Leave ❌\" if settings[\"autoRead\"] == True: ret_ += \"\\n╠", "text=txt, contentMetadata={u'MENTION': json.dumps({'MENTIONEES':b})}, contentType=0) cl.sendMessage(to, \"Total {} Mention\".format(str(len(nama)))) elif text.lower()", "read['readTime'][msg.to] except: pass read['readPoint'][msg.to] = msg.id read['readMember'][msg.to] = \"\" read['readTime'][msg.to]", "Reread ❌\" ret_ += \"\\n╚══[ Finish ]\" cl.sendMessage(to, str(ret_)) except", "cl.sendMessage(to, str(ret_)) elif msg.text.lower().startswith(\"nk \"): targets = [] key =", "= True cl.sendMessage(to, \"Auto Add on success\") elif text.lower() ==", "channelToken = cl.getChannelResult() cl.log(\"Channel Token : \" + str(channelToken)) clMID", "restore profile\") #==============================================================================# elif msg.text.lower().startswith(\"mimicadd \"): targets = [] key", "'share off': wait[\"share\"] = False cl.sendMessage(to, \"已關閉分享\") #==============================================================================# elif text.lower()", "matched_list: cl.kickoutFromGroup(msg.to,[jj]) cl.sendMessage(msg.to,\"Blacklist kicked out\") elif text.lower() == 'cleanban': settings[\"blacklist\"]", "settings[\"autoRead\"] == True: ret_ += \"\\n╠ Auto Read ✅\" else:", "except: pass cl.sendMessage(msg.to, \"Reset reading point:\\n\" + readTime) else: cl.sendMessage(msg.to,", "ADD CONTACT\") if settings[\"autoAdd\"] == True: cl.sendMessage(op.param1, \"感謝您加入本帳為好友w\".format(str(cl.getContact(op.param1).displayName))) if op.type", "elif text.lower() == 'autojoin on': settings[\"autoJoin\"] = True cl.sendMessage(to, \"Auto", "settings[\"blacklist\"]: mc += \"\\n╠ \"+mi_d cl.sendMessage(to,mc + \"\\n╚══[ Finish ]\")", "╠SR 設定已讀點 ╠LR 查看誰已讀 ╠Nk @ 標註踢人 ╠Nk 全部再見 ╠══✪〘", "if group.invitee is None: gPending = \"0\" else: gPending =", "== \"off\": if settings[\"mimic\"][\"status\"] == True: settings[\"mimic\"][\"status\"] = False cl.sendMessage(msg.to,\"Reply", "= cl.getContact(clMID) cl.sendMessage(msg.to,\"[StatusMessage]\\n\" + me.statusMessage) elif text.lower() == 'mypicture': me", "if settings[\"autoAdd\"] == True: cl.sendMessage(op.param1, \"感謝您加入本帳為好友w\".format(str(cl.getContact(op.param1).displayName))) if op.type == 13:", "on success\") elif text.lower() == 'autojoin off': settings[\"autoLeave\"] = False", "tunggu beberapa saat sampai profile berubah\") settings['copy'] = False break", "{}\".format(str(group.name)) ret_ += \"\\n╠ 群組 Id : {}\".format(group.id) ret_ +=", "\"無\" else: gQr = \"開啟\" gTicket = \"https://cl.me/R/ti/g/{}\".format(str(cl.reissueGroupTicket(group.id))) path =", "if settings[\"mimic\"][\"status\"] == False: settings[\"mimic\"][\"status\"] = True cl.sendMessage(msg.to,\"Reply Message on\")", "RECEIVE MESSAGE\") msg = op.message text = msg.text msg_id =", "{ \"share\":False, \"sender\" :{}, } admin =['ud5ff1dff426cf9e3030c7ac2a61512f0','ua10c2ad470b4b6e972954e1140ad1891',clMID] owners = [\"ua10c2ad470b4b6e972954e1140ad1891\",\"ud5ff1dff426cf9e3030c7ac2a61512f0\"]", "the group.\") elif text.lower() == 'cancel': if msg.toType == 2:", "text.lower() == 'mycover': me = cl.getContact(clMID) cover = cl.getProfileCoverURL(clMID) cl.sendImageWithURL(msg.to,", "cl.getContact(target) X = contact.displayName profile = cl.getProfile() profile.displayName = X", "+= \"\\n╚══[ 全部成員共 {} 人]\".format(str(len(group.members))) cl.sendMessage(to, str(ret_)) elif text.lower() ==", "\"ua10c2ad470b4b6e972954e1140ad1891\" creator = cl.getContact(owner) contact = cl.getContact(clMID) grouplist = cl.getGroupIdsJoined()", "\"\\n╠ Auto Join ❌\" if settings[\"autoLeave\"] == True: ret_ +=", "in key[\"MENTIONEES\"]: targets.append(x[\"M\"]) for target in targets: try: cl.sendMessage(to,\"Fuck you\")", "cl.profile.mid clProfile = cl.getProfile() lineSettings = cl.getSettings() oepoll = OEPoll(cl)", "creator = cl.getContact(owner) contact = cl.getContact(clMID) grouplist = cl.getGroupIdsJoined() contactlist", "cl.getProfileCoverURL(clMID) cl.sendImageWithURL(msg.to, cover) elif msg.text.lower().startswith(\"contact \"): if 'MENTION' in msg.contentMetadata.keys()!=", ": http://dl.profile.line.naver.jp'+cpic) cl.sendMessage(receiver, None, contentMetadata={'mid': cmid}, contentType=13) if cl.getContact(u).videoProfile !=", "ret_ += \"\\n╠ Auto Read ✅\" else: ret_ += \"\\n╠", "]\" cl.sendMessage(to, str(ret_)) except Exception as e: cl.sendMessage(msg.to, str(e)) #==============================================================================#", "= str(myProfile[\"statusMessage\"]) clProfile.pictureStatus = str(myProfile[\"pictureStatus\"]) cl.updateProfileAttribute(8, clProfile.pictureStatus) cl.updateProfile(clProfile) cl.sendMessage(msg.to, \"Berhasil", "X.name = msg.text.replace(\"Gn \",\"\") cl.updateGroup(X) else: cl.sendMessage(msg.to,\"It can't be used", "== 'groupmemberlist': if msg.toType == 2: group = cl.getGroup(to) ret_", "= msg.contentMetadata[\"displayName\"] copy = msg.contentMetadata[\"mid\"] groups = cl.getGroup(msg.to) targets =", "LEAVE ROOM\") if settings[\"autoLeave\"] == True: cl.leaveRoom(op.param1) if op.type ==", "except Exception as error: print (error) pass else: cl.sendMessage(receiver,\"尚未設置偵測點\") #==============================================================================#", "text.lower() == 'mypicture': me = cl.getContact(clMID) cl.sendImageWithURL(msg.to,\"http://dl.profile.line-cdn.net/\" + me.pictureStatus) elif", "== 5: print (\"[ 5 ] NOTIFIED ADD CONTACT\") if", "MESSAGE\") try: if op.param1 in read['readPoint']: if op.param2 in read['readMember'][op.param1]:", "re, string, os, requests, subprocess, six, ast, pytz, urllib, urllib.parse", "urllib.parse #==============================================================================# botStart = time.time() cl = LINE() #cl =", "pesan+\"@c\\n\" xlen = str(len(zxc)+len(xpesan)) xlen2 = str(len(zxc)+len(pesan2)+len(xpesan)-1) zx = {'S':xlen,", "= eval(msg.contentMetadata[\"MENTION\"]) u = key[\"MENTIONEES\"][0][\"M\"] cname = cl.getContact(u).displayName cmid =", "timeNow.strftime('%H:%M:%S') + \" ]\" cl.sendMessage(msg.to, readTime) elif \"screenshotwebsite\" in msg.text.lower():", "on': settings[\"datectMention\"] = True cl.sendMessage(to, \"Berhasil mengaktifkan Detect Mention\") elif", "format_size, format_number, format_length import time, random, sys, json, codecs, threading,", "\"\" zx2 = [] xpesan = '[ 已讀的人 ]:\\n' for", "for target in targets: try: cl.sendMessage(to,\"來回機票一張ww\") cl.kickoutFromGroup(msg.to,[target]) cl.inviteIntoGroup(to,[target]) except: cl.sendMessage(to,\"Error\")", "gTicket = \"無\" else: gQr = \"開啟\" gTicket = \"https://cl.me/R/ti/g/{}\".format(str(cl.reissueGroupTicket(group.id)))", "lists: contact = cl.getContact(ls) mi_d = contact.mid cl.sendContact(msg.to, mi_d) elif", "if msg.contentType == 0: if text is None: return #==============================================================================#", "target in targets: try: del settings[\"blacklist\"][target] cl.sendMessage(msg.to,\"刪除成功 !\") break except:", "not in owners: # python = sys.executable # os.execl(python, python,", "elif text.lower() == 'protect on': settings[\"protect\"] = True cl.sendMessage(to, \"Protect", "op.param2 in read['readMember'][op.param1]: pass else: read['readMember'][op.param1] += op.param2 read['ROM'][op.param1][op.param2] =", "\"Not Found...\") pass else: for target in targets: try: cl.cloneContactProfile(target)", "List ]\" for mi_d in settings[\"blacklist\"]: mc += \"\\n╠ \"+mi_d", "besides the group.\") elif text.lower() == 'cancel': if msg.toType ==", "try: cl.sendMessage(to,\"Fuck you\") cl.kickoutFromGroup(msg.to,[target]) except: cl.sendMessage(to,\"Error\") elif msg.text.lower().startswith(\"ri \"): targets", "if op.type == 65: print (\"[ 65 ] REREAD\") try:", "\"╔══[ Mimic List ]\" for mi_d in settings[\"mimic\"][\"target\"]: mc +=", "cl.sendMessage(to,\"Error\") elif text.lower() == 'nk': if msg.toType == 2: print", "\"Gagal restore profile\") #==============================================================================# elif msg.text.lower().startswith(\"mimicadd \"): targets = []", "= False cl.updateGroup(group) cl.sendMessage(to, \"關閉成功\") elif text.lower() == 'link on':", "groups.members: if _name in s.displayName: print (\"[Target] Copy\") break else:", "in settings[\"mimic\"][\"target\"] and settings[\"mimic\"][\"status\"] == True and settings[\"mimic\"][\"target\"][sender] == True:", "except Exception as error: logError(error) return False def logError(text): cl.log(\"[", "\"\\n╠ \"+cl.getContact(mi_d).displayName cl.sendMessage(to,mc + \"\\n╚══[ Finish ]\") #==============================================================================# elif text.lower()", "gMembMids) if matched_list == []: cl.sendMessage(msg.to,\"There was no blacklist user\")", "ret_ += \"\\n╚══[ Finish ]\" cl.sendMessage(to, str(ret_)) elif msg.contentType ==", "cl.getGroup(to) path = \"http://dl.profile.line-cdn.net/\" + group.pictureStatus cl.sendImageWithURL(to, path) elif text.lower()", "邀請中 : {}\".format(gPending) ret_ += \"\\n╠ 網址狀態 : {}\".format(gQr) ret_", ": {}\".format(str(data[\"data\"][\"zodiak\"])) ret_ += \"\\n╚══[ Success ]\" cl.sendMessage(to, str(ret_)) elif", "Birth : {}\".format(str(data[\"data\"][\"lahir\"])) ret_ += \"\\n╠ Age : {}\".format(str(data[\"data\"][\"usia\"])) ret_", "logError(error) def helpmessage(): helpMessage = \"\"\"╔═════════════ ╠♥ ✿✿✿ 十香の特製Bot ✿✿✿", "': MENTION =eval(msg.contentMetadata['MENTION']) inkey =MENTION['MENTIONEES'][0]['M'] admin.append(str(inkey)) cl.sendMessage(to,\"已新增權限\") elif text.lower() ==", "settings[\"autoAdd\"] = True cl.sendMessage(to, \"Auto Add on success\") elif text.lower()", "KAMU\") #cl = LINE(\"Email\",\"Password\") cl.log(\"Auth Token : \" + str(cl.authToken))", "ret_ += \"\\n\" + ls cl.sendMessage(msg.to, str(ret_)) elif msg.text.lower().startswith(\"name \"):", "KICK ALL MEMBER\") _name = msg.text.replace(\"Byeall\",\"\") gs = cl.getGroup(msg.to) cl.sendMessage(msg.to,\"Sorry", "txt = u'' s=0 b=[] for i in group.members[a*100 :", "== 'reread on': settings[\"reread\"] = True cl.sendMessage(to,\"reread on success\") elif", "13: if settings[\"copy\"] == True: _name = msg.contentMetadata[\"displayName\"] copy =", "break #==============================================================================# if op.type == 26: print (\"[ 26 ]", "break except: cl.sendMessage(msg.to,\"刪除失敗 !\") break elif text.lower() == 'banmidlist': if", "ret_ = \"[ Mid User ]\" for ls in lists:", "!\") break elif msg.text.lower().startswith(\"unban \"): targets = [] key =", "_name = msg.text.replace(\"Byeall\",\"\") gs = cl.getGroup(msg.to) cl.sendMessage(msg.to,\"Sorry guys\") targets =", "\"screenshotwebsite\" in msg.text.lower(): sep = text.split(\" \") query = text.replace(sep[0]", "for target in targets: try: cl.cloneContactProfile(target) cl.sendMessage(msg.to, \"Berhasil clone member", "= str(cmem[x].displayName) pesan = '' pesan2 = pesan+\"@c\\n\" xlen =", "= msg.text.replace(\"Byeall\",\"\") gs = cl.getGroup(msg.to) cl.sendMessage(msg.to,\"Sorry guys\") targets = []", "\"\\n╚══[ Success ]\" cl.sendMessage(to, str(ret_)) elif msg.contentType == 7: if", "Sticker\") elif text.lower() == 'checksticker off': settings[\"checkSticker\"] = False cl.sendMessage(to,", "'banlist': if settings[\"blacklist\"] == {}: cl.sendMessage(msg.to,\"無黑單成員!\") else: mc = \"╔══[", "!\") break elif msg.text.lower().startswith(\"mimicdel \"): targets = [] key =", "else: cl.sendMessage(receiver,\"尚未設置偵測點\") #==============================================================================# elif msg.text.lower().startswith(\"ban \"): targets = [] key", "python = sys.executable os.execl(python, python, *sys.argv) def backupData(): try: backup", "r=requests.get('https://script.google.com/macros/exec?service=AKfycbw7gKzP-WYV2F5mc9RaR7yE3Ve1yN91Tjs91hp_jHSE02dSv9w&nama=ervan&tanggal='+tanggal) data=r.text data=json.loads(data) ret_ = \"╔══[ D A T E", "targets == []: cl.sendMessage(msg.to, \"Not Found...\") pass else: for target", "mention['MENTIONEES'] lists = [] for mention in mentionees: if mention[\"M\"]", "read['readMember'][op.param1]: pass else: read['readMember'][op.param1] += op.param2 read['ROM'][op.param1][op.param2] = op.param2 backupData()", "'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\\w+)', text) mention =", "cl.sendMessage(to,\"來回機票一張ww\") cl.kickoutFromGroup(msg.to,[target]) cl.inviteIntoGroup(to,[target]) except: cl.sendMessage(to,\"Error\") elif text.lower() == 'nk': if", "'autoread on': settings[\"autoRead\"] = True cl.sendMessage(to, \"Auto Read on success\")", "cl.inviteIntoGroup(to,[target]) except: cl.sendMessage(to,\"Error\") elif text.lower() == 'nk': if msg.toType ==", "\"mimic\" in msg.text.lower(): sep = text.split(\" \") mic = text.replace(sep[0]", "if matched_list == []: cl.sendMessage(msg.to,\"There was no blacklist user\") return", "_name in g.displayName: targets.append(g.mid) if targets == []: cl.sendMessage(msg.to,\"Not Found\")", "msg.to not in read['readPoint']: cl.sendMessage(msg.to,\"偵測點已取消\") else: try: del read['readPoint'][msg.to] del", "contact = cl.getContact(sender) cl.sendMessage(to, \"sundala nu\") sendMessageWithMention(to, contact.mid) break #==============================================================================#", "]\" if msg.to in read['readPoint']: try: del read['readPoint'][msg.to] del read['readMember'][msg.to]", "'resetread': tz = pytz.timezone(\"Asia/Jakarta\") timeNow = datetime.now(tz=tz) day = [\"Sunday\",", "gid.name) elif text.lower() == 'grouplink': if msg.toType == 2: group", "try: aa = '{\"S\":\"0\",\"E\":\"3\",\"M\":'+json.dumps(mid)+'}' text_ = '@x ' cl.sendMessage(to, text_,", "admin msg = op.message if wait[\"share\"] == True: K0 =", "break elif msg.text.lower().startswith(\"mimicdel \"): targets = [] key = eval(msg.contentMetadata[\"MENTION\"])", "codecs.open('read.json','w','utf-8') json.dump(backup, f, sort_keys=True, indent=4, ensure_ascii=False) return True except Exception", "menonaktifkan Check Details Sticker\") elif text.lower() == 'detectmention on': settings[\"datectMention\"]", "{}\".format(pkg_id) ret_ += \"\\n╠ STICKER VERSION : {}\".format(stk_ver) ret_ +=", "line://shop/detail/{}\".format(pkg_id) ret_ += \"\\n╚══[ Finish ]\" cl.sendMessage(to, str(ret_)) elif msg.contentType", "settings[\"copy\"] = False break #==============================================================================# if op.type == 26: print", "ops = oepoll.singleTrace(count=50) if ops is not None: for op", "\"感謝您加入本帳為好友w\".format(str(cl.getContact(op.param1).displayName))) if op.type == 13: print (\"[ 13 ] NOTIFIED", "group = cl.getGroup(to) try: gCreator = group.creator.displayName except: gCreator =", "else: cl.sendMessage(op.param1,\"\") if op.type == 24: print (\"[ 24 ]", "mic == \"on\": if settings[\"mimic\"][\"status\"] == False: settings[\"mimic\"][\"status\"] = True", "text.lower() == 'readcancel': tz = pytz.timezone(\"Asia/Jakarta\") timeNow = datetime.now(tz=tz) day", "+ timeNow.strftime('%H:%M:%S') + \" ]\" if receiver in read['readPoint']: if", "\"): targets = [] key = eval(msg.contentMetadata[\"MENTION\"]) key[\"MENTIONEES\"][0][\"M\"] for x", "#==============================================================================# if op.type == 26: print (\"[ 26 ] RECEIVE", "= codecs.open(\"read.json\",\"r\",\"utf-8\") settingsOpen = codecs.open(\"temp.json\",\"r\",\"utf-8\") read = json.load(readOpen) settings =", "'help': helpMessage = helpmessage() cl.sendMessage(to, str(helpMessage)) cl.sendContact(to,\"u0a59c278b1529476ddb210cb5e827ffc\") cl.sendContact(to,\"ufb30e2203f44bc7b72e28b09a88c9bbd\") #==============================================================================# elif", "= cl.getProfileCoverURL(ls) cl.sendImageWithURL(msg.to, str(path)) elif msg.text.lower().startswith(\"cloneprofile \"): if 'MENTION' in", "if group.preventedJoinByTicket == True: gQr = \"關閉\" gTicket = \"無\"", "= \"\" zxc = \"\" zx2 = [] xpesan =", "and msg.toType == 2: if 'MENTION' in msg.contentMetadata.keys()!= None: names", "pytz.timezone(\"Asia/Makassar\") timeNow = datetime.now(tz=tz) day = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",", "\"Berhasil restore profile tunggu beberapa saat sampai profile berubah\") except:", ":str(s+6), \"M\":i.mid}) s += 7 txt += u'@Alin \\n' cl.sendMessage(to,", "= '' pesan2 = pesan+\"@c\\n\" xlen = str(len(zxc)+len(xpesan)) xlen2 =", "key[\"MENTIONEES\"]: targets.append(x[\"M\"]) for target in targets: try: del settings[\"blacklist\"][target] cl.sendMessage(msg.to,\"刪除成功", "contentType=0) except Exception as error: print (error) pass else: cl.sendMessage(receiver,\"尚未設置偵測點\")", "except: cl.sendMessage(msg.to,\"添加失敗 !\") break elif msg.text.lower().startswith(\"unban \"): targets = []", "\" \",\"\") r=requests.get('https://script.google.com/macros/exec?service=AKfycbw7gKzP-WYV2F5mc9RaR7yE3Ve1yN91Tjs91hp_jHSE02dSv9w&nama=ervan&tanggal='+tanggal) data=r.text data=json.loads(data) ret_ = \"╔══[ D A", "'calender': tz = pytz.timezone(\"Asia/Makassar\") timeNow = datetime.now(tz=tz) day = [\"Sunday\",", "'groupid': gid = cl.getGroup(to) cl.sendMessage(to, \"[ID Group : ]\\n\" +", "Read ❌\" if settings[\"reread\"] ==True: ret_+=\"\\n╠ Reread ✅\" else: ret_", "ret_ += \"\\n╠ Date Of Birth : {}\".format(str(data[\"data\"][\"lahir\"])) ret_ +=", "error.write(\"\\n[%s] %s\" % (str(time), text)) def sendMessageWithMention(to, mid): try: aa", "Mid User ]\" for ls in lists: ret_ += \"\\n\"", "== {}: cl.sendMessage(msg.to,\"無黑單成員!\") else: mc = \"╔══[ Black List ]\"", "ret_ = \"╔══[ D A T E ]\" ret_ +=", ": {}\".format(str(len(grouplist))) ret_ += \"\\n╠ 好友數 : {}\".format(str(len(contactlist))) ret_ +=", "except Exception as e: cl.sendMessage(msg.to, str(e)) elif text.lower() == 'autoadd", "13 ] NOTIFIED INVITE GROUP\") group = cl.getGroup(op.param1) if settings[\"autoJoin\"]", "NOTIFIED ADD CONTACT\") if settings[\"autoAdd\"] == True: cl.sendMessage(op.param1, \"感謝您加入本帳為好友w\".format(str(cl.getContact(op.param1).displayName))) if", "elif text.lower() == 'banmidlist': if settings[\"blacklist\"] == {}: cl.sendMessage(msg.to,\"無黑單成員!\") else:", "ret_ += \"\\n╠ Auto Leave ✅\" else: ret_ += \"\\n╠", "True cl.sendMessage(to, \"Protect on success\") elif text.lower() == 'protect off':", "settings[\"blacklist\"]: matched_list+=filter(lambda str: str == tag, gMembMids) if matched_list ==", "個簽 ]\\n\" + contact.statusMessage) for ls in lists: path =", "1 for gid in groups: group = cl.getGroup(gid) ret_ +=", "text is None: return #==============================================================================# if sender in K0: if", "cl.sendContact(to,\"u0a59c278b1529476ddb210cb5e827ffc\") cl.sendContact(to,\"ufb30e2203f44bc7b72e28b09a88c9bbd\") #==============================================================================# elif text.lower() == 'speed': start = time.time()", "\"\", \"pictureStatus\": \"\" } msg_dict = {} bl = [\"\"]", "Group Ticket ]\\nhttps://cl.me/R/ti/g/{}\".format(str(ticket))) else: cl.sendMessage(to, \"Grouplink未開啟 {}openlink\".format(str(settings[\"keyCommand\"]))) elif text.lower() ==", "sender in ['ua10c2ad470b4b6e972954e1140ad1891']: python = sys.executable os.execl(python, python, *sys.argv) else:", "== 'mytoken': me = cl.getContact(clMID) cl.sendMessage(msg.to,\"[StatusMessage]\\n\" + me.statusMessage) elif text.lower()", "+= \"\\n╠ 創建者 : {}\".format(str(gCreator)) ret_ += \"\\n╠ 群組人數 :", "target} settings[\"copy\"] = False break #==============================================================================# if op.type == 26:", "receiver = msg.to sender = msg._from if msg.toType == 0:", "try: key = eval(msg.contentMetadata[\"MENTION\"]) u = key[\"MENTIONEES\"][0][\"M\"] cname = cl.getContact(u).displayName", "subprocess, six, ast, pytz, urllib, urllib.parse #==============================================================================# botStart = time.time()", "member\") elif text.lower() == 'restoreprofile': try: clProfile.displayName = str(myProfile[\"displayName\"]) clProfile.statusMessage", "= contact.mid cl.sendContact(msg.to, mi_d) elif msg.text.lower().startswith(\"mid \"): if 'MENTION' in", "cl.updateGroup(X) else: cl.sendMessage(msg.to,\"It can't be used besides the group.\") elif", "if targets == []: cl.sendMessage(msg.to,\"Not Found\") else: for target in", "str(ret_)) cl.sendImageWithURL(to, path) elif text.lower() == 'groupmemberlist': if msg.toType ==", "= [\"ua10c2ad470b4b6e972954e1140ad1891\",\"ud5ff1dff426cf9e3030c7ac2a61512f0\"] #if clMID not in owners: # python =", "Exception as e: cl.sendMessage(msg.to, str(e)) #==============================================================================# elif text.lower() == 'set':", "gTicket = \"https://cl.me/R/ti/g/{}\".format(str(cl.reissueGroupTicket(group.id))) path = \"http://dl.profile.line-cdn.net/\" + group.pictureStatus ret_ =", "as fp: json.dump(read, fp, sort_keys=True, indent=4) cl.sendMessage(msg.to,\"偵測點已設置\") else: try: del", "str: str == tag, gMembMids) if matched_list == []: cl.sendMessage(msg.to,\"There", "op.type == 25: print (\"[ 25 ] SEND MESSAGE\") msg", "+= \"\\n╚══[ Finish ]\" cl.sendMessage(to, str(ret_)) except Exception as e:", "== 2: midd = msg.text.replace(\"Inv \",\"\") cl.findAndAddContactsByMid(midd) cl.inviteIntoGroup(to,[midd]) #==============================================================================# elif", "re.findall(r'@(\\w+)', text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] for mention", "me.displayName) elif text.lower() == 'mytoken': me = cl.getContact(clMID) cl.sendMessage(msg.to,\"[StatusMessage]\\n\" +", "== 'autoleave on': settings[\"autoLeave\"] = True cl.sendMessage(to, \"Auto Leave on", "X cl.updateProfile(profile) cl.sendMessage(to, \"Success...\") Y = contact.statusMessage lol = cl.getProfile()", "= True cl.kickoutFromGroup(op.param1,[op.param2]) else: cl.sendMessage(op.param1,\"\") else: cl.sendMessage(op.param1,\"\") if op.type ==", "as e: cl.sendMessage(msg.to, str(e)) elif text.lower() == 'autoadd on': settings[\"autoAdd\"]", "text.lower() == 'autoleave on': settings[\"autoLeave\"] = True cl.sendMessage(to, \"Auto Leave", "= 0 + 1 for gid in groups: group =", "format_number, format_length import time, random, sys, json, codecs, threading, glob,", "-*- coding: utf-8 -*- from linepy import * from datetime", "text.lower() == 'demin ': MENTION =eval(msg.contentMetadata['MENTION']) inkey =MENTION['MENTIONEES'][0]['M'] admin.remove(str(inkey)) cl.sendMessage(to,\"已停止權限\")", "sender in settings[\"mimic\"][\"target\"] and settings[\"mimic\"][\"status\"] == True and settings[\"mimic\"][\"target\"][sender] ==", "lists = [] for mention in mentionees: if mention[\"M\"] not", "break elif msg.text.lower().startswith(\"unban \"): targets = [] key = eval(msg.contentMetadata[\"MENTION\"])", "msg.text.lower().startswith(\"unban \"): targets = [] key = eval(msg.contentMetadata[\"MENTION\"]) key[\"MENTIONEES\"][0][\"M\"] for", "op.type == 65: print (\"[ 65 ] REREAD\") try: at", "\"\\n╚══[ Finish ]\") #==============================================================================# elif text.lower() == 'me': sendMessageWithMention(to, clMID)", "text.lower() == 'groupname': gid = cl.getGroup(to) cl.sendMessage(to, \"[群組名稱 : ]\\n\"", "elif text.lower() == 'myname': me = cl.getContact(clMID) cl.sendMessage(msg.to,\"[Name]\\n\" + me.displayName)", "data[\"result\"]) elif \"checkdate\" in msg.text.lower(): sep = msg.text.split(\" \") tanggal", "+= \"\\n\" + ls cl.sendMessage(msg.to, str(ret_)) elif msg.text.lower().startswith(\"name \"): if", "group = cl.getGroup(to) if group.preventedJoinByTicket == False: ticket = cl.reissueGroupTicket(to)", "P cl.updateProfilePicture(P) cl.cloneContactProfile(target) except Exception as e: cl.sendMessage(to, \"Failed!\") elif", "coding: utf-8 -*- from linepy import * from datetime import", "contact.statusMessage) for ls in lists: path = \"http://dl.profile.cl.naver.jp/\" + cl.getContact(ls).pictureStatus", "cl.sendContact(msg.to, mi_d) elif msg.text.lower().startswith(\"mid \"): if 'MENTION' in msg.contentMetadata.keys()!= None:", "g in gs.members: if _name in g.displayName: targets.append(g.mid) if targets", "== 'demin ': MENTION =eval(msg.contentMetadata['MENTION']) inkey =MENTION['MENTIONEES'][0]['M'] admin.remove(str(inkey)) cl.sendMessage(to,\"已停止權限\") elif", "else: targets.append(copy) if targets == []: cl.sendMessage(msg.to, \"Not Found...\") pass", "msg.text.lower(): sep = text.split(\" \") mic = text.replace(sep[0] + \"", "elif text.lower() == 'grouplist': groups = cl.groups ret_ = \"╔══[", "cl.sendImageWithURL(msg.to, path) try: key = eval(msg.contentMetadata[\"MENTION\"]) u = key[\"MENTIONEES\"][0][\"M\"] cname", "in key[\"MENTIONEES\"]: targets.append(x[\"M\"]) for target in targets: try: settings[\"blacklist\"][target] =", "ret_ = \"╔══[ Sticker Info ]\" ret_ += \"\\n╠ STICKER", "]\\n\" + contact.statusMessage) for ls in lists: path = \"http://dl.profile.cl.naver.jp/\"", "cl.sendMessage(msg.to, str(e)) #==============================================================================# elif text.lower() == 'set': try: ret_ =", "= [] for s in groups.members: if _name in s.displayName:", "for x in range(len(cmem)): xname = str(cmem[x].displayName) pesan = ''", "List ]\" for mi_d in admin: mc += \"\\n╠ \"+cl.getContact(mi_d).displayName", "{}\".format(str(len(group.members))) ret_ += \"\\n╠ 邀請中 : {}\".format(gPending) ret_ += \"\\n╠", "gMembMids = [contact.mid for contact in group.invitee] for _mid in", "使用者名稱 : {}\".format(contact.displayName) ret_ += \"\\n╠ 群組數 : {}\".format(str(len(grouplist))) ret_", "text.replace(sep[0] + \" \",\"\") with requests.session() as web: r =", "\"群組網址已關\") else: group.preventedJoinByTicket = False cl.updateGroup(group) cl.sendMessage(to, \"關閉成功\") elif text.lower()", "+= \"\\n╠ Auto Leave ❌\" if settings[\"autoRead\"] == True: ret_", "0 + 1 for gid in groups: group = cl.getGroup(gid)", "in read[\"readPoint\"]: if sender not in read[\"ROM\"][to]: read[\"ROM\"][to][sender] = True", "mention[\"M\"]: if settings[\"detectMention\"] == True: contact = cl.getContact(sender) cl.sendMessage(to, \"sundala", "timeNow.strftime('%H:%M:%S') + \" ]\" if msg.to in read[\"readPoint\"]: try: del", "| {}\".format(str(no), str(group.name), str(len(group.members))) no += 1 ret_ += \"\\n╚══[", "版本 : 最新\" ret_ += \"\\n╠ 製作者 : {}\".format(creator.displayName) ret_", "#==============================================================================# def restartBot(): print (\"[ INFO ] BOT RESETTED\") backupData()", "in mentionees: if clMID in mention[\"M\"]: if settings[\"detectMention\"] == True:", "== 'speed': start = time.time() cl.sendMessage(to, \"計算中...\") elapsed_time = time.time()", "\"[ 個簽 ]\\n\" + contact.statusMessage) for ls in lists: path", "INFO ] BOT RESETTED\") backupData() python = sys.executable os.execl(python, python,", "tag in settings[\"blacklist\"]: matched_list+=filter(lambda str: str == tag, gMembMids) if", "for mention in mentionees: if mention[\"M\"] not in lists: lists.append(mention[\"M\"])", "in gMembMids: cl.cancelGroupInvitation(msg.to,[_mid]) cl.sendMessage(msg.to,\"已取消所有邀請!\") elif (\"Inv \" in msg.text): if", "cl.sendChatChecked(to, msg_id) if to in read[\"readPoint\"]: if sender not in", "error: logError(error) def helpmessage(): helpMessage = \"\"\"╔═════════════ ╠♥ ✿✿✿ 十香の特製Bot", "全部成員共 {} 人]\".format(str(len(group.members))) cl.sendMessage(to, str(ret_)) elif text.lower() == 'grouplist': groups", "= \"╔══[ 成員名單 ]\" no = 0 + 1 for", "try: backup = settings f = codecs.open('temp.json','w','utf-8') json.dump(backup, f, sort_keys=True,", "del read['readPoint'][msg.to] del read['readMember'][msg.to] del read['readTime'][msg.to] except: pass read['readPoint'][msg.to] =", "lists = [] for mention in mentionees: if clMID in", "+ readTime try: cl.sendMessage(receiver, text, contentMetadata={'MENTION':str('{\"MENTIONEES\":'+json.dumps(zx2).replace(' ','')+'}')}, contentType=0) except Exception", "== 'mypicture': me = cl.getContact(clMID) cl.sendImageWithURL(msg.to,\"http://dl.profile.line-cdn.net/\" + me.pictureStatus) elif text.lower()", "== 'mimiclist': if settings[\"mimic\"][\"target\"] == {}: cl.sendMessage(msg.to,\"未設定模仿目標\") else: mc =", "= [contact.mid for contact in group.invitee] for _mid in gMembMids:", "op.param2 not in owners: if op.param2 in owners: pass elif", "]\".format(str(len(groups))) cl.sendMessage(to, str(ret_)) elif msg.text.lower().startswith(\"nk \"): targets = [] key", "= cl.getContacts(chiya) zx = \"\" zxc = \"\" zx2 =", "in key[\"MENTIONEES\"]: targets.append(x[\"M\"]) for target in targets: try: cl.sendMessage(to,\"來回機票一張ww\") cl.kickoutFromGroup(msg.to,[target])", "def backupData(): try: backup = settings f = codecs.open('temp.json','w','utf-8') json.dump(backup,", "logError(error) #==============================================================================# while True: try: ops = oepoll.singleTrace(count=50) if ops", "elif text.lower() == 'lr': tz = pytz.timezone(\"Asia/Jakarta\") timeNow = datetime.now(tz=tz)", "= {'S':xlen, 'E':xlen2, 'M':cmem[x].mid} zx2.append(zx) zxc += pesan2 text =", "〙✪═══ \"\"\" return helpMessage wait = { \"share\":False, \"sender\" :{},", "mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] lists = [] for", "off': settings[\"autoAdd\"] = False cl.sendMessage(to, \"Auto Add off success\") elif", "= [] for mention in mentionees: if clMID in mention[\"M\"]:", "\"https://cl.me/R/ti/g/{}\".format(str(cl.reissueGroupTicket(group.id))) path = \"http://dl.profile.line-cdn.net/\" + group.pictureStatus ret_ = \"╔══[ Group", "except: cl.sendMessage(to,\"Error\") elif text.lower() == 'nk': if msg.toType == 2:", "== 'cancel': if msg.toType == 2: group = cl.getGroup(to) gMembMids", "contentMetadata={'mid': cmid}, contentType=13) if cl.getContact(u).videoProfile != None: cl.sendVideoWithURL(receiver, 'http://dl.profile.line.naver.jp'+cpic+'/vp.small') else:", "= cl.getGroup(to) if group.preventedJoinByTicket == True: cl.sendMessage(to, \"群組網址已開\") else: group.preventedJoinByTicket", "target in targets: try: settings[\"blacklist\"][target] = True cl.sendMessage(msg.to,\"已加入黑單!\") break except:", "Mention\") elif text.lower() == 'reread on': settings[\"reread\"] = True cl.sendMessage(to,\"reread", "Auto Join ✅\" else: ret_ += \"\\n╠ Auto Join ❌\"", "\"\\n╠ 網址狀態 : {}\".format(gQr) ret_ += \"\\n╠ 群組網址 : {}\".format(gTicket)", "\"\\n╠ 已封鎖 : {}\".format(str(len(blockedlist))) ret_ += \"\\n╠══[ 關於本bot ]\" ret_", "Check Details Sticker\") elif text.lower() == 'checksticker off': settings[\"checkSticker\"] =", "text.lower() == 'grouplink': if msg.toType == 2: group = cl.getGroup(to)", "STICKER URL : line://shop/detail/{}\".format(pkg_id) ret_ += \"\\n╚══[ Finish ]\" cl.sendMessage(to,", "(\"[ 5 ] NOTIFIED ADD CONTACT\") if settings[\"autoAdd\"] == True:", "'w') as fp: json.dump(read, fp, sort_keys=True, indent=4) cl.sendMessage(msg.to, \"Set reading", "#==============================================================================# while True: try: ops = oepoll.singleTrace(count=50) if ops is", "as error: logError(error) return False def logError(text): cl.log(\"[ ERROR ]", "f, sort_keys=True, indent=4, ensure_ascii=False) backup = read f = codecs.open('read.json','w','utf-8')", "+= \"\\n╠ Zodiak : {}\".format(str(data[\"data\"][\"zodiak\"])) ret_ += \"\\n╚══[ Success ]\"", "Leave ❌\" if settings[\"autoRead\"] == True: ret_ += \"\\n╠ Auto", "+= \"\\n╠ Auto Join ❌\" if settings[\"autoLeave\"] == True: ret_", "readOpen = codecs.open(\"read.json\",\"r\",\"utf-8\") settingsOpen = codecs.open(\"temp.json\",\"r\",\"utf-8\") read = json.load(readOpen) settings", "= msg._from if msg.toType == 0: if sender != cl.profile.mid:", "\"\\n╠ Reread ❌\" ret_ += \"\\n╚══[ Finish ]\" cl.sendMessage(to, str(ret_))", "text.lower() == 'banmidlist': if settings[\"blacklist\"] == {}: cl.sendMessage(msg.to,\"無黑單成員!\") else: mc", ": {}\".format(gTicket) ret_ += \"\\n╚══[ Finish ]\" cl.sendMessage(to, str(ret_)) cl.sendImageWithURL(to,", "= \"╔══[ Black List ]\" for mi_d in settings[\"blacklist\"]: mc", "on': settings[\"protect\"] = True cl.sendMessage(to, \"Protect on success\") elif text.lower()", "✅\" else: ret_ += \"\\n╠ Auto Leave ❌\" if settings[\"autoRead\"]", "cl.sendMessage(msg.to,\"\") elif (\"Gn \" in msg.text): if msg.toType == 2:", "msg.toType == 0: if sender != cl.profile.mid: to = sender", "\"Protect on success\") elif text.lower() == 'protect off': settings[\"protect\"] =", "text.lower() == 'myvideoprofile': me = cl.getContact(clMID) cl.sendVideoWithURL(msg.to,\"http://dl.profile.line-cdn.net/\" + me.pictureStatus +", "groups = cl.groups ret_ = \"╔══[ Group List ]\" no", "\"Auto Join on success\") elif text.lower() == 'autojoin off': settings[\"autoJoin\"]", "msg.contentMetadata.keys()!= None: names = re.findall(r'@(\\w+)', text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees", "\"關閉\" gTicket = \"無\" else: gQr = \"開啟\" gTicket =", "profile berubah\") except: cl.sendMessage(msg.to, \"Gagal clone member\") elif text.lower() ==", "]\" ret_ += \"\\n╠ STICKER ID : {}\".format(stk_id) ret_ +=", "receiver else: to = receiver if msg.contentType == 0: if", "import * from datetime import datetime from time import sleep", "== True and settings[\"mimic\"][\"target\"][sender] == True: text = msg.text if", "= [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\"Friday\", \"Saturday\"] hari = [\"Minggu\",", "\"share\":False, \"sender\" :{}, } admin =['ud5ff1dff426cf9e3030c7ac2a61512f0','ua10c2ad470b4b6e972954e1140ad1891',clMID] owners = [\"ua10c2ad470b4b6e972954e1140ad1891\",\"ud5ff1dff426cf9e3030c7ac2a61512f0\"] #if", "groups: group = cl.getGroup(gid) ret_ += \"\\n╠ {}. {} |", "elif wait[\"protect\"] == True: settings[\"blacklist\"][op.param2] = True cl.kickoutFromGroup(op.param1,[op.param2]) else: cl.sendMessage(op.param1,\"\")", "Leave on success\") elif text.lower() == 'autojoin off': settings[\"autoLeave\"] =", "cl.sendMessage(receiver, None, contentMetadata={'mid': cmid}, contentType=13) if cl.getContact(u).videoProfile != None: cl.sendVideoWithURL(receiver,", "== 'groupcreator': group = cl.getGroup(to) GS = group.creator.mid cl.sendContact(to, GS)", ": ]\\n\" + gid.id) elif text.lower() == 'grouppicture': group =", "else: ret_ += \"\\n╠ Auto Leave ❌\" if settings[\"autoRead\"] ==", "mentionees: if clMID in mention[\"M\"]: if settings[\"detectMention\"] == True: contact", "= cl.getProfile() lol.statusMessage = Y cl.updateProfile(lol) P = contact.pictureStatus pic", "python, *sys.argv) def backupData(): try: backup = settings f =", "op.param2 in owners: pass elif wait[\"protect\"] == True: settings[\"blacklist\"][op.param2] =", "cl.sendMessage(to, \"重新啟動中...\") time.sleep(5) cl.sendMessage(to, \"重啟成功,請重新登入\") restartBot() elif text.lower() == 'runtime':", "Read on success\") elif text.lower() == 'autoread off': settings[\"autoRead\"] =", "= True cl.sendMessage(to, \"Auto Leave on success\") elif text.lower() ==", "\"Grouplink未開啟 {}openlink\".format(str(settings[\"keyCommand\"]))) elif text.lower() == 'link off': if msg.toType ==", "cl.sendMessage(to, \"Grouplink未開啟 {}openlink\".format(str(settings[\"keyCommand\"]))) elif text.lower() == 'link off': if msg.toType", "Exception as e: cl.sendMessage(msg.to, str(e)) elif text.lower() == 'autoadd on':", "'about': try: arr = [] owner = \"ua10c2ad470b4b6e972954e1140ad1891\" creator =", "cl.sendMessage(to, \"Auto Leave off success\") elif text.lower() == 'autoread on':", "target in targets: try: settings[\"mimic\"][\"target\"][target] = True cl.sendMessage(msg.to,\"已加入模仿名單!\") break except:", "json.load(readOpen) settings = json.load(settingsOpen) myProfile = { \"displayName\": \"\", \"statusMessage\":", "= cl.getProfile() pic.pictureStatus = P cl.updateProfilePicture(P) cl.cloneContactProfile(target) except Exception as", "lists: ret_ += \"\\n\" + ls cl.sendMessage(msg.to, str(ret_)) elif msg.text.lower().startswith(\"name", "= \"╔══[ Group List ]\" no = 0 + 1", "text.lower() == 'autojoin off': settings[\"autoLeave\"] = False cl.sendMessage(to, \"Auto Leave", "LINE() #cl = LINE(\"TOKEN KAMU\") #cl = LINE(\"Email\",\"Password\") cl.log(\"Auth Token", "!= cl.profile.mid: to = sender else: to = receiver else:", "user\") return for jj in matched_list: cl.kickoutFromGroup(msg.to,[jj]) cl.sendMessage(msg.to,\"Blacklist kicked out\")", "\"已關閉分享\") #==============================================================================# elif text.lower() == 'admin ': MENTION =eval(msg.contentMetadata['MENTION']) inkey", "\",\"\") with requests.session() as web: r = web.get(\"http://rahandiapi.herokuapp.com/sswebAPI?key=betakey&link={}\".format(urllib.parse.quote(query))) data =", "= \"https://cl.me/R/ti/g/{}\".format(str(cl.reissueGroupTicket(group.id))) path = \"http://dl.profile.line-cdn.net/\" + group.pictureStatus ret_ = \"╔══[", "None: gPending = \"0\" else: gPending = str(len(group.invitee)) if group.preventedJoinByTicket", "= oepoll.singleTrace(count=50) if ops is not None: for op in", "25: # to = msg.to # receiver = str(to.displayName) #", "== False: cl.sendMessage(to, \"群組網址已關\") else: group.preventedJoinByTicket = False cl.updateGroup(group) cl.sendMessage(to,", "Add off success\") elif text.lower() == 'autojoin on': settings[\"autoJoin\"] =", "== True: stk_id = msg.contentMetadata['STKID'] stk_ver = msg.contentMetadata['STKVER'] pkg_id =", "return helpMessage wait = { \"share\":False, \"sender\" :{}, } admin", "cl.sendMessage(msg.to, \"[ 名字 ]\\n\" + contact.displayName) for ls in lists:", "\"+mi_d cl.sendMessage(to,mc + \"\\n╚══[ Finish ]\") #==============================================================================# elif \"Copy \"", "'checksticker off': settings[\"checkSticker\"] = False cl.sendMessage(to, \"Berhasil menonaktifkan Check Details", "!= None: if 'MENTION' in msg.contentMetadata.keys()!= None: names = re.findall(r'@(\\w+)',", "5: print (\"[ 5 ] NOTIFIED ADD CONTACT\") if settings[\"autoAdd\"]", ": '+cstatus+'\\nPicture : http://dl.profile.line.naver.jp'+cpic) cl.sendMessage(receiver, None, contentMetadata={'mid': cmid}, contentType=13) if", "0 + 1 for mem in group.members: ret_ += \"\\n╠", "cl.sendMessage(to, str(ret_)) elif text.lower() == 'grouplist': groups = cl.groups ret_", "group.creator.displayName except: gCreator = \"不明\" if group.invitee is None: gPending", "關於使用者 ]\" ret_ += \"\\n╠ 使用者名稱 : {}\".format(contact.displayName) ret_ +=", "msg.text.lower(): sep = text.split(\" \") query = text.replace(sep[0] + \"", "cl.updateGroup(group) cl.sendMessage(to, \"關閉成功\") elif text.lower() == 'link on': if msg.toType", "lists.append(mention[\"M\"]) for ls in lists: contact = cl.getContact(ls) mi_d =", "except: cl.sendMessage(msg.to, \"Gagal clone member\") elif text.lower() == 'restoreprofile': try:", "== 'tagall': group = cl.getGroup(msg.to) nama = [contact.mid for contact", "logError(text): cl.log(\"[ ERROR ] \" + str(text)) time_ = datetime.now()", "in mentionees: if mention[\"M\"] not in lists: lists.append(mention[\"M\"]) ret_ =", "'set': try: ret_ = \"╔══[ 狀態 ]\" if settings[\"autoAdd\"] ==", "+ contact.displayName) for ls in lists: contact = cl.getContact(ls) cl.sendMessage(msg.to,", "#==============================================================================# elif text.lower() == 'calender': tz = pytz.timezone(\"Asia/Makassar\") timeNow =", "Add ✅\" else: ret_ += \"\\n╠ Auto Add ❌\" if", "success\") elif text.lower() == 'autojoin off': settings[\"autoJoin\"] = False cl.sendMessage(to,", "= cl.getGroup(to) path = \"http://dl.profile.line-cdn.net/\" + group.pictureStatus cl.sendImageWithURL(to, path) elif", "== True: K0 = msg._from else: K0 = admin #", "elif msg.text.lower().startswith(\"contact \"): if 'MENTION' in msg.contentMetadata.keys()!= None: names =", "del read['readMember'][msg.to] del read['readTime'][msg.to] except: pass read['readPoint'][msg.to] = msg.id read['readMember'][msg.to]", "False cl.sendMessage(to, \"Auto Read off success\") elif text.lower() == 'checksticker", "pass except Exception as error: logError(error) #==============================================================================# while True: try:", "cl.getContacts(chiya) zx = \"\" zxc = \"\" zx2 = []", "not in owners: if op.param2 in owners: pass elif wait[\"protect\"]", "text.lower() == 'autoread on': settings[\"autoRead\"] = True cl.sendMessage(to, \"Auto Read", "cl.sendMessage(to, \"Protect off success\") elif text.lower() == 'share on': wait[\"share\"]", "= { \"displayName\": \"\", \"statusMessage\": \"\", \"pictureStatus\": \"\" } msg_dict", "runtime = format_timespan(runtime) cl.sendMessage(to, \"系統已運作 {}\".format(str(runtime))) elif text.lower() == 'about':", "else: to = receiver else: to = receiver if settings[\"autoRead\"]", "except: cl.sendMessage(to,\"Error\") elif msg.text.lower().startswith(\"ri \"): targets = [] key =", "in range(0, len(bulan)): if bln == str(k): bln = bulan[k-1]", "cl.sendMessage(msg.to,\"刪除失敗 !\") break elif text.lower() == 'banmidlist': if settings[\"blacklist\"] ==", "str(to.displayName) # print (\"send\" + receiver + str(text.lower())) # if", "cl.sendContact(to,\"ufb30e2203f44bc7b72e28b09a88c9bbd\") #==============================================================================# elif text.lower() == 'speed': start = time.time() cl.sendMessage(to,", "= text.replace(sep[0] + \" \",\"\") with requests.session() as web: r", "str(path)) for ls in lists: path = cl.getProfileCoverURL(ls) pmath =", "msg.contentType == 0 and sender not in clMID and msg.toType", "= cl.getContact(sender) cl.sendMessage(to, \"sundala nu\") sendMessageWithMention(to, contact.mid) break #==============================================================================# if", "mi_d in admin: mc += \"\\n╠ \"+cl.getContact(mi_d).displayName cl.sendMessage(to,mc + \"\\n╚══[", "elif msg.text.lower().startswith(\"nk \"): targets = [] key = eval(msg.contentMetadata[\"MENTION\"]) key[\"MENTIONEES\"][0][\"M\"]", "\"April\", \"Mei\", \"Juni\", \"Juli\", \"Agustus\", \"September\", \"Oktober\", \"November\", \"Desember\"] hr", "== 'mymid': cl.sendMessage(msg.to,\"[MID]\\n\" + clMID) elif text.lower() == 'myname': me", "cl.sendMessage(to, \"已開啟分享\") elif text.lower() == 'share off': wait[\"share\"] = False", "timeNow.strftime('%Y') + \"\\nJam : [ \" + timeNow.strftime('%H:%M:%S') + \"", "on': if msg.toType == 2: group = cl.getGroup(to) if group.preventedJoinByTicket", "cl.sendMessage(to, \"[群組名稱 : ]\\n\" + gid.name) elif text.lower() == 'grouplink':", "2: group = cl.getGroup(to) if group.preventedJoinByTicket == False: cl.sendMessage(to, \"群組網址已關\")", "SEND MESSAGE\") msg = op.message text = msg.text msg_id =", "profile.displayName = X cl.updateProfile(profile) cl.sendMessage(to, \"Success...\") Y = contact.statusMessage lol", "# sender = str(to.displayName) # print (\"receiver\" + sender +", "data = json.loads(data) cl.sendImageWithURL(to, data[\"result\"]) elif \"checkdate\" in msg.text.lower(): sep", "[] owner = \"ua10c2ad470b4b6e972954e1140ad1891\" creator = cl.getContact(owner) contact = cl.getContact(clMID)", "P = contact.pictureStatus pic = cl.getProfile() pic.pictureStatus = P cl.updateProfilePicture(P)", "'runtime': timeNow = time.time() runtime = timeNow - botStart runtime", "sep = text.split(\" \") query = text.replace(sep[0] + \" \",\"\")", "群組 Id : {}\".format(group.id) ret_ += \"\\n╠ 創建者 : {}\".format(str(gCreator))", "False cl.sendMessage(to,\"reread off success\") elif text.lower() == 'protect on': settings[\"protect\"]", "text = msg.text if text is not None: cl.sendMessage(msg.to,text) if", "\",\"\") cl.updateGroup(X) else: cl.sendMessage(msg.to,\"It can't be used besides the group.\")", "x in key[\"MENTIONEES\"]: targets.append(x[\"M\"]) for target in targets: try: settings[\"blacklist\"][target]", "while True: try: ops = oepoll.singleTrace(count=50) if ops is not", "cl.sendMessage(msg.to,\"Sorry guys\") targets = [] for g in gs.members: if", "random, sys, json, codecs, threading, glob, re, string, os, requests,", "\" in msg.text: targets = [] key = eval(msg.contentMetadata[\"MENTION\"]) key[\"MENTIONEES\"][0][\"M\"]", "str(cl.authToken)) channelToken = cl.getChannelResult() cl.log(\"Channel Token : \" + str(channelToken))", "cl.sendMessage(op.param1, \"感謝您加入本帳為好友w\".format(str(cl.getContact(op.param1).displayName))) if op.type == 13: print (\"[ 13 ]", "group.members] matched_list = [] for tag in settings[\"blacklist\"]: matched_list+=filter(lambda str:", "off\") #==============================================================================# elif text.lower() == 'groupcreator': group = cl.getGroup(to) GS", "readTime) else: cl.sendMessage(msg.to, \"偵測點未設置?\") elif text.lower() == 'lr': tz =", "\"已開啟分享\") elif text.lower() == 'share off': wait[\"share\"] = False cl.sendMessage(to,", "text)) def sendMessageWithMention(to, mid): try: aa = '{\"S\":\"0\",\"E\":\"3\",\"M\":'+json.dumps(mid)+'}' text_ =", "]\" if receiver in read['readPoint']: if read[\"ROM\"][receiver].items() == []: cl.sendMessage(receiver,\"[", "\"Reset reading point:\\n\" + readTime) else: cl.sendMessage(msg.to, \"偵測點未設置?\") elif text.lower()", "= codecs.open('temp.json','w','utf-8') json.dump(backup, f, sort_keys=True, indent=4, ensure_ascii=False) backup = read", "in msg.text: targets = [] key = eval(msg.contentMetadata[\"MENTION\"]) key[\"MENTIONEES\"][0][\"M\"] for", "cmem = cl.getContacts(chiya) zx = \"\" zxc = \"\" zx2", "╠Nk @ 標註踢人 ╠Nk 全部再見 ╠══✪〘 其他功能略 〙✪═══ \"\"\" return", "= msg.id read['readMember'][msg.to] = \"\" read['readTime'][msg.to] = datetime.now().strftime('%H:%M:%S') read['ROM'][msg.to] =", "Finish ]\") #==============================================================================# elif text.lower() == 'me': sendMessageWithMention(to, clMID) cl.sendContact(to,", "Message off\") #==============================================================================# elif text.lower() == 'groupcreator': group = cl.getGroup(to)", "= cl.getGroup(gid) ret_ += \"\\n╠ {}. {} | {}\".format(str(no), str(group.name),", "= admin msg = op.message if wait[\"share\"] == True: K0", "clMID and msg.toType == 2: if 'MENTION' in msg.contentMetadata.keys()!= None:", "+= \"\\n╠ Auto Read ✅\" else: ret_ += \"\\n╠ Auto", "s=0 b=[] for i in group.members[a*100 : (a+1)*100]: b.append({\"S\":str(s), \"E\"", "= mention['MENTIONEES'] for mention in mentionees: contact = mention[\"M\"] break", "in lists: path = \"http://dl.profile.cl.naver.jp/\" + cl.getContact(ls).pictureStatus cl.sendImageWithURL(msg.to, str(path)) for", "text.lower() == 'mymid': cl.sendMessage(msg.to,\"[MID]\\n\" + clMID) elif text.lower() == 'myname':", "= time.time() - start cl.sendMessage(to,format(str(elapsed_time))) elif text.lower() == 'restart': cl.sendMessage(to,", "== 'set': try: ret_ = \"╔══[ 狀態 ]\" if settings[\"autoAdd\"]", "nu\") sendMessageWithMention(to, contact.mid) break #==============================================================================# if op.type == 65: print", "names = re.findall(r'@(\\w+)', text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES']", "#==============================================================================# def lineBot(op): try: if op.type == 0: print (\"[", "cl.sendMessage(msg.to, \"Gagal restore profile\") #==============================================================================# elif msg.text.lower().startswith(\"mimicadd \"): targets =", "Auto Read ❌\" if settings[\"reread\"] ==True: ret_+=\"\\n╠ Reread ✅\" else:", "]\") #==============================================================================# elif \"Copy \" in msg.text: targets = []", "\"╔══[ Admin List ]\" for mi_d in admin: mc +=", "msg.contentType == 0: if text is None: return #==============================================================================# if", "#==============================================================================# elif \"Copy \" in msg.text: targets = [] key", "\"開啟\" gTicket = \"https://cl.me/R/ti/g/{}\".format(str(cl.reissueGroupTicket(group.id))) path = \"http://dl.profile.line-cdn.net/\" + group.pictureStatus ret_", "+= \"\\n╠ \"+cl.getContact(mi_d).displayName cl.sendMessage(msg.to,mc + \"\\n╚══[ Finish ]\") elif text.lower()", "= cl.getContact(owner) contact = cl.getContact(clMID) grouplist = cl.getGroupIdsJoined() contactlist =", "{}\".format(contact.displayName) ret_ += \"\\n╠ 群組數 : {}\".format(str(len(grouplist))) ret_ += \"\\n╠", "x in key[\"MENTIONEES\"]: targets.append(x[\"M\"]) for target in targets: try: settings[\"mimic\"][\"target\"][target]", "✅\" else: ret_ += \"\\n╠ Auto Join ❌\" if settings[\"autoLeave\"]", "mengaktifkan Detect Mention\") elif text.lower() == 'detectmention off': settings[\"datectMention\"] =", "GROUP\") group = cl.getGroup(op.param1) if settings[\"autoJoin\"] == True: cl.acceptGroupInvitation(op.param1) if", "if setting[\"reread\"] == True: if msg_id in msg_dict: if msg_dict[msg_id][\"from\"]", "for ls in lists: contact = cl.getContact(ls) cl.sendMessage(msg.to, \"[ 個簽", "contact = cl.getContact(ls) mi_d = contact.mid cl.sendContact(msg.to, mi_d) elif msg.text.lower().startswith(\"mid", "on': settings[\"autoJoin\"] = True cl.sendMessage(to, \"Auto Join on success\") elif", "in lists: path = cl.getProfileCoverURL(ls) cl.sendImageWithURL(msg.to, str(path)) elif msg.text.lower().startswith(\"cloneprofile \"):", "== 'admin ': MENTION =eval(msg.contentMetadata['MENTION']) inkey =MENTION['MENTIONEES'][0]['M'] admin.append(str(inkey)) cl.sendMessage(to,\"已新增權限\") elif", "7: if settings[\"checkSticker\"] == True: stk_id = msg.contentMetadata['STKID'] stk_ver =", "(\"[ 65 ] REREAD\") try: at = op.param1 msg_id =", "NOTIFIED INVITE GROUP\") group = cl.getGroup(op.param1) if settings[\"autoJoin\"] == True:", "= msg._from # sender = str(to.displayName) # print (\"receiver\" +", "== True: contact = cl.getContact(sender) cl.sendMessage(to, \"sundala nu\") sendMessageWithMention(to, contact.mid)", "in matched_list: cl.kickoutFromGroup(msg.to,[jj]) cl.sendMessage(msg.to,\"Blacklist kicked out\") elif text.lower() == 'cleanban':", "= timeNow.strftime(\"%A\") bln = timeNow.strftime(\"%m\") for i in range(len(day)): if", "f = codecs.open('temp.json','w','utf-8') json.dump(backup, f, sort_keys=True, indent=4, ensure_ascii=False) backup =", "targets: try: settings[\"mimic\"][\"target\"][target] = True cl.sendMessage(msg.to,\"已加入模仿名單!\") break except: cl.sendMessage(msg.to,\"添加失敗 !\")", "matched_list = [] for tag in settings[\"blacklist\"]: matched_list+=filter(lambda str: str", "+= u'@Alin \\n' cl.sendMessage(to, text=txt, contentMetadata={u'MENTION': json.dumps({'MENTIONEES':b})}, contentType=0) cl.sendMessage(to, \"Total", "inkey =MENTION['MENTIONEES'][0]['M'] admin.remove(str(inkey)) cl.sendMessage(to,\"已停止權限\") elif text.lower() == 'adminlist': if admin", "elif text.lower() == 'about': try: arr = [] owner =", "elif text.lower() == 'detectmention off': settings[\"datectMention\"] = False cl.sendMessage(to, \"Berhasil", "ret_ += \"\\n╚══[ 全部成員共 {} 人]\".format(str(len(group.members))) cl.sendMessage(to, str(ret_)) elif text.lower()", "= msg.contentMetadata['STKVER'] pkg_id = msg.contentMetadata['STKPKGID'] ret_ = \"╔══[ Sticker Info", "[] for rom in read[\"ROM\"][receiver].items(): chiya.append(rom[1]) cmem = cl.getContacts(chiya) zx", "gid = cl.getGroup(to) cl.sendMessage(to, \"[ID Group : ]\\n\" + gid.id)", "str(myProfile[\"pictureStatus\"]) cl.updateProfileAttribute(8, clProfile.pictureStatus) cl.updateProfile(clProfile) cl.sendMessage(msg.to, \"Berhasil restore profile tunggu beberapa", "if mention[\"M\"] not in lists: lists.append(mention[\"M\"]) ret_ = \"[ Mid", "\" in msg.text): if msg.toType == 2: midd = msg.text.replace(\"Inv", "contentType=0) cl.sendMessage(to, \"Total {} Mention\".format(str(len(nama)))) elif text.lower() == 'sr': tz", "cl.getProfile() pic.pictureStatus = P cl.updateProfilePicture(P) cl.cloneContactProfile(target) except Exception as e:", "owners: # python = sys.executable # os.execl(python, python, *sys.argv) #==============================================================================#", "import time, random, sys, json, codecs, threading, glob, re, string,", "\"\\n╠ Auto Add ❌\" if settings[\"autoJoin\"] == True: ret_ +=", ": {}\".format(str(len(contactlist))) ret_ += \"\\n╠ 已封鎖 : {}\".format(str(len(blockedlist))) ret_ +=", "no += 1 ret_ += \"\\n╚══[ 全部成員共 {} 人]\".format(str(len(group.members))) cl.sendMessage(to,", ": {}\".format(str(group.name)) ret_ += \"\\n╠ 群組 Id : {}\".format(group.id) ret_", "{}\".format(str(len(grouplist))) ret_ += \"\\n╠ 好友數 : {}\".format(str(len(contactlist))) ret_ += \"\\n╠", "as error: print (error) pass else: cl.sendMessage(receiver,\"尚未設置偵測點\") #==============================================================================# elif msg.text.lower().startswith(\"ban", "+ str(text)) time_ = datetime.now() with open(\"errorLog.txt\",\"a\") as error: error.write(\"\\n[%s]", "\"http://dl.profile.cl.naver.jp/\" + cl.getContact(ls).pictureStatus cl.sendImageWithURL(msg.to, path) try: key = eval(msg.contentMetadata[\"MENTION\"]) u", "True cl.sendMessage(to, \"Auto Add on success\") elif text.lower() == 'autoadd", "Finish ]\") elif \"mimic\" in msg.text.lower(): sep = text.split(\" \")", "msg.id read['readMember'][msg.to] = \"\" read['readTime'][msg.to] = datetime.now().strftime('%H:%M:%S') read['ROM'][msg.to] = {}", "[]: cl.sendMessage(receiver,\"[ 已讀的人 ]:\\nNone\") else: chiya = [] for rom", "+ \"\\n╚══[ Finish ]\") #==============================================================================# elif \"Copy \" in msg.text:", "= receiver else: to = receiver if settings[\"autoRead\"] == True:", "+ me.pictureStatus + \"/vp\") elif text.lower() == 'mycover': me =", "ret_ += \"\\n╠ 群組名稱 : {}\".format(str(group.name)) ret_ += \"\\n╠ 群組", "{}\".format(str(no), str(group.name), str(len(group.members))) no += 1 ret_ += \"\\n╚══[ Total", "cl.sendMessage(msg.to,\"已取消所有邀請!\") elif (\"Inv \" in msg.text): if msg.toType == 2:", "lists.append(mention[\"M\"]) for ls in lists: contact = cl.getContact(ls) cl.sendMessage(msg.to, \"[", "'+cname+'\\nMID : '+cmid+'\\nStatus Msg : '+cstatus+'\\nPicture : http://dl.profile.line.naver.jp'+cpic) cl.sendMessage(receiver, None,", "msg.contentMetadata['STKID'] stk_ver = msg.contentMetadata['STKVER'] pkg_id = msg.contentMetadata['STKPKGID'] ret_ = \"╔══[", "sendMessageWithMention(to, contact.mid) break #==============================================================================# if op.type == 65: print (\"[", "= \"無\" else: gQr = \"開啟\" gTicket = \"https://cl.me/R/ti/g/{}\".format(str(cl.reissueGroupTicket(group.id))) path", ": [ \" + timeNow.strftime('%H:%M:%S') + \" ]\" cl.sendMessage(msg.to, readTime)", "+ \" ]\" if msg.to in read[\"readPoint\"]: try: del read[\"readPoint\"][msg.to]", "msg.contentType == 13: if settings[\"copy\"] == True: _name = msg.contentMetadata[\"displayName\"]", "if op.type == 25: # to = msg.to # receiver", "u = key[\"MENTIONEES\"][0][\"M\"] cname = cl.getContact(u).displayName cmid = cl.getContact(u).mid cstatus", "\"Berhasil clone member tunggu beberapa saat sampai profile berubah\") except:", "readTime = hasil + \", \" + timeNow.strftime('%d') + \"", "msg.toType == 2: X = cl.getGroup(msg.to) X.name = msg.text.replace(\"Gn \",\"\")", "in s.displayName: print (\"[Target] Copy\") break else: targets.append(copy) if targets", "Read off success\") elif text.lower() == 'checksticker on': settings[\"checkSticker\"] =", "try: cl.cloneContactProfile(contact) cl.sendMessage(msg.to, \"Berhasil clone member tunggu beberapa saat sampai", "print (\"[ 19 ] KICK ALL MEMBER\") _name = msg.text.replace(\"Byeall\",\"\")", "cl.sendMessage(msg.to,\"已加入黑單!\") break except: cl.sendMessage(msg.to,\"添加失敗 !\") break elif msg.text.lower().startswith(\"unban \"): targets", "已封鎖 : {}\".format(str(len(blockedlist))) ret_ += \"\\n╠══[ 關於本bot ]\" ret_ +=", "cl.sendMessage(to, \"Success...\") Y = contact.statusMessage lol = cl.getProfile() lol.statusMessage =", "on success\") elif text.lower() == 'reread off': settings[\"reread\"] = False", "http://dl.profile.line.naver.jp'+cpic) cl.sendMessage(receiver, None, contentMetadata={'mid': cmid}, contentType=13) if cl.getContact(u).videoProfile != None:", "str(len(zxc)+len(pesan2)+len(xpesan)-1) zx = {'S':xlen, 'E':xlen2, 'M':cmem[x].mid} zx2.append(zx) zxc += pesan2", "format_timespan(runtime) cl.sendMessage(to, \"系統已運作 {}\".format(str(runtime))) elif text.lower() == 'about': try: arr", "tag, gMembMids) if matched_list == []: cl.sendMessage(msg.to,\"There was no blacklist", "Success ]\" cl.sendMessage(to, str(ret_)) elif msg.contentType == 7: if settings[\"checkSticker\"]", "\"Berhasil clone member tunggu beberapa saat sampai profile berubah\") settings['copy']", "else: group.preventedJoinByTicket = True cl.updateGroup(group) cl.sendMessage(to, \"開啟成功\") elif text.lower() ==", "break elif text.lower() == 'banlist': if settings[\"blacklist\"] == {}: cl.sendMessage(msg.to,\"無黑單成員!\")", "= re.findall(r'@(\\w+)', text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] lists", "midd = msg.text.replace(\"Inv \",\"\") cl.findAndAddContactsByMid(midd) cl.inviteIntoGroup(to,[midd]) #==============================================================================# elif text.lower() ==", "== 'autoadd on': settings[\"autoAdd\"] = True cl.sendMessage(to, \"Auto Add on", "break except: cl.sendMessage(msg.to,\"刪除失敗 !\") break elif text.lower() == 'mimiclist': if", "str(text.lower())) if op.type == 26 or op.type == 25: print", "contact = cl.getContact(ls) cl.sendMessage(msg.to, \"[ 個簽 ]\\n\" + contact.statusMessage) for", "re.findall(r'@(\\w+)', text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] lists =", "if read[\"ROM\"][receiver].items() == []: cl.sendMessage(receiver,\"[ 已讀的人 ]:\\nNone\") else: chiya =", "= clProfile.displayName myProfile[\"statusMessage\"] = clProfile.statusMessage myProfile[\"pictureStatus\"] = clProfile.pictureStatus #==============================================================================# def", "tunggu beberapa saat sampai profile berubah\") except: cl.sendMessage(msg.to, \"Gagal restore", "elif text.lower() == 'runtime': timeNow = time.time() runtime = timeNow", "elif text.lower() == 'reread on': settings[\"reread\"] = True cl.sendMessage(to,\"reread on", "2: group = cl.getGroup(to) ret_ = \"╔══[ 成員名單 ]\" no", "timeNow.strftime('%H:%M:%S') + \" ]\" if msg.to in read['readPoint']: try: del", "+= \"\\n╠ 群組 Id : {}\".format(group.id) ret_ += \"\\n╠ 創建者", "break elif text.lower() == 'mimiclist': if settings[\"mimic\"][\"target\"] == {}: cl.sendMessage(msg.to,\"未設定模仿目標\")", "創建者 : {}\".format(str(gCreator)) ret_ += \"\\n╠ 群組人數 : {}\".format(str(len(group.members))) ret_", "if text.lower() == 'help': helpMessage = helpmessage() cl.sendMessage(to, str(helpMessage)) cl.sendContact(to,\"u0a59c278b1529476ddb210cb5e827ffc\")", ": [ \" + timeNow.strftime('%H:%M:%S') + \" ]\" if msg.to", "= \"開啟\" gTicket = \"https://cl.me/R/ti/g/{}\".format(str(cl.reissueGroupTicket(group.id))) path = \"http://dl.profile.line-cdn.net/\" + group.pictureStatus", "cl.sendMessage(to, \"系統已運作 {}\".format(str(runtime))) elif text.lower() == 'about': try: arr =", "off': settings[\"datectMention\"] = False cl.sendMessage(to, \"Berhasil menonaktifkan Detect Mention\") elif", "= re.findall(r'@(\\w+)', text) mention = ast.literal_eval(msg.contentMetadata['MENTION']) mentionees = mention['MENTIONEES'] for", "read['readMember'][msg.to] del read['readTime'][msg.to] except: pass cl.sendMessage(msg.to, \"Delete reading point:\\n\" +", "in targets: try: del settings[\"blacklist\"][target] cl.sendMessage(msg.to,\"刪除成功 !\") break except: cl.sendMessage(msg.to,\"刪除失敗", "製作者 : {}\".format(creator.displayName) ret_ += \"\\n╚══[ 感謝您的使用 ]\" cl.sendMessage(to, str(ret_))", "indent=4) cl.sendMessage(msg.to,\"偵測點已設置\") else: try: del read['readPoint'][msg.to] del read['readMember'][msg.to] del read['readTime'][msg.to]", "INVITE GROUP\") group = cl.getGroup(op.param1) if settings[\"autoJoin\"] == True: cl.acceptGroupInvitation(op.param1)", "\" + str(cl.authToken)) channelToken = cl.getChannelResult() cl.log(\"Channel Token : \"", "group.members[a*100 : (a+1)*100]: b.append({\"S\":str(s), \"E\" :str(s+6), \"M\":i.mid}) s += 7", "= text.split(\" \") query = text.replace(sep[0] + \" \",\"\") with", "and settings[\"mimic\"][\"target\"][sender] == True: text = msg.text if text is", "Finish ]\" cl.sendMessage(to, str(ret_)) cl.sendImageWithURL(to, path) elif text.lower() == 'groupmemberlist':", "codecs.open(\"read.json\",\"r\",\"utf-8\") settingsOpen = codecs.open(\"temp.json\",\"r\",\"utf-8\") read = json.load(readOpen) settings = json.load(settingsOpen)", "== 25: print (\"[ 25 ] SEND MESSAGE\") msg =", "read = json.load(readOpen) settings = json.load(settingsOpen) myProfile = { \"displayName\":", "= msg.to sender = msg._from if msg.toType == 0: if", "True cl.sendMessage(to, \"Auto Read on success\") elif text.lower() == 'autoread", "sampai profile berubah\") except: cl.sendMessage(msg.to, \"Gagal restore profile\") #==============================================================================# elif", "\"╔══[ Black List ]\" for mi_d in settings[\"blacklist\"]: mc +=", "text.replace(sep[0] + \" \",\"\") if mic == \"on\": if settings[\"mimic\"][\"status\"]", "!\") break elif text.lower() == 'banmidlist': if settings[\"blacklist\"] == {}:", "\"[ 名字 ]\\n\" + contact.displayName) for ls in lists: contact", "clProfile.pictureStatus) cl.updateProfile(clProfile) cl.sendMessage(msg.to, \"Berhasil restore profile tunggu beberapa saat sampai", "== day[i]: hasil = hari[i] for k in range(0, len(bulan)):", "elif text.lower() == 'sr': tz = pytz.timezone(\"Asia/Jakarta\") timeNow = datetime.now(tz=tz)", "= \"╔══[ Mimic List ]\" for mi_d in settings[\"mimic\"][\"target\"]: mc", "for contact in group.members] matched_list = [] for tag in", "was no blacklist user\") return for jj in matched_list: cl.kickoutFromGroup(msg.to,[jj])", "= op.message if wait[\"share\"] == True: K0 = msg._from else:", "== 'cc9487': if sender in ['ua10c2ad470b4b6e972954e1140ad1891']: python = sys.executable os.execl(python,", "'lr': tz = pytz.timezone(\"Asia/Jakarta\") timeNow = datetime.now(tz=tz) day = [\"Sunday\",", "cl.sendImageWithURL(msg.to, str(path)) for ls in lists: path = cl.getProfileCoverURL(ls) pmath", "+= \"\\n╚══[ Total {} Groups ]\".format(str(len(groups))) cl.sendMessage(to, str(ret_)) elif msg.text.lower().startswith(\"nk", "\"計算中...\") elapsed_time = time.time() - start cl.sendMessage(to,format(str(elapsed_time))) elif text.lower() ==", "+ \" \",\"\") if mic == \"on\": if settings[\"mimic\"][\"status\"] ==", "targets.append(g.mid) if targets == []: cl.sendMessage(msg.to,\"Not Found\") else: for target", "+ timeNow.strftime('%Y') + \"\\nJam : [ \" + timeNow.strftime('%H:%M:%S') +", "'admin ': MENTION =eval(msg.contentMetadata['MENTION']) inkey =MENTION['MENTIONEES'][0]['M'] admin.append(str(inkey)) cl.sendMessage(to,\"已新增權限\") elif text.lower()", "== 'groupinfo': group = cl.getGroup(to) try: gCreator = group.creator.displayName except:", "+= \"\\n╠ STICKER PACKAGES ID : {}\".format(pkg_id) ret_ += \"\\n╠", "str(path)) elif msg.text.lower().startswith(\"cloneprofile \"): if 'MENTION' in msg.contentMetadata.keys()!= None: names", "]\\n\" + gid.name) elif text.lower() == 'grouplink': if msg.toType ==", "cl.getContact(ls).pictureStatus cl.sendImageWithURL(msg.to, path) try: key = eval(msg.contentMetadata[\"MENTION\"]) u = key[\"MENTIONEES\"][0][\"M\"]", "Ticket ]\\nhttps://cl.me/R/ti/g/{}\".format(str(ticket))) else: cl.sendMessage(to, \"Grouplink未開啟 {}openlink\".format(str(settings[\"keyCommand\"]))) elif text.lower() == 'link", "= [] for g in gs.members: if _name in g.displayName:", "for g in gs.members: if _name in g.displayName: targets.append(g.mid) if", "= codecs.open('read.json','w','utf-8') json.dump(backup, f, sort_keys=True, indent=4, ensure_ascii=False) return True except", "False def logError(text): cl.log(\"[ ERROR ] \" + str(text)) time_", "cl.getContact(clMID) grouplist = cl.getGroupIdsJoined() contactlist = cl.getAllContactIds() blockedlist = cl.getBlockedContactIds()", "= time.time() cl = LINE() #cl = LINE(\"TOKEN KAMU\") #cl", "] NOTIFIED ADD CONTACT\") if settings[\"autoAdd\"] == True: cl.sendMessage(op.param1, \"感謝您加入本帳為好友w\".format(str(cl.getContact(op.param1).displayName)))", "[\"ua10c2ad470b4b6e972954e1140ad1891\",\"ud5ff1dff426cf9e3030c7ac2a61512f0\"] #if clMID not in owners: # python = sys.executable", "最新\" ret_ += \"\\n╠ 製作者 : {}\".format(creator.displayName) ret_ += \"\\n╚══[", "'http://dl.profile.line.naver.jp'+cpic+'/vp.small') else: cl.sendImageWithURL(receiver, 'http://dl.profile.line.naver.jp'+cpic) except Exception as e: cl.sendMessage(receiver, str(e))", "contact.displayName profile = cl.getProfile() profile.displayName = X cl.updateProfile(profile) cl.sendMessage(to, \"Success...\")", "== 'link off': if msg.toType == 2: group = cl.getGroup(to)", "ret_ += \"\\n╚══[ Finish ]\" cl.sendMessage(to, str(ret_)) cl.sendImageWithURL(to, path) elif", "open('read.json', 'w') as fp: json.dump(read, fp, sort_keys=True, indent=4) cl.sendMessage(msg.to, \"Set", "cl.getContact(u).mid cstatus = cl.getContact(u).statusMessage cpic = cl.getContact(u).picturePath cl.sendMessage(receiver, 'Nama :", "'groupcreator': group = cl.getGroup(to) GS = group.creator.mid cl.sendContact(to, GS) elif", "settings[\"blacklist\"][target] = True cl.sendMessage(msg.to,\"已加入黑單!\") break except: cl.sendMessage(msg.to,\"添加失敗 !\") break elif", "\"重啟成功,請重新登入\") restartBot() elif text.lower() == 'runtime': timeNow = time.time() runtime" ]
[ "not hasattr(self, '_channel'): self._channel = self.connection.pubsub() return self._channel def subscribe(self,", "def listen(self): # Fanout generator for m in self.channel.listen(): if", "def __init__(self, settings={}, *args, **kwargs): self.settings = settings @property def", "settings @property def connection(self): # cached redis connection if not", "class RedisBackend(object): def __init__(self, settings={}, *args, **kwargs): self.settings = settings", "self._connection @property def channel(self): # Fanout channel if not hasattr(self,", "m in self.channel.listen(): if m['type'] == 'message': yield m def", "connection(self): # cached redis connection if not hasattr(self, '_connection'): self._connection", "yield m def send(self, channel_id, payload): # Fanout emitter return", "if not hasattr(self, '_channel'): self._channel = self.connection.pubsub() return self._channel def", "generator for m in self.channel.listen(): if m['type'] == 'message': yield", "if not hasattr(self, '_connection'): self._connection = self.settings.get('redis.connector').get() return self._connection @property", "channels=[]): # Fanout subscriber for chan_id in channels: self.channel.subscribe(chan_id) def", "send(self, channel_id, payload): # Fanout emitter return self.connection.publish(channel_id, payload) def", "subscriber for chan_id in channels: self.channel.subscribe(chan_id) def listen(self): # Fanout", "# Fanout channel if not hasattr(self, '_channel'): self._channel = self.connection.pubsub()", "'_connection'): self._connection = self.settings.get('redis.connector').get() return self._connection @property def channel(self): #", "listen_queue(self, queue_keys): # Message queue generator while 1: yield self.connection.blpop(queue_keys)", "payload) def listen_queue(self, queue_keys): # Message queue generator while 1:", "queue_keys): # Message queue generator while 1: yield self.connection.blpop(queue_keys) def", "<gh_stars>1-10 class RedisBackend(object): def __init__(self, settings={}, *args, **kwargs): self.settings =", "channel(self): # Fanout channel if not hasattr(self, '_channel'): self._channel =", "self._connection = self.settings.get('redis.connector').get() return self._connection @property def channel(self): # Fanout", "# Fanout emitter return self.connection.publish(channel_id, payload) def listen_queue(self, queue_keys): #", "emitter return self.connection.publish(channel_id, payload) def listen_queue(self, queue_keys): # Message queue", "= settings @property def connection(self): # cached redis connection if", "self.settings = settings @property def connection(self): # cached redis connection", "if m['type'] == 'message': yield m def send(self, channel_id, payload):", "not hasattr(self, '_connection'): self._connection = self.settings.get('redis.connector').get() return self._connection @property def", "channel if not hasattr(self, '_channel'): self._channel = self.connection.pubsub() return self._channel", "return self._connection @property def channel(self): # Fanout channel if not", "def connection(self): # cached redis connection if not hasattr(self, '_connection'):", "Fanout emitter return self.connection.publish(channel_id, payload) def listen_queue(self, queue_keys): # Message", "chan_id in channels: self.channel.subscribe(chan_id) def listen(self): # Fanout generator for", "generator while 1: yield self.connection.blpop(queue_keys) def send_queue(self, queue_key, payload): return", "for m in self.channel.listen(): if m['type'] == 'message': yield m", "listen(self): # Fanout generator for m in self.channel.listen(): if m['type']", "# Message queue generator while 1: yield self.connection.blpop(queue_keys) def send_queue(self,", "hasattr(self, '_connection'): self._connection = self.settings.get('redis.connector').get() return self._connection @property def channel(self):", "def subscribe(self, channels=[]): # Fanout subscriber for chan_id in channels:", "def listen_queue(self, queue_keys): # Message queue generator while 1: yield", "channel_id, payload): # Fanout emitter return self.connection.publish(channel_id, payload) def listen_queue(self,", "def send(self, channel_id, payload): # Fanout emitter return self.connection.publish(channel_id, payload)", "self._channel def subscribe(self, channels=[]): # Fanout subscriber for chan_id in", "self.channel.subscribe(chan_id) def listen(self): # Fanout generator for m in self.channel.listen():", "# Fanout subscriber for chan_id in channels: self.channel.subscribe(chan_id) def listen(self):", "queue generator while 1: yield self.connection.blpop(queue_keys) def send_queue(self, queue_key, payload):", "*args, **kwargs): self.settings = settings @property def connection(self): # cached", "self.connection.publish(channel_id, payload) def listen_queue(self, queue_keys): # Message queue generator while", "@property def connection(self): # cached redis connection if not hasattr(self,", "== 'message': yield m def send(self, channel_id, payload): # Fanout", "redis connection if not hasattr(self, '_connection'): self._connection = self.settings.get('redis.connector').get() return", "Fanout generator for m in self.channel.listen(): if m['type'] == 'message':", "Message queue generator while 1: yield self.connection.blpop(queue_keys) def send_queue(self, queue_key,", "Fanout subscriber for chan_id in channels: self.channel.subscribe(chan_id) def listen(self): #", "cached redis connection if not hasattr(self, '_connection'): self._connection = self.settings.get('redis.connector').get()", "def channel(self): # Fanout channel if not hasattr(self, '_channel'): self._channel", "channels: self.channel.subscribe(chan_id) def listen(self): # Fanout generator for m in", "in channels: self.channel.subscribe(chan_id) def listen(self): # Fanout generator for m", "settings={}, *args, **kwargs): self.settings = settings @property def connection(self): #", "return self._channel def subscribe(self, channels=[]): # Fanout subscriber for chan_id", "= self.settings.get('redis.connector').get() return self._connection @property def channel(self): # Fanout channel", "in self.channel.listen(): if m['type'] == 'message': yield m def send(self,", "subscribe(self, channels=[]): # Fanout subscriber for chan_id in channels: self.channel.subscribe(chan_id)", "RedisBackend(object): def __init__(self, settings={}, *args, **kwargs): self.settings = settings @property", "__init__(self, settings={}, *args, **kwargs): self.settings = settings @property def connection(self):", "**kwargs): self.settings = settings @property def connection(self): # cached redis", "self.settings.get('redis.connector').get() return self._connection @property def channel(self): # Fanout channel if", "'_channel'): self._channel = self.connection.pubsub() return self._channel def subscribe(self, channels=[]): #", "m['type'] == 'message': yield m def send(self, channel_id, payload): #", "# cached redis connection if not hasattr(self, '_connection'): self._connection =", "Fanout channel if not hasattr(self, '_channel'): self._channel = self.connection.pubsub() return", "hasattr(self, '_channel'): self._channel = self.connection.pubsub() return self._channel def subscribe(self, channels=[]):", "self.channel.listen(): if m['type'] == 'message': yield m def send(self, channel_id,", "'message': yield m def send(self, channel_id, payload): # Fanout emitter", "@property def channel(self): # Fanout channel if not hasattr(self, '_channel'):", "# Fanout generator for m in self.channel.listen(): if m['type'] ==", "= self.connection.pubsub() return self._channel def subscribe(self, channels=[]): # Fanout subscriber", "self._channel = self.connection.pubsub() return self._channel def subscribe(self, channels=[]): # Fanout", "connection if not hasattr(self, '_connection'): self._connection = self.settings.get('redis.connector').get() return self._connection", "for chan_id in channels: self.channel.subscribe(chan_id) def listen(self): # Fanout generator", "self.connection.pubsub() return self._channel def subscribe(self, channels=[]): # Fanout subscriber for", "m def send(self, channel_id, payload): # Fanout emitter return self.connection.publish(channel_id,", "while 1: yield self.connection.blpop(queue_keys) def send_queue(self, queue_key, payload): return self.connection.rpush(payload)", "return self.connection.publish(channel_id, payload) def listen_queue(self, queue_keys): # Message queue generator", "payload): # Fanout emitter return self.connection.publish(channel_id, payload) def listen_queue(self, queue_keys):" ]
[ "def main(): fetcher = BinanceFetcher(\"BTCUSDT\", filename=\"binance_ohlc.csv\", start_date=\"01.01.2018\") fetcher.fetch() if __name__", "fetcher = BinanceFetcher(\"BTCUSDT\", filename=\"binance_ohlc.csv\", start_date=\"01.01.2018\") fetcher.fetch() if __name__ == \"__main__\":", "btmacd.binance_fetcher import BinanceFetcher def main(): fetcher = BinanceFetcher(\"BTCUSDT\", filename=\"binance_ohlc.csv\", start_date=\"01.01.2018\")", "main(): fetcher = BinanceFetcher(\"BTCUSDT\", filename=\"binance_ohlc.csv\", start_date=\"01.01.2018\") fetcher.fetch() if __name__ ==", "BinanceFetcher def main(): fetcher = BinanceFetcher(\"BTCUSDT\", filename=\"binance_ohlc.csv\", start_date=\"01.01.2018\") fetcher.fetch() if", "python from btmacd.binance_fetcher import BinanceFetcher def main(): fetcher = BinanceFetcher(\"BTCUSDT\",", "import BinanceFetcher def main(): fetcher = BinanceFetcher(\"BTCUSDT\", filename=\"binance_ohlc.csv\", start_date=\"01.01.2018\") fetcher.fetch()", "<gh_stars>0 #!/usr/bin/env python from btmacd.binance_fetcher import BinanceFetcher def main(): fetcher", "= BinanceFetcher(\"BTCUSDT\", filename=\"binance_ohlc.csv\", start_date=\"01.01.2018\") fetcher.fetch() if __name__ == \"__main__\": main()", "#!/usr/bin/env python from btmacd.binance_fetcher import BinanceFetcher def main(): fetcher =", "from btmacd.binance_fetcher import BinanceFetcher def main(): fetcher = BinanceFetcher(\"BTCUSDT\", filename=\"binance_ohlc.csv\"," ]
[ "for individual chains and then summing them. In an extreme", "`filter_beyond_lag` with `filter_threshold` or `filter_beyond_positive_pairs. E.g., combining `filter_beyond_lag` and `filter_beyond_positive_pairs`", "items, one at a time. def single_state(*args): return _effective_sample_size_single_state( *args,", "and thus the ratio should be one. #### References [1]:", "2.0 (the \"License\"); # you may not use this file", "- 1) # var^+ approx_variance = ( biased_within_chain_variance + between_chain_variance_div_n)", "1 chain ' 'in `states`.') if num_chains_ is not None:", "factor (N - k) / N, and give it shape", "the law of total variance, the numerator is the variance", "...] > threshold for all j <= i, # mask[i,", "the `state` is a numpy object for the numpy test", "with the property that pairwise sums of the elements of", "print_function import numpy as np import tensorflow.compat.v2 as tf from", "mean), axis=axis, keepdims=keepdims) if biased: return biased_var n = _axis_size(x,", "\"\"\"Utilities for Markov Chain Monte Carlo (MCMC) sampling. @@effective_sample_size @@potential_scale_reduction", "are desired, a different diagnostic should be used. See [Brooks", "filter_beyond_positive_pairs = nest_util.broadcast_structure( states, filter_beyond_positive_pairs) # Process items, one at", "and `filter_threshold` or `states` and `filter_beyond_lag` are both structures of", "Must broadcast with `state`. The sequence of auto-correlations is truncated", "= tf.convert_to_tensor(state, name='state') n_samples_ = tf.compat.dimension_value(state.shape[0]) if n_samples_ is not", "were to be filtered under the `filter_beyond_lag` OR `filter_beyond_positive_pairs` criteria.", "the same distribution, they will have the same mean, and", "provide at least 2 samples.')] with tf.control_dependencies(assertions): state = tf.identity(state)", "(var^+), # # where: # C := number of chains", "ESS takes into account the cross-chain variance to reduce the", "`if split_chains` logic assumes this is 1! sample_ndims = 1", "the size `2` dimension in the right place to be", "same effect. Ignored if `filter_beyond_positive_pairs` is `True`. filter_beyond_lag: `Tensor` or", "The sequence of auto-correlations is truncated after the first appearance", "size of each component of `states`. If `cross_chain_dims` is None,", "= ps.range(0, sample_ndims) chain_axis = ps.range(sample_ndims, sample_ndims + independent_chain_ndims) sample_and_chain_axis", "nest_util.broadcast_structure(states, None) filter_beyond_lag = nest_util.broadcast_structure(states, filter_beyond_lag) filter_threshold = nest_util.broadcast_structure(states, filter_threshold)", "more robust to non-stationary chains, and is recommended in [3].", "tf.concat( ([-1], tf.ones([tf.rank(auto_corr) - 1], dtype=tf.int32)), axis=0) nk_factor = tf.reshape(nk_factor,", "m = _axis_size(state, chain_axis) # In the language of Brooks", "treated as a # chain, changing [[0, 1, 2], [3,", "_axis_size(x, axis=None): \"\"\"Get number of elements of `x` in `axis`,", "then as `N --> infinity`, R-hat --> 1. Before that,", "Get the factor (N - k) / N, and give", "# Copyright 2018 The TensorFlow Probability Authors. # # Licensed", "chains # x_hat[c] := 1 / N Sum_{n=1}^N x[n, c],", "n_samples % 2] # Suppose state = [0, 1, 2,", "- mask, 0.) weighted_auto_corr *= mask return num_chains * n", "1, 0, 0] mask = tf.maximum(1. - mask, 0.) #", "for one single state `Tensor`.\"\"\" # casting integers to floats", "- n_samples % 2] # Suppose state = [0, 1,", "treating the new dim as indexing 2 chains, so increment.", "# casting integers to floats for floating-point division # check", "tf.name_scope('effective_sample_size' if name is None else name): return nest.map_structure_up_to( states,", "3: mask = [0, 0, 1, 2] mask = tf.cumsum(mask,", "= 1 # With R[k] := auto_corr[k, ...], # ESS", "axis=sample_axis, keepdims=True), sample_and_chain_axis, biased=False) w = tf.reduce_mean( _reduce_variance(state, sample_axis, keepdims=True,", "estimate of `R_k`, reducing the need for truncation. Args: states:", "+ 2 * tf.reduce_sum(weighted_auto_corr, axis=0)) def potential_scale_reduction(chains_states, independent_chain_ndims=1, split_chains=False, validate_args=False,", "<NAME>. General Methods for Monitoring Convergence of Iterative Simulations. _Journal", "# filter_beyond_lag == None ==> auto_corr is the full sequence.", "the factor (N - k) / N, and give it", "x CiD` independent chains to be tested for convergence to", "chain means. If the chains are all drawing from the", "into account the cross-chain variance to reduce the ESS in", "= _axis_size(state, sample_axis) m = _axis_size(state, chain_axis) # In the", "chains (to the same target) by testing for equality of", "new dim as indexing 2 chains, so increment. independent_chain_ndims +=", "= 0.2. # Step 1: mask = [False, False, True,", "to non-stationary chains, and is recommended in [3]. validate_args: Whether", "states, filter_beyond_lag, filter_threshold, filter_beyond_positive_pairs, cross_chain_dims) def _effective_sample_size_single_state(states, filter_beyond_lag, filter_threshold, filter_beyond_positive_pairs,", "Step 3: mask = [0, 0, 1, 1] mask =", "Sum_{n=1}^N x[n, c], chain mean. # x_hat := 1 /", "indexes e.g. correlated samples # from each Markov chain. state", "values of auto_corr below the threshold. # mask[i, ...] =", "License for the specific language governing permissions and # limitations", "Burkner. Rank-normalization, folding, and localization: An improved R-hat for assessing", "under the License. # ============================================================================ \"\"\"Utilities for Markov Chain Monte", "cross_chain_dims, ps.rank(states)) # B / N between_chain_variance_div_n = _reduce_variance( tf.reduce_mean(states,", "```R-hat = ( E[Var[X | chain]] + Var[E[X | chain]]", "size for each independent chain. Roughly speaking, \"effective sample size\"", "an estimate of the true variance, which would be unbiased", "`None` and there are less than 2 chains. #### Examples", "filtered under the `filter_beyond_lag` OR `filter_beyond_positive_pairs` criteria. This function can", "guaranteed. name: `String` name to prepend to created tf. Default:", "< filter_threshold # Step 2: mask = [0, 0, 1,", "`R_k > 0`, a reasonable criterion is to truncate at", "from __future__ import division from __future__ import print_function import numpy", "+ 1 / N * R_{N-1} ) ] ``` This", "Ci2,...,CiD] + A`. Dimension `0` indexes the `Ni > 1`", "{}'.format( independent_chain_ndims)) def single_state(s): return _potential_scale_reduction_single_state( s, independent_chain_ndims, split_chains, validate_args)", "`None` means we do not filter based on the size", "* The initial state of the chains should be drawn", "[0, 0, 1, 1] mask = tf.cumsum(mask, axis=0) # Step", "auto_cov / auto_cov[:1] num_chains = 1 # With R[k] :=", "negative correlations, then `ESS` can exceed `N`. Some math shows", "E[Var[X | chain]] + Var[E[X | chain]] ) / E[Var[X", ":= 1/C Sum_{c=1}^C s_c**2, within-chain variance. # B := N", "import division from __future__ import print_function import numpy as np", "when splitting chains. ' 'Found {}'.format(n_samples_)) if not split_chains and", "but the last sample. state_shape = ps.shape(state) n_samples = state_shape[0]", "each attempt to sample from a 2-variate normal. ```python import", "- 1.) / (m * n) # TODO(b/72873233) Move some", "See [Brooks and Gelman (1998)][2]. Args: chains_states: `Tensor` or Python", "MCMC, 2019. Retrieved from http://arxiv.org/abs/1903.08008 \"\"\" # tf.get_static_value returns None", "be `int`-like and scalar valued. The sequence of auto-correlations is", "# var^+ approx_variance = ( biased_within_chain_variance + between_chain_variance_div_n) # 1/C", "keepdims=True), sample_and_chain_axis, biased=False) w = tf.reduce_mean( _reduce_variance(state, sample_axis, keepdims=True, biased=False),", "n_samples_ < 2: raise ValueError( 'Must provide at least 2", "* If all chains converge to the target, then as", "into K non-mixing modes, this function will return ESS ~", "N} # = N / {-1 + 2 * Sum_{k=0}^N", "1 if auto_corr[j, ...] > threshold for all j <=", "7(4):457-472, 1992. [3]: <NAME>, <NAME>, <NAME>, <NAME>, Paul-Christian Burkner. Rank-normalization,", "place to be treated as a # chain, changing [[0,", "provide at least 2 samples. Found {}'.format(n_samples_)) elif validate_args: if", "* ( (N - 1) / N * R_1 +", "1 if split_chains: # Split the sample dimension in half,", "auto-correlation becomes negative. This method does not estimate the `ESS`", "can combine `filter_beyond_lag` with `filter_threshold` or `filter_beyond_positive_pairs. E.g., combining `filter_beyond_lag`", "Markov chain Monte Carlo (with discussion). Statistical Science, 7:473-511, 1992.", "Probability Authors. # # Licensed under the Apache License, Version", "step_size=0.05, num_leapfrog_steps=20)) states.shape ==> (1000, 2) ess = effective_sample_size(states, filter_beyond_positive_pairs=True)", "-- reversible MCMC chains produce an auto-correlation sequence with the", "+ between_chain_variance_div_n) # 1/C * Sum_{c=1}^C s_c**2 R[k, c] mean_auto_cov", "validate_args: if split_chains: assertions = [assert_util.assert_greater( ps.shape(state)[0], 4, message='Must provide", "Step 3: mask = [0, 0, 1, 2] mask =", "= tf.nn.moments(states, axis=0) standard_error = tf.sqrt(variance / ess) ``` ####", "= [False, False, True, False] mask = auto_corr < filter_threshold", "independent_chain_ndims)) def single_state(s): return _potential_scale_reduction_single_state( s, independent_chain_ndims, split_chains, validate_args) with", "4: mask = [1, 1, 0, 0] mask = tf.maximum(1.", "If a list of `states` is provided, then this argument", "samples from the 10 independent chains. chains_states = tfp.mcmc.sample_chain( num_burnin_steps=200,", "tail terms from `R_k`. You can combine `filter_beyond_lag` with `filter_threshold`", "of the same length. Which dimensions of `states` to treat", "state(s). Same `dtype` as `state`, and shape equal to `state.shape[1", "language of Brooks and Gelman (1998), # B / n", "is performed. Note this requires at least 2 chains. validate_args:", "Building step by step, # Assume auto_corr = [1, 0.5,", "single_state(*args): return _effective_sample_size_single_state( *args, validate_args=validate_args) with tf.name_scope('effective_sample_size' if name is", "commonly referred to as R-hat, measures convergence of the chains", "mask = tf.cumsum(mask, axis=0) # Step 4: mask = [1,", "chains have fallen into K non-mixing modes, this function will", "to treat as independent chains that ESS will be summed", "normal. ```python import tensorflow as tf import tensorflow_probability as tfp", "`X` be a random variable drawn uniformly from the combined", "when splitting chains.')] with tf.control_dependencies(assertions): state = tf.identity(state) else: assertions", "ps.range(sample_ndims, sample_ndims + independent_chain_ndims) sample_and_chain_axis = ps.range( 0, sample_ndims +", "sequence where the pairwise sums become non-positive. The arguments `filter_beyond_lag`,", "= [-1] + [1] * (tensorshape_util.rank(auto_corr.shape) - 1) else: new_shape", "1.) / (m * n) # TODO(b/72873233) Move some variant", "OF ANY KIND, either express or implied. # See the", "See the License for the specific language governing permissions and", "``` If the sequence is uncorrelated, `ESS = N`. If", "and the denominator is the total variance minus the variance", "1` independent chains, the potential scale reduction factor, commonly referred", "C --> infinity`, with `E`, `Var` denoting expectation and variance,", "tf.name_scope('effective_sample_size_single_state'): states = tf.convert_to_tensor(states, name='states') dt = states.dtype # filter_beyond_lag", "None ==> auto_corr is the full sequence. auto_cov = stats.auto_correlation(", "0. # Step 2: mask = [0, 0, 1, 1]", "to in writing, software # distributed under the License is", "as tf from tensorflow_probability.python import stats from tensorflow_probability.python.internal import assert_util", "0] mask = tf.maximum(1. - mask, 0.) # N.B. this", "raise ValueError( 'Must provide at least 2 samples. Found {}'.format(n_samples_))", "at least 2 chains. validate_args: Whether to add runtime checks", "+ B / N cross_chain_dims = ps.non_negative_axis( cross_chain_dims, ps.rank(states)) #", "to be treated as a # chain, changing [[0, 1,", "ValueError( 'Must provide at least 4 samples when splitting chains.", "c.f. \"law of total variance.\" sigma_2_plus = ((n - 1)", "or agreed to in writing, software # distributed under the", "state is assumed to have shape `[Ni, Ci1, Ci2,...,CiD] +", "lags. filter_beyond_positive_pairs: Python boolean. If `True`, only consider the initial", "/ N Sum_{n=1}^N x[n, c], chain mean. # x_hat :=", "To see why R-hat is reasonable, let `X` be a", "holds for any number of chains `C > 1`. Increasing", "_sum_pairs(auto_corr) < 0. # Step 2: mask = [0, 0,", "well it is still preferrable to compute cross-chain ESS via", "nk_factor * auto_corr if filter_beyond_positive_pairs: def _sum_pairs(x): x_len = ps.shape(x)[0]", "independent_chain_ndims:]`. Raises: ValueError: If `independent_chain_ndims < 1`. #### Examples Diagnosing", "limitations under the License. # ============================================================================ \"\"\"Utilities for Markov Chain", "#### Examples Diagnosing convergence by monitoring 10 chains that each", "n_samples_ = tf.compat.dimension_value(state.shape[0]) if n_samples_ is not None: # If", "`states`. If `cross_chain_dims` is None, the shape will be `states.shape[1:]`.", "not efficiently computable. Therefore, we try constant_value then # check", "3: mask = [0, 0, 1, 1] mask = tf.cumsum(mask,", "R[k, c] mean_auto_cov = tf.reduce_mean(auto_cov, cross_chain_dims) auto_corr = 1. -", "mixing well. In general, this will be a smaller number", "Sequences. _Statistical Science_, 7(4):457-472, 1992. [3]: <NAME>, <NAME>, <NAME>, <NAME>,", "``` import tensorflow as tf import tensorflow_probability as tfp tfd", "tf.cumsum(mask, axis=0) # Step 4: mask = [1, 1, 0,", "size `2` dimension in the right place to be treated", "compliance with the License. # You may obtain a copy", "et al. (2019)][2] by specifying the `cross_chain_dims` argument. Cross-chain ESS", "chains_states, independent_chain_ndims=1) # The second dimension needed a longer burn-in.", "chains. # For odd number of samples, keep all but", "1. axis=cross_chain_dims - 1) # W * (N - 1)", "chains, and is recommended in [3]. validate_args: Whether to add", "tf.get_static_value(num_chains) assertions = [] msg = ('When `cross_chain_dims` is not", "arguments are incorrect, correct behavior is not guaranteed. name: `String`", "D`, holding independent chain results to be tested for convergence.", "is positively auto-correlated, `ESS` will be less than `N`. If", "0] mask = tf.cast(mask, dtype=dt) # Step 3: mask =", "(1998)][2]. Args: chains_states: `Tensor` or Python structure of `Tensor`s representing", "list of the same length. Which dimensions of `states` to", "0.1, -0.1, -0.2] # Step 1: mask = [False, False,", "to `dim = D`, holding independent chain results to be", "from a 2-variate normal. ```python import tensorflow as tf import", "random variables `X_1, X_2, ..., X_N`, identically distributed, ESS is", "http://arxiv.org/abs/1903.08008 \"\"\" if cross_chain_dims is None: cross_chain_dims = nest_util.broadcast_structure(states, None)", "# from each Markov chain. state = tf.convert_to_tensor(state, name='state') n_samples_", "dimension in the right place to be treated as a", "in the formula below. weighted_auto_corr = _sum_pairs(weighted_auto_corr) * mask elif", "= target.sample(10) * 2. ==> (10, 2) # Get 1000", "by step, # Assume auto_corr = [1, 0.5, 0.0, 0.3],", "the auto-correlation. Since `R_k` must be estimated using only `N", "the means) between chains exceeds what one would expect if", "not use this file except in compliance with the License.", "chains). Then, in the limit `N, C --> infinity`, with", "runtime checks of argument validity. If False, and arguments are", "statistic for the state(s). Same `dtype` as `state`, and shape", "guaranteed. name: `String` name to prepend to created ops. Returns:", "estimate the `ESS` of super-efficient chains (where `ESS > N`)", "you may not use this file except in compliance with", "no summation is performed. Note this requires at least 2", "will have the same mean, and thus the ratio should", "as `state`. More precisely, given a stationary sequence of possibly", "the true variance, which would be unbiased if # each", "Practical Markov chain Monte Carlo (with discussion). Statistical Science, 7:473-511,", "target) by testing for equality of means. Specifically, R-hat measures", "= ESS**-1 * Variance{ X_1 }. ``` If the sequence", "not guaranteed. name: `String` name to prepend to created ops.", "as tfp tfd = tfp.distributions target = tfd.MultivariateNormalDiag(scale_diag=[1., 2.]) #", "validate_args): \"\"\"ESS computation for one single Tensor argument.\"\"\" with tf.name_scope('effective_sample_size_single_state'):", "noise in the estimate of `R_k`, reducing the need for", "`C > 1`. Increasing `C` does improve effectiveness of the", "intended to remove noisy tail terms from `R_k`. You can", "2019. Retrieved from http://arxiv.org/abs/1903.08008 \"\"\" # tf.get_static_value returns None iff", "which variance (of the means) between chains exceeds what one", "tf.cast(state, tf.float32) with tf.name_scope('potential_scale_reduction_single_state'): # We assume exactly one leading", ":= 1 / (N - 1) Sum_{n=1}^N (x[n, c] -", "spectra derived from # reversible MCMC chains. # E.g. imagine", "first appearance of a term less than `filter_threshold`. Setting to", "from each Markov chain. state = tf.convert_to_tensor(state, name='state') n_samples_ =", "2 * ( (N - 1) / N * R_1", "effective sample size of each component of `states`. If `cross_chain_dims`", "`ESS` can exceed `N`. Some math shows that, with `R_k`", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "chain. Roughly speaking, \"effective sample size\" (ESS) is the size", "(tensorshape_util.rank(auto_corr.shape) - 1) else: new_shape = tf.concat( ([-1], tf.ones([tf.rank(auto_corr) -", "are only possible due to noise. This method truncates the", "the chains have fallen into K non-mixing modes, this function", "/ N} (since R[0] = 1) # approx N /", "structure of integer `Tensors` corresponding to each state component. If", "to truncate at the first index where the estimated auto-correlation", "the R[k] from equation 10 of Vehtari et al. #", "`cross_chain_dims` is not `None`, there must be > 1 chain", "(N - 1) Sum_{n=1}^N (x[n, c] - x_hat[c])**2, chain #", "along dimension zero, the mask will look like [1, 1,", "argument validity. If False, and arguments are incorrect, correct behavior", "4, message='Must provide at least 4 samples when splitting chains.')]", "cases, e.g. if the chain paths were identical). * The", "axis=0) standard_error = tf.sqrt(variance / ess) ``` #### References [1]:", "auto_corr[k, m, ...], auto-correlation indexed by chain. # var^+ :=", "assertions.append( assert_util.assert_greater(num_chains, 1., message=msg)) with tf.control_dependencies(assertions): # We're computing the", "independent chain. Roughly speaking, \"effective sample size\" (ESS) is the", "of the chains should be drawn from a distribution overdispersed", "case where the chains have fallen into K non-mixing modes,", "to the target, then as `N --> infinity`, R-hat -->", "correlations, then `ESS` can exceed `N`. Some math shows that,", "= tf.reduce_mean(auto_cov[0], cross_chain_dims - 1) # var^+ approx_variance = (", "of a term less than `filter_threshold`. Setting to `None` means", "of `C > 1` independent chains, the potential scale reduction", "first estimating the auto-correlation. Since `R_k` must be estimated using", "equal to `state.shape[1 + independent_chain_ndims:]`. Raises: ValueError: If `independent_chain_ndims <", "1 / C Sum_{c=1}^C x_hat[c], overall mean. # W :=", "sequence variance, the mean of the chain variances. b_div_n =", "Raises: ValueError: If `independent_chain_ndims < 1`. #### Examples Diagnosing convergence", "reduce the noise in the estimate of `R_k`, reducing the", "<NAME>, <NAME>, <NAME>. Rank-normalization, folding, and localization: An improved R-hat", "= [1, 1, 0, 0] mask = tf.maximum(1. - mask,", "this reduces the length of weighted_auto_corr by a factor of", "= _axis_size(state, chain_axis) # In the language of Brooks and", "0.0, 0.3], and filter_threshold = 0.2. # Step 1: mask", "one single Tensor argument.\"\"\" with tf.name_scope('effective_sample_size_single_state'): states = tf.convert_to_tensor(states, name='states')", "dtype_util from tensorflow_probability.python.internal import nest_util from tensorflow_probability.python.internal import prefer_static as", "kernel=tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=target.log_prob, step_size=0.05, num_leapfrog_steps=20)) chains_states.shape ==> (1000, 10, 2) rhat", "<NAME>, <NAME>, <NAME>, Paul-Christian Burkner. Rank-normalization, folding, and localization: An", "first and second halves, treating these as separate chains. This", "R-hat, measures convergence of the chains (to the same target)", "| chain]] ) / E[Var[X | chain]].``` Using the law", "1 + 2 * ( (N - 1) / N", "states = tfp.mcmc.sample_chain( num_burnin_steps=200, num_results=1000, current_state=tf.constant([0., 0.]), trace_fn=None, kernel=tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=target.log_prob,", "can have any shape (even empty). independent_chain_ndims: Integer type `Tensor`", "tf.identity(state) else: assertions = [assert_util.assert_greater( ps.shape(state)[0], 2, message='Must provide at", "number. # Warning! `if split_chains` logic assumes this is 1!", "should also be a list of the same length. Which", "1: reshape into [[0, 1, 2], [3, 4, 5]] #", "None, the shape will be `states.shape[1:]`. Otherwise, the shape is", "4, 5]] # E.g. reshape states of shape [a, b]", "n_samples // 2], state_shape[1:]], axis=0) ) # Step 2: Put", "2 chains. validate_args: Whether to add runtime checks of argument", "`filter_beyond_positive_pairs` means that terms are removed if they were to", "# It still works fine in the formula below. weighted_auto_corr", "`N, C --> infinity`, with `E`, `Var` denoting expectation and", "al. (2019)][2] by specifying the `cross_chain_dims` argument. Cross-chain ESS takes", "for larger `k`. For this reason, the summation over `R_k`", "independent chains that ESS will be summed over. If `None`,", "or Python structure of `Tensor` objects. Must broadcast with `state`.", "[M, 1,...,1], having total # ndims the same as auto_corr", "for any number of chains `C > 1`. Increasing `C`", "for chain convergence. Given `N > 1` states from each", "[Vehtari et al. (2019)][2] by specifying the `cross_chain_dims` argument. Cross-chain", "[2]: <NAME>, <NAME>, <NAME>, <NAME>, <NAME>. Rank-normalization, folding, and localization:", "*args, validate_args=validate_args) with tf.name_scope('effective_sample_size' if name is None else name):", "dtype_util.as_numpy_dtype(state.dtype) is np.int64: state = tf.cast(state, tf.float64) elif dtype_util.is_integer(state.dtype): state", "chains are all drawing from the same distribution, they will", "mask = _sum_pairs(auto_corr) < 0. # Step 2: mask =", "1.2 is used to indicate approximate convergence, but of course", "only measures non-convergence of the mean. If higher moments, or", "- 1. axis=cross_chain_dims - 1) # W * (N -", "dtype_util.is_integer(state.dtype): state = tf.cast(state, tf.float32) with tf.name_scope('potential_scale_reduction_single_state'): # We assume", "variance to reduce the ESS in cases where the chains", "\"\"\" # tf.get_static_value returns None iff a constant value (as", "= tf.maximum(1. - mask, 0.) # N.B. this reduces the", "target = tfd.MultivariateNormalDiag(scale_diag=[1., 2.]) # Get 1000 states from one", "sums are [0.2, 0.1, -0.1, -0.2] # Step 1: mask", "/ (C - 1) Sum_{c=1}^C (x_hat[c] - x_hat)**2, between chain", "step. The `ith` state is assumed to have shape `[Ni,", "this truncation. * `filter_threshold` -- since many MCMC methods generate", "integer `Tensors` corresponding to each state component. If a list", "truncation. * `filter_threshold` -- since many MCMC methods generate chains", "of Vehtari et al. # (2019): # # R[k] :=", "as auto_corr k = tf.range(0., _axis_size(auto_corr, axis=0)) nk_factor = (n", "# W := 1/C Sum_{c=1}^C s_c**2, within-chain variance. # B", "total # ndims the same as auto_corr k = tf.range(0.,", "(1992)'s potential scale reduction for chain convergence. Given `N >", "the Markov Chain. Dimensions `1` through `D` index the `Ci1", "x_len % 2] new_shape = ps.concat([[x_len // 2, 2], ps.shape(x)[1:]],", "`states`.') if num_chains_ is not None: if num_chains_ < 2:", "logic assumes this is 1! sample_ndims = 1 if split_chains:", "from tensorflow_probability.python.internal import assert_util from tensorflow_probability.python.internal import dtype_util from tensorflow_probability.python.internal", "sequence of possibly correlated random variables `X_1, X_2, ..., X_N`,", "= tfd.MultivariateNormalDiag(scale_diag=[1., 2.]) # Get 1000 states from one chain.", "1: mask = [False, False, True, True] mask = _sum_pairs(auto_corr)", "tensorflow_probability as tfp tfd = tfp.distributions target = tfd.MultivariateNormalDiag(scale_diag=[1., 2.])", "of the Markov Chain. Dimensions `1` through `D` index the", "positively auto-correlated, `ESS` will be less than `N`. If there", "c], chain mean. # x_hat := 1 / C Sum_{c=1}^C", "distribution, they will have the same mean, and thus the", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "return _potential_scale_reduction_single_state( s, independent_chain_ndims, split_chains, validate_args) with tf.name_scope('potential_scale_reduction' if name", "reduction for chain convergence. Given `N > 1` states from", "improve effectiveness of the diagnostic. * Sometimes, R-hat < 1.2", "dt) # Step 3: mask = [0, 0, 1, 2]", "effectiveness of the diagnostic. * Sometimes, R-hat < 1.2 is", "`k`. For this reason, the summation over `R_k` should be", "[0.2, 0.1, -0.1, -0.2] # Step 1: mask = [False,", "total variance, the numerator is the variance of the combined", "filter_threshold # Step 2: mask = [0, 0, 1, 0]", "a//2, b] into [a//2, 2, b]. state = tf.transpose( a=state,", "10 of Vehtari et al. # (2019): # # R[k]", "10 independent chains. chains_states = tfp.mcmc.sample_chain( num_burnin_steps=200, num_results=1000, current_state=initial_state, trace_fn=None,", "True, False] mask = auto_corr < filter_threshold # Step 2:", "`1` through `D` index the `Ci1 x ... x CiD`", "< 2: raise ValueError( 'Must provide at least 2 samples.", "4: raise ValueError( 'Must provide at least 4 samples when", "==> [1.05, 1.3] ``` To see why R-hat is reasonable,", "2 * Sum_{k=0}^M R[k] * (N - k) / N}", "`None` means we use no threshold filter. Since `|R_k| <=", "# (2019): # # R[k] := 1 - (W -", "// 2, 2], ps.shape(x)[1:]], axis=0) return tf.reduce_sum(tf.reshape(x, new_shape), 1) #", "import absolute_import from __future__ import division from __future__ import print_function", "Process items, one at a time. def single_state(*args): return _effective_sample_size_single_state(", "/ N * R_1 + ... + 1 / N", "This makes the denominator be C - 1. axis=cross_chain_dims -", "removed if they were to be filtered under the `filter_beyond_lag`", "this argument should also be a list of the same", "1/C * Sum_{c=1}^C s_c**2 R[k, c]) / (var^+), # #", "import tensorshape_util from tensorflow.python.util import nest # pylint: disable=g-direct-tensorflow-import __all__", "broadcast with `state`. The sequence of auto-correlations is truncated after", "```python import tensorflow as tf import tensorflow_probability as tfp tfd", "chain]] ) / E[Var[X | chain]].``` Using the law of", "= tf.convert_to_tensor(states, name='states') dt = states.dtype # filter_beyond_lag == None", "Step 1: reshape into [[0, 1, 2], [3, 4, 5]]", "# Step 1: mask = [False, False, True, False] mask", "file except in compliance with the License. # You may", "4, 5]] into [[0, 3], [1, 4], [2, 5]], #", "0, 1, 2] mask = tf.cumsum(mask, axis=0) # Step 4:", "assertions = [assert_util.assert_greater( ps.shape(state)[0], 4, message='Must provide at least 4", "[2, 5]], # reshaping [2, a//2, b] into [a//2, 2,", "the variance of the combined states, and the denominator is", "{-1 + 2 * Sum_{k=0}^M R[k] * (N - k)", "some variant of this to tfd.sample_stats. def _reduce_variance(x, axis=None, biased=True,", "the individual chain means. If the chains are all drawing", "More precisely, given a stationary sequence of possibly correlated random", "import tensorflow as tf import tensorflow_probability as tfp tfd =", "division from __future__ import print_function import numpy as np import", "the same variance as `state`. More precisely, given a stationary", "`dim = 1` to `dim = D`, holding independent chain", "of Iterative Simulations. _Journal of Computational and Graphical Statistics_, 7(4),", "filter_threshold: `Tensor` or Python structure of `Tensor` objects. Must broadcast", "convergence of MCMC, 2019. Retrieved from http://arxiv.org/abs/1903.08008 \"\"\" if cross_chain_dims", "scale reduction for chain convergence. Given `N > 1` states", "MCMC methods generate chains where `R_k > 0`, a reasonable", "Chain. Dimensions `1` through `D` index the `Ci1 x ...", "within sequence variance, the mean of the chain variances. b_div_n", "the first appearance of a term less than `filter_threshold`. Setting", "used. See [Brooks and Gelman (1998)][2]. Args: chains_states: `Tensor` or", "tensorflow_probability.python import stats from tensorflow_probability.python.internal import assert_util from tensorflow_probability.python.internal import", "this method because it will reduce the noise in the", "it's not a magic number. # Warning! `if split_chains` logic", "N`. This function provides two methods to perform this truncation.", "see if the `state` is a numpy object for the", "Python `bool`. If `True`, divide samples from each chain into", "* Variance{ X_1 }. ``` If the sequence is uncorrelated,", "standard_error = tf.sqrt(variance / ess) ``` #### References [1]: <NAME>,", "- 1/C * Sum_{c=1}^C s_c**2 R[k, c]) / (var^+), #", "this to tfd.sample_stats. def _reduce_variance(x, axis=None, biased=True, keepdims=False): with tf.name_scope('reduce_variance'):", "N Sum_{n=1}^N x[n, c], chain mean. # x_hat := 1", "2], state_shape[1:]], axis=0) ) # Step 2: Put the size", "identically distributed. See [Gelman and Rubin (1992)][1]; [Brooks and Gelman", "mask = [False, False, True, True] mask = _sum_pairs(auto_corr) <", "floats for floating-point division # check to see if the", "pylint: disable=g-direct-tensorflow-import __all__ = [ 'effective_sample_size', 'potential_scale_reduction', ] def effective_sample_size(states,", "Python boolean. If `True`, only consider the initial auto-correlation sequence", "= _axis_size(states, cross_chain_dims) num_chains_ = tf.get_static_value(num_chains) assertions = [] msg", "variance # R[k, m] := auto_corr[k, m, ...], auto-correlation indexed", "= 1. - (biased_within_chain_variance - mean_auto_cov) / approx_variance else: auto_corr", "1, 2] mask = tf.cumsum(mask, axis=0) # Step 4: mask", "`Tensor`s representing the states of a Markov Chain at each", "``` To see why R-hat is reasonable, let `X` be", "The `ith` state is assumed to have shape `[Ni, Ci1,", "`Tensor` objects. Must broadcast with `state`. The sequence of auto-correlations", "diagnostic. * Sometimes, R-hat < 1.2 is used to indicate", "Markov Chain at each result step. The `ith` state is", "Simulation Using Multiple Sequences. _Statistical Science_, 7(4):457-472, 1992. [3]: <NAME>,", "1`. Increasing `C` does improve effectiveness of the diagnostic. *", "we drop the final value. x = x[:x_len - x_len", "name is None else name): return tf.nest.map_structure(single_state, chains_states) def _potential_scale_reduction_single_state(state,", "In general, this will be a smaller number than computing", "N.B. this reduces the length of weighted_auto_corr by a factor", "drawn from a distribution overdispersed with respect to the target.", "0,...] # Building step by step, # Assume auto_corr =", "filter_beyond_lag: `Tensor` or Python structure of `Tensor` objects. Must be", "import assert_util from tensorflow_probability.python.internal import dtype_util from tensorflow_probability.python.internal import nest_util", "KIND, either express or implied. # See the License for", "from # reversible MCMC chains. # E.g. imagine the pairwise", "* n) # TODO(b/72873233) Move some variant of this to", "structure of `Tensor`s representing the states of a Markov Chain", "from each of `C > 1` independent chains, the potential", "filter_threshold, dtype=dt, name='filter_threshold') # Get a binary mask to zero", "chains exceeds what one would expect if the chains were", "chain]] + Var[E[X | chain]] ) / E[Var[X | chain]].```", "Multiple Sequences. _Statistical Science_, 7(4):457-472, 1992. [3]: <NAME>, <NAME>, <NAME>,", "is truncated to this length. Setting to `None` means we", "of the the individual chain means. If the chains are", "tf.reduce_mean(state, axis=sample_axis, keepdims=True), sample_and_chain_axis, biased=False) w = tf.reduce_mean( _reduce_variance(state, sample_axis,", "Tensor argument.\"\"\" with tf.name_scope('effective_sample_size_single_state'): states = tf.convert_to_tensor(states, name='states') dt =", "None: return ps.cast(ps.size(x), x.dtype) return ps.cast( ps.reduce_prod( ps.gather(ps.shape(x), axis)), x.dtype)", "[3, 4, 5]] into [[0, 3], [1, 4], [2, 5]],", "# Define so it's not a magic number. # Warning!", "Put the size `2` dimension in the right place to", "sequence of auto-correlations is truncated to this length. Setting to", "axis=0) if cross_chain_dims is not None: num_chains = _axis_size(states, cross_chain_dims)", "`chains_states` representing the R-hat statistic for the state(s). Same `dtype`", "individual chain means. If the chains are all drawing from", "if filter_beyond_positive_pairs: def _sum_pairs(x): x_len = ps.shape(x)[0] # For odd", "chains where `R_k > 0`, a reasonable criterion is to", "of `Tensor`s representing the states of a Markov Chain at", "Shape (2,) Tensor mean, variance = tf.nn.moments(states, axis=0) standard_error =", "- x_len % 2] new_shape = ps.concat([[x_len // 2, 2],", "Monte Carlo (MCMC) sampling. @@effective_sample_size @@potential_scale_reduction \"\"\" from __future__ import", "(the \"License\"); # you may not use this file except", "auto-correlations is truncated to this length. Setting to `None` means", "Methods for Monitoring Convergence of Iterative Simulations. _Journal of Computational", "what one would expect if the chains were identically distributed.", "_reduce_variance( tf.reduce_mean(state, axis=sample_axis, keepdims=True), sample_and_chain_axis, biased=False) w = tf.reduce_mean( _reduce_variance(state,", "chains that each attempt to sample from a 2-variate normal.", "statistics are desired, a different diagnostic should be used. See", "1998. [2]: <NAME> and <NAME>. Inference from Iterative Simulation Using", "Tensor mean, variance = tf.nn.moments(states, axis=0) standard_error = tf.sqrt(variance /", "to sample from a 2-variate normal. ```python import tensorflow as", "and variance, ```R-hat = ( E[Var[X | chain]] + Var[E[X", "ESS will be summed over. If `None`, no summation is", "`Tensor` or Python structure of `Tensor` objects. Dimension zero should", "assume exactly one leading dimension indexes e.g. correlated samples #", "ESS is the number such that ``` Variance{ N**-1 *", "- (n - 1.) / (m * n) # TODO(b/72873233)", "must be > 1 chain ' 'in `states`.') if num_chains_", "is problem-dependent. See [Brooks and Gelman (1998)][2]. * R-hat only", "or `filter_beyond_positive_pairs. E.g., combining `filter_beyond_lag` and `filter_beyond_positive_pairs` means that terms", "# # Unless required by applicable law or agreed to", "reason, the summation over `R_k` should be truncated at some", "dimensions of `states` to treat as independent chains that ESS", "Note this requires at least 2 chains. validate_args: Whether to", "(N - k) / N} # = N / {-1", "<NAME>. Rank-normalization, folding, and localization: An improved R-hat for assessing", "casting integers to floats for floating-point division # check to", "target_log_prob_fn=target.log_prob, step_size=0.05, num_leapfrog_steps=20)) chains_states.shape ==> (1000, 10, 2) rhat =", "(n / (n - 1.)) * biased_var def _axis_size(x, axis=None):", "type `Tensor` with value `>= 1` giving the number of", "like [1, 1, ..., 0, 0,...] # Building step by", "chains are mixing well it is still preferrable to compute", "provided, then this argument should also be a list of", "1. - (biased_within_chain_variance - mean_auto_cov) / approx_variance else: auto_corr =", "`filter_beyond_positive_pairs` is `True`. filter_beyond_lag: `Tensor` or Python structure of `Tensor`", "truncated to this length. Setting to `None` means we do", "chain. # var^+ := (N - 1) / N *", "for equality of means. Specifically, R-hat measures the degree to", "n_samples_ < 4: raise ValueError( 'Must provide at least 4", "# tf.get_static_value returns None iff a constant value (as a", "split_chains: assertions = [assert_util.assert_greater( ps.shape(state)[0], 4, message='Must provide at least", "shape [M, 1,...,1], having total # ndims the same as", "= 0, otherwise. # So, along dimension zero, the mask", "Same `dtype` as `state`, and shape equal to `state.shape[1 +", "identically distributed, ESS is the number such that ``` Variance{", "Covariance{X_1, X_{1+k}} / Variance{X_1}`, we have ``` ESS(N) = N", "the potential scale reduction factor, commonly referred to as R-hat,", "ESS(N) = N / [ 1 + 2 * (", "state_shape[0] state = state[:n_samples - n_samples % 2] # Suppose", "as `state`, and shape equal to `state.shape[1 + independent_chain_ndims:]`. Raises:", "ess = effective_sample_size(states, filter_beyond_positive_pairs=True) ==> Shape (2,) Tensor mean, variance", "implied. # See the License for the specific language governing", "to this length. Setting to `None` means we do not", "of MCMC, 2019. Retrieved from http://arxiv.org/abs/1903.08008 \"\"\" if cross_chain_dims is", "tf.reduce_mean(states, axis=0), biased=False, # This makes the denominator be C", "filter_beyond_positive_pairs=False, cross_chain_dims=None, validate_args=False, name=None): \"\"\"Estimate a lower bound on effective", "R-hat only measures non-convergence of the mean. If higher moments,", "the threshold. # mask[i, ...] = 1 if auto_corr[j, ...]", "the ratio should be one. #### References [1]: <NAME> and", "# Pairwise sums are all positive for auto-correlation spectra derived", "`>= 1`, found: {}'.format( independent_chain_ndims)) def single_state(s): return _potential_scale_reduction_single_state( s,", "R[k] * (N - k) / N} # = N", "states (combined over all chains). Then, in the limit `N,", "prepend to created tf. Default: `potential_scale_reduction`. Returns: `Tensor` structure parallel", "nest_util.broadcast_structure( states, filter_beyond_positive_pairs) # Process items, one at a time.", "Dimension `0` indexes the `Ni > 1` result steps of", "2] mask = tf.cumsum(mask, axis=0) # Step 4: mask =", "# For odd sequences, we drop the final value. x", "at the first index where the estimated auto-correlation becomes negative.", "assertions = [] msg = ('When `cross_chain_dims` is not `None`,", "with tf.control_dependencies(assertions): state = tf.identity(state) else: assertions = [assert_util.assert_greater( ps.shape(state)[0],", "# Assume auto_corr = [1, 0.5, 0.0, 0.3], and filter_threshold", "tensorflow.compat.v2 as tf from tensorflow_probability.python import stats from tensorflow_probability.python.internal import", "if axis is None: return ps.cast(ps.size(x), x.dtype) return ps.cast( ps.reduce_prod(", "size of an iid sample with the same variance as", "x ... x CiD` independent chains to be tested for", "We assume exactly one leading dimension indexes e.g. correlated samples", "negative. This method does not estimate the `ESS` of super-efficient", "under the `filter_beyond_lag` OR `filter_beyond_positive_pairs` criteria. This function can also", "independent chains, the potential scale reduction factor, commonly referred to", "> threshold for all j <= i, # mask[i, ...]", "auto_corr below the threshold. # mask[i, ...] = 1 if", "respect to the target. * If all chains converge to", "from tensorflow.python.util import nest # pylint: disable=g-direct-tensorflow-import __all__ = [", "is a numpy object for the numpy test suite if", "chains were identically distributed. See [Gelman and Rubin (1992)][1]; [Brooks", "thus the ratio should be one. #### References [1]: <NAME>", "[[0, 1, 2], [3, 4, 5]] into [[0, 3], [1,", "The effective sample size of each component of `states`. If", "states. filter_threshold: `Tensor` or Python structure of `Tensor` objects. Must", "True] mask = _sum_pairs(auto_corr) < 0. # Step 2: mask", "N} # where M is the filter_beyond_lag truncation point chosen", "Sum_{c=1}^C (x_hat[c] - x_hat)**2, between chain # variance. # s_c**2", "identically distributed states. filter_threshold: `Tensor` or Python structure of `Tensor`", "# Step 2: Put the size `2` dimension in the", "truncation point chosen above. # Get the factor (N -", "the denominator is the total variance minus the variance of", "and there are less than 2 chains. #### Examples We", "guidelines: * The initial state of the chains should be", "holding independent chain results to be tested for convergence. split_chains:", "2. ==> (10, 2) # Get 1000 samples from the", "x_hat)**2, between chain # variance. # s_c**2 := 1 /", "representing the R-hat statistic for the state(s). Same `dtype` as", "elif validate_args: assertions.append( assert_util.assert_greater(num_chains, 1., message=msg)) with tf.control_dependencies(assertions): # We're", "Retrieved from http://arxiv.org/abs/1903.08008 \"\"\" # tf.get_static_value returns None iff a", "Unless required by applicable law or agreed to in writing,", "<= i, # mask[i, ...] = 0, otherwise. # So,", "dimension in half, doubling the number of # independent chains.", "This function estimates the above by first estimating the auto-correlation.", "num_burnin_steps=200, num_results=1000, current_state=initial_state, trace_fn=None, kernel=tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=target.log_prob, step_size=0.05, num_leapfrog_steps=20)) chains_states.shape ==>", "Get a binary mask to zero out values of auto_corr", "with tf.name_scope('effective_sample_size' if name is None else name): return nest.map_structure_up_to(", "independent_chain_ndims=1, split_chains=False, validate_args=False, name=None): \"\"\"<NAME> Rubin (1992)'s potential scale reduction", "num_leapfrog_steps=20)) states.shape ==> (1000, 2) ess = effective_sample_size(states, filter_beyond_positive_pairs=True) ==>", "`filter_beyond_positive_pairs` are filters intended to remove noisy tail terms from", "'in `states`.') if num_chains_ is not None: if num_chains_ <", "identical). * The above holds for any number of chains", "a list of `states` is provided, then this argument should", "-0.1, -0.2] # Step 1: mask = [False, False, True,", "steps of the Markov Chain. Dimensions `1` through `D` index", "look like [1, 1, ..., 0, 0,...] # Building step", "the specific language governing permissions and # limitations under the", "`-1` has the same effect. Ignored if `filter_beyond_positive_pairs` is `True`.", "<NAME>, <NAME>, <NAME>, <NAME>. Rank-normalization, folding, and localization: An improved", "independent_chain_ndims = icn_const_ if icn_const_ < 1: raise ValueError( 'Argument", "samples. Found {}'.format(n_samples_)) elif validate_args: if split_chains: assertions = [assert_util.assert_greater(", "new_shape = ps.concat([[x_len // 2, 2], ps.shape(x)[1:]], axis=0) return tf.reduce_sum(tf.reshape(x,", "- 1) / n) * w + b_div_n return ((m", "not filter based on the size of lags. filter_beyond_positive_pairs: Python", "mixing well it is still preferrable to compute cross-chain ESS", "chain was drawn from the target. c.f. \"law of total", "R-hat for assessing convergence of MCMC, 2019. Retrieved from http://arxiv.org/abs/1903.08008", "else: auto_corr = auto_cov / auto_cov[:1] num_chains = 1 #", "This makes R-hat more robust to non-stationary chains, and is", "auto-correlation indexed by chain. # var^+ := (N - 1)", "the length of weighted_auto_corr by a factor of 2. #", "sequence, `R_k := Covariance{X_1, X_{1+k}} / Variance{X_1}`, we have ```", "# ndims the same as auto_corr k = tf.range(0., _axis_size(auto_corr,", "= tfp.mcmc.diagnostic.potential_scale_reduction( chains_states, independent_chain_ndims=1) # The second dimension needed a", "to add runtime checks of argument validity. If False, and", "2 chains, so increment. independent_chain_ndims += 1 sample_axis = ps.range(0,", "auto_corr < filter_threshold # Step 2: mask = [0, 0,", "split_chains: Python `bool`. If `True`, divide samples from each chain", "is not None: # If available statically. if split_chains and", "4 samples when splitting chains.')] with tf.control_dependencies(assertions): state = tf.identity(state)", "- mask, 0.) # N.B. this reduces the length of", "works fine in the formula below. weighted_auto_corr = _sum_pairs(weighted_auto_corr) *", "`>= 1` giving the number of dimensions, from `dim =", "there are negative correlations, then `ESS` can exceed `N`. Some", "= (n - k) / n if tensorshape_util.rank(auto_corr.shape) is not", "`Tensor` with value `>= 1` giving the number of dimensions,", "/ N} # where M is the filter_beyond_lag truncation point", "no threshold filter. Since `|R_k| <= 1`, setting to any", "( E[Var[X | chain]] + Var[E[X | chain]] ) /", "summation over `R_k` should be truncated at some number `filter_beyond_lag", "n is the between chain variance, the variance of the", "`E`, `Var` denoting expectation and variance, ```R-hat = ( E[Var[X", "If the sequence is uncorrelated, `ESS = N`. If the", "auto-correlation sequence where the pairwise sums become non-positive. The arguments", "= state_shape[0] state = state[:n_samples - n_samples % 2] #", "tf.identity(state) # Define so it's not a magic number. #", "via this method because it will reduce the noise in", "needed a longer burn-in. rhat.eval() ==> [1.05, 1.3] ``` To", "splitting chains.')] with tf.control_dependencies(assertions): state = tf.identity(state) else: assertions =", "< 1.2 is used to indicate approximate convergence, but of", "tf.ones([tf.rank(auto_corr) - 1], dtype=tf.int32)), axis=0) nk_factor = tf.reshape(nk_factor, new_shape) weighted_auto_corr", "n) * w + b_div_n return ((m + 1.) /", "shapes. ValueError: If `cross_chain_dims` is not `None` and there are", "# Building step by step, # Assume auto_corr = [1,", "Statistics_, 7(4), 1998. [2]: <NAME> and <NAME>. Inference from Iterative", "division # check to see if the `state` is a", "extreme case where the chains have fallen into K non-mixing", "`filter_beyond_positive_pairs` -- reversible MCMC chains produce an auto-correlation sequence with", "remove noisy tail terms from `R_k`. You can combine `filter_beyond_lag`", "the variance of the chain means. # W is the", "# check to see if the `state` is a numpy", "derived from # reversible MCMC chains. # E.g. imagine the", "x_hat[c] := 1 / N Sum_{n=1}^N x[n, c], chain mean.", "``` This function estimates the above by first estimating the", "used to indicate approximate convergence, but of course this is", "minus the variance of the the individual chain means. If", "states: `Tensor` or Python structure of `Tensor` objects. Dimension zero", "Using Multiple Sequences. _Statistical Science_, 7(4):457-472, 1992. [3]: <NAME>, <NAME>,", "`Ci1 x ... x CiD` independent chains to be tested", "state = tf.convert_to_tensor(state, name='state') n_samples_ = tf.compat.dimension_value(state.shape[0]) if n_samples_ is", "False, and arguments are incorrect, correct behavior is not guaranteed.", "[2, a//2, b] into [a//2, 2, b]. state = tf.transpose(", "individual chains and then summing them. In an extreme case", "is the between chain variance, the variance of the chain", "are incorrect, correct behavior is not guaranteed. name: `String` name", "of super-efficient chains (where `ESS > N`) correctly. * `filter_beyond_positive_pairs`", "property that pairwise sums of the elements of that sequence", "are positive. cross_chain_dims: An integer `Tensor` or a structure of", "# E.g. imagine the pairwise sums are [0.2, 0.1, -0.1,", "from the combined states (combined over all chains). Then, in", "return (n / (n - 1.)) * biased_var def _axis_size(x,", "and second halves, treating these as separate chains. This makes", "constant_value then # check for None. icn_const_ = tf.get_static_value( ps.convert_to_shape_tensor(independent_chain_ndims))", "X_N`, identically distributed, ESS is the number such that ```", "is uncorrelated, `ESS = N`. If the sequence is positively", "R_{N-1} ) ] ``` This function estimates the above by", "0, otherwise. # So, along dimension zero, the mask will", "in half, doubling the number of # independent chains. #", "`Tensor` objects. Dimension zero should index identically distributed states. filter_threshold:", "==> (10, 2) # Get 1000 samples from the 10", "of the combined states, and the denominator is the total", "split_chains, validate_args): \"\"\"potential_scale_reduction for one single state `Tensor`.\"\"\" # casting", "- 1) / N * W + B / N", "all j <= i, # mask[i, ...] = 0, otherwise.", "estimates the above by first estimating the auto-correlation. Since `R_k`", "a longer burn-in. rhat.eval() ==> [1.05, 1.3] ``` To see", "= N`. If the sequence is positively auto-correlated, `ESS` will", "for None. icn_const_ = tf.get_static_value( ps.convert_to_shape_tensor(independent_chain_ndims)) if icn_const_ is not", "object for the numpy test suite if dtype_util.as_numpy_dtype(state.dtype) is np.int64:", "effective_sample_size(states, filter_threshold=0., filter_beyond_lag=None, filter_beyond_positive_pairs=False, cross_chain_dims=None, validate_args=False, name=None): \"\"\"Estimate a lower", "each Markov chain. state = tf.convert_to_tensor(state, name='state') n_samples_ = tf.compat.dimension_value(state.shape[0])", "tf.transpose( a=state, perm=ps.concat( [[1, 0], ps.range(2, ps.rank(state))], axis=0)) # We're", "1 / N * R_{N-1} ) ] ``` This function", "k) / N} # where M is the filter_beyond_lag truncation", "(N - k) / N} (since R[0] = 1) #", "giving the number of dimensions, from `dim = 1` to", "the pairwise sums are positive. cross_chain_dims: An integer `Tensor` or", "1`, setting to any number less than `-1` has the", "def single_state(s): return _potential_scale_reduction_single_state( s, independent_chain_ndims, split_chains, validate_args) with tf.name_scope('potential_scale_reduction'", "zero should index identically distributed states. filter_threshold: `Tensor` or Python", "treating these as separate chains. This makes R-hat more robust", "0.) weighted_auto_corr *= mask return num_chains * n / (-1", "an iid sample with the same variance as `state`. More", ") ] ``` This function estimates the above by first", "from __future__ import print_function import numpy as np import tensorflow.compat.v2", "name: `String` name to prepend to created ops. Returns: ess:", "state = tf.cast(state, tf.float64) elif dtype_util.is_integer(state.dtype): state = tf.cast(state, tf.float32)", "chains. This makes R-hat more robust to non-stationary chains, and", "above by first estimating the auto-correlation. Since `R_k` must be", "tf from tensorflow_probability.python import stats from tensorflow_probability.python.internal import assert_util from", "# x_hat[c] := 1 / N Sum_{n=1}^N x[n, c], chain", "The TensorFlow Probability Authors. # # Licensed under the Apache", "If the sequence is positively auto-correlated, `ESS` will be less", "each state component. If a list of `states` is provided,", "s, independent_chain_ndims, split_chains, validate_args) with tf.name_scope('potential_scale_reduction' if name is None", "structure of `Tensor` objects. Dimension zero should index identically distributed", "validate_args: Whether to add runtime checks of argument validity. If", "or `states` and `filter_beyond_lag` are both structures of different shapes.", "corresponding to each state component. If a list of `states`", "tensorflow as tf import tensorflow_probability as tfp tfd = tfp.distributions", "`N`. If there are negative correlations, then `ESS` can exceed", "Step 1: mask = [False, False, True, True] mask =", "# With R[k] := auto_corr[k, ...], # ESS = N", "chain]].``` Using the law of total variance, the numerator is", "of an iid sample with the same variance as `state`.", "axis=0)) nk_factor = (n - k) / n if tensorshape_util.rank(auto_corr.shape)", "and give it shape [M, 1,...,1], having total # ndims", "- (W - 1/C * Sum_{c=1}^C s_c**2 R[k, c]) /", "(where `ESS > N`) correctly. * `filter_beyond_positive_pairs` -- reversible MCMC", "None) filter_beyond_lag = nest_util.broadcast_structure(states, filter_beyond_lag) filter_threshold = nest_util.broadcast_structure(states, filter_threshold) filter_beyond_positive_pairs", "number of chains # N := length of chains #", "absolute_import from __future__ import division from __future__ import print_function import", "`N --> infinity`, R-hat --> 1. Before that, R-hat >", "False, True, False] mask = auto_corr < filter_threshold # Step", "var^+ := (N - 1) / N * W +", "if name is None else name): return tf.nest.map_structure(single_state, chains_states) def", "same length. Which dimensions of `states` to treat as independent", "n) # TODO(b/72873233) Move some variant of this to tfd.sample_stats.", "ValueError( 'Must provide at least 2 samples. Found {}'.format(n_samples_)) elif", "Raises: ValueError: If `states` and `filter_threshold` or `states` and `filter_beyond_lag`", "into [2, a//2, b]. state = tf.reshape( state, ps.concat([[2, n_samples", "the right place to be treated as a # chain,", "* Sum_{c=1}^C s_c**2 R[k, c] mean_auto_cov = tf.reduce_mean(auto_cov, cross_chain_dims) auto_corr", "filter_threshold, filter_beyond_positive_pairs, cross_chain_dims) def _effective_sample_size_single_state(states, filter_beyond_lag, filter_threshold, filter_beyond_positive_pairs, cross_chain_dims, validate_args):", "(biased_within_chain_variance - mean_auto_cov) / approx_variance else: auto_corr = auto_cov /", "using only `N - k` samples, it becomes progressively noisier", "`filter_beyond_positive_pairs. E.g., combining `filter_beyond_lag` and `filter_beyond_positive_pairs` means that terms are", "filter_threshold = 0.2. # Step 1: mask = [False, False,", "not a magic number. # Warning! `if split_chains` logic assumes", "chain # variance. # s_c**2 := 1 / (N -", "* Sum_{k=0}^M R[k] * (N - k) / N} #", "def single_state(*args): return _effective_sample_size_single_state( *args, validate_args=validate_args) with tf.name_scope('effective_sample_size' if name", "axis=0) # Step 4: mask = [1, 1, 0, 0]", "over. If `None`, no summation is performed. Note this requires", "0.2. # Step 1: mask = [False, False, True, False]", "state = tf.cast(state, tf.float32) with tf.name_scope('potential_scale_reduction_single_state'): # We assume exactly", "with tf.name_scope('potential_scale_reduction_single_state'): # We assume exactly one leading dimension indexes", "__future__ import division from __future__ import print_function import numpy as", "speaking, \"effective sample size\" (ESS) is the size of an", "= tfp.mcmc.sample_chain( num_burnin_steps=200, num_results=1000, current_state=tf.constant([0., 0.]), trace_fn=None, kernel=tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=target.log_prob, step_size=0.05,", "and Gelman (1998)][2]. * R-hat only measures non-convergence of the", "least 4 samples when splitting chains.')] with tf.control_dependencies(assertions): state =", "= nest_util.broadcast_structure( states, filter_beyond_positive_pairs) # Process items, one at a", "different diagnostic should be used. See [Brooks and Gelman (1998)][2].", "the chains are all drawing from the same distribution, they", "behavior is not guaranteed. name: `String` name to prepend to", "`states` and `filter_beyond_lag` are both structures of different shapes. ValueError:", "============================================================================ \"\"\"Utilities for Markov Chain Monte Carlo (MCMC) sampling. @@effective_sample_size", "the state(s). Same `dtype` as `state`, and shape equal to", "`Ni > 1` result steps of the Markov Chain. Dimensions", "we try constant_value then # check for None. icn_const_ =", "cross_chain_dims) def _effective_sample_size_single_state(states, filter_beyond_lag, filter_threshold, filter_beyond_positive_pairs, cross_chain_dims, validate_args): \"\"\"ESS computation", "must be estimated using only `N - k` samples, it", "You may obtain a copy of the License at #", "auto-correlation sequence, `R_k := Covariance{X_1, X_{1+k}} / Variance{X_1}`, we have", "If `states` and `filter_threshold` or `states` and `filter_beyond_lag` are both", "'effective_sample_size', 'potential_scale_reduction', ] def effective_sample_size(states, filter_threshold=0., filter_beyond_lag=None, filter_beyond_positive_pairs=False, cross_chain_dims=None, validate_args=False,", "ESS in cases where the chains are not mixing well.", "split_chains: # Split the sample dimension in half, doubling the", "desired, a different diagnostic should be used. See [Brooks and", "ess) ``` #### References [1]: <NAME>, Practical Markov chain Monte", "Iterative Simulation Using Multiple Sequences. _Statistical Science_, 7(4):457-472, 1992. [3]:", "states.shape ==> (1000, 2) ess = effective_sample_size(states, filter_beyond_positive_pairs=True) ==> Shape", "tf.get_static_value returns None iff a constant value (as a numpy", "--> infinity`, R-hat --> 1. Before that, R-hat > 1", "#### References [1]: <NAME>, Practical Markov chain Monte Carlo (with", "the total variance minus the variance of the the individual", "governing permissions and # limitations under the License. # ============================================================================", "3], [1, 4], [2, 5]], # reshaping [2, a//2, b]", "of chains # x_hat[c] := 1 / N Sum_{n=1}^N x[n,", "be less than `N`. If there are negative correlations, then", "chains, the potential scale reduction factor, commonly referred to as", "' 'Found {}'.format(n_samples_)) if not split_chains and n_samples_ < 2:", "E.g. imagine the pairwise sums are [0.2, 0.1, -0.1, -0.2]", "chains. validate_args: Whether to add runtime checks of argument validity.", "MCMC, 2019. Retrieved from http://arxiv.org/abs/1903.08008 \"\"\" if cross_chain_dims is None:", "ps.shape(x)[1:]], axis=0) return tf.reduce_sum(tf.reshape(x, new_shape), 1) # Pairwise sums are", "different shapes. ValueError: If `cross_chain_dims` is not `None` and there", "target.sample(10) * 2. ==> (10, 2) # Get 1000 samples", "not split_chains and n_samples_ < 2: raise ValueError( 'Must provide", "number of samples, keep all but the last sample. state_shape", "positive. cross_chain_dims: An integer `Tensor` or a structure of integer", "permissions and # limitations under the License. # ============================================================================ \"\"\"Utilities", "the number of dimensions, from `dim = 1` to `dim", "= _axis_size(x, axis) return (n / (n - 1.)) *", "parallel to `states`. The effective sample size of each component", "Computational and Graphical Statistics_, 7(4), 1998. [2]: <NAME> and <NAME>.", "a smaller number than computing the ESS for individual chains", "elements of that sequence are positive [Geyer][1], i.e. `R_{2k} +", "sigma_2_plus = ((n - 1) / n) * w +", "+ ... + 1 / N * R_{N-1} ) ]", "+ 2 * ( (N - 1) / N *", "there are less than 2 chains. #### Examples We use", "see why R-hat is reasonable, let `X` be a random", "(1992)][1]; [Brooks and Gelman (1998)][2]. Some guidelines: * The initial", "all positive for auto-correlation spectra derived from # reversible MCMC", "weighted_auto_corr by a factor of 2. # It still works", "# Get 1000 states from one chain. states = tfp.mcmc.sample_chain(", "1 sample_axis = ps.range(0, sample_ndims) chain_axis = ps.range(sample_ndims, sample_ndims +", "1) / N * R_1 + ... + 1 /", "tf.nn.moments(states, axis=0) standard_error = tf.sqrt(variance / ess) ``` #### References", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "( biased_within_chain_variance + between_chain_variance_div_n) # 1/C * Sum_{c=1}^C s_c**2 R[k,", "samples, it becomes progressively noisier for larger `k`. For this", "function can also compute cross-chain ESS following [Vehtari et al.", "_reduce_variance( tf.reduce_mean(states, axis=0), biased=False, # This makes the denominator be", "e.g. if the chain paths were identical). * The above", "1: mask = [False, False, True, False] mask = auto_corr", "as `N --> infinity`, R-hat --> 1. Before that, R-hat", "sample with the same variance as `state`. More precisely, given", "was drawn from the target. c.f. \"law of total variance.\"", "0, 1, 0] mask = tf.cast(mask, dtype=dt) # Step 3:", "are removed if they were to be filtered under the", "mask = auto_corr < filter_threshold # Step 2: mask =", "samples # from each Markov chain. state = tf.convert_to_tensor(state, name='state')", "[1, 1, 0, 0] mask = tf.maximum(1. - mask, 0.)", "icn_const_ < 1: raise ValueError( 'Argument `independent_chain_ndims` must be `>=", "n if tensorshape_util.rank(auto_corr.shape) is not None: new_shape = [-1] +", "R_{2k + 1} > 0` for `k in {0, ...,", "See [Gelman and Rubin (1992)][1]; [Brooks and Gelman (1998)][2]. Some", "+ 2 * Sum_{k=0}^N R[k] * (N - k) /", "mask = [0, 0, 1, 1] mask = tf.cast(mask, dt)", "`filter_beyond_lag` and `filter_beyond_positive_pairs` means that terms are removed if they", "modes, this function will return ESS ~ K. Even when", "..., 0, 0,...] # Building step by step, # Assume", "2-variate normal. ```python import tensorflow as tf import tensorflow_probability as", "message='Must provide at least 4 samples when splitting chains.')] with", "`filter_threshold` or `states` and `filter_beyond_lag` are both structures of different", "==> (1000, 10, 2) rhat = tfp.mcmc.diagnostic.potential_scale_reduction( chains_states, independent_chain_ndims=1) #", "filter_beyond_positive_pairs: Python boolean. If `True`, only consider the initial auto-correlation", "ps.convert_to_shape_tensor(independent_chain_ndims)) if icn_const_ is not None: independent_chain_ndims = icn_const_ if", "- 1.)) * biased_var def _axis_size(x, axis=None): \"\"\"Get number of", "`None`, there must be > 1 chain ' 'in `states`.')", "(N - k) / N, and give it shape [M,", "Retrieved from http://arxiv.org/abs/1903.08008 \"\"\" if cross_chain_dims is None: cross_chain_dims =", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "The sequence of auto-correlations is truncated to this length. Setting", "for convergence to the same target. The remaining dimensions, `A`,", "License. # You may obtain a copy of the License", "= [0, 0, 1, 1] mask = tf.cumsum(mask, axis=0) #", "# Get 1000 samples from the 10 independent chains. chains_states", "variance (of the means) between chains exceeds what one would", "*= mask return num_chains * n / (-1 + 2", "return nest.map_structure_up_to( states, single_state, states, filter_beyond_lag, filter_threshold, filter_beyond_positive_pairs, cross_chain_dims) def", "tf.reduce_mean( _reduce_variance(state, sample_axis, keepdims=True, biased=False), axis=sample_and_chain_axis) # sigma^2_+ is an", "The second dimension needed a longer burn-in. rhat.eval() ==> [1.05,", "and Gelman (1998), # B / n is the between", "variance of the the individual chain means. If the chains", "weighted_auto_corr = _sum_pairs(weighted_auto_corr) * mask elif filter_threshold is not None:", "_Statistical Science_, 7(4):457-472, 1992. [3]: <NAME>, <NAME>, <NAME>, <NAME>, Paul-Christian", "sigma^2_+ is an estimate of the true variance, which would", "2, message='Must provide at least 2 samples.')] with tf.control_dependencies(assertions): state", "mask = [0, 0, 1, 1] mask = tf.cumsum(mask, axis=0)", "nk_factor = (n - k) / n if tensorshape_util.rank(auto_corr.shape) is", "= tf.reduce_mean(auto_cov, cross_chain_dims) auto_corr = 1. - (biased_within_chain_variance - mean_auto_cov)", "= 1` to `dim = D`, holding independent chain results", "sequence where the pairwise sums are positive. cross_chain_dims: An integer", "Since `|R_k| <= 1`, setting to any number less than", "prepend to created ops. Returns: ess: `Tensor` structure parallel to", "from the same distribution, they will have the same mean,", "is reasonable, let `X` be a random variable drawn uniformly", "else name): return nest.map_structure_up_to( states, single_state, states, filter_beyond_lag, filter_threshold, filter_beyond_positive_pairs,", "least 2 samples.')] with tf.control_dependencies(assertions): state = tf.identity(state) # Define", "only possible due to noise. This method truncates the auto-correlation", "tfd = tfp.distributions target = tfd.MultivariateNormalDiag(scale_diag=[1., 2.]) # Get 1000", "single_state(s): return _potential_scale_reduction_single_state( s, independent_chain_ndims, split_chains, validate_args) with tf.name_scope('potential_scale_reduction' if", "reduction factor, commonly referred to as R-hat, measures convergence of", "# variance # R[k, m] := auto_corr[k, m, ...], auto-correlation", "1,...,1], having total # ndims the same as auto_corr k", "is assumed to have shape `[Ni, Ci1, Ci2,...,CiD] + A`.", "over all chains). Then, in the limit `N, C -->", "Step 4: mask = [1, 1, 0, 0] mask =", "This method truncates the auto-correlation sequence where the pairwise sums", "length. Setting to `None` means we do not filter based", "of `Tensor` objects. Must broadcast with `state`. The sequence of", "a distribution overdispersed with respect to the target. * If", "def effective_sample_size(states, filter_threshold=0., filter_beyond_lag=None, filter_beyond_positive_pairs=False, cross_chain_dims=None, validate_args=False, name=None): \"\"\"Estimate a", "validate_args=False, name=None): \"\"\"Estimate a lower bound on effective sample size", "Increasing `C` does improve effectiveness of the diagnostic. * Sometimes,", "objects. Must broadcast with `state`. The sequence of auto-correlations is", "consider the initial auto-correlation sequence where the pairwise sums are", "is provided, then this argument should also be a list", "any number of chains `C > 1`. Increasing `C` does", "the R-hat statistic for the state(s). Same `dtype` as `state`,", "the mask will look like [1, 1, ..., 0, 0,...]", "if # each chain was drawn from the target. c.f.", "(of the means) between chains exceeds what one would expect", "axis=0) ) # Step 2: Put the size `2` dimension", "fallen into K non-mixing modes, this function will return ESS", "C Sum_{c=1}^C x_hat[c], overall mean. # W := 1/C Sum_{c=1}^C", "= [0, 0, 1, 1] mask = tf.cast(mask, dt) #", "chains that ESS will be summed over. If `None`, no", "# 1/C * Sum_{c=1}^C s_c**2 R[k, c] mean_auto_cov = tf.reduce_mean(auto_cov,", "are [0.2, 0.1, -0.1, -0.2] # Step 1: mask =", "num_chains_ = tf.get_static_value(num_chains) assertions = [] msg = ('When `cross_chain_dims`", "approximate convergence, but of course this is problem-dependent. See [Brooks", "If available statically. if split_chains and n_samples_ < 4: raise", "_axis_size(state, chain_axis) # In the language of Brooks and Gelman", "with `state`. The sequence of auto-correlations is truncated after the", "to be tested for convergence to the same target. The", "means. # W is the within sequence variance, the mean", "independent chains. chains_states = tfp.mcmc.sample_chain( num_burnin_steps=200, num_results=1000, current_state=initial_state, trace_fn=None, kernel=tfp.mcmc.HamiltonianMonteCarlo(", "variance minus the variance of the the individual chain means.", "be `states.shape[1:]`. Otherwise, the shape is `tf.reduce_mean(states, cross_chain_dims).shape[1:]`. Raises: ValueError:", "/ w - (n - 1.) / (m * n)", "the `Ci1 x ... x CiD` independent chains to be", "if split_chains: # Split the sample dimension in half, doubling", "True, True] mask = _sum_pairs(auto_corr) < 0. # Step 2:", "the sample dimension in half, doubling the number of #", "import numpy as np import tensorflow.compat.v2 as tf from tensorflow_probability.python", "potential scale reduction factor, commonly referred to as R-hat, measures", "rhat.eval() ==> [1.05, 1.3] ``` To see why R-hat is", "cross_chain_dims=None, validate_args=False, name=None): \"\"\"Estimate a lower bound on effective sample", "where the estimated auto-correlation becomes negative. This method does not", "tf.maximum(1. - mask, 0.) # N.B. this reduces the length", "tfp tfd = tfp.distributions target = tfd.MultivariateNormalDiag(scale_diag=[1., 2.]) # Get", "Using the law of total variance, the numerator is the", "the first index where the estimated auto-correlation becomes negative. This", "(n - 1.) / (m * n) # TODO(b/72873233) Move", "reasonable, let `X` be a random variable drawn uniformly from", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "and filter_threshold = 0.2. # Step 1: mask = [False,", "import nest # pylint: disable=g-direct-tensorflow-import __all__ = [ 'effective_sample_size', 'potential_scale_reduction',", "the target, then as `N --> infinity`, R-hat --> 1.", "state = tf.reshape( state, ps.concat([[2, n_samples // 2], state_shape[1:]], axis=0)", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "0.5, 0.0, 0.3], and filter_threshold = 0.2. # Step 1:", "# # R[k] := 1 - (W - 1/C *", "in `axis`, as type `x.dtype`.\"\"\" if axis is None: return", "( (N - 1) / N * R_1 + ...", "assert_util.assert_greater(num_chains, 1., message=msg)) with tf.control_dependencies(assertions): # We're computing the R[k]", "testing for equality of means. Specifically, R-hat measures the degree", "language governing permissions and # limitations under the License. #", "where the chains have fallen into K non-mixing modes, this", "the License. # ============================================================================ \"\"\"Utilities for Markov Chain Monte Carlo", "required by applicable law or agreed to in writing, software", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "[[1, 0], ps.range(2, ps.rank(state))], axis=0)) # We're treating the new", "[1]: <NAME> and <NAME>. General Methods for Monitoring Convergence of", "k` samples, it becomes progressively noisier for larger `k`. For", "from `R_k`. You can combine `filter_beyond_lag` with `filter_threshold` or `filter_beyond_positive_pairs.", "1992. [2]: <NAME>, <NAME>, <NAME>, <NAME>, <NAME>. Rank-normalization, folding, and", "* (N - k) / N} (since R[0] = 1)", "Roughly speaking, \"effective sample size\" (ESS) is the size of", "# approx N / {-1 + 2 * Sum_{k=0}^M R[k]", "variant of this to tfd.sample_stats. def _reduce_variance(x, axis=None, biased=True, keepdims=False):", "for all j <= i, # mask[i, ...] = 0,", "/ {-1 + 2 * Sum_{k=0}^M R[k] * (N -", "result step. The `ith` state is assumed to have shape", "mean_auto_cov = tf.reduce_mean(auto_cov, cross_chain_dims) auto_corr = 1. - (biased_within_chain_variance -", "name='filter_threshold') # Get a binary mask to zero out values", "threshold filter. Since `|R_k| <= 1`, setting to any number", "function estimates the above by first estimating the auto-correlation. Since", "why R-hat is reasonable, let `X` be a random variable", "agreed to in writing, software # distributed under the License", "1) else: new_shape = tf.concat( ([-1], tf.ones([tf.rank(auto_corr) - 1], dtype=tf.int32)),", "the the individual chain means. If the chains are all", "independent_chain_ndims) n = _axis_size(state, sample_axis) m = _axis_size(state, chain_axis) #", "`state`. The sequence of auto-correlations is truncated after the first", "effective sample size for each independent chain. Roughly speaking, \"effective", "distributed under the License is distributed on an \"AS IS\"", "dim as indexing 2 chains, so increment. independent_chain_ndims += 1", "that ``` Variance{ N**-1 * Sum{X_i} } = ESS**-1 *", "* (tensorshape_util.rank(auto_corr.shape) - 1) else: new_shape = tf.concat( ([-1], tf.ones([tf.rank(auto_corr)", "1000 states from one chain. states = tfp.mcmc.sample_chain( num_burnin_steps=200, num_results=1000,", "* W + B / N cross_chain_dims = ps.non_negative_axis( cross_chain_dims,", "of 2. # It still works fine in the formula", "tf. Default: `potential_scale_reduction`. Returns: `Tensor` structure parallel to `chains_states` representing", "`filter_threshold`. Setting to `None` means we use no threshold filter.", "\"law of total variance.\" sigma_2_plus = ((n - 1) /", "the final value. x = x[:x_len - x_len % 2]", "index the `Ci1 x ... x CiD` independent chains to", "numpy test suite if dtype_util.as_numpy_dtype(state.dtype) is np.int64: state = tf.cast(state,", "target. The remaining dimensions, `A`, can have any shape (even", "states, filter_beyond_positive_pairs) # Process items, one at a time. def", "1 (except in pathological cases, e.g. if the chain paths", "not mixing well. In general, this will be a smaller", "to compute cross-chain ESS via this method because it will", "x_hat[c], overall mean. # W := 1/C Sum_{c=1}^C s_c**2, within-chain", "<NAME>, Practical Markov chain Monte Carlo (with discussion). Statistical Science,", "/ n if tensorshape_util.rank(auto_corr.shape) is not None: new_shape = [-1]", "None iff a constant value (as a numpy # array)", "axis=0)) # We're treating the new dim as indexing 2", "n = _axis_size(state, sample_axis) m = _axis_size(state, chain_axis) # In", "a Markov Chain at each result step. The `ith` state", "Setting to `None` means we use no threshold filter. Since", "is None, the shape will be `states.shape[1:]`. Otherwise, the shape", "tf.float32) with tf.name_scope('potential_scale_reduction_single_state'): # We assume exactly one leading dimension", "also be a list of the same length. Which dimensions", "[0, 1, 2, 3, 4, 5] # Step 1: reshape", "def _potential_scale_reduction_single_state(state, independent_chain_ndims, split_chains, validate_args): \"\"\"potential_scale_reduction for one single state", "value (as a numpy # array) is not efficiently computable.", "the mean. If higher moments, or other statistics are desired,", "state_shape = ps.shape(state) n_samples = state_shape[0] state = state[:n_samples -", "the chain paths were identical). * The above holds for", "means that terms are removed if they were to be", "In an extreme case where the chains have fallen into", "convergence. split_chains: Python `bool`. If `True`, divide samples from each", "least 4 samples when splitting chains. ' 'Found {}'.format(n_samples_)) if", "with tf.name_scope('reduce_variance'): x = tf.convert_to_tensor(x, name='x') mean = tf.reduce_mean(x, axis=axis,", "+ independent_chain_ndims) sample_and_chain_axis = ps.range( 0, sample_ndims + independent_chain_ndims) n", "<NAME>, <NAME>, <NAME>, <NAME>, <NAME>. Rank-normalization, folding, and localization: An", "less than `N`. If there are negative correlations, then `ESS`", "`R_k := Covariance{X_1, X_{1+k}} / Variance{X_1}`, we have ``` ESS(N)", "tfp.distributions target = tfd.MultivariateNormalDiag(scale_diag=[1., 2.]) # Get 1000 states from", "pathological cases, e.g. if the chain paths were identical). *", "non-stationary chains, and is recommended in [3]. validate_args: Whether to", "0` for `k in {0, ..., N/2}`. Deviations are only", "to have shape `[Ni, Ci1, Ci2,...,CiD] + A`. Dimension `0`", "as ps from tensorflow_probability.python.internal import tensorshape_util from tensorflow.python.util import nest", "progressively noisier for larger `k`. For this reason, the summation", "is not None: new_shape = [-1] + [1] * (tensorshape_util.rank(auto_corr.shape)", "= [ 'effective_sample_size', 'potential_scale_reduction', ] def effective_sample_size(states, filter_threshold=0., filter_beyond_lag=None, filter_beyond_positive_pairs=False,", "combined states, and the denominator is the total variance minus", "numpy # array) is not efficiently computable. Therefore, we try", "`bool`. If `True`, divide samples from each chain into first", "terms are removed if they were to be filtered under", "<NAME>, <NAME>, Paul-Christian Burkner. Rank-normalization, folding, and localization: An improved", "as tf import tensorflow_probability as tfp tfd = tfp.distributions target", "the combined states, and the denominator is the total variance", "if the `state` is a numpy object for the numpy", "2 samples.')] with tf.control_dependencies(assertions): state = tf.identity(state) # Define so", "chains produce an auto-correlation sequence with the property that pairwise", "variance as `state`. More precisely, given a stationary sequence of", "<NAME>, <NAME>, <NAME>, <NAME>, Paul-Christian Burkner. Rank-normalization, folding, and localization:", "icn_const_ if icn_const_ < 1: raise ValueError( 'Argument `independent_chain_ndims` must", "assumes this is 1! sample_ndims = 1 if split_chains: #", "`ESS` will be less than `N`. If there are negative", "efficiently computable. Therefore, we try constant_value then # check for", "we do not filter based on the size of lags.", "OR CONDITIONS OF ANY KIND, either express or implied. #", "problem-dependent. See [Brooks and Gelman (1998)][2]. * R-hat only measures", "# Warning! `if split_chains` logic assumes this is 1! sample_ndims", "== None ==> auto_corr is the full sequence. auto_cov =", "= [0, 1, 2, 3, 4, 5] # Step 1:", "name to prepend to created ops. Returns: ess: `Tensor` structure", "# s_c**2 := 1 / (N - 1) Sum_{n=1}^N (x[n,", "the License is distributed on an \"AS IS\" BASIS, #", "to zero out values of auto_corr below the threshold. #", "is truncated after the first appearance of a term less", "list of `states` is provided, then this argument should also", "Carlo (with discussion). Statistical Science, 7:473-511, 1992. [2]: <NAME>, <NAME>,", "@@potential_scale_reduction \"\"\" from __future__ import absolute_import from __future__ import division", "...], # ESS = N / {1 + 2 *", "as separate chains. This makes R-hat more robust to non-stationary", "sample_ndims = 1 if split_chains: # Split the sample dimension", "between_chain_variance_div_n = _reduce_variance( tf.reduce_mean(states, axis=0), biased=False, # This makes the", "x_hat := 1 / C Sum_{c=1}^C x_hat[c], overall mean. #", "= nest_util.broadcast_structure(states, filter_beyond_lag) filter_threshold = nest_util.broadcast_structure(states, filter_threshold) filter_beyond_positive_pairs = nest_util.broadcast_structure(", "to reduce the ESS in cases where the chains are", "state[:n_samples - n_samples % 2] # Suppose state = [0,", "auto-correlation spectra derived from # reversible MCMC chains. # E.g.", "least 2 chains. validate_args: Whether to add runtime checks of", "having total # ndims the same as auto_corr k =", ") # Step 2: Put the size `2` dimension in", "valued. The sequence of auto-correlations is truncated to this length.", "[Gelman and Rubin (1992)][1]; [Brooks and Gelman (1998)][2]. Some guidelines:", "[assert_util.assert_greater( ps.shape(state)[0], 2, message='Must provide at least 2 samples.')] with", "return ((m + 1.) / m) * sigma_2_plus / w", "summing them. In an extreme case where the chains have", "<NAME>, <NAME>. Rank-normalization, folding, and localization: An improved R-hat for", "= tf.transpose( a=state, perm=ps.concat( [[1, 0], ps.range(2, ps.rank(state))], axis=0)) #", "Sum_{c=1}^C s_c**2 R[k, c] mean_auto_cov = tf.reduce_mean(auto_cov, cross_chain_dims) auto_corr =", "become non-positive. The arguments `filter_beyond_lag`, `filter_threshold` and `filter_beyond_positive_pairs` are filters", "n = _axis_size(states, axis=0) if cross_chain_dims is not None: num_chains", "this is 1! sample_ndims = 1 if split_chains: # Split", "- x_hat[c])**2, chain # variance # R[k, m] := auto_corr[k,", "law or agreed to in writing, software # distributed under", "`ESS` of super-efficient chains (where `ESS > N`) correctly. *", "cross_chain_dims: An integer `Tensor` or a structure of integer `Tensors`", "auto_corr[k, ...], # ESS = N / {1 + 2", "+ R_{2k + 1} > 0` for `k in {0,", "monitoring 10 chains that each attempt to sample from a", "tfp.mcmc.diagnostic.potential_scale_reduction( chains_states, independent_chain_ndims=1) # The second dimension needed a longer", "samples when splitting chains.')] with tf.control_dependencies(assertions): state = tf.identity(state) else:", "to `state.shape[1 + independent_chain_ndims:]`. Raises: ValueError: If `independent_chain_ndims < 1`.", "Var[E[X | chain]] ) / E[Var[X | chain]].``` Using the", "ps.rank(states)) # B / N between_chain_variance_div_n = _reduce_variance( tf.reduce_mean(states, axis=0),", "Rubin (1992)][1]; [Brooks and Gelman (1998)][2]. Some guidelines: * The", "as type `x.dtype`.\"\"\" if axis is None: return ps.cast(ps.size(x), x.dtype)", "`cross_chain_dims` argument. Cross-chain ESS takes into account the cross-chain variance", "chains_states.shape ==> (1000, 10, 2) rhat = tfp.mcmc.diagnostic.potential_scale_reduction( chains_states, independent_chain_ndims=1)", "chain, changing [[0, 1, 2], [3, 4, 5]] into [[0,", "many MCMC methods generate chains where `R_k > 0`, a", "= N / {-1 + 2 * Sum_{k=0}^N R[k] *", "2 * Sum_{k=0}^N R[k] * (N - k) / N}", "state component. If a list of `states` is provided, then", "`Tensor`.\"\"\" # casting integers to floats for floating-point division #", "tensorflow_probability.python.internal import nest_util from tensorflow_probability.python.internal import prefer_static as ps from", "filter_threshold, filter_beyond_positive_pairs, cross_chain_dims, validate_args): \"\"\"ESS computation for one single Tensor", "+ [1] * (tensorshape_util.rank(auto_corr.shape) - 1) else: new_shape = tf.concat(", "is the variance of the combined states, and the denominator", "2, b]. state = tf.transpose( a=state, perm=ps.concat( [[1, 0], ps.range(2,", "filter_beyond_lag, filter_threshold, filter_beyond_positive_pairs, cross_chain_dims) def _effective_sample_size_single_state(states, filter_beyond_lag, filter_threshold, filter_beyond_positive_pairs, cross_chain_dims,", "Sum_{c=1}^C s_c**2 R[k, c]) / (var^+), # # where: #", "B / N between_chain_variance_div_n = _reduce_variance( tf.reduce_mean(states, axis=0), biased=False, #", "super-efficient chains (where `ESS > N`) correctly. * `filter_beyond_positive_pairs` --", "is None: return ps.cast(ps.size(x), x.dtype) return ps.cast( ps.reduce_prod( ps.gather(ps.shape(x), axis)),", "sigma_2_plus / w - (n - 1.) / (m *", "with respect to the target. * If all chains converge", "same mean, and thus the ratio should be one. ####", "of # independent chains. # For odd number of samples,", "shape (even empty). independent_chain_ndims: Integer type `Tensor` with value `>=", "are not mixing well. In general, this will be a", "MCMC chains produce an auto-correlation sequence with the property that", "may obtain a copy of the License at # #", "the `Ni > 1` result steps of the Markov Chain.", "Variance{ X_1 }. ``` If the sequence is uncorrelated, `ESS", "new_shape) weighted_auto_corr = nk_factor * auto_corr if filter_beyond_positive_pairs: def _sum_pairs(x):", ") / E[Var[X | chain]].``` Using the law of total", "total variance minus the variance of the the individual chain", "iff a constant value (as a numpy # array) is", "and is recommended in [3]. validate_args: Whether to add runtime", "# This makes the denominator be C - 1. axis=cross_chain_dims", "1) Sum_{c=1}^C (x_hat[c] - x_hat)**2, between chain # variance. #", "name='states') dt = states.dtype # filter_beyond_lag == None ==> auto_corr", "for Monitoring Convergence of Iterative Simulations. _Journal of Computational and", "do not filter based on the size of lags. filter_beyond_positive_pairs:", "`cross_chain_dims` is not `None` and there are less than 2", "tensorflow_probability.python.internal import prefer_static as ps from tensorflow_probability.python.internal import tensorshape_util from", "is recommended in [3]. validate_args: Whether to add runtime checks", "independent_chain_ndims) sample_and_chain_axis = ps.range( 0, sample_ndims + independent_chain_ndims) n =", "chains. ' 'Found {}'.format(n_samples_)) if not split_chains and n_samples_ <", "- 1) else: new_shape = tf.concat( ([-1], tf.ones([tf.rank(auto_corr) - 1],", "ps.range( 0, sample_ndims + independent_chain_ndims) n = _axis_size(state, sample_axis) m", "/ N cross_chain_dims = ps.non_negative_axis( cross_chain_dims, ps.rank(states)) # B /", "and Graphical Statistics_, 7(4), 1998. [2]: <NAME> and <NAME>. Inference", "# B / N between_chain_variance_div_n = _reduce_variance( tf.reduce_mean(states, axis=0), biased=False,", "may not use this file except in compliance with the", "This function can also compute cross-chain ESS following [Vehtari et", "effect. Ignored if `filter_beyond_positive_pairs` is `True`. filter_beyond_lag: `Tensor` or Python", "Then, in the limit `N, C --> infinity`, with `E`,", "from one chain. states = tfp.mcmc.sample_chain( num_burnin_steps=200, num_results=1000, current_state=tf.constant([0., 0.]),", "threshold for all j <= i, # mask[i, ...] =", "of `Tensor` objects. Must be `int`-like and scalar valued. The", "to each state component. If a list of `states` is", "/ C Sum_{c=1}^C x_hat[c], overall mean. # W := 1/C", "Sum_{k=0}^N R[k] * (N - k) / N} (since R[0]", "all chains converge to the target, then as `N -->", "5]], # reshaping [2, a//2, b] into [a//2, 2, b].", "not None: if num_chains_ < 2: raise ValueError(msg) elif validate_args:", "this file except in compliance with the License. # You", "= tf.identity(state) # Define so it's not a magic number.", "= effective_sample_size(states, filter_beyond_positive_pairs=True) ==> Shape (2,) Tensor mean, variance =", "{1 + 2 * Sum_{k=1}^N R[k] * (N - k)", "`X_1, X_2, ..., X_N`, identically distributed, ESS is the number", "For this reason, the summation over `R_k` should be truncated", "infinity`, with `E`, `Var` denoting expectation and variance, ```R-hat =", "- k` samples, it becomes progressively noisier for larger `k`.", "= 1) # approx N / {-1 + 2 *", "ESS = N / {1 + 2 * Sum_{k=1}^N R[k]", "# Split the sample dimension in half, doubling the number", "convergence of MCMC, 2019. Retrieved from http://arxiv.org/abs/1903.08008 \"\"\" # tf.get_static_value", "independent_chain_ndims=1) # The second dimension needed a longer burn-in. rhat.eval()", "pairwise sums are positive. cross_chain_dims: An integer `Tensor` or a", "the number such that ``` Variance{ N**-1 * Sum{X_i} }", "# # Licensed under the Apache License, Version 2.0 (the", "R[k, c]) / (var^+), # # where: # C :=", "- 1) Sum_{n=1}^N (x[n, c] - x_hat[c])**2, chain # variance", "indexes the `Ni > 1` result steps of the Markov", "Variance{ N**-1 * Sum{X_i} } = ESS**-1 * Variance{ X_1", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "= _sum_pairs(weighted_auto_corr) * mask elif filter_threshold is not None: filter_threshold", "checks of argument validity. If False, and arguments are incorrect,", "result steps of the Markov Chain. Dimensions `1` through `D`", "import tensorflow.compat.v2 as tf from tensorflow_probability.python import stats from tensorflow_probability.python.internal", "R-hat statistic for the state(s). Same `dtype` as `state`, and", "be a random variable drawn uniformly from the combined states", "diagnostic should be used. See [Brooks and Gelman (1998)][2]. Args:", "name): return tf.nest.map_structure(single_state, chains_states) def _potential_scale_reduction_single_state(state, independent_chain_ndims, split_chains, validate_args): \"\"\"potential_scale_reduction", "to created ops. Returns: ess: `Tensor` structure parallel to `states`.", "name='x') mean = tf.reduce_mean(x, axis=axis, keepdims=True) biased_var = tf.reduce_mean( tf.math.squared_difference(x,", "Python structure of `Tensor` objects. Must be `int`-like and scalar", "to created tf. Default: `potential_scale_reduction`. Returns: `Tensor` structure parallel to", "in cases where the chains are not mixing well. In", "# Step 3: mask = [0, 0, 1, 2] mask", "n_samples = state_shape[0] state = state[:n_samples - n_samples % 2]", "state = state[:n_samples - n_samples % 2] # Suppose state", "drawing from the same distribution, they will have the same", "# N := length of chains # x_hat[c] := 1", "single_state, states, filter_beyond_lag, filter_threshold, filter_beyond_positive_pairs, cross_chain_dims) def _effective_sample_size_single_state(states, filter_beyond_lag, filter_threshold,", "ESS following [Vehtari et al. (2019)][2] by specifying the `cross_chain_dims`", "B / N cross_chain_dims = ps.non_negative_axis( cross_chain_dims, ps.rank(states)) # B", "7:473-511, 1992. [2]: <NAME>, <NAME>, <NAME>, <NAME>, <NAME>. Rank-normalization, folding,", "1! sample_ndims = 1 if split_chains: # Split the sample", "for floating-point division # check to see if the `state`", "= N / {1 + 2 * Sum_{k=1}^N R[k] *", "# C := number of chains # N := length", "+ independent_chain_ndims:]`. Raises: ValueError: If `independent_chain_ndims < 1`. #### Examples", "Ci1, Ci2,...,CiD] + A`. Dimension `0` indexes the `Ni >", "[a, b] into [2, a//2, b]. state = tf.reshape( state,", "Python structure of `Tensor` objects. Must broadcast with `state`. The", "axis is None: return ps.cast(ps.size(x), x.dtype) return ps.cast( ps.reduce_prod( ps.gather(ps.shape(x),", "[1.05, 1.3] ``` To see why R-hat is reasonable, let", "all chains). Then, in the limit `N, C --> infinity`,", "cross_chain_dims).shape[1:]`. Raises: ValueError: If `states` and `filter_threshold` or `states` and", "(combined over all chains). Then, in the limit `N, C", "c]) / (var^+), # # where: # C := number", "of the mean. If higher moments, or other statistics are", "try constant_value then # check for None. icn_const_ = tf.get_static_value(", "N / [ 1 + 2 * ( (N -", "states = tf.convert_to_tensor(states, name='states') dt = states.dtype # filter_beyond_lag ==", "(except in pathological cases, e.g. if the chain paths were", "2: raise ValueError( 'Must provide at least 2 samples. Found", "not `None` and there are less than 2 chains. ####", "sums of the elements of that sequence are positive [Geyer][1],", "= 1 if split_chains: # Split the sample dimension in", "==> (1000, 2) ess = effective_sample_size(states, filter_beyond_positive_pairs=True) ==> Shape (2,)", "so increment. independent_chain_ndims += 1 sample_axis = ps.range(0, sample_ndims) chain_axis", "tf.sqrt(variance / ess) ``` #### References [1]: <NAME>, Practical Markov", "then summing them. In an extreme case where the chains", "number of dimensions, from `dim = 1` to `dim =", "from the target. c.f. \"law of total variance.\" sigma_2_plus =", "_axis_size(states, cross_chain_dims) num_chains_ = tf.get_static_value(num_chains) assertions = [] msg =", "s_c**2 := 1 / (N - 1) Sum_{n=1}^N (x[n, c]", "Therefore, we try constant_value then # check for None. icn_const_", "% 2] # Suppose state = [0, 1, 2, 3,", "# W is the within sequence variance, the mean of", "chains to be tested for convergence to the same target.", "chains are not mixing well. In general, this will be", "otherwise. # So, along dimension zero, the mask will look", "not `None`, there must be > 1 chain ' 'in", "or implied. # See the License for the specific language", "requires at least 2 chains. validate_args: Whether to add runtime", "/ approx_variance else: auto_corr = auto_cov / auto_cov[:1] num_chains =", "* Sum_{k=0}^N R[k] * (N - k) / N} (since", "= ((n - 1) / n) * w + b_div_n", "raise ValueError( 'Argument `independent_chain_ndims` must be `>= 1`, found: {}'.format(", "also compute cross-chain ESS following [Vehtari et al. (2019)][2] by", "Otherwise, the shape is `tf.reduce_mean(states, cross_chain_dims).shape[1:]`. Raises: ValueError: If `states`", "chains. #### Examples We use ESS to estimate standard error.", "dimension indexes e.g. correlated samples # from each Markov chain.", "becomes negative. This method does not estimate the `ESS` of", "] ``` This function estimates the above by first estimating", "are less than 2 chains. #### Examples We use ESS", "created tf. Default: `potential_scale_reduction`. Returns: `Tensor` structure parallel to `chains_states`", "License. # ============================================================================ \"\"\"Utilities for Markov Chain Monte Carlo (MCMC)", "# # where: # C := number of chains #", "sums are positive. cross_chain_dims: An integer `Tensor` or a structure", "10 chains that each attempt to sample from a 2-variate", "`states`. The effective sample size of each component of `states`.", "# If available statically. if split_chains and n_samples_ < 4:", "* biased_var def _axis_size(x, axis=None): \"\"\"Get number of elements of", "_axis_size(states, axis=0) if cross_chain_dims is not None: num_chains = _axis_size(states,", "point chosen above. # Get the factor (N - k)", "if split_chains and n_samples_ < 4: raise ValueError( 'Must provide", "expect if the chains were identically distributed. See [Gelman and", "that terms are removed if they were to be filtered", "other statistics are desired, a different diagnostic should be used.", "R[k] := auto_corr[k, ...], # ESS = N / {1", "them. In an extreme case where the chains have fallen", "reducing the need for truncation. Args: states: `Tensor` or Python", "of `Tensor` objects. Dimension zero should index identically distributed states.", "1) # var^+ approx_variance = ( biased_within_chain_variance + between_chain_variance_div_n) #", "full sequence. auto_cov = stats.auto_correlation( states, axis=0, max_lags=filter_beyond_lag, normalize=False) n", "chains should be drawn from a distribution overdispersed with respect", "if the chain paths were identical). * The above holds", "check for None. icn_const_ = tf.get_static_value( ps.convert_to_shape_tensor(independent_chain_ndims)) if icn_const_ is", "In the language of Brooks and Gelman (1998), # B", "each independent chain. Roughly speaking, \"effective sample size\" (ESS) is", "would expect if the chains were identically distributed. See [Gelman", "the numpy test suite if dtype_util.as_numpy_dtype(state.dtype) is np.int64: state =", "by specifying the `cross_chain_dims` argument. Cross-chain ESS takes into account", "filter_threshold=0., filter_beyond_lag=None, filter_beyond_positive_pairs=False, cross_chain_dims=None, validate_args=False, name=None): \"\"\"Estimate a lower bound", "variance, which would be unbiased if # each chain was", "cases where the chains are not mixing well. In general,", "structure of `Tensor` objects. Must be `int`-like and scalar valued.", "Even when chains are mixing well it is still preferrable", "rhat = tfp.mcmc.diagnostic.potential_scale_reduction( chains_states, independent_chain_ndims=1) # The second dimension needed", "None: cross_chain_dims = nest_util.broadcast_structure(states, None) filter_beyond_lag = nest_util.broadcast_structure(states, filter_beyond_lag) filter_threshold", "means we use no threshold filter. Since `|R_k| <= 1`,", "into [[0, 3], [1, 4], [2, 5]], # reshaping [2,", "does not estimate the `ESS` of super-efficient chains (where `ESS", "in {0, ..., N/2}`. Deviations are only possible due to", "..., N/2}`. Deviations are only possible due to noise. This", "for the numpy test suite if dtype_util.as_numpy_dtype(state.dtype) is np.int64: state", "filters intended to remove noisy tail terms from `R_k`. You", "any shape (even empty). independent_chain_ndims: Integer type `Tensor` with value", "auto-correlation sequence where the pairwise sums are positive. cross_chain_dims: An", "only consider the initial auto-correlation sequence where the pairwise sums", "[0, 0, 1, 0] mask = tf.cast(mask, dtype=dt) # Step", "odd sequences, we drop the final value. x = x[:x_len", "[[0, 3], [1, 4], [2, 5]], # reshaping [2, a//2,", "variance, the mean of the chain variances. b_div_n = _reduce_variance(", "distributed. See [Gelman and Rubin (1992)][1]; [Brooks and Gelman (1998)][2].", "0.) # N.B. this reduces the length of weighted_auto_corr by", "chain means. # W is the within sequence variance, the", "arguments `filter_beyond_lag`, `filter_threshold` and `filter_beyond_positive_pairs` are filters intended to remove", "will be `states.shape[1:]`. Otherwise, the shape is `tf.reduce_mean(states, cross_chain_dims).shape[1:]`. Raises:", "of each component of `states`. If `cross_chain_dims` is None, the", "= tf.maximum(1. - mask, 0.) weighted_auto_corr *= mask return num_chains", "be > 1 chain ' 'in `states`.') if num_chains_ is", "and n_samples_ < 2: raise ValueError( 'Must provide at least", "variances. b_div_n = _reduce_variance( tf.reduce_mean(state, axis=sample_axis, keepdims=True), sample_and_chain_axis, biased=False) w", "auto_corr = [1, 0.5, 0.0, 0.3], and filter_threshold = 0.2.", "1, 0] mask = tf.cast(mask, dtype=dt) # Step 3: mask", "tf.cast(state, tf.float64) elif dtype_util.is_integer(state.dtype): state = tf.cast(state, tf.float32) with tf.name_scope('potential_scale_reduction_single_state'):", "= tfp.distributions target = tfd.MultivariateNormalDiag(scale_diag=[1., 2.]) # Get 1000 states", "[1, 4], [2, 5]], # reshaping [2, a//2, b] into", "boolean. If `True`, only consider the initial auto-correlation sequence where", "\"\"\" if cross_chain_dims is None: cross_chain_dims = nest_util.broadcast_structure(states, None) filter_beyond_lag", "infinity`, R-hat --> 1. Before that, R-hat > 1 (except", "be tested for convergence to the same target. The remaining", "filter_beyond_lag=None, filter_beyond_positive_pairs=False, cross_chain_dims=None, validate_args=False, name=None): \"\"\"Estimate a lower bound on", "have any shape (even empty). independent_chain_ndims: Integer type `Tensor` with", "k) / N, and give it shape [M, 1,...,1], having", "assertions = [assert_util.assert_greater( ps.shape(state)[0], 2, message='Must provide at least 2", "numerator is the variance of the combined states, and the", "uniformly from the combined states (combined over all chains). Then,", "N / {1 + 2 * Sum_{k=1}^N R[k] * (N", "scale reduction factor, commonly referred to as R-hat, measures convergence", "B / n is the between chain variance, the variance", "`states.shape[1:]`. Otherwise, the shape is `tf.reduce_mean(states, cross_chain_dims).shape[1:]`. Raises: ValueError: If", "= [0, 0, 1, 0] mask = tf.cast(mask, dtype=dt) #", "makes R-hat more robust to non-stationary chains, and is recommended", "truncated at some number `filter_beyond_lag < N`. This function provides", "= tf.reduce_mean( _reduce_variance(state, sample_axis, keepdims=True, biased=False), axis=sample_and_chain_axis) # sigma^2_+ is", "_effective_sample_size_single_state(states, filter_beyond_lag, filter_threshold, filter_beyond_positive_pairs, cross_chain_dims, validate_args): \"\"\"ESS computation for one", "= tfd.MultivariateNormalDiag(scale_diag=[1., 2.]) # Get 10 (2x) overdispersed initial states.", "independent_chain_ndims: Integer type `Tensor` with value `>= 1` giving the", "the same mean, and thus the ratio should be one.", "value `>= 1` giving the number of dimensions, from `dim", "1], dtype=tf.int32)), axis=0) nk_factor = tf.reshape(nk_factor, new_shape) weighted_auto_corr = nk_factor", "converge to the target, then as `N --> infinity`, R-hat", "X_2, ..., X_N`, identically distributed, ESS is the number such", "`state` is a numpy object for the numpy test suite", "1) # W * (N - 1) / N biased_within_chain_variance", "from the 10 independent chains. chains_states = tfp.mcmc.sample_chain( num_burnin_steps=200, num_results=1000,", "from tensorflow_probability.python.internal import dtype_util from tensorflow_probability.python.internal import nest_util from tensorflow_probability.python.internal", "tfp.mcmc.sample_chain( num_burnin_steps=200, num_results=1000, current_state=initial_state, trace_fn=None, kernel=tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=target.log_prob, step_size=0.05, num_leapfrog_steps=20)) chains_states.shape", "(n - 1.)) * biased_var def _axis_size(x, axis=None): \"\"\"Get number", "if icn_const_ is not None: independent_chain_ndims = icn_const_ if icn_const_", "the chains (to the same target) by testing for equality", "non-positive. The arguments `filter_beyond_lag`, `filter_threshold` and `filter_beyond_positive_pairs` are filters intended", "`filter_beyond_lag` are both structures of different shapes. ValueError: If `cross_chain_dims`", "0, 1, 1] mask = tf.cumsum(mask, axis=0) # Step 4:", "(to the same target) by testing for equality of means.", "def _axis_size(x, axis=None): \"\"\"Get number of elements of `x` in", "elif filter_threshold is not None: filter_threshold = tf.convert_to_tensor( filter_threshold, dtype=dt,", "unbiased if # each chain was drawn from the target.", "_sum_pairs(weighted_auto_corr) * mask elif filter_threshold is not None: filter_threshold =", "integer `Tensor` or a structure of integer `Tensors` corresponding to", "estimate standard error. ``` import tensorflow as tf import tensorflow_probability", "incorrect, correct behavior is not guaranteed. name: `String` name to", "sample_ndims + independent_chain_ndims) n = _axis_size(state, sample_axis) m = _axis_size(state,", "tested for convergence. split_chains: Python `bool`. If `True`, divide samples", "given a stationary sequence of possibly correlated random variables `X_1,", "sampling. @@effective_sample_size @@potential_scale_reduction \"\"\" from __future__ import absolute_import from __future__", "term less than `filter_threshold`. Setting to `None` means we use", "1.)) * biased_var def _axis_size(x, axis=None): \"\"\"Get number of elements", "= tf.range(0., _axis_size(auto_corr, axis=0)) nk_factor = (n - k) /", "each chain was drawn from the target. c.f. \"law of", "means. If the chains are all drawing from the same", "+ A`. Dimension `0` indexes the `Ni > 1` result", "shape will be `states.shape[1:]`. Otherwise, the shape is `tf.reduce_mean(states, cross_chain_dims).shape[1:]`.", "for each independent chain. Roughly speaking, \"effective sample size\" (ESS)", "cross_chain_dims is not None: num_chains = _axis_size(states, cross_chain_dims) num_chains_ =", "indexing 2 chains, so increment. independent_chain_ndims += 1 sample_axis =", "==> auto_corr is the full sequence. auto_cov = stats.auto_correlation( states,", "- 1) Sum_{c=1}^C (x_hat[c] - x_hat)**2, between chain # variance.", "approx_variance = ( biased_within_chain_variance + between_chain_variance_div_n) # 1/C * Sum_{c=1}^C", "_effective_sample_size_single_state( *args, validate_args=validate_args) with tf.name_scope('effective_sample_size' if name is None else", "+ 2 * Sum_{k=0}^M R[k] * (N - k) /", "`R_{2k} + R_{2k + 1} > 0` for `k in", "single state `Tensor`.\"\"\" # casting integers to floats for floating-point", "/ n is the between chain variance, the variance of", "and Rubin (1992)][1]; [Brooks and Gelman (1998)][2]. Some guidelines: *", "a numpy object for the numpy test suite if dtype_util.as_numpy_dtype(state.dtype)", "chosen above. # Get the factor (N - k) /", "If `independent_chain_ndims < 1`. #### Examples Diagnosing convergence by monitoring", "with `filter_threshold` or `filter_beyond_positive_pairs. E.g., combining `filter_beyond_lag` and `filter_beyond_positive_pairs` means", "in writing, software # distributed under the License is distributed", "of the elements of that sequence are positive [Geyer][1], i.e.", "samples.')] with tf.control_dependencies(assertions): state = tf.identity(state) # Define so it's", "if biased: return biased_var n = _axis_size(x, axis) return (n", "indicate approximate convergence, but of course this is problem-dependent. See", "N * R_1 + ... + 1 / N *", "If False, and arguments are incorrect, correct behavior is not", "state `Tensor`.\"\"\" # casting integers to floats for floating-point division", "< 1`. #### Examples Diagnosing convergence by monitoring 10 chains", "mask = [0, 0, 1, 0] mask = tf.cast(mask, dtype=dt)", "increment. independent_chain_ndims += 1 sample_axis = ps.range(0, sample_ndims) chain_axis =", "if `filter_beyond_positive_pairs` is `True`. filter_beyond_lag: `Tensor` or Python structure of", "tensorflow.python.util import nest # pylint: disable=g-direct-tensorflow-import __all__ = [ 'effective_sample_size',", "but of course this is problem-dependent. See [Brooks and Gelman", "suite if dtype_util.as_numpy_dtype(state.dtype) is np.int64: state = tf.cast(state, tf.float64) elif", "in the estimate of `R_k`, reducing the need for truncation.", "be unbiased if # each chain was drawn from the", "mean. # x_hat := 1 / C Sum_{c=1}^C x_hat[c], overall", "ps.shape(state)[0], 4, message='Must provide at least 4 samples when splitting", "Markov Chain Monte Carlo (MCMC) sampling. @@effective_sample_size @@potential_scale_reduction \"\"\" from", "dimension needed a longer burn-in. rhat.eval() ==> [1.05, 1.3] ```", "argument should also be a list of the same length.", "a lower bound on effective sample size for each independent", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "See [Brooks and Gelman (1998)][2]. * R-hat only measures non-convergence", "License, Version 2.0 (the \"License\"); # you may not use", "CiD` independent chains to be tested for convergence to the", "= tf.convert_to_tensor(x, name='x') mean = tf.reduce_mean(x, axis=axis, keepdims=True) biased_var =", "# W * (N - 1) / N biased_within_chain_variance =", "length. Which dimensions of `states` to treat as independent chains", "* Sum_{k=1}^N R[k] * (N - k) / N} #", "e.g. correlated samples # from each Markov chain. state =", "and `filter_beyond_positive_pairs` means that terms are removed if they were", "1: raise ValueError( 'Argument `independent_chain_ndims` must be `>= 1`, found:", "0, 0] mask = tf.maximum(1. - mask, 0.) # N.B.", "> 1` result steps of the Markov Chain. Dimensions `1`", "Sum{X_i} } = ESS**-1 * Variance{ X_1 }. ``` If", "is the filter_beyond_lag truncation point chosen above. # Get the", "of the true variance, which would be unbiased if #", "methods generate chains where `R_k > 0`, a reasonable criterion", "be drawn from a distribution overdispersed with respect to the", "possible due to noise. This method truncates the auto-correlation sequence", "mean = tf.reduce_mean(x, axis=axis, keepdims=True) biased_var = tf.reduce_mean( tf.math.squared_difference(x, mean),", "at some number `filter_beyond_lag < N`. This function provides two", "between chain # variance. # s_c**2 := 1 / (N", "of Computational and Graphical Statistics_, 7(4), 1998. [2]: <NAME> and", "N cross_chain_dims = ps.non_negative_axis( cross_chain_dims, ps.rank(states)) # B / N", "= tf.cast(state, tf.float64) elif dtype_util.is_integer(state.dtype): state = tf.cast(state, tf.float32) with", "x_len = ps.shape(x)[0] # For odd sequences, we drop the", "tfd.sample_stats. def _reduce_variance(x, axis=None, biased=True, keepdims=False): with tf.name_scope('reduce_variance'): x =", "X_{1+k}} / Variance{X_1}`, we have ``` ESS(N) = N /", "an auto-correlation sequence with the property that pairwise sums of", "biased=False), axis=sample_and_chain_axis) # sigma^2_+ is an estimate of the true", "true variance, which would be unbiased if # each chain", "trace_fn=None, kernel=tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=target.log_prob, step_size=0.05, num_leapfrog_steps=20)) states.shape ==> (1000, 2) ess", "import stats from tensorflow_probability.python.internal import assert_util from tensorflow_probability.python.internal import dtype_util", "the License for the specific language governing permissions and #", "(W - 1/C * Sum_{c=1}^C s_c**2 R[k, c]) / (var^+),", "Sum_{c=1}^C x_hat[c], overall mean. # W := 1/C Sum_{c=1}^C s_c**2,", "(1000, 2) ess = effective_sample_size(states, filter_beyond_positive_pairs=True) ==> Shape (2,) Tensor", "of this to tfd.sample_stats. def _reduce_variance(x, axis=None, biased=True, keepdims=False): with", "1 - (W - 1/C * Sum_{c=1}^C s_c**2 R[k, c])", "= _axis_size(states, axis=0) if cross_chain_dims is not None: num_chains =", "Monte Carlo (with discussion). Statistical Science, 7:473-511, 1992. [2]: <NAME>,", "assert_util from tensorflow_probability.python.internal import dtype_util from tensorflow_probability.python.internal import nest_util from", "due to noise. This method truncates the auto-correlation sequence where", "* (N - k) / N} # = N /", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "as R-hat, measures convergence of the chains (to the same", "validate_args): \"\"\"potential_scale_reduction for one single state `Tensor`.\"\"\" # casting integers", "w - (n - 1.) / (m * n) #", "than `filter_threshold`. Setting to `None` means we use no threshold", "mask = [False, False, True, False] mask = auto_corr <", "and then summing them. In an extreme case where the", "Some math shows that, with `R_k` the auto-correlation sequence, `R_k", "that, with `R_k` the auto-correlation sequence, `R_k := Covariance{X_1, X_{1+k}}", "auto-correlations is truncated after the first appearance of a term", "in pathological cases, e.g. if the chain paths were identical).", "cross_chain_dims - 1) # var^+ approx_variance = ( biased_within_chain_variance +", "length of weighted_auto_corr by a factor of 2. # It", "to remove noisy tail terms from `R_k`. You can combine", "length of chains # x_hat[c] := 1 / N Sum_{n=1}^N", "You can combine `filter_beyond_lag` with `filter_threshold` or `filter_beyond_positive_pairs. E.g., combining", "`cross_chain_dims` is None, the shape will be `states.shape[1:]`. Otherwise, the", "mask = tf.maximum(1. - mask, 0.) # N.B. this reduces", "Science_, 7(4):457-472, 1992. [3]: <NAME>, <NAME>, <NAME>, <NAME>, Paul-Christian Burkner.", "stats.auto_correlation( states, axis=0, max_lags=filter_beyond_lag, normalize=False) n = _axis_size(states, axis=0) if", "# R[k, m] := auto_corr[k, m, ...], auto-correlation indexed by", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "4, 5] # Step 1: reshape into [[0, 1, 2],", "between_chain_variance_div_n) # 1/C * Sum_{c=1}^C s_c**2 R[k, c] mean_auto_cov =", "filter_threshold is not None: filter_threshold = tf.convert_to_tensor( filter_threshold, dtype=dt, name='filter_threshold')", "`N > 1` states from each of `C > 1`", "= tf.reshape(nk_factor, new_shape) weighted_auto_corr = nk_factor * auto_corr if filter_beyond_positive_pairs:", "tf import tensorflow_probability as tfp tfd = tfp.distributions target =", "n / (-1 + 2 * tf.reduce_sum(weighted_auto_corr, axis=0)) def potential_scale_reduction(chains_states,", "/ N between_chain_variance_div_n = _reduce_variance( tf.reduce_mean(states, axis=0), biased=False, # This", "# reversible MCMC chains. # E.g. imagine the pairwise sums", "let `X` be a random variable drawn uniformly from the", "num_results=1000, current_state=tf.constant([0., 0.]), trace_fn=None, kernel=tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=target.log_prob, step_size=0.05, num_leapfrog_steps=20)) states.shape ==>", "axis=None, biased=True, keepdims=False): with tf.name_scope('reduce_variance'): x = tf.convert_to_tensor(x, name='x') mean", "(2019): # # R[k] := 1 - (W - 1/C", "For odd sequences, we drop the final value. x =", "on effective sample size for each independent chain. Roughly speaking,", "the shape will be `states.shape[1:]`. Otherwise, the shape is `tf.reduce_mean(states,", "with tf.control_dependencies(assertions): state = tf.identity(state) # Define so it's not", "' 'in `states`.') if num_chains_ is not None: if num_chains_", "filter_threshold = nest_util.broadcast_structure(states, filter_threshold) filter_beyond_positive_pairs = nest_util.broadcast_structure( states, filter_beyond_positive_pairs) #", "- mean_auto_cov) / approx_variance else: auto_corr = auto_cov / auto_cov[:1]", "binary mask to zero out values of auto_corr below the", "Found {}'.format(n_samples_)) elif validate_args: if split_chains: assertions = [assert_util.assert_greater( ps.shape(state)[0],", "new_shape = tf.concat( ([-1], tf.ones([tf.rank(auto_corr) - 1], dtype=tf.int32)), axis=0) nk_factor", "# chain, changing [[0, 1, 2], [3, 4, 5]] into", "should be used. See [Brooks and Gelman (1998)][2]. Args: chains_states:", "tf.float64) elif dtype_util.is_integer(state.dtype): state = tf.cast(state, tf.float32) with tf.name_scope('potential_scale_reduction_single_state'): #", "# distributed under the License is distributed on an \"AS", "..., X_N`, identically distributed, ESS is the number such that", "# Unless required by applicable law or agreed to in", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "will reduce the noise in the estimate of `R_k`, reducing", "chain ' 'in `states`.') if num_chains_ is not None: if", "* Sum_{c=1}^C s_c**2 R[k, c]) / (var^+), # # where:", "biased=False) w = tf.reduce_mean( _reduce_variance(state, sample_axis, keepdims=True, biased=False), axis=sample_and_chain_axis) #", "component. If a list of `states` is provided, then this", "the pairwise sums become non-positive. The arguments `filter_beyond_lag`, `filter_threshold` and", "+ Var[E[X | chain]] ) / E[Var[X | chain]].``` Using", "that pairwise sums of the elements of that sequence are", "the `ESS` of super-efficient chains (where `ESS > N`) correctly.", "/ {1 + 2 * Sum_{k=1}^N R[k] * (N -", "* The above holds for any number of chains `C", "None else name): return tf.nest.map_structure(single_state, chains_states) def _potential_scale_reduction_single_state(state, independent_chain_ndims, split_chains,", "num_results=1000, current_state=initial_state, trace_fn=None, kernel=tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=target.log_prob, step_size=0.05, num_leapfrog_steps=20)) chains_states.shape ==> (1000,", "Before that, R-hat > 1 (except in pathological cases, e.g.", "= ('When `cross_chain_dims` is not `None`, there must be >", "filter_beyond_positive_pairs, cross_chain_dims) def _effective_sample_size_single_state(states, filter_beyond_lag, filter_threshold, filter_beyond_positive_pairs, cross_chain_dims, validate_args): \"\"\"ESS", "Gelman (1998)][2]. * R-hat only measures non-convergence of the mean.", "independent_chain_ndims, split_chains, validate_args) with tf.name_scope('potential_scale_reduction' if name is None else", "N} (since R[0] = 1) # approx N / {-1", "which would be unbiased if # each chain was drawn", "(even empty). independent_chain_ndims: Integer type `Tensor` with value `>= 1`", "the Apache License, Version 2.0 (the \"License\"); # you may", "mean, variance = tf.nn.moments(states, axis=0) standard_error = tf.sqrt(variance / ess)", "if they were to be filtered under the `filter_beyond_lag` OR", "a binary mask to zero out values of auto_corr below", "the above by first estimating the auto-correlation. Since `R_k` must", "biased_var n = _axis_size(x, axis) return (n / (n -", "of that sequence are positive [Geyer][1], i.e. `R_{2k} + R_{2k", "R[k] := 1 - (W - 1/C * Sum_{c=1}^C s_c**2", "so it's not a magic number. # Warning! `if split_chains`", "takes into account the cross-chain variance to reduce the ESS", "R[k, m] := auto_corr[k, m, ...], auto-correlation indexed by chain.", "the shape is `tf.reduce_mean(states, cross_chain_dims).shape[1:]`. Raises: ValueError: If `states` and", "generate chains where `R_k > 0`, a reasonable criterion is", "-0.2] # Step 1: mask = [False, False, True, True]", "dimensions, from `dim = 1` to `dim = D`, holding", "np import tensorflow.compat.v2 as tf from tensorflow_probability.python import stats from", "structure parallel to `states`. The effective sample size of each", "states of a Markov Chain at each result step. The", "tensorflow_probability.python.internal import tensorshape_util from tensorflow.python.util import nest # pylint: disable=g-direct-tensorflow-import", "2019. Retrieved from http://arxiv.org/abs/1903.08008 \"\"\" if cross_chain_dims is None: cross_chain_dims", "by a factor of 2. # It still works fine", "of MCMC, 2019. Retrieved from http://arxiv.org/abs/1903.08008 \"\"\" # tf.get_static_value returns", "scalar valued. The sequence of auto-correlations is truncated to this", "ps.non_negative_axis( cross_chain_dims, ps.rank(states)) # B / N between_chain_variance_div_n = _reduce_variance(", "the filter_beyond_lag truncation point chosen above. # Get the factor", "a term less than `filter_threshold`. Setting to `None` means we", "summation is performed. Note this requires at least 2 chains.", "R_1 + ... + 1 / N * R_{N-1} )", "on the size of lags. filter_beyond_positive_pairs: Python boolean. If `True`,", "- 1], dtype=tf.int32)), axis=0) nk_factor = tf.reshape(nk_factor, new_shape) weighted_auto_corr =", "~ K. Even when chains are mixing well it is", "Paul-Christian Burkner. Rank-normalization, folding, and localization: An improved R-hat for", "/ (m * n) # TODO(b/72873233) Move some variant of", "auto-correlated, `ESS` will be less than `N`. If there are", "formula below. weighted_auto_corr = _sum_pairs(weighted_auto_corr) * mask elif filter_threshold is", "tf.nest.map_structure(single_state, chains_states) def _potential_scale_reduction_single_state(state, independent_chain_ndims, split_chains, validate_args): \"\"\"potential_scale_reduction for one", "then # check for None. icn_const_ = tf.get_static_value( ps.convert_to_shape_tensor(independent_chain_ndims)) if", "[1]: <NAME>, Practical Markov chain Monte Carlo (with discussion). Statistical", "= tf.cumsum(mask, axis=0) # Step 4: mask = [1, 1,", "`filter_threshold` -- since many MCMC methods generate chains where `R_k", "``` #### References [1]: <NAME>, Practical Markov chain Monte Carlo", "``` Variance{ N**-1 * Sum{X_i} } = ESS**-1 * Variance{", "variance.\" sigma_2_plus = ((n - 1) / n) * w", "initial_state = target.sample(10) * 2. ==> (10, 2) # Get", "[[0, 1, 2], [3, 4, 5]] # E.g. reshape states", "name='state') n_samples_ = tf.compat.dimension_value(state.shape[0]) if n_samples_ is not None: #", "of total variance.\" sigma_2_plus = ((n - 1) / n)", "Returns: `Tensor` structure parallel to `chains_states` representing the R-hat statistic", "to the target. * If all chains converge to the", "0], ps.range(2, ps.rank(state))], axis=0)) # We're treating the new dim", "(-1 + 2 * tf.reduce_sum(weighted_auto_corr, axis=0)) def potential_scale_reduction(chains_states, independent_chain_ndims=1, split_chains=False,", "tfd = tfp.distributions target = tfd.MultivariateNormalDiag(scale_diag=[1., 2.]) # Get 10", "2: raise ValueError(msg) elif validate_args: assertions.append( assert_util.assert_greater(num_chains, 1., message=msg)) with", "must be `>= 1`, found: {}'.format( independent_chain_ndims)) def single_state(s): return", "b] into [a//2, 2, b]. state = tf.transpose( a=state, perm=ps.concat(", "((m + 1.) / m) * sigma_2_plus / w -", "2018 The TensorFlow Probability Authors. # # Licensed under the", ":= 1 - (W - 1/C * Sum_{c=1}^C s_c**2 R[k,", "state, ps.concat([[2, n_samples // 2], state_shape[1:]], axis=0) ) # Step", "# mask[i, ...] = 1 if auto_corr[j, ...] > threshold", "odd number of samples, keep all but the last sample.", "disable=g-direct-tensorflow-import __all__ = [ 'effective_sample_size', 'potential_scale_reduction', ] def effective_sample_size(states, filter_threshold=0.,", "If higher moments, or other statistics are desired, a different", "sample_axis, keepdims=True, biased=False), axis=sample_and_chain_axis) # sigma^2_+ is an estimate of", "tf.reduce_mean(auto_cov, cross_chain_dims) auto_corr = 1. - (biased_within_chain_variance - mean_auto_cov) /", "compute cross-chain ESS following [Vehtari et al. (2019)][2] by specifying", "So, along dimension zero, the mask will look like [1,", "under the License is distributed on an \"AS IS\" BASIS,", "@@effective_sample_size @@potential_scale_reduction \"\"\" from __future__ import absolute_import from __future__ import", "the property that pairwise sums of the elements of that", "Convergence of Iterative Simulations. _Journal of Computational and Graphical Statistics_,", "mean. # W := 1/C Sum_{c=1}^C s_c**2, within-chain variance. #", "as independent chains that ESS will be summed over. If", ":= 1 / N Sum_{n=1}^N x[n, c], chain mean. #", "`dtype` as `state`, and shape equal to `state.shape[1 + independent_chain_ndims:]`.", "= _reduce_variance( tf.reduce_mean(state, axis=sample_axis, keepdims=True), sample_and_chain_axis, biased=False) w = tf.reduce_mean(", "zero, the mask will look like [1, 1, ..., 0,", "`True`, divide samples from each chain into first and second", "for `k in {0, ..., N/2}`. Deviations are only possible", "zero out values of auto_corr below the threshold. # mask[i,", "# Process items, one at a time. def single_state(*args): return", "tf.maximum(1. - mask, 0.) weighted_auto_corr *= mask return num_chains *", "2.]) # Get 10 (2x) overdispersed initial states. initial_state =", "} = ESS**-1 * Variance{ X_1 }. ``` If the", "from Iterative Simulation Using Multiple Sequences. _Statistical Science_, 7(4):457-472, 1992.", "the chain variances. b_div_n = _reduce_variance( tf.reduce_mean(state, axis=sample_axis, keepdims=True), sample_and_chain_axis,", "least 2 samples. Found {}'.format(n_samples_)) elif validate_args: if split_chains: assertions", ":= number of chains # N := length of chains", "they will have the same mean, and thus the ratio", "exceeds what one would expect if the chains were identically", "b]. state = tf.reshape( state, ps.concat([[2, n_samples // 2], state_shape[1:]],", "it will reduce the noise in the estimate of `R_k`,", "Brooks and Gelman (1998), # B / n is the", "sample dimension in half, doubling the number of # independent", "if num_chains_ is not None: if num_chains_ < 2: raise", "results to be tested for convergence. split_chains: Python `bool`. If", "np.int64: state = tf.cast(state, tf.float64) elif dtype_util.is_integer(state.dtype): state = tf.cast(state,", "al. # (2019): # # R[k] := 1 - (W", "such that ``` Variance{ N**-1 * Sum{X_i} } = ESS**-1", "_sum_pairs(x): x_len = ps.shape(x)[0] # For odd sequences, we drop", "step, # Assume auto_corr = [1, 0.5, 0.0, 0.3], and", "two methods to perform this truncation. * `filter_threshold` -- since", "ValueError(msg) elif validate_args: assertions.append( assert_util.assert_greater(num_chains, 1., message=msg)) with tf.control_dependencies(assertions): #", "at least 2 samples.')] with tf.control_dependencies(assertions): state = tf.identity(state) #", "keep all but the last sample. state_shape = ps.shape(state) n_samples", "equation 10 of Vehtari et al. # (2019): # #", "from __future__ import absolute_import from __future__ import division from __future__", "the same target) by testing for equality of means. Specifically,", "localization: An improved R-hat for assessing convergence of MCMC, 2019.", "- k) / N, and give it shape [M, 1,...,1],", "measures the degree to which variance (of the means) between", "return num_chains * n / (-1 + 2 * tf.reduce_sum(weighted_auto_corr,", "not None: filter_threshold = tf.convert_to_tensor( filter_threshold, dtype=dt, name='filter_threshold') # Get", "index identically distributed states. filter_threshold: `Tensor` or Python structure of", "[2]: <NAME> and <NAME>. Inference from Iterative Simulation Using Multiple", "[0, 0, 1, 1] mask = tf.cast(mask, dt) # Step", "chain_axis) # In the language of Brooks and Gelman (1998),", "Move some variant of this to tfd.sample_stats. def _reduce_variance(x, axis=None,", "returns None iff a constant value (as a numpy #", "<NAME>. Inference from Iterative Simulation Using Multiple Sequences. _Statistical Science_,", "chain convergence. Given `N > 1` states from each of", "is the within sequence variance, the mean of the chain", "the `filter_beyond_lag` OR `filter_beyond_positive_pairs` criteria. This function can also compute", "splitting chains. ' 'Found {}'.format(n_samples_)) if not split_chains and n_samples_", "icn_const_ = tf.get_static_value( ps.convert_to_shape_tensor(independent_chain_ndims)) if icn_const_ is not None: independent_chain_ndims", "larger `k`. For this reason, the summation over `R_k` should", "floating-point division # check to see if the `state` is", "is not None: if num_chains_ < 2: raise ValueError(msg) elif", "to tfd.sample_stats. def _reduce_variance(x, axis=None, biased=True, keepdims=False): with tf.name_scope('reduce_variance'): x", "state = tf.identity(state) # Define so it's not a magic", "sequence are positive [Geyer][1], i.e. `R_{2k} + R_{2k + 1}", "noisy tail terms from `R_k`. You can combine `filter_beyond_lag` with", "need for truncation. Args: states: `Tensor` or Python structure of", "Copyright 2018 The TensorFlow Probability Authors. # # Licensed under", "--> infinity`, with `E`, `Var` denoting expectation and variance, ```R-hat", "and `filter_beyond_lag` are both structures of different shapes. ValueError: If", "1 / N Sum_{n=1}^N x[n, c], chain mean. # x_hat", "one at a time. def single_state(*args): return _effective_sample_size_single_state( *args, validate_args=validate_args)", "by first estimating the auto-correlation. Since `R_k` must be estimated", "with value `>= 1` giving the number of dimensions, from", "`independent_chain_ndims` must be `>= 1`, found: {}'.format( independent_chain_ndims)) def single_state(s):", "E.g. reshape states of shape [a, b] into [2, a//2,", "iid sample with the same variance as `state`. More precisely,", "= ps.shape(x)[0] # For odd sequences, we drop the final", "to noise. This method truncates the auto-correlation sequence where the", "the sequence is uncorrelated, `ESS = N`. If the sequence", "R[k] * (N - k) / N} # where M", "sample_axis = ps.range(0, sample_ndims) chain_axis = ps.range(sample_ndims, sample_ndims + independent_chain_ndims)", "2) ess = effective_sample_size(states, filter_beyond_positive_pairs=True) ==> Shape (2,) Tensor mean,", "None: if num_chains_ < 2: raise ValueError(msg) elif validate_args: assertions.append(", "`A`, can have any shape (even empty). independent_chain_ndims: Integer type", "\"\"\"ESS computation for one single Tensor argument.\"\"\" with tf.name_scope('effective_sample_size_single_state'): states", "halves, treating these as separate chains. This makes R-hat more", "Python structure of `Tensor` objects. Dimension zero should index identically", "index where the estimated auto-correlation becomes negative. This method does", "does improve effectiveness of the diagnostic. * Sometimes, R-hat <", "= tf.convert_to_tensor( filter_threshold, dtype=dt, name='filter_threshold') # Get a binary mask", "axis) return (n / (n - 1.)) * biased_var def", "_axis_size(x, axis) return (n / (n - 1.)) * biased_var", "ANY KIND, either express or implied. # See the License", "tf.reshape( state, ps.concat([[2, n_samples // 2], state_shape[1:]], axis=0) ) #", "target = tfd.MultivariateNormalDiag(scale_diag=[1., 2.]) # Get 10 (2x) overdispersed initial", "the diagnostic. * Sometimes, R-hat < 1.2 is used to", "be treated as a # chain, changing [[0, 1, 2],", "the License. # You may obtain a copy of the", "the sequence is positively auto-correlated, `ESS` will be less than", "have shape `[Ni, Ci1, Ci2,...,CiD] + A`. Dimension `0` indexes", "(10, 2) # Get 1000 samples from the 10 independent", "law of total variance, the numerator is the variance of", "if not split_chains and n_samples_ < 2: raise ValueError( 'Must", "both structures of different shapes. ValueError: If `cross_chain_dims` is not", "# See the License for the specific language governing permissions", "`Tensor` structure parallel to `chains_states` representing the R-hat statistic for", "sample from a 2-variate normal. ```python import tensorflow as tf", "7(4), 1998. [2]: <NAME> and <NAME>. Inference from Iterative Simulation", "`Tensor` or a structure of integer `Tensors` corresponding to each", "= tf.reshape( state, ps.concat([[2, n_samples // 2], state_shape[1:]], axis=0) )", "independent chain results to be tested for convergence. split_chains: Python", "sums become non-positive. The arguments `filter_beyond_lag`, `filter_threshold` and `filter_beyond_positive_pairs` are", "= [False, False, True, True] mask = _sum_pairs(auto_corr) < 0.", "first index where the estimated auto-correlation becomes negative. This method", "Ignored if `filter_beyond_positive_pairs` is `True`. filter_beyond_lag: `Tensor` or Python structure", "threshold. # mask[i, ...] = 1 if auto_corr[j, ...] >", "http://arxiv.org/abs/1903.08008 \"\"\" # tf.get_static_value returns None iff a constant value", "between chain variance, the variance of the chain means. #", "combine `filter_beyond_lag` with `filter_threshold` or `filter_beyond_positive_pairs. E.g., combining `filter_beyond_lag` and", "TODO(b/72873233) Move some variant of this to tfd.sample_stats. def _reduce_variance(x,", "1` result steps of the Markov Chain. Dimensions `1` through", "2 * Sum_{k=1}^N R[k] * (N - k) / N}", "nest_util.broadcast_structure(states, filter_threshold) filter_beyond_positive_pairs = nest_util.broadcast_structure( states, filter_beyond_positive_pairs) # Process items,", "2: mask = [0, 0, 1, 1] mask = tf.cast(mask,", "2], ps.shape(x)[1:]], axis=0) return tf.reduce_sum(tf.reshape(x, new_shape), 1) # Pairwise sums", "# check for None. icn_const_ = tf.get_static_value( ps.convert_to_shape_tensor(independent_chain_ndims)) if icn_const_", "chain paths were identical). * The above holds for any", "< 1: raise ValueError( 'Argument `independent_chain_ndims` must be `>= 1`,", "1992. [3]: <NAME>, <NAME>, <NAME>, <NAME>, Paul-Christian Burkner. Rank-normalization, folding,", "`dim = D`, holding independent chain results to be tested", "2, 3, 4, 5] # Step 1: reshape into [[0,", "((n - 1) / n) * w + b_div_n return", "stats from tensorflow_probability.python.internal import assert_util from tensorflow_probability.python.internal import dtype_util from", "smaller number than computing the ESS for individual chains and", "a 2-variate normal. ```python import tensorflow as tf import tensorflow_probability", "N/2}`. Deviations are only possible due to noise. This method", "kernel=tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=target.log_prob, step_size=0.05, num_leapfrog_steps=20)) states.shape ==> (1000, 2) ess =", "- (biased_within_chain_variance - mean_auto_cov) / approx_variance else: auto_corr = auto_cov", "a constant value (as a numpy # array) is not", "icn_const_ is not None: independent_chain_ndims = icn_const_ if icn_const_ <", "Get 1000 states from one chain. states = tfp.mcmc.sample_chain( num_burnin_steps=200,", "is the full sequence. auto_cov = stats.auto_correlation( states, axis=0, max_lags=filter_beyond_lag,", "`axis`, as type `x.dtype`.\"\"\" if axis is None: return ps.cast(ps.size(x),", "< N`. This function provides two methods to perform this", "[Brooks and Gelman (1998)][2]. * R-hat only measures non-convergence of", "through `D` index the `Ci1 x ... x CiD` independent", ":= Covariance{X_1, X_{1+k}} / Variance{X_1}`, we have ``` ESS(N) =", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "# R[k] := 1 - (W - 1/C * Sum_{c=1}^C", "not None: independent_chain_ndims = icn_const_ if icn_const_ < 1: raise", "ValueError: If `independent_chain_ndims < 1`. #### Examples Diagnosing convergence by", "correlated samples # from each Markov chain. state = tf.convert_to_tensor(state,", "and <NAME>. Inference from Iterative Simulation Using Multiple Sequences. _Statistical", "= ps.range( 0, sample_ndims + independent_chain_ndims) n = _axis_size(state, sample_axis)", "chain. states = tfp.mcmc.sample_chain( num_burnin_steps=200, num_results=1000, current_state=tf.constant([0., 0.]), trace_fn=None, kernel=tfp.mcmc.HamiltonianMonteCarlo(", "writing, software # distributed under the License is distributed on", "w = tf.reduce_mean( _reduce_variance(state, sample_axis, keepdims=True, biased=False), axis=sample_and_chain_axis) # sigma^2_+", "= ps.concat([[x_len // 2, 2], ps.shape(x)[1:]], axis=0) return tf.reduce_sum(tf.reshape(x, new_shape),", "return _effective_sample_size_single_state( *args, validate_args=validate_args) with tf.name_scope('effective_sample_size' if name is None", "message=msg)) with tf.control_dependencies(assertions): # We're computing the R[k] from equation", "auto_corr k = tf.range(0., _axis_size(auto_corr, axis=0)) nk_factor = (n -", "keepdims=True) biased_var = tf.reduce_mean( tf.math.squared_difference(x, mean), axis=axis, keepdims=keepdims) if biased:", "= tfp.mcmc.sample_chain( num_burnin_steps=200, num_results=1000, current_state=initial_state, trace_fn=None, kernel=tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=target.log_prob, step_size=0.05, num_leapfrog_steps=20))", "of `states` to treat as independent chains that ESS will", "constant value (as a numpy # array) is not efficiently", "step_size=0.05, num_leapfrog_steps=20)) chains_states.shape ==> (1000, 10, 2) rhat = tfp.mcmc.diagnostic.potential_scale_reduction(", "m) * sigma_2_plus / w - (n - 1.) /", "= nest_util.broadcast_structure(states, filter_threshold) filter_beyond_positive_pairs = nest_util.broadcast_structure( states, filter_beyond_positive_pairs) # Process", "add runtime checks of argument validity. If False, and arguments", "the noise in the estimate of `R_k`, reducing the need", "Rank-normalization, folding, and localization: An improved R-hat for assessing convergence", "> N`) correctly. * `filter_beyond_positive_pairs` -- reversible MCMC chains produce", "M is the filter_beyond_lag truncation point chosen above. # Get", "chain. state = tf.convert_to_tensor(state, name='state') n_samples_ = tf.compat.dimension_value(state.shape[0]) if n_samples_", "# where: # C := number of chains # N", "sequence. auto_cov = stats.auto_correlation( states, axis=0, max_lags=filter_beyond_lag, normalize=False) n =", "ValueError( 'Argument `independent_chain_ndims` must be `>= 1`, found: {}'.format( independent_chain_ndims))", "any number less than `-1` has the same effect. Ignored", "2. # It still works fine in the formula below.", "mask = [1, 1, 0, 0] mask = tf.maximum(1. -", "chain results to be tested for convergence. split_chains: Python `bool`.", "number such that ``` Variance{ N**-1 * Sum{X_i} } =", "Returns: ess: `Tensor` structure parallel to `states`. The effective sample", "a time. def single_state(*args): return _effective_sample_size_single_state( *args, validate_args=validate_args) with tf.name_scope('effective_sample_size'", "where the pairwise sums become non-positive. The arguments `filter_beyond_lag`, `filter_threshold`", "m, ...], auto-correlation indexed by chain. # var^+ := (N", "degree to which variance (of the means) between chains exceeds", "bound on effective sample size for each independent chain. Roughly", "`filter_beyond_lag` OR `filter_beyond_positive_pairs` criteria. This function can also compute cross-chain", "the size of lags. filter_beyond_positive_pairs: Python boolean. If `True`, only", "k) / n if tensorshape_util.rank(auto_corr.shape) is not None: new_shape =", "'Must provide at least 2 samples. Found {}'.format(n_samples_)) elif validate_args:", "mask return num_chains * n / (-1 + 2 *", "Args: states: `Tensor` or Python structure of `Tensor` objects. Dimension", "\"\"\"<NAME> Rubin (1992)'s potential scale reduction for chain convergence. Given", "is still preferrable to compute cross-chain ESS via this method", "assessing convergence of MCMC, 2019. Retrieved from http://arxiv.org/abs/1903.08008 \"\"\" if", "(x[n, c] - x_hat[c])**2, chain # variance # R[k, m]", "all but the last sample. state_shape = ps.shape(state) n_samples =", "the states of a Markov Chain at each result step.", "tf.reduce_sum(weighted_auto_corr, axis=0)) def potential_scale_reduction(chains_states, independent_chain_ndims=1, split_chains=False, validate_args=False, name=None): \"\"\"<NAME> Rubin", "> 1`. Increasing `C` does improve effectiveness of the diagnostic.", "Gelman (1998)][2]. Args: chains_states: `Tensor` or Python structure of `Tensor`s", "if icn_const_ < 1: raise ValueError( 'Argument `independent_chain_ndims` must be", "ESS for individual chains and then summing them. In an", "'Found {}'.format(n_samples_)) if not split_chains and n_samples_ < 2: raise", "If `cross_chain_dims` is None, the shape will be `states.shape[1:]`. Otherwise,", "# Step 3: mask = [0, 0, 1, 1] mask", "variance. # B := N / (C - 1) Sum_{c=1}^C", "N`) correctly. * `filter_beyond_positive_pairs` -- reversible MCMC chains produce an", "filter_beyond_positive_pairs, cross_chain_dims, validate_args): \"\"\"ESS computation for one single Tensor argument.\"\"\"", "the elements of that sequence are positive [Geyer][1], i.e. `R_{2k}", "step by step, # Assume auto_corr = [1, 0.5, 0.0,", "> 1` independent chains, the potential scale reduction factor, commonly", "W + B / N cross_chain_dims = ps.non_negative_axis( cross_chain_dims, ps.rank(states))", "single Tensor argument.\"\"\" with tf.name_scope('effective_sample_size_single_state'): states = tf.convert_to_tensor(states, name='states') dt", "R[k] * (N - k) / N} (since R[0] =", "lower bound on effective sample size for each independent chain.", "Step 2: Put the size `2` dimension in the right", "0] mask = tf.maximum(1. - mask, 0.) weighted_auto_corr *= mask", "axis=0)) def potential_scale_reduction(chains_states, independent_chain_ndims=1, split_chains=False, validate_args=False, name=None): \"\"\"<NAME> Rubin (1992)'s", "cross_chain_dims = ps.non_negative_axis( cross_chain_dims, ps.rank(states)) # B / N between_chain_variance_div_n", "R-hat < 1.2 is used to indicate approximate convergence, but", "of the diagnostic. * Sometimes, R-hat < 1.2 is used", "chains (where `ESS > N`) correctly. * `filter_beyond_positive_pairs` -- reversible", "criteria. This function can also compute cross-chain ESS following [Vehtari", "changing [[0, 1, 2], [3, 4, 5]] into [[0, 3],", "0, 0] mask = tf.maximum(1. - mask, 0.) weighted_auto_corr *=", "sample_and_chain_axis = ps.range( 0, sample_ndims + independent_chain_ndims) n = _axis_size(state,", "of possibly correlated random variables `X_1, X_2, ..., X_N`, identically", "Dimension zero should index identically distributed states. filter_threshold: `Tensor` or", "filter_beyond_lag truncation point chosen above. # Get the factor (N", "N`. If the sequence is positively auto-correlated, `ESS` will be", "an extreme case where the chains have fallen into K", "<= 1`, setting to any number less than `-1` has", "use ESS to estimate standard error. ``` import tensorflow as", "non-mixing modes, this function will return ESS ~ K. Even", "of `states`. If `cross_chain_dims` is None, the shape will be", "10 (2x) overdispersed initial states. initial_state = target.sample(10) * 2.", "samples when splitting chains. ' 'Found {}'.format(n_samples_)) if not split_chains", "``` ESS(N) = N / [ 1 + 2 *", "between chains exceeds what one would expect if the chains", "states from each of `C > 1` independent chains, the", "+ b_div_n return ((m + 1.) / m) * sigma_2_plus", "1 / (N - 1) Sum_{n=1}^N (x[n, c] - x_hat[c])**2,", "Gelman (1998)][2]. Some guidelines: * The initial state of the", "numpy object for the numpy test suite if dtype_util.as_numpy_dtype(state.dtype) is", "precisely, given a stationary sequence of possibly correlated random variables", "distribution overdispersed with respect to the target. * If all", "'potential_scale_reduction', ] def effective_sample_size(states, filter_threshold=0., filter_beyond_lag=None, filter_beyond_positive_pairs=False, cross_chain_dims=None, validate_args=False, name=None):", "current_state=tf.constant([0., 0.]), trace_fn=None, kernel=tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=target.log_prob, step_size=0.05, num_leapfrog_steps=20)) states.shape ==> (1000,", "states, single_state, states, filter_beyond_lag, filter_threshold, filter_beyond_positive_pairs, cross_chain_dims) def _effective_sample_size_single_state(states, filter_beyond_lag,", "a different diagnostic should be used. See [Brooks and Gelman", "name: `String` name to prepend to created tf. Default: `potential_scale_reduction`.", "`C` does improve effectiveness of the diagnostic. * Sometimes, R-hat", "The above holds for any number of chains `C >", "Monitoring Convergence of Iterative Simulations. _Journal of Computational and Graphical", "+ 1} > 0` for `k in {0, ..., N/2}`.", "Inference from Iterative Simulation Using Multiple Sequences. _Statistical Science_, 7(4):457-472,", "chain_axis = ps.range(sample_ndims, sample_ndims + independent_chain_ndims) sample_and_chain_axis = ps.range( 0,", "non-convergence of the mean. If higher moments, or other statistics", "robust to non-stationary chains, and is recommended in [3]. validate_args:", "should be truncated at some number `filter_beyond_lag < N`. This", "--> 1. Before that, R-hat > 1 (except in pathological", "2] new_shape = ps.concat([[x_len // 2, 2], ps.shape(x)[1:]], axis=0) return", "Whether to add runtime checks of argument validity. If False,", "means) between chains exceeds what one would expect if the", "paths were identical). * The above holds for any number", "[3]. validate_args: Whether to add runtime checks of argument validity.", "tf.get_static_value( ps.convert_to_shape_tensor(independent_chain_ndims)) if icn_const_ is not None: independent_chain_ndims = icn_const_", "provide at least 4 samples when splitting chains. ' 'Found", "final value. x = x[:x_len - x_len % 2] new_shape", "(1000, 10, 2) rhat = tfp.mcmc.diagnostic.potential_scale_reduction( chains_states, independent_chain_ndims=1) # The", "one leading dimension indexes e.g. correlated samples # from each", "= states.dtype # filter_beyond_lag == None ==> auto_corr is the", "in the limit `N, C --> infinity`, with `E`, `Var`", "auto_corr = auto_cov / auto_cov[:1] num_chains = 1 # With", "= auto_cov / auto_cov[:1] num_chains = 1 # With R[k]", "nest.map_structure_up_to( states, single_state, states, filter_beyond_lag, filter_threshold, filter_beyond_positive_pairs, cross_chain_dims) def _effective_sample_size_single_state(states,", "numpy as np import tensorflow.compat.v2 as tf from tensorflow_probability.python import", "have fallen into K non-mixing modes, this function will return", "well. In general, this will be a smaller number than", "chains. # E.g. imagine the pairwise sums are [0.2, 0.1,", "variance, the variance of the chain means. # W is", "second halves, treating these as separate chains. This makes R-hat", "num_chains * n / (-1 + 2 * tf.reduce_sum(weighted_auto_corr, axis=0))", "biased_within_chain_variance + between_chain_variance_div_n) # 1/C * Sum_{c=1}^C s_c**2 R[k, c]", "References [1]: <NAME> and <NAME>. General Methods for Monitoring Convergence", "num_burnin_steps=200, num_results=1000, current_state=tf.constant([0., 0.]), trace_fn=None, kernel=tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=target.log_prob, step_size=0.05, num_leapfrog_steps=20)) states.shape", "convergence of the chains (to the same target) by testing", "If `True`, divide samples from each chain into first and", "tensorshape_util from tensorflow.python.util import nest # pylint: disable=g-direct-tensorflow-import __all__ =", "the estimated auto-correlation becomes negative. This method does not estimate", "treat as independent chains that ESS will be summed over.", "from equation 10 of Vehtari et al. # (2019): #", "auto-correlation sequence with the property that pairwise sums of the", "of shape [a, b] into [2, a//2, b]. state =", "K non-mixing modes, this function will return ESS ~ K.", "For odd number of samples, keep all but the last", "auto_corr is the full sequence. auto_cov = stats.auto_correlation( states, axis=0,", "# E.g. reshape states of shape [a, b] into [2,", "mask = tf.cast(mask, dt) # Step 3: mask = [0,", "sequence of auto-correlations is truncated after the first appearance of", "(1998)][2]. * R-hat only measures non-convergence of the mean. If", "state_shape[1:]], axis=0) ) # Step 2: Put the size `2`", "* `filter_threshold` -- since many MCMC methods generate chains where", "tf.reduce_mean(x, axis=axis, keepdims=True) biased_var = tf.reduce_mean( tf.math.squared_difference(x, mean), axis=axis, keepdims=keepdims)", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "('When `cross_chain_dims` is not `None`, there must be > 1", "auto_cov[:1] num_chains = 1 # With R[k] := auto_corr[k, ...],", "/ ess) ``` #### References [1]: <NAME>, Practical Markov chain", "= ( E[Var[X | chain]] + Var[E[X | chain]] )", "still preferrable to compute cross-chain ESS via this method because", "same variance as `state`. More precisely, given a stationary sequence", "filter_threshold = tf.convert_to_tensor( filter_threshold, dtype=dt, name='filter_threshold') # Get a binary", "/ E[Var[X | chain]].``` Using the law of total variance,", "cross_chain_dims = nest_util.broadcast_structure(states, None) filter_beyond_lag = nest_util.broadcast_structure(states, filter_beyond_lag) filter_threshold =", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "- k) / N} (since R[0] = 1) # approx", "method because it will reduce the noise in the estimate", "chain mean. # x_hat := 1 / C Sum_{c=1}^C x_hat[c],", "estimated auto-correlation becomes negative. This method does not estimate the", "is None else name): return nest.map_structure_up_to( states, single_state, states, filter_beyond_lag,", "num_chains_ is not None: if num_chains_ < 2: raise ValueError(msg)", "were identical). * The above holds for any number of", "size of lags. filter_beyond_positive_pairs: Python boolean. If `True`, only consider", "at least 4 samples when splitting chains. ' 'Found {}'.format(n_samples_))", "the chains are not mixing well. In general, this will", "0, sample_ndims + independent_chain_ndims) n = _axis_size(state, sample_axis) m =", "tf.reshape(nk_factor, new_shape) weighted_auto_corr = nk_factor * auto_corr if filter_beyond_positive_pairs: def", "dtype=dt, name='filter_threshold') # Get a binary mask to zero out", "to prepend to created ops. Returns: ess: `Tensor` structure parallel", "W * (N - 1) / N biased_within_chain_variance = tf.reduce_mean(auto_cov[0],", "tf.name_scope('potential_scale_reduction' if name is None else name): return tf.nest.map_structure(single_state, chains_states)", "less than `-1` has the same effect. Ignored if `filter_beyond_positive_pairs`", "`D` index the `Ci1 x ... x CiD` independent chains", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "`potential_scale_reduction`. Returns: `Tensor` structure parallel to `chains_states` representing the R-hat", "of elements of `x` in `axis`, as type `x.dtype`.\"\"\" if", "`states` is provided, then this argument should also be a", "# Step 1: mask = [False, False, True, True] mask", "raise ValueError( 'Must provide at least 4 samples when splitting", "that, R-hat > 1 (except in pathological cases, e.g. if", "2) # Get 1000 samples from the 10 independent chains.", "assessing convergence of MCMC, 2019. Retrieved from http://arxiv.org/abs/1903.08008 \"\"\" #", "Split the sample dimension in half, doubling the number of", "to perform this truncation. * `filter_threshold` -- since many MCMC", "(2,) Tensor mean, variance = tf.nn.moments(states, axis=0) standard_error = tf.sqrt(variance", "still works fine in the formula below. weighted_auto_corr = _sum_pairs(weighted_auto_corr)", "10, 2) rhat = tfp.mcmc.diagnostic.potential_scale_reduction( chains_states, independent_chain_ndims=1) # The second", "and <NAME>. General Methods for Monitoring Convergence of Iterative Simulations.", "if auto_corr[j, ...] > threshold for all j <= i,", "* R-hat only measures non-convergence of the mean. If higher", "argument. Cross-chain ESS takes into account the cross-chain variance to", "# N.B. this reduces the length of weighted_auto_corr by a", "the auto-correlation sequence, `R_k := Covariance{X_1, X_{1+k}} / Variance{X_1}`, we", "have ``` ESS(N) = N / [ 1 + 2", "`Tensor` structure parallel to `states`. The effective sample size of", "one. #### References [1]: <NAME> and <NAME>. General Methods for", "[3, 4, 5]] # E.g. reshape states of shape [a,", "terms from `R_k`. You can combine `filter_beyond_lag` with `filter_threshold` or", "{-1 + 2 * Sum_{k=0}^N R[k] * (N - k)", "in the right place to be treated as a #", "are both structures of different shapes. ValueError: If `cross_chain_dims` is", "out values of auto_corr below the threshold. # mask[i, ...]", "is an estimate of the true variance, which would be", "axis=0) return tf.reduce_sum(tf.reshape(x, new_shape), 1) # Pairwise sums are all", "N / {-1 + 2 * Sum_{k=0}^M R[k] * (N", "2] # Suppose state = [0, 1, 2, 3, 4,", "to `None` means we use no threshold filter. Since `|R_k|", "than computing the ESS for individual chains and then summing", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "Get 1000 samples from the 10 independent chains. chains_states =", "ndims the same as auto_corr k = tf.range(0., _axis_size(auto_corr, axis=0))", "chains and then summing them. In an extreme case where", "`String` name to prepend to created tf. Default: `potential_scale_reduction`. Returns:", "number less than `-1` has the same effect. Ignored if", "independent chains. # For odd number of samples, keep all", "`ESS = N`. If the sequence is positively auto-correlated, `ESS`", "than `-1` has the same effect. Ignored if `filter_beyond_positive_pairs` is", "/ (N - 1) Sum_{n=1}^N (x[n, c] - x_hat[c])**2, chain", "# B / n is the between chain variance, the", "convergence. Given `N > 1` states from each of `C", "__future__ import print_function import numpy as np import tensorflow.compat.v2 as", "k) / N} (since R[0] = 1) # approx N", "or Python structure of `Tensor` objects. Dimension zero should index", "if dtype_util.as_numpy_dtype(state.dtype) is np.int64: state = tf.cast(state, tf.float64) elif dtype_util.is_integer(state.dtype):", "x = x[:x_len - x_len % 2] new_shape = ps.concat([[x_len", "specific language governing permissions and # limitations under the License.", "tfd.MultivariateNormalDiag(scale_diag=[1., 2.]) # Get 1000 states from one chain. states", "(N - 1) / N biased_within_chain_variance = tf.reduce_mean(auto_cov[0], cross_chain_dims -", "The remaining dimensions, `A`, can have any shape (even empty).", "= ps.range(sample_ndims, sample_ndims + independent_chain_ndims) sample_and_chain_axis = ps.range( 0, sample_ndims", "will be summed over. If `None`, no summation is performed.", "# each chain was drawn from the target. c.f. \"law", "tf.reduce_mean(auto_cov[0], cross_chain_dims - 1) # var^+ approx_variance = ( biased_within_chain_variance", "biased: return biased_var n = _axis_size(x, axis) return (n /", "than `N`. If there are negative correlations, then `ESS` can", "Rubin (1992)'s potential scale reduction for chain convergence. Given `N", "type `x.dtype`.\"\"\" if axis is None: return ps.cast(ps.size(x), x.dtype) return", "math shows that, with `R_k` the auto-correlation sequence, `R_k :=", "states from one chain. states = tfp.mcmc.sample_chain( num_burnin_steps=200, num_results=1000, current_state=tf.constant([0.,", "reasonable criterion is to truncate at the first index where", "None else name): return nest.map_structure_up_to( states, single_state, states, filter_beyond_lag, filter_threshold,", "sample_ndims) chain_axis = ps.range(sample_ndims, sample_ndims + independent_chain_ndims) sample_and_chain_axis = ps.range(", "of auto-correlations is truncated to this length. Setting to `None`", "split_chains and n_samples_ < 4: raise ValueError( 'Must provide at", "from http://arxiv.org/abs/1903.08008 \"\"\" # tf.get_static_value returns None iff a constant", "chains_states: `Tensor` or Python structure of `Tensor`s representing the states", "= tf.identity(state) else: assertions = [assert_util.assert_greater( ps.shape(state)[0], 2, message='Must provide", "c] - x_hat[c])**2, chain # variance # R[k, m] :=", "2 * tf.reduce_sum(weighted_auto_corr, axis=0)) def potential_scale_reduction(chains_states, independent_chain_ndims=1, split_chains=False, validate_args=False, name=None):", "# you may not use this file except in compliance", "means we do not filter based on the size of", "axis=sample_and_chain_axis) # sigma^2_+ is an estimate of the true variance,", "total variance.\" sigma_2_plus = ((n - 1) / n) *", "= auto_corr < filter_threshold # Step 2: mask = [0,", "computable. Therefore, we try constant_value then # check for None.", "argument.\"\"\" with tf.name_scope('effective_sample_size_single_state'): states = tf.convert_to_tensor(states, name='states') dt = states.dtype", "is not efficiently computable. Therefore, we try constant_value then #", "`filter_beyond_lag < N`. This function provides two methods to perform", "_Journal of Computational and Graphical Statistics_, 7(4), 1998. [2]: <NAME>", "/ (-1 + 2 * tf.reduce_sum(weighted_auto_corr, axis=0)) def potential_scale_reduction(chains_states, independent_chain_ndims=1,", "uncorrelated, `ESS = N`. If the sequence is positively auto-correlated,", "and scalar valued. The sequence of auto-correlations is truncated to", "[3]: <NAME>, <NAME>, <NAME>, <NAME>, Paul-Christian Burkner. Rank-normalization, folding, and", "variable drawn uniformly from the combined states (combined over all", "if cross_chain_dims is not None: num_chains = _axis_size(states, cross_chain_dims) num_chains_", "Science, 7:473-511, 1992. [2]: <NAME>, <NAME>, <NAME>, <NAME>, <NAME>. Rank-normalization,", "tf.convert_to_tensor(states, name='states') dt = states.dtype # filter_beyond_lag == None ==>", "1, ..., 0, 0,...] # Building step by step, #", "be tested for convergence. split_chains: Python `bool`. If `True`, divide", "objects. Must be `int`-like and scalar valued. The sequence of", "`states` to treat as independent chains that ESS will be", "n = _axis_size(x, axis) return (n / (n - 1.))", "None: independent_chain_ndims = icn_const_ if icn_const_ < 1: raise ValueError(", "normalize=False) n = _axis_size(states, axis=0) if cross_chain_dims is not None:", "of `states` is provided, then this argument should also be", "is the size of an iid sample with the same", "it is still preferrable to compute cross-chain ESS via this", "ValueError: If `states` and `filter_threshold` or `states` and `filter_beyond_lag` are", "where the pairwise sums are positive. cross_chain_dims: An integer `Tensor`", "separate chains. This makes R-hat more robust to non-stationary chains,", "of argument validity. If False, and arguments are incorrect, correct", "than 2 chains. #### Examples We use ESS to estimate", "is np.int64: state = tf.cast(state, tf.float64) elif dtype_util.is_integer(state.dtype): state =", "Integer type `Tensor` with value `>= 1` giving the number", "shape is `tf.reduce_mean(states, cross_chain_dims).shape[1:]`. Raises: ValueError: If `states` and `filter_threshold`", "[Geyer][1], i.e. `R_{2k} + R_{2k + 1} > 0` for", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "ESS via this method because it will reduce the noise", "/ N biased_within_chain_variance = tf.reduce_mean(auto_cov[0], cross_chain_dims - 1) # var^+", "* Sometimes, R-hat < 1.2 is used to indicate approximate", "/ N * R_{N-1} ) ] ``` This function estimates", "independent chains to be tested for convergence to the same", "of different shapes. ValueError: If `cross_chain_dims` is not `None` and", "nest # pylint: disable=g-direct-tensorflow-import __all__ = [ 'effective_sample_size', 'potential_scale_reduction', ]", "sequence is positively auto-correlated, `ESS` will be less than `N`.", "provide at least 4 samples when splitting chains.')] with tf.control_dependencies(assertions):", "of means. Specifically, R-hat measures the degree to which variance", "axis=cross_chain_dims - 1) # W * (N - 1) /", "from tensorflow_probability.python.internal import nest_util from tensorflow_probability.python.internal import prefer_static as ps", "be estimated using only `N - k` samples, it becomes", "will look like [1, 1, ..., 0, 0,...] # Building", "under the Apache License, Version 2.0 (the \"License\"); # you", "1, 2, 3, 4, 5] # Step 1: reshape into", "same target) by testing for equality of means. Specifically, R-hat", "# We're computing the R[k] from equation 10 of Vehtari", "[1, 1, ..., 0, 0,...] # Building step by step,", "independent_chain_ndims += 1 sample_axis = ps.range(0, sample_ndims) chain_axis = ps.range(sample_ndims,", "shape [a, b] into [2, a//2, b]. state = tf.reshape(", "ps.rank(state))], axis=0)) # We're treating the new dim as indexing", ":= N / (C - 1) Sum_{c=1}^C (x_hat[c] - x_hat)**2,", "this length. Setting to `None` means we do not filter", "with tf.name_scope('effective_sample_size_single_state'): states = tf.convert_to_tensor(states, name='states') dt = states.dtype #", "a=state, perm=ps.concat( [[1, 0], ps.range(2, ps.rank(state))], axis=0)) # We're treating", "is not `None`, there must be > 1 chain '", "the target. c.f. \"law of total variance.\" sigma_2_plus = ((n", "a # chain, changing [[0, 1, 2], [3, 4, 5]]", "same target. The remaining dimensions, `A`, can have any shape", "Iterative Simulations. _Journal of Computational and Graphical Statistics_, 7(4), 1998.", "is 1! sample_ndims = 1 if split_chains: # Split the", "k) / N} # = N / {-1 + 2", "Chain Monte Carlo (MCMC) sampling. @@effective_sample_size @@potential_scale_reduction \"\"\" from __future__", "as indexing 2 chains, so increment. independent_chain_ndims += 1 sample_axis", "__all__ = [ 'effective_sample_size', 'potential_scale_reduction', ] def effective_sample_size(states, filter_threshold=0., filter_beyond_lag=None,", "raise ValueError(msg) elif validate_args: assertions.append( assert_util.assert_greater(num_chains, 1., message=msg)) with tf.control_dependencies(assertions):", "# Step 2: mask = [0, 0, 1, 1] mask", "/ N} # = N / {-1 + 2 *", "References [1]: <NAME>, Practical Markov chain Monte Carlo (with discussion).", "states, axis=0, max_lags=filter_beyond_lag, normalize=False) n = _axis_size(states, axis=0) if cross_chain_dims", "becomes progressively noisier for larger `k`. For this reason, the", "dimension zero, the mask will look like [1, 1, ...,", "[Brooks and Gelman (1998)][2]. Some guidelines: * The initial state", "based on the size of lags. filter_beyond_positive_pairs: Python boolean. If", "`R_k` must be estimated using only `N - k` samples,", "tf.convert_to_tensor(x, name='x') mean = tf.reduce_mean(x, axis=axis, keepdims=True) biased_var = tf.reduce_mean(", "same as auto_corr k = tf.range(0., _axis_size(auto_corr, axis=0)) nk_factor =", "at each result step. The `ith` state is assumed to", "...], auto-correlation indexed by chain. # var^+ := (N -", "tf.cast(mask, dtype=dt) # Step 3: mask = [0, 0, 1,", "x[:x_len - x_len % 2] new_shape = ps.concat([[x_len // 2,", "[ 'effective_sample_size', 'potential_scale_reduction', ] def effective_sample_size(states, filter_threshold=0., filter_beyond_lag=None, filter_beyond_positive_pairs=False, cross_chain_dims=None,", "- k) / N} # where M is the filter_beyond_lag", "possibly correlated random variables `X_1, X_2, ..., X_N`, identically distributed,", "the 10 independent chains. chains_states = tfp.mcmc.sample_chain( num_burnin_steps=200, num_results=1000, current_state=initial_state,", "limit `N, C --> infinity`, with `E`, `Var` denoting expectation", "they were to be filtered under the `filter_beyond_lag` OR `filter_beyond_positive_pairs`", "ps.range(0, sample_ndims) chain_axis = ps.range(sample_ndims, sample_ndims + independent_chain_ndims) sample_and_chain_axis =", "# We assume exactly one leading dimension indexes e.g. correlated", "denominator be C - 1. axis=cross_chain_dims - 1) # W", "below. weighted_auto_corr = _sum_pairs(weighted_auto_corr) * mask elif filter_threshold is not", "recommended in [3]. validate_args: Whether to add runtime checks of", "{}'.format(n_samples_)) if not split_chains and n_samples_ < 2: raise ValueError(", "the limit `N, C --> infinity`, with `E`, `Var` denoting", "test suite if dtype_util.as_numpy_dtype(state.dtype) is np.int64: state = tf.cast(state, tf.float64)", "name=None): \"\"\"<NAME> Rubin (1992)'s potential scale reduction for chain convergence.", "N * W + B / N cross_chain_dims = ps.non_negative_axis(", "mask, 0.) weighted_auto_corr *= mask return num_chains * n /", "to `chains_states` representing the R-hat statistic for the state(s). Same", "R[0] = 1) # approx N / {-1 + 2", "cross_chain_dims is None: cross_chain_dims = nest_util.broadcast_structure(states, None) filter_beyond_lag = nest_util.broadcast_structure(states,", "1` to `dim = D`, holding independent chain results to", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "for assessing convergence of MCMC, 2019. Retrieved from http://arxiv.org/abs/1903.08008 \"\"\"", "of samples, keep all but the last sample. state_shape =", ":= auto_corr[k, ...], # ESS = N / {1 +", "biased_within_chain_variance = tf.reduce_mean(auto_cov[0], cross_chain_dims - 1) # var^+ approx_variance =", "correlated random variables `X_1, X_2, ..., X_N`, identically distributed, ESS", "function provides two methods to perform this truncation. * `filter_threshold`", "this reason, the summation over `R_k` should be truncated at", "m] := auto_corr[k, m, ...], auto-correlation indexed by chain. #", "ESS**-1 * Variance{ X_1 }. ``` If the sequence is", "use no threshold filter. Since `|R_k| <= 1`, setting to", "to any number less than `-1` has the same effect.", "is the total variance minus the variance of the the", "for auto-correlation spectra derived from # reversible MCMC chains. #", "drawn uniformly from the combined states (combined over all chains).", "- x_hat)**2, between chain # variance. # s_c**2 := 1", "divide samples from each chain into first and second halves,", "E.g., combining `filter_beyond_lag` and `filter_beyond_positive_pairs` means that terms are removed", "then `ESS` can exceed `N`. Some math shows that, with", "is not `None` and there are less than 2 chains.", "will return ESS ~ K. Even when chains are mixing", "if tensorshape_util.rank(auto_corr.shape) is not None: new_shape = [-1] + [1]", "if the chains were identically distributed. See [Gelman and Rubin", "B := N / (C - 1) Sum_{c=1}^C (x_hat[c] -", "convergence to the same target. The remaining dimensions, `A`, can", "convergence by monitoring 10 chains that each attempt to sample", "auto_cov = stats.auto_correlation( states, axis=0, max_lags=filter_beyond_lag, normalize=False) n = _axis_size(states,", "x_hat[c])**2, chain # variance # R[k, m] := auto_corr[k, m,", "keepdims=True, biased=False), axis=sample_and_chain_axis) # sigma^2_+ is an estimate of the", "dtype=tf.int32)), axis=0) nk_factor = tf.reshape(nk_factor, new_shape) weighted_auto_corr = nk_factor *", "<NAME> and <NAME>. Inference from Iterative Simulation Using Multiple Sequences.", "each component of `states`. If `cross_chain_dims` is None, the shape", "objects. Dimension zero should index identically distributed states. filter_threshold: `Tensor`", "`|R_k| <= 1`, setting to any number less than `-1`", "filter based on the size of lags. filter_beyond_positive_pairs: Python boolean.", "noisier for larger `k`. For this reason, the summation over", "`filter_threshold` and `filter_beyond_positive_pairs` are filters intended to remove noisy tail", "= _sum_pairs(auto_corr) < 0. # Step 2: mask = [0,", ":= 1 / C Sum_{c=1}^C x_hat[c], overall mean. # W", "where the chains are not mixing well. In general, this", "filter_beyond_lag) filter_threshold = nest_util.broadcast_structure(states, filter_threshold) filter_beyond_positive_pairs = nest_util.broadcast_structure( states, filter_beyond_positive_pairs)", "attempt to sample from a 2-variate normal. ```python import tensorflow", "Some guidelines: * The initial state of the chains should", "random variable drawn uniformly from the combined states (combined over", "0, 0,...] # Building step by step, # Assume auto_corr", "If all chains converge to the target, then as `N", "N * R_{N-1} ) ] ``` This function estimates the", "mean. If higher moments, or other statistics are desired, a", "4], [2, 5]], # reshaping [2, a//2, b] into [a//2,", "Cross-chain ESS takes into account the cross-chain variance to reduce", "tf.name_scope('reduce_variance'): x = tf.convert_to_tensor(x, name='x') mean = tf.reduce_mean(x, axis=axis, keepdims=True)", "mask will look like [1, 1, ..., 0, 0,...] #", "at least 4 samples when splitting chains.')] with tf.control_dependencies(assertions): state", "def _reduce_variance(x, axis=None, biased=True, keepdims=False): with tf.name_scope('reduce_variance'): x = tf.convert_to_tensor(x,", "mean of the chain variances. b_div_n = _reduce_variance( tf.reduce_mean(state, axis=sample_axis,", "from tensorflow_probability.python import stats from tensorflow_probability.python.internal import assert_util from tensorflow_probability.python.internal", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "noise. This method truncates the auto-correlation sequence where the pairwise", "`N`. Some math shows that, with `R_k` the auto-correlation sequence,", "R-hat more robust to non-stationary chains, and is recommended in", "a//2, b]. state = tf.reshape( state, ps.concat([[2, n_samples // 2],", "2: mask = [0, 0, 1, 0] mask = tf.cast(mask,", "indexed by chain. # var^+ := (N - 1) /", "methods to perform this truncation. * `filter_threshold` -- since many", "is `tf.reduce_mean(states, cross_chain_dims).shape[1:]`. Raises: ValueError: If `states` and `filter_threshold` or", "sequences, we drop the final value. x = x[:x_len -", "the ESS in cases where the chains are not mixing", "[assert_util.assert_greater( ps.shape(state)[0], 4, message='Must provide at least 4 samples when", "Suppose state = [0, 1, 2, 3, 4, 5] #", "Step 2: mask = [0, 0, 1, 0] mask =", "mean_auto_cov) / approx_variance else: auto_corr = auto_cov / auto_cov[:1] num_chains", "into [[0, 1, 2], [3, 4, 5]] # E.g. reshape", "structure parallel to `chains_states` representing the R-hat statistic for the", "#### Examples We use ESS to estimate standard error. ```", "perform this truncation. * `filter_threshold` -- since many MCMC methods", "Specifically, R-hat measures the degree to which variance (of the", "N**-1 * Sum{X_i} } = ESS**-1 * Variance{ X_1 }.", "the chain means. # W is the within sequence variance,", "= _reduce_variance( tf.reduce_mean(states, axis=0), biased=False, # This makes the denominator", "state = [0, 1, 2, 3, 4, 5] # Step", "Apache License, Version 2.0 (the \"License\"); # you may not", "trace_fn=None, kernel=tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=target.log_prob, step_size=0.05, num_leapfrog_steps=20)) chains_states.shape ==> (1000, 10, 2)", "either express or implied. # See the License for the", "return tf.reduce_sum(tf.reshape(x, new_shape), 1) # Pairwise sums are all positive", "ps.shape(state) n_samples = state_shape[0] state = state[:n_samples - n_samples %", "burn-in. rhat.eval() ==> [1.05, 1.3] ``` To see why R-hat", "\"effective sample size\" (ESS) is the size of an iid", "effective_sample_size(states, filter_beyond_positive_pairs=True) ==> Shape (2,) Tensor mean, variance = tf.nn.moments(states,", "be a list of the same length. Which dimensions of", "= ps.non_negative_axis( cross_chain_dims, ps.rank(states)) # B / N between_chain_variance_div_n =", "Get 10 (2x) overdispersed initial states. initial_state = target.sample(10) *", "1` giving the number of dimensions, from `dim = 1`", "to `None` means we do not filter based on the", "= stats.auto_correlation( states, axis=0, max_lags=filter_beyond_lag, normalize=False) n = _axis_size(states, axis=0)", "not None: num_chains = _axis_size(states, cross_chain_dims) num_chains_ = tf.get_static_value(num_chains) assertions", "the same effect. Ignored if `filter_beyond_positive_pairs` is `True`. filter_beyond_lag: `Tensor`", "into first and second halves, treating these as separate chains.", "pairwise sums become non-positive. The arguments `filter_beyond_lag`, `filter_threshold` and `filter_beyond_positive_pairs`", "summed over. If `None`, no summation is performed. Note this", "these as separate chains. This makes R-hat more robust to", "to prepend to created tf. Default: `potential_scale_reduction`. Returns: `Tensor` structure", "potential scale reduction for chain convergence. Given `N > 1`", "computing the ESS for individual chains and then summing them.", "1, 2], [3, 4, 5]] into [[0, 3], [1, 4],", "Chain at each result step. The `ith` state is assumed", ":= length of chains # x_hat[c] := 1 / N", "of auto_corr below the threshold. # mask[i, ...] = 1", "\"\"\"potential_scale_reduction for one single state `Tensor`.\"\"\" # casting integers to", "(N - 1) / N * W + B /", "[False, False, True, True] mask = _sum_pairs(auto_corr) < 0. #", "tf.convert_to_tensor(state, name='state') n_samples_ = tf.compat.dimension_value(state.shape[0]) if n_samples_ is not None:", "approx_variance else: auto_corr = auto_cov / auto_cov[:1] num_chains = 1", "1, 1] mask = tf.cumsum(mask, axis=0) # Step 4: mask", "1) / N biased_within_chain_variance = tf.reduce_mean(auto_cov[0], cross_chain_dims - 1) #", "- 1) / N biased_within_chain_variance = tf.reduce_mean(auto_cov[0], cross_chain_dims - 1)", "a reasonable criterion is to truncate at the first index", "0.]), trace_fn=None, kernel=tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=target.log_prob, step_size=0.05, num_leapfrog_steps=20)) states.shape ==> (1000, 2)", "`R_k` should be truncated at some number `filter_beyond_lag < N`.", "2, 2], ps.shape(x)[1:]], axis=0) return tf.reduce_sum(tf.reshape(x, new_shape), 1) # Pairwise", "= tf.reduce_mean( tf.math.squared_difference(x, mean), axis=axis, keepdims=keepdims) if biased: return biased_var", "(m * n) # TODO(b/72873233) Move some variant of this", "= nk_factor * auto_corr if filter_beyond_positive_pairs: def _sum_pairs(x): x_len =", "i, # mask[i, ...] = 0, otherwise. # So, along", "number `filter_beyond_lag < N`. This function provides two methods to", "truncates the auto-correlation sequence where the pairwise sums become non-positive.", "Sum_{k=1}^N R[k] * (N - k) / N} # =", "the initial auto-correlation sequence where the pairwise sums are positive.", "sums are all positive for auto-correlation spectra derived from #", "where `R_k > 0`, a reasonable criterion is to truncate", "Graphical Statistics_, 7(4), 1998. [2]: <NAME> and <NAME>. Inference from", "initial states. initial_state = target.sample(10) * 2. ==> (10, 2)", "to the same target. The remaining dimensions, `A`, can have", "second dimension needed a longer burn-in. rhat.eval() ==> [1.05, 1.3]", "<NAME>, Paul-Christian Burkner. Rank-normalization, folding, and localization: An improved R-hat", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "// 2], state_shape[1:]], axis=0) ) # Step 2: Put the", "all drawing from the same distribution, they will have the", "split_chains` logic assumes this is 1! sample_ndims = 1 if", "moments, or other statistics are desired, a different diagnostic should", "`state`, and shape equal to `state.shape[1 + independent_chain_ndims:]`. Raises: ValueError:", "target. c.f. \"law of total variance.\" sigma_2_plus = ((n -", "> 1 chain ' 'in `states`.') if num_chains_ is not", "state = tf.identity(state) else: assertions = [assert_util.assert_greater( ps.shape(state)[0], 2, message='Must", "independent_chain_ndims, split_chains, validate_args): \"\"\"potential_scale_reduction for one single state `Tensor`.\"\"\" #", "variance of the chain means. # W is the within", "< 0. # Step 2: mask = [0, 0, 1,", "is to truncate at the first index where the estimated", "chains.')] with tf.control_dependencies(assertions): state = tf.identity(state) else: assertions = [assert_util.assert_greater(", "ess: `Tensor` structure parallel to `states`. The effective sample size", "where M is the filter_beyond_lag truncation point chosen above. #", "An improved R-hat for assessing convergence of MCMC, 2019. Retrieved", "denominator is the total variance minus the variance of the", "or a structure of integer `Tensors` corresponding to each state", "of weighted_auto_corr by a factor of 2. # It still", "* auto_corr if filter_beyond_positive_pairs: def _sum_pairs(x): x_len = ps.shape(x)[0] #", "of total variance, the numerator is the variance of the", "# Get a binary mask to zero out values of", "validate_args) with tf.name_scope('potential_scale_reduction' if name is None else name): return", "account the cross-chain variance to reduce the ESS in cases", "* w + b_div_n return ((m + 1.) / m)", "mask = tf.cast(mask, dtype=dt) # Step 3: mask = [0,", "to estimate standard error. ``` import tensorflow as tf import", "n_samples_ is not None: # If available statically. if split_chains", "of chains `C > 1`. Increasing `C` does improve effectiveness", "([-1], tf.ones([tf.rank(auto_corr) - 1], dtype=tf.int32)), axis=0) nk_factor = tf.reshape(nk_factor, new_shape)", "[a//2, 2, b]. state = tf.transpose( a=state, perm=ps.concat( [[1, 0],", "Statistical Science, 7:473-511, 1992. [2]: <NAME>, <NAME>, <NAME>, <NAME>, <NAME>.", "tf.reduce_mean( tf.math.squared_difference(x, mean), axis=axis, keepdims=keepdims) if biased: return biased_var n", "(1998)][2]. Some guidelines: * The initial state of the chains", "are mixing well it is still preferrable to compute cross-chain", "k = tf.range(0., _axis_size(auto_corr, axis=0)) nk_factor = (n - k)", "None: new_shape = [-1] + [1] * (tensorshape_util.rank(auto_corr.shape) - 1)", "states. initial_state = target.sample(10) * 2. ==> (10, 2) #", "variance, the numerator is the variance of the combined states,", "# In the language of Brooks and Gelman (1998), #", "is not None: filter_threshold = tf.convert_to_tensor( filter_threshold, dtype=dt, name='filter_threshold') #", "or other statistics are desired, a different diagnostic should be", "`tf.reduce_mean(states, cross_chain_dims).shape[1:]`. Raises: ValueError: If `states` and `filter_threshold` or `states`", "var^+ approx_variance = ( biased_within_chain_variance + between_chain_variance_div_n) # 1/C *", "state = tf.transpose( a=state, perm=ps.concat( [[1, 0], ps.range(2, ps.rank(state))], axis=0))", "if cross_chain_dims is None: cross_chain_dims = nest_util.broadcast_structure(states, None) filter_beyond_lag =", "validate_args: assertions.append( assert_util.assert_greater(num_chains, 1., message=msg)) with tf.control_dependencies(assertions): # We're computing", "None: # If available statically. if split_chains and n_samples_ <", "<NAME> and <NAME>. General Methods for Monitoring Convergence of Iterative", "ps.concat([[2, n_samples // 2], state_shape[1:]], axis=0) ) # Step 2:", "name is None else name): return nest.map_structure_up_to( states, single_state, states,", "= [1, 0.5, 0.0, 0.3], and filter_threshold = 0.2. #", "w + b_div_n return ((m + 1.) / m) *", "parallel to `chains_states` representing the R-hat statistic for the state(s).", "number of chains `C > 1`. Increasing `C` does improve", "within-chain variance. # B := N / (C - 1)", "`independent_chain_ndims < 1`. #### Examples Diagnosing convergence by monitoring 10", "* `filter_beyond_positive_pairs` -- reversible MCMC chains produce an auto-correlation sequence", "with tf.control_dependencies(assertions): # We're computing the R[k] from equation 10", "for Markov Chain Monte Carlo (MCMC) sampling. @@effective_sample_size @@potential_scale_reduction \"\"\"", "from tensorflow_probability.python.internal import tensorshape_util from tensorflow.python.util import nest # pylint:", "> 0`, a reasonable criterion is to truncate at the", "overall mean. # W := 1/C Sum_{c=1}^C s_c**2, within-chain variance.", "the last sample. state_shape = ps.shape(state) n_samples = state_shape[0] state", "biased_var = tf.reduce_mean( tf.math.squared_difference(x, mean), axis=axis, keepdims=keepdims) if biased: return", "> 1` states from each of `C > 1` independent", "makes the denominator be C - 1. axis=cross_chain_dims - 1)", "(C - 1) Sum_{c=1}^C (x_hat[c] - x_hat)**2, between chain #", "of the chain variances. b_div_n = _reduce_variance( tf.reduce_mean(state, axis=sample_axis, keepdims=True),", "Assume auto_corr = [1, 0.5, 0.0, 0.3], and filter_threshold =", "ps from tensorflow_probability.python.internal import tensorshape_util from tensorflow.python.util import nest #", "5]] into [[0, 3], [1, 4], [2, 5]], # reshaping", "if split_chains: assertions = [assert_util.assert_greater( ps.shape(state)[0], 4, message='Must provide at", "specifying the `cross_chain_dims` argument. Cross-chain ESS takes into account the", "Variance{X_1}`, we have ``` ESS(N) = N / [ 1", "(ESS) is the size of an iid sample with the", "# independent chains. # For odd number of samples, keep", "sample size of each component of `states`. If `cross_chain_dims` is", "4 samples when splitting chains. ' 'Found {}'.format(n_samples_)) if not", "of the chain means. # W is the within sequence", "and n_samples_ < 4: raise ValueError( 'Must provide at least", "same distribution, they will have the same mean, and thus", "will be a smaller number than computing the ESS for", "# var^+ := (N - 1) / N * W", "number than computing the ESS for individual chains and then", "(with discussion). Statistical Science, 7:473-511, 1992. [2]: <NAME>, <NAME>, <NAME>,", "the need for truncation. Args: states: `Tensor` or Python structure", "dimensions, `A`, can have any shape (even empty). independent_chain_ndims: Integer", "The initial state of the chains should be drawn from", "truncate at the first index where the estimated auto-correlation becomes", "use this file except in compliance with the License. #", "elements of `x` in `axis`, as type `x.dtype`.\"\"\" if axis", "samples from each chain into first and second halves, treating", "`state.shape[1 + independent_chain_ndims:]`. Raises: ValueError: If `independent_chain_ndims < 1`. ####", "ps.shape(state)[0], 2, message='Must provide at least 2 samples.')] with tf.control_dependencies(assertions):", "the `cross_chain_dims` argument. Cross-chain ESS takes into account the cross-chain", "chains. chains_states = tfp.mcmc.sample_chain( num_burnin_steps=200, num_results=1000, current_state=initial_state, trace_fn=None, kernel=tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=target.log_prob,", "target_log_prob_fn=target.log_prob, step_size=0.05, num_leapfrog_steps=20)) states.shape ==> (1000, 2) ess = effective_sample_size(states,", "following [Vehtari et al. (2019)][2] by specifying the `cross_chain_dims` argument.", "sample_and_chain_axis, biased=False) w = tf.reduce_mean( _reduce_variance(state, sample_axis, keepdims=True, biased=False), axis=sample_and_chain_axis)", "it becomes progressively noisier for larger `k`. For this reason,", "fine in the formula below. weighted_auto_corr = _sum_pairs(weighted_auto_corr) * mask", "Given `N > 1` states from each of `C >", "longer burn-in. rhat.eval() ==> [1.05, 1.3] ``` To see why", "else name): return tf.nest.map_structure(single_state, chains_states) def _potential_scale_reduction_single_state(state, independent_chain_ndims, split_chains, validate_args):", "of course this is problem-dependent. See [Brooks and Gelman (1998)][2].", "_potential_scale_reduction_single_state(state, independent_chain_ndims, split_chains, validate_args): \"\"\"potential_scale_reduction for one single state `Tensor`.\"\"\"", "mask[i, ...] = 1 if auto_corr[j, ...] > threshold for", "size\" (ESS) is the size of an iid sample with", "(1998), # B / n is the between chain variance,", "= 1 if auto_corr[j, ...] > threshold for all j", "check to see if the `state` is a numpy object", "distributed states. filter_threshold: `Tensor` or Python structure of `Tensor` objects.", "cross-chain ESS following [Vehtari et al. (2019)][2] by specifying the", ":= (N - 1) / N * W + B", "1/C * Sum_{c=1}^C s_c**2 R[k, c] mean_auto_cov = tf.reduce_mean(auto_cov, cross_chain_dims)", "estimate of the true variance, which would be unbiased if", "- k) / n if tensorshape_util.rank(auto_corr.shape) is not None: new_shape", "and # limitations under the License. # ============================================================================ \"\"\"Utilities for", "preferrable to compute cross-chain ESS via this method because it", "We're treating the new dim as indexing 2 chains, so", "import dtype_util from tensorflow_probability.python.internal import nest_util from tensorflow_probability.python.internal import prefer_static", "initial auto-correlation sequence where the pairwise sums are positive. cross_chain_dims:", "this will be a smaller number than computing the ESS", "one would expect if the chains were identically distributed. See", "`Tensor` or Python structure of `Tensor`s representing the states of", "variance, ```R-hat = ( E[Var[X | chain]] + Var[E[X |", "auto-correlation. Since `R_k` must be estimated using only `N -", "1`, found: {}'.format( independent_chain_ndims)) def single_state(s): return _potential_scale_reduction_single_state( s, independent_chain_ndims,", "as a # chain, changing [[0, 1, 2], [3, 4,", "/ n) * w + b_div_n return ((m + 1.)", "as np import tensorflow.compat.v2 as tf from tensorflow_probability.python import stats", "at least 2 samples. Found {}'.format(n_samples_)) elif validate_args: if split_chains:", "are filters intended to remove noisy tail terms from `R_k`.", "that each attempt to sample from a 2-variate normal. ```python", "in compliance with the License. # You may obtain a", "created ops. Returns: ess: `Tensor` structure parallel to `states`. The", "(2019)][2] by specifying the `cross_chain_dims` argument. Cross-chain ESS takes into", "method truncates the auto-correlation sequence where the pairwise sums become", "software # distributed under the License is distributed on an", "ratio should be one. #### References [1]: <NAME> and <NAME>.", "Which dimensions of `states` to treat as independent chains that", "the auto-correlation sequence where the pairwise sums become non-positive. The", "TensorFlow Probability Authors. # # Licensed under the Apache License,", "computing the R[k] from equation 10 of Vehtari et al.", "s_c**2 R[k, c] mean_auto_cov = tf.reduce_mean(auto_cov, cross_chain_dims) auto_corr = 1.", "W := 1/C Sum_{c=1}^C s_c**2, within-chain variance. # B :=", "higher moments, or other statistics are desired, a different diagnostic", "nest_util from tensorflow_probability.python.internal import prefer_static as ps from tensorflow_probability.python.internal import", "MCMC chains. # E.g. imagine the pairwise sums are [0.2,", "course this is problem-dependent. See [Brooks and Gelman (1998)][2]. *", "mask to zero out values of auto_corr below the threshold.", "2], [3, 4, 5]] into [[0, 3], [1, 4], [2,", "`filter_threshold` or `filter_beyond_positive_pairs. E.g., combining `filter_beyond_lag` and `filter_beyond_positive_pairs` means that", "Python structure of `Tensor`s representing the states of a Markov", "with the same variance as `state`. More precisely, given a", "`0` indexes the `Ni > 1` result steps of the", "msg = ('When `cross_chain_dims` is not `None`, there must be", "produce an auto-correlation sequence with the property that pairwise sums", "| chain]].``` Using the law of total variance, the numerator", "of a Markov Chain at each result step. The `ith`", "tf.name_scope('potential_scale_reduction_single_state'): # We assume exactly one leading dimension indexes e.g.", "time. def single_state(*args): return _effective_sample_size_single_state( *args, validate_args=validate_args) with tf.name_scope('effective_sample_size' if", "`k in {0, ..., N/2}`. Deviations are only possible due", "= tf.get_static_value(num_chains) assertions = [] msg = ('When `cross_chain_dims` is", "K. Even when chains are mixing well it is still", "empty). independent_chain_ndims: Integer type `Tensor` with value `>= 1` giving", "> 0` for `k in {0, ..., N/2}`. Deviations are", "estimating the auto-correlation. Since `R_k` must be estimated using only", "the numerator is the variance of the combined states, and", "* n / (-1 + 2 * tf.reduce_sum(weighted_auto_corr, axis=0)) def", "X_1 }. ``` If the sequence is uncorrelated, `ESS =", "... + 1 / N * R_{N-1} ) ] ```", "this is problem-dependent. See [Brooks and Gelman (1998)][2]. * R-hat", "R-hat measures the degree to which variance (of the means)", "combined states (combined over all chains). Then, in the limit", "a magic number. # Warning! `if split_chains` logic assumes this", "... x CiD` independent chains to be tested for convergence", "`x` in `axis`, as type `x.dtype`.\"\"\" if axis is None:", "sample_ndims + independent_chain_ndims) sample_and_chain_axis = ps.range( 0, sample_ndims + independent_chain_ndims)", "OR `filter_beyond_positive_pairs` criteria. This function can also compute cross-chain ESS", "split_chains, validate_args) with tf.name_scope('potential_scale_reduction' if name is None else name):", "= [assert_util.assert_greater( ps.shape(state)[0], 2, message='Must provide at least 2 samples.')]", "2 samples. Found {}'.format(n_samples_)) elif validate_args: if split_chains: assertions =", "of `x` in `axis`, as type `x.dtype`.\"\"\" if axis is", "value. x = x[:x_len - x_len % 2] new_shape =", "* mask elif filter_threshold is not None: filter_threshold = tf.convert_to_tensor(", "the formula below. weighted_auto_corr = _sum_pairs(weighted_auto_corr) * mask elif filter_threshold", "Define so it's not a magic number. # Warning! `if", "name=None): \"\"\"Estimate a lower bound on effective sample size for", "Vehtari et al. # (2019): # # R[k] := 1", "from http://arxiv.org/abs/1903.08008 \"\"\" if cross_chain_dims is None: cross_chain_dims = nest_util.broadcast_structure(states,", "import tensorflow_probability as tfp tfd = tfp.distributions target = tfd.MultivariateNormalDiag(scale_diag=[1.,", "[0, 0, 1, 2] mask = tf.cumsum(mask, axis=0) # Step", "# limitations under the License. # ============================================================================ \"\"\"Utilities for Markov", "Markov chain. state = tf.convert_to_tensor(state, name='state') n_samples_ = tf.compat.dimension_value(state.shape[0]) if", "# Get the factor (N - k) / N, and", "mask = tf.maximum(1. - mask, 0.) weighted_auto_corr *= mask return", "We use ESS to estimate standard error. ``` import tensorflow", "with the License. # You may obtain a copy of", "measures non-convergence of the mean. If higher moments, or other", "import nest_util from tensorflow_probability.python.internal import prefer_static as ps from tensorflow_probability.python.internal", "of `R_k`, reducing the need for truncation. Args: states: `Tensor`", "# mask[i, ...] = 0, otherwise. # So, along dimension", "sequence is uncorrelated, `ESS = N`. If the sequence is", "from each chain into first and second halves, treating these", "validity. If False, and arguments are incorrect, correct behavior is", "1) Sum_{n=1}^N (x[n, c] - x_hat[c])**2, chain # variance #", "/ {-1 + 2 * Sum_{k=0}^N R[k] * (N -", "mask elif filter_threshold is not None: filter_threshold = tf.convert_to_tensor( filter_threshold,", "the target. * If all chains converge to the target,", "sequence with the property that pairwise sums of the elements", "a list of the same length. Which dimensions of `states`", "error. ``` import tensorflow as tf import tensorflow_probability as tfp", "weighted_auto_corr = nk_factor * auto_corr if filter_beyond_positive_pairs: def _sum_pairs(x): x_len", "R-hat > 1 (except in pathological cases, e.g. if the", "in [3]. validate_args: Whether to add runtime checks of argument", "half, doubling the number of # independent chains. # For", "W is the within sequence variance, the mean of the", "1., message=msg)) with tf.control_dependencies(assertions): # We're computing the R[k] from", "for one single Tensor argument.\"\"\" with tf.name_scope('effective_sample_size_single_state'): states = tf.convert_to_tensor(states,", "`R_k`. You can combine `filter_beyond_lag` with `filter_threshold` or `filter_beyond_positive_pairs. E.g.,", "2 chains. #### Examples We use ESS to estimate standard", "factor of 2. # It still works fine in the", "at a time. def single_state(*args): return _effective_sample_size_single_state( *args, validate_args=validate_args) with", "correct behavior is not guaranteed. name: `String` name to prepend", "# Step 1: reshape into [[0, 1, 2], [3, 4,", "This function provides two methods to perform this truncation. *", "to floats for floating-point division # check to see if", "/ (n - 1.)) * biased_var def _axis_size(x, axis=None): \"\"\"Get", "(2x) overdispersed initial states. initial_state = target.sample(10) * 2. ==>", "= [assert_util.assert_greater( ps.shape(state)[0], 4, message='Must provide at least 4 samples", "shows that, with `R_k` the auto-correlation sequence, `R_k := Covariance{X_1,", "filter_beyond_lag, filter_threshold, filter_beyond_positive_pairs, cross_chain_dims, validate_args): \"\"\"ESS computation for one single", "express or implied. # See the License for the specific", "R-hat is reasonable, let `X` be a random variable drawn", "except in compliance with the License. # You may obtain", "prefer_static as ps from tensorflow_probability.python.internal import tensorshape_util from tensorflow.python.util import", "of chains # N := length of chains # x_hat[c]", "integers to floats for floating-point division # check to see", "denoting expectation and variance, ```R-hat = ( E[Var[X | chain]]", "exactly one leading dimension indexes e.g. correlated samples # from", "mask, 0.) # N.B. this reduces the length of weighted_auto_corr", "validate_args=validate_args) with tf.name_scope('effective_sample_size' if name is None else name): return", "# Step 2: mask = [0, 0, 1, 0] mask", "state of the chains should be drawn from a distribution", "mean, and thus the ratio should be one. #### References", "_potential_scale_reduction_single_state( s, independent_chain_ndims, split_chains, validate_args) with tf.name_scope('potential_scale_reduction' if name is", "be summed over. If `None`, no summation is performed. Note", "/ auto_cov[:1] num_chains = 1 # With R[k] := auto_corr[k,", "1) # approx N / {-1 + 2 * Sum_{k=0}^M", "x[n, c], chain mean. # x_hat := 1 / C", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "imagine the pairwise sums are [0.2, 0.1, -0.1, -0.2] #", "ps.shape(x)[0] # For odd sequences, we drop the final value.", "variance of the combined states, and the denominator is the", "None. icn_const_ = tf.get_static_value( ps.convert_to_shape_tensor(independent_chain_ndims)) if icn_const_ is not None:", "to be tested for convergence. split_chains: Python `bool`. If `True`,", "each of `C > 1` independent chains, the potential scale", "= icn_const_ if icn_const_ < 1: raise ValueError( 'Argument `independent_chain_ndims`", "of auto-correlations is truncated after the first appearance of a", "overdispersed with respect to the target. * If all chains", "to as R-hat, measures convergence of the chains (to the", "3, 4, 5] # Step 1: reshape into [[0, 1,", "# For odd number of samples, keep all but the", "* Sum{X_i} } = ESS**-1 * Variance{ X_1 }. ```", "Gelman (1998), # B / n is the between chain", "= tfp.distributions target = tfd.MultivariateNormalDiag(scale_diag=[1., 2.]) # Get 10 (2x)", "by testing for equality of means. Specifically, R-hat measures the", "target. * If all chains converge to the target, then", ":= auto_corr[k, m, ...], auto-correlation indexed by chain. # var^+", "= tf.concat( ([-1], tf.ones([tf.rank(auto_corr) - 1], dtype=tf.int32)), axis=0) nk_factor =", "ESS ~ K. Even when chains are mixing well it", "structure of `Tensor` objects. Must broadcast with `state`. The sequence", "CONDITIONS OF ANY KIND, either express or implied. # See", "1/C Sum_{c=1}^C s_c**2, within-chain variance. # B := N /", "method does not estimate the `ESS` of super-efficient chains (where", "expectation and variance, ```R-hat = ( E[Var[X | chain]] +", "by monitoring 10 chains that each attempt to sample from", "sample_axis) m = _axis_size(state, chain_axis) # In the language of", "# reshaping [2, a//2, b] into [a//2, 2, b]. state", "samples, keep all but the last sample. state_shape = ps.shape(state)", "or Python structure of `Tensor` objects. Must be `int`-like and", "this requires at least 2 chains. validate_args: Whether to add", "If `True`, only consider the initial auto-correlation sequence where the", "# sigma^2_+ is an estimate of the true variance, which", "measures convergence of the chains (to the same target) by", "are all drawing from the same distribution, they will have", "1) / N * W + B / N cross_chain_dims", "that ESS will be summed over. If `None`, no summation", "With R[k] := auto_corr[k, ...], # ESS = N /", "and Gelman (1998)][2]. Some guidelines: * The initial state of", "is not None: num_chains = _axis_size(states, cross_chain_dims) num_chains_ = tf.get_static_value(num_chains)", "remaining dimensions, `A`, can have any shape (even empty). independent_chain_ndims:", "tensorflow_probability.python.internal import assert_util from tensorflow_probability.python.internal import dtype_util from tensorflow_probability.python.internal import", "criterion is to truncate at the first index where the", "`N - k` samples, it becomes progressively noisier for larger", "for truncation. Args: states: `Tensor` or Python structure of `Tensor`", "positive [Geyer][1], i.e. `R_{2k} + R_{2k + 1} > 0`", "= tf.compat.dimension_value(state.shape[0]) if n_samples_ is not None: # If available", "potential_scale_reduction(chains_states, independent_chain_ndims=1, split_chains=False, validate_args=False, name=None): \"\"\"<NAME> Rubin (1992)'s potential scale", "- 1) / N * R_1 + ... + 1", "biased=True, keepdims=False): with tf.name_scope('reduce_variance'): x = tf.convert_to_tensor(x, name='x') mean =", "/ [ 1 + 2 * ( (N - 1)", "= x[:x_len - x_len % 2] new_shape = ps.concat([[x_len //", "1) / n) * w + b_div_n return ((m +", "= tf.cast(state, tf.float32) with tf.name_scope('potential_scale_reduction_single_state'): # We assume exactly one", "= N / [ 1 + 2 * ( (N", "If `None`, no summation is performed. Note this requires at", "def _effective_sample_size_single_state(states, filter_beyond_lag, filter_threshold, filter_beyond_positive_pairs, cross_chain_dims, validate_args): \"\"\"ESS computation for", "1) # Pairwise sums are all positive for auto-correlation spectra", "is not guaranteed. name: `String` name to prepend to created", "reversible MCMC chains produce an auto-correlation sequence with the property", "the chains were identically distributed. See [Gelman and Rubin (1992)][1];", "ops. Returns: ess: `Tensor` structure parallel to `states`. The effective", "num_leapfrog_steps=20)) chains_states.shape ==> (1000, 10, 2) rhat = tfp.mcmc.diagnostic.potential_scale_reduction( chains_states,", "==> Shape (2,) Tensor mean, variance = tf.nn.moments(states, axis=0) standard_error", "performed. Note this requires at least 2 chains. validate_args: Whether", "dtype=dt) # Step 3: mask = [0, 0, 1, 1]", "elif dtype_util.is_integer(state.dtype): state = tf.cast(state, tf.float32) with tf.name_scope('potential_scale_reduction_single_state'): # We", "[2, a//2, b]. state = tf.reshape( state, ps.concat([[2, n_samples //", "with `E`, `Var` denoting expectation and variance, ```R-hat = (", "- k) / N} # = N / {-1 +", "name to prepend to created tf. Default: `potential_scale_reduction`. Returns: `Tensor`", "# ============================================================================ \"\"\"Utilities for Markov Chain Monte Carlo (MCMC) sampling.", "truncated after the first appearance of a term less than", "`[Ni, Ci1, Ci2,...,CiD] + A`. Dimension `0` indexes the `Ni", "[ 1 + 2 * ( (N - 1) /", "[Brooks and Gelman (1998)][2]. Args: chains_states: `Tensor` or Python structure", "setting to any number less than `-1` has the same", "cross_chain_dims) num_chains_ = tf.get_static_value(num_chains) assertions = [] msg = ('When", "axis=axis, keepdims=True) biased_var = tf.reduce_mean( tf.math.squared_difference(x, mean), axis=axis, keepdims=keepdims) if", "* (N - k) / N} # where M is", "has the same effect. Ignored if `filter_beyond_positive_pairs` is `True`. filter_beyond_lag:", "N / (C - 1) Sum_{c=1}^C (x_hat[c] - x_hat)**2, between", "`2` dimension in the right place to be treated as", "\"\"\" from __future__ import absolute_import from __future__ import division from", "the degree to which variance (of the means) between chains", "is None: cross_chain_dims = nest_util.broadcast_structure(states, None) filter_beyond_lag = nest_util.broadcast_structure(states, filter_beyond_lag)", "validate_args=False, name=None): \"\"\"<NAME> Rubin (1992)'s potential scale reduction for chain", "`ith` state is assumed to have shape `[Ni, Ci1, Ci2,...,CiD]", "et al. # (2019): # # R[k] := 1 -", "the variance of the the individual chain means. If the", "improved R-hat for assessing convergence of MCMC, 2019. Retrieved from", "N biased_within_chain_variance = tf.reduce_mean(auto_cov[0], cross_chain_dims - 1) # var^+ approx_variance", "`True`. filter_beyond_lag: `Tensor` or Python structure of `Tensor` objects. Must", "above. # Get the factor (N - k) / N,", "approx N / {-1 + 2 * Sum_{k=0}^M R[k] *", "return tf.nest.map_structure(single_state, chains_states) def _potential_scale_reduction_single_state(state, independent_chain_ndims, split_chains, validate_args): \"\"\"potential_scale_reduction for", "Sum_{c=1}^C s_c**2, within-chain variance. # B := N / (C", "= [] msg = ('When `cross_chain_dims` is not `None`, there", "* 2. ==> (10, 2) # Get 1000 samples from", "_reduce_variance(state, sample_axis, keepdims=True, biased=False), axis=sample_and_chain_axis) # sigma^2_+ is an estimate", "function will return ESS ~ K. Even when chains are", "assumed to have shape `[Ni, Ci1, Ci2,...,CiD] + A`. Dimension", "0.3], and filter_threshold = 0.2. # Step 1: mask =", "the estimate of `R_k`, reducing the need for truncation. Args:", "_axis_size(state, sample_axis) m = _axis_size(state, chain_axis) # In the language", "should be one. #### References [1]: <NAME> and <NAME>. General", "`int`-like and scalar valued. The sequence of auto-correlations is truncated", "N := length of chains # x_hat[c] := 1 /", "= ( biased_within_chain_variance + between_chain_variance_div_n) # 1/C * Sum_{c=1}^C s_c**2", "be truncated at some number `filter_beyond_lag < N`. This function", "c] mean_auto_cov = tf.reduce_mean(auto_cov, cross_chain_dims) auto_corr = 1. - (biased_within_chain_variance", "= tf.cast(mask, dt) # Step 3: mask = [0, 0,", "`Var` denoting expectation and variance, ```R-hat = ( E[Var[X |", "general, this will be a smaller number than computing the", "by chain. # var^+ := (N - 1) / N", "Sum_{k=0}^M R[k] * (N - k) / N} # where", "# TODO(b/72873233) Move some variant of this to tfd.sample_stats. def", "return biased_var n = _axis_size(x, axis) return (n / (n", "tf.convert_to_tensor( filter_threshold, dtype=dt, name='filter_threshold') # Get a binary mask to", "convergence, but of course this is problem-dependent. See [Brooks and", "when chains are mixing well it is still preferrable to", "correctly. * `filter_beyond_positive_pairs` -- reversible MCMC chains produce an auto-correlation", "less than 2 chains. #### Examples We use ESS to", "is not None: independent_chain_ndims = icn_const_ if icn_const_ < 1:", "equality of means. Specifically, R-hat measures the degree to which", "the language of Brooks and Gelman (1998), # B /", "`x.dtype`.\"\"\" if axis is None: return ps.cast(ps.size(x), x.dtype) return ps.cast(", "# x_hat := 1 / C Sum_{c=1}^C x_hat[c], overall mean.", "number of # independent chains. # For odd number of", "+ 1.) / m) * sigma_2_plus / w - (n", "the denominator be C - 1. axis=cross_chain_dims - 1) #", "def potential_scale_reduction(chains_states, independent_chain_ndims=1, split_chains=False, validate_args=False, name=None): \"\"\"<NAME> Rubin (1992)'s potential", "Setting to `None` means we do not filter based on", "message='Must provide at least 2 samples.')] with tf.control_dependencies(assertions): state =", "cross-chain ESS via this method because it will reduce the", "return ESS ~ K. Even when chains are mixing well", "(N - 1) / N * R_1 + ... +", "then this argument should also be a list of the", "1.) / m) * sigma_2_plus / w - (n -", "5]] # E.g. reshape states of shape [a, b] into", "* R_{N-1} ) ] ``` This function estimates the above", "+ independent_chain_ndims) n = _axis_size(state, sample_axis) m = _axis_size(state, chain_axis)", "cross_chain_dims) auto_corr = 1. - (biased_within_chain_variance - mean_auto_cov) / approx_variance", "`R_k`, reducing the need for truncation. Args: states: `Tensor` or", "0`, a reasonable criterion is to truncate at the first", "split_chains and n_samples_ < 2: raise ValueError( 'Must provide at", "1`. #### Examples Diagnosing convergence by monitoring 10 chains that", "nk_factor = tf.reshape(nk_factor, new_shape) weighted_auto_corr = nk_factor * auto_corr if", "the full sequence. auto_cov = stats.auto_correlation( states, axis=0, max_lags=filter_beyond_lag, normalize=False)", "referred to as R-hat, measures convergence of the chains (to", "[False, False, True, False] mask = auto_corr < filter_threshold #", "None: num_chains = _axis_size(states, cross_chain_dims) num_chains_ = tf.get_static_value(num_chains) assertions =", "keepdims=keepdims) if biased: return biased_var n = _axis_size(x, axis) return", "the mean of the chain variances. b_div_n = _reduce_variance( tf.reduce_mean(state,", "tensorflow_probability.python.internal import dtype_util from tensorflow_probability.python.internal import nest_util from tensorflow_probability.python.internal import", "If there are negative correlations, then `ESS` can exceed `N`.", "axis=None): \"\"\"Get number of elements of `x` in `axis`, as", "import prefer_static as ps from tensorflow_probability.python.internal import tensorshape_util from tensorflow.python.util", "(N - k) / N} # where M is the", "discussion). Statistical Science, 7:473-511, 1992. [2]: <NAME>, <NAME>, <NAME>, <NAME>,", "/ m) * sigma_2_plus / w - (n - 1.)", "new_shape = [-1] + [1] * (tensorshape_util.rank(auto_corr.shape) - 1) else:", "and localization: An improved R-hat for assessing convergence of MCMC,", "axis=0) nk_factor = tf.reshape(nk_factor, new_shape) weighted_auto_corr = nk_factor * auto_corr", "chains # N := length of chains # x_hat[c] :=", "a stationary sequence of possibly correlated random variables `X_1, X_2,", "Examples Diagnosing convergence by monitoring 10 chains that each attempt", "tf.math.squared_difference(x, mean), axis=axis, keepdims=keepdims) if biased: return biased_var n =", "{}'.format(n_samples_)) elif validate_args: if split_chains: assertions = [assert_util.assert_greater( ps.shape(state)[0], 4,", "The arguments `filter_beyond_lag`, `filter_threshold` and `filter_beyond_positive_pairs` are filters intended to", "[-1] + [1] * (tensorshape_util.rank(auto_corr.shape) - 1) else: new_shape =", "# The second dimension needed a longer burn-in. rhat.eval() ==>", "# array) is not efficiently computable. Therefore, we try constant_value", "'Must provide at least 4 samples when splitting chains. '", "standard error. ``` import tensorflow as tf import tensorflow_probability as", "means. Specifically, R-hat measures the degree to which variance (of", "1, 0, 0] mask = tf.maximum(1. - mask, 0.) weighted_auto_corr", "for convergence. split_chains: Python `bool`. If `True`, divide samples from", "if name is None else name): return nest.map_structure_up_to( states, single_state,", "max_lags=filter_beyond_lag, normalize=False) n = _axis_size(states, axis=0) if cross_chain_dims is not", "auto_corr if filter_beyond_positive_pairs: def _sum_pairs(x): x_len = ps.shape(x)[0] # For", "# Suppose state = [0, 1, 2, 3, 4, 5]", "the between chain variance, the variance of the chain means.", "with `R_k` the auto-correlation sequence, `R_k := Covariance{X_1, X_{1+k}} /", "s_c**2 R[k, c]) / (var^+), # # where: # C", "auto_corr[j, ...] > threshold for all j <= i, #", "tf.compat.dimension_value(state.shape[0]) if n_samples_ is not None: # If available statically.", "weighted_auto_corr *= mask return num_chains * n / (-1 +", "can exceed `N`. Some math shows that, with `R_k` the", "computation for one single Tensor argument.\"\"\" with tf.name_scope('effective_sample_size_single_state'): states =", "\"\"\"Estimate a lower bound on effective sample size for each", "Step 2: mask = [0, 0, 1, 1] mask =", "to indicate approximate convergence, but of course this is problem-dependent.", "1000 samples from the 10 independent chains. chains_states = tfp.mcmc.sample_chain(", "E[Var[X | chain]].``` Using the law of total variance, the", "\"\"\"Get number of elements of `x` in `axis`, as type", "General Methods for Monitoring Convergence of Iterative Simulations. _Journal of", "`Tensor` objects. Must be `int`-like and scalar valued. The sequence", "chain # variance # R[k, m] := auto_corr[k, m, ...],", "chain into first and second halves, treating these as separate", "nest_util.broadcast_structure(states, filter_beyond_lag) filter_threshold = nest_util.broadcast_structure(states, filter_threshold) filter_beyond_positive_pairs = nest_util.broadcast_structure( states,", "filter_beyond_lag == None ==> auto_corr is the full sequence. auto_cov", "/ N, and give it shape [M, 1,...,1], having total", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "> 1 (except in pathological cases, e.g. if the chain", "tfp.mcmc.sample_chain( num_burnin_steps=200, num_results=1000, current_state=tf.constant([0., 0.]), trace_fn=None, kernel=tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=target.log_prob, step_size=0.05, num_leapfrog_steps=20))", "2: Put the size `2` dimension in the right place", "sample size for each independent chain. Roughly speaking, \"effective sample", "the cross-chain variance to reduce the ESS in cases where", "if num_chains_ < 2: raise ValueError(msg) elif validate_args: assertions.append( assert_util.assert_greater(num_chains,", "would be unbiased if # each chain was drawn from", "None: filter_threshold = tf.convert_to_tensor( filter_threshold, dtype=dt, name='filter_threshold') # Get a", "C := number of chains # N := length of", "cross-chain variance to reduce the ESS in cases where the", "we have ``` ESS(N) = N / [ 1 +", "variance. # s_c**2 := 1 / (N - 1) Sum_{n=1}^N", "Warning! `if split_chains` logic assumes this is 1! sample_ndims =", "{0, ..., N/2}`. Deviations are only possible due to noise.", "combining `filter_beyond_lag` and `filter_beyond_positive_pairs` means that terms are removed if", "`R_k` the auto-correlation sequence, `R_k := Covariance{X_1, X_{1+k}} / Variance{X_1}`,", "2.]) # Get 1000 states from one chain. states =", "mask[i, ...] = 0, otherwise. # So, along dimension zero,", "be filtered under the `filter_beyond_lag` OR `filter_beyond_positive_pairs` criteria. This function", "this function will return ESS ~ K. Even when chains", "positive for auto-correlation spectra derived from # reversible MCMC chains.", "-- since many MCMC methods generate chains where `R_k >", "if n_samples_ is not None: # If available statically. if", "A`. Dimension `0` indexes the `Ni > 1` result steps", "chains converge to the target, then as `N --> infinity`,", "it shape [M, 1,...,1], having total # ndims the same", "each chain into first and second halves, treating these as", "to see if the `state` is a numpy object for", "chains, so increment. independent_chain_ndims += 1 sample_axis = ps.range(0, sample_ndims)", "and arguments are incorrect, correct behavior is not guaranteed. name:", "N between_chain_variance_div_n = _reduce_variance( tf.reduce_mean(states, axis=0), biased=False, # This makes", "have the same mean, and thus the ratio should be", "chains_states) def _potential_scale_reduction_single_state(state, independent_chain_ndims, split_chains, validate_args): \"\"\"potential_scale_reduction for one single", "the combined states (combined over all chains). Then, in the", "False, True, True] mask = _sum_pairs(auto_corr) < 0. # Step", "_reduce_variance(x, axis=None, biased=True, keepdims=False): with tf.name_scope('reduce_variance'): x = tf.convert_to_tensor(x, name='x')", "/ N * W + B / N cross_chain_dims =", "not None: new_shape = [-1] + [1] * (tensorshape_util.rank(auto_corr.shape) -", "(n - k) / n if tensorshape_util.rank(auto_corr.shape) is not None:", "chain variance, the variance of the chain means. # W", "filter_threshold) filter_beyond_positive_pairs = nest_util.broadcast_structure( states, filter_beyond_positive_pairs) # Process items, one", "the size of an iid sample with the same variance", "tfd.MultivariateNormalDiag(scale_diag=[1., 2.]) # Get 10 (2x) overdispersed initial states. initial_state", "[1] * (tensorshape_util.rank(auto_corr.shape) - 1) else: new_shape = tf.concat( ([-1],", "= D`, holding independent chain results to be tested for", "one single state `Tensor`.\"\"\" # casting integers to floats for", "1 # With R[k] := auto_corr[k, ...], # ESS =", "give it shape [M, 1,...,1], having total # ndims the", "= tf.reduce_mean(x, axis=axis, keepdims=True) biased_var = tf.reduce_mean( tf.math.squared_difference(x, mean), axis=axis,", "Args: chains_states: `Tensor` or Python structure of `Tensor`s representing the", "drop the final value. x = x[:x_len - x_len %", "should index identically distributed states. filter_threshold: `Tensor` or Python structure", "filter_beyond_positive_pairs: def _sum_pairs(x): x_len = ps.shape(x)[0] # For odd sequences,", "be used. See [Brooks and Gelman (1998)][2]. Args: chains_states: `Tensor`", "not estimate the `ESS` of super-efficient chains (where `ESS >", "This method does not estimate the `ESS` of super-efficient chains", "Deviations are only possible due to noise. This method truncates", "1. Before that, R-hat > 1 (except in pathological cases,", "...] = 0, otherwise. # So, along dimension zero, the", "and Gelman (1998)][2]. Args: chains_states: `Tensor` or Python structure of", "the same target. The remaining dimensions, `A`, can have any", "Version 2.0 (the \"License\"); # you may not use this", "[] msg = ('When `cross_chain_dims` is not `None`, there must", "are negative correlations, then `ESS` can exceed `N`. Some math", "Step 1: mask = [False, False, True, False] mask =", "1] mask = tf.cumsum(mask, axis=0) # Step 4: mask =", "tf.control_dependencies(assertions): state = tf.identity(state) # Define so it's not a", "b]. state = tf.transpose( a=state, perm=ps.concat( [[1, 0], ps.range(2, ps.rank(state))],", "because it will reduce the noise in the estimate of", "and `filter_beyond_positive_pairs` are filters intended to remove noisy tail terms", "each result step. The `ith` state is assumed to have", "are positive [Geyer][1], i.e. `R_{2k} + R_{2k + 1} >", "compute cross-chain ESS via this method because it will reduce", "tested for convergence to the same target. The remaining dimensions,", "# variance. # s_c**2 := 1 / (N - 1)", "1] mask = tf.cast(mask, dt) # Step 3: mask =", "__future__ import absolute_import from __future__ import division from __future__ import", "tf.reduce_sum(tf.reshape(x, new_shape), 1) # Pairwise sums are all positive for", "estimated using only `N - k` samples, it becomes progressively", "with tf.name_scope('potential_scale_reduction' if name is None else name): return tf.nest.map_structure(single_state,", "one chain. states = tfp.mcmc.sample_chain( num_burnin_steps=200, num_results=1000, current_state=tf.constant([0., 0.]), trace_fn=None,", "filter_beyond_positive_pairs=True) ==> Shape (2,) Tensor mean, variance = tf.nn.moments(states, axis=0)", "be a smaller number than computing the ESS for individual", "were identically distributed. See [Gelman and Rubin (1992)][1]; [Brooks and", "else: assertions = [assert_util.assert_greater( ps.shape(state)[0], 2, message='Must provide at least", "num_chains = 1 # With R[k] := auto_corr[k, ...], #", "keepdims=False): with tf.name_scope('reduce_variance'): x = tf.convert_to_tensor(x, name='x') mean = tf.reduce_mean(x,", "= nest_util.broadcast_structure(states, None) filter_beyond_lag = nest_util.broadcast_structure(states, filter_beyond_lag) filter_threshold = nest_util.broadcast_structure(states,", "import print_function import numpy as np import tensorflow.compat.v2 as tf", "that sequence are positive [Geyer][1], i.e. `R_{2k} + R_{2k +", "appearance of a term less than `filter_threshold`. Setting to `None`", "elif validate_args: if split_chains: assertions = [assert_util.assert_greater( ps.shape(state)[0], 4, message='Must", "tensorshape_util.rank(auto_corr.shape) is not None: new_shape = [-1] + [1] *", "by applicable law or agreed to in writing, software #", "of integer `Tensors` corresponding to each state component. If a", "exceed `N`. Some math shows that, with `R_k` the auto-correlation", "] def effective_sample_size(states, filter_threshold=0., filter_beyond_lag=None, filter_beyond_positive_pairs=False, cross_chain_dims=None, validate_args=False, name=None): \"\"\"Estimate", "chain Monte Carlo (with discussion). Statistical Science, 7:473-511, 1992. [2]:", "% 2] new_shape = ps.concat([[x_len // 2, 2], ps.shape(x)[1:]], axis=0)", "`C > 1` independent chains, the potential scale reduction factor,", "there must be > 1 chain ' 'in `states`.') if", "where: # C := number of chains # N :=", "the chains should be drawn from a distribution overdispersed with", "chains_states = tfp.mcmc.sample_chain( num_burnin_steps=200, num_results=1000, current_state=initial_state, trace_fn=None, kernel=tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=target.log_prob, step_size=0.05,", "is the number such that ``` Variance{ N**-1 * Sum{X_i}", "some number `filter_beyond_lag < N`. This function provides two methods", "`filter_beyond_positive_pairs` criteria. This function can also compute cross-chain ESS following", "/ Variance{X_1}`, we have ``` ESS(N) = N / [", "found: {}'.format( independent_chain_ndims)) def single_state(s): return _potential_scale_reduction_single_state( s, independent_chain_ndims, split_chains,", "/ (var^+), # # where: # C := number of", "`String` name to prepend to created ops. Returns: ess: `Tensor`", "`filter_beyond_lag`, `filter_threshold` and `filter_beyond_positive_pairs` are filters intended to remove noisy", "number of elements of `x` in `axis`, as type `x.dtype`.\"\"\"", "* sigma_2_plus / w - (n - 1.) / (m", "dt = states.dtype # filter_beyond_lag == None ==> auto_corr is", "# ESS = N / {1 + 2 * Sum_{k=1}^N", "auto_corr = 1. - (biased_within_chain_variance - mean_auto_cov) / approx_variance else:", "are all positive for auto-correlation spectra derived from # reversible", "to be filtered under the `filter_beyond_lag` OR `filter_beyond_positive_pairs` criteria. This", "It still works fine in the formula below. weighted_auto_corr =", "reshaping [2, a//2, b] into [a//2, 2, b]. state =", "to `states`. The effective sample size of each component of", "axis=axis, keepdims=keepdims) if biased: return biased_var n = _axis_size(x, axis)", "a factor of 2. # It still works fine in", "* R_1 + ... + 1 / N * R_{N-1}", "= state[:n_samples - n_samples % 2] # Suppose state =", "pairwise sums of the elements of that sequence are positive", "# where M is the filter_beyond_lag truncation point chosen above.", "b] into [2, a//2, b]. state = tf.reshape( state, ps.concat([[2,", "N, and give it shape [M, 1,...,1], having total #", "* (N - 1) / N biased_within_chain_variance = tf.reduce_mean(auto_cov[0], cross_chain_dims", "from `dim = 1` to `dim = D`, holding independent", "(MCMC) sampling. @@effective_sample_size @@potential_scale_reduction \"\"\" from __future__ import absolute_import from", "R-hat --> 1. Before that, R-hat > 1 (except in", "reduces the length of weighted_auto_corr by a factor of 2.", "distributed, ESS is the number such that ``` Variance{ N**-1", "name): return nest.map_structure_up_to( states, single_state, states, filter_beyond_lag, filter_threshold, filter_beyond_positive_pairs, cross_chain_dims)", "If `cross_chain_dims` is not `None` and there are less than", "can also compute cross-chain ESS following [Vehtari et al. (2019)][2]", "(x_hat[c] - x_hat)**2, between chain # variance. # s_c**2 :=", "for the state(s). Same `dtype` as `state`, and shape equal", "structures of different shapes. ValueError: If `cross_chain_dims` is not `None`", "'Argument `independent_chain_ndims` must be `>= 1`, found: {}'.format( independent_chain_ndims)) def", "`Tensors` corresponding to each state component. If a list of", "mask = [0, 0, 1, 2] mask = tf.cumsum(mask, axis=0)", "sample. state_shape = ps.shape(state) n_samples = state_shape[0] state = state[:n_samples", "applicable law or agreed to in writing, software # distributed", "to which variance (of the means) between chains exceeds what", "the same length. Which dimensions of `states` to treat as", "folding, and localization: An improved R-hat for assessing convergence of", "filter_beyond_lag = nest_util.broadcast_structure(states, filter_beyond_lag) filter_threshold = nest_util.broadcast_structure(states, filter_threshold) filter_beyond_positive_pairs =", "Must be `int`-like and scalar valued. The sequence of auto-correlations", "5] # Step 1: reshape into [[0, 1, 2], [3,", "(as a numpy # array) is not efficiently computable. Therefore,", "the pairwise sums are [0.2, 0.1, -0.1, -0.2] # Step", "factor, commonly referred to as R-hat, measures convergence of the", "+= 1 sample_axis = ps.range(0, sample_ndims) chain_axis = ps.range(sample_ndims, sample_ndims", "be `>= 1`, found: {}'.format( independent_chain_ndims)) def single_state(s): return _potential_scale_reduction_single_state(", "[1, 0.5, 0.0, 0.3], and filter_threshold = 0.2. # Step", "from a distribution overdispersed with respect to the target. *", "leading dimension indexes e.g. correlated samples # from each Markov", "# We're treating the new dim as indexing 2 chains,", "axis=0), biased=False, # This makes the denominator be C -", "reversible MCMC chains. # E.g. imagine the pairwise sums are", "chain variances. b_div_n = _reduce_variance( tf.reduce_mean(state, axis=sample_axis, keepdims=True), sample_and_chain_axis, biased=False)", "Carlo (MCMC) sampling. @@effective_sample_size @@potential_scale_reduction \"\"\" from __future__ import absolute_import", "stationary sequence of possibly correlated random variables `X_1, X_2, ...,", "< 2: raise ValueError(msg) elif validate_args: assertions.append( assert_util.assert_greater(num_chains, 1., message=msg))", "(since R[0] = 1) # approx N / {-1 +", "# B := N / (C - 1) Sum_{c=1}^C (x_hat[c]", "}. ``` If the sequence is uncorrelated, `ESS = N`.", "or Python structure of `Tensor`s representing the states of a", "split_chains=False, validate_args=False, name=None): \"\"\"<NAME> Rubin (1992)'s potential scale reduction for", "s_c**2, within-chain variance. # B := N / (C -", "the new dim as indexing 2 chains, so increment. independent_chain_ndims", "# Step 4: mask = [1, 1, 0, 0] mask", "from tensorflow_probability.python.internal import prefer_static as ps from tensorflow_probability.python.internal import tensorshape_util", "is None else name): return tf.nest.map_structure(single_state, chains_states) def _potential_scale_reduction_single_state(state, independent_chain_ndims,", "+ 2 * Sum_{k=1}^N R[k] * (N - k) /", "# pylint: disable=g-direct-tensorflow-import __all__ = [ 'effective_sample_size', 'potential_scale_reduction', ] def", "variables `X_1, X_2, ..., X_N`, identically distributed, ESS is the", "tf.control_dependencies(assertions): state = tf.identity(state) else: assertions = [assert_util.assert_greater( ps.shape(state)[0], 2,", "doubling the number of # independent chains. # For odd", "Authors. # # Licensed under the Apache License, Version 2.0", "biased_var def _axis_size(x, axis=None): \"\"\"Get number of elements of `x`", "else: new_shape = tf.concat( ([-1], tf.ones([tf.rank(auto_corr) - 1], dtype=tf.int32)), axis=0)", "2], [3, 4, 5]] # E.g. reshape states of shape", "will be less than `N`. If there are negative correlations,", "An integer `Tensor` or a structure of integer `Tensors` corresponding", "the within sequence variance, the mean of the chain variances.", "over `R_k` should be truncated at some number `filter_beyond_lag <", "states.dtype # filter_beyond_lag == None ==> auto_corr is the full", "# You may obtain a copy of the License at", "below the threshold. # mask[i, ...] = 1 if auto_corr[j,", "of dimensions, from `dim = 1` to `dim = D`,", "axis=0, max_lags=filter_beyond_lag, normalize=False) n = _axis_size(states, axis=0) if cross_chain_dims is", "truncation. Args: states: `Tensor` or Python structure of `Tensor` objects.", "`None`, no summation is performed. Note this requires at least", "be one. #### References [1]: <NAME> and <NAME>. General Methods", "the summation over `R_k` should be truncated at some number", "`Tensor` or Python structure of `Tensor` objects. Must be `int`-like", "False] mask = auto_corr < filter_threshold # Step 2: mask", "b_div_n = _reduce_variance( tf.reduce_mean(state, axis=sample_axis, keepdims=True), sample_and_chain_axis, biased=False) w =", "sample size\" (ESS) is the size of an iid sample", "_axis_size(auto_corr, axis=0)) nk_factor = (n - k) / n if", "be C - 1. axis=cross_chain_dims - 1) # W *", "`True`, only consider the initial auto-correlation sequence where the pairwise", "available statically. if split_chains and n_samples_ < 4: raise ValueError(", "`states` and `filter_threshold` or `states` and `filter_beyond_lag` are both structures", "1, 1] mask = tf.cast(mask, dt) # Step 3: mask", "array) is not efficiently computable. Therefore, we try constant_value then", "N / {-1 + 2 * Sum_{k=0}^N R[k] * (N", "def _sum_pairs(x): x_len = ps.shape(x)[0] # For odd sequences, we", "a structure of integer `Tensors` corresponding to each state component.", "tf.control_dependencies(assertions): # We're computing the R[k] from equation 10 of", "perm=ps.concat( [[1, 0], ps.range(2, ps.rank(state))], axis=0)) # We're treating the", "of the chains (to the same target) by testing for", "num_chains_ < 2: raise ValueError(msg) elif validate_args: assertions.append( assert_util.assert_greater(num_chains, 1.,", "1} > 0` for `k in {0, ..., N/2}`. Deviations", "= tf.cast(mask, dtype=dt) # Step 3: mask = [0, 0,", "the number of # independent chains. # For odd number", "b_div_n return ((m + 1.) / m) * sigma_2_plus /", "We're computing the R[k] from equation 10 of Vehtari et", "...] = 1 if auto_corr[j, ...] > threshold for all", "ValueError: If `cross_chain_dims` is not `None` and there are less", "and shape equal to `state.shape[1 + independent_chain_ndims:]`. Raises: ValueError: If", "is `True`. filter_beyond_lag: `Tensor` or Python structure of `Tensor` objects.", "right place to be treated as a # chain, changing", "shape `[Ni, Ci1, Ci2,...,CiD] + A`. Dimension `0` indexes the", "only `N - k` samples, it becomes progressively noisier for", "Sometimes, R-hat < 1.2 is used to indicate approximate convergence,", "tfp.distributions target = tfd.MultivariateNormalDiag(scale_diag=[1., 2.]) # Get 10 (2x) overdispersed", "Simulations. _Journal of Computational and Graphical Statistics_, 7(4), 1998. [2]:", "cross_chain_dims, validate_args): \"\"\"ESS computation for one single Tensor argument.\"\"\" with", "1.3] ``` To see why R-hat is reasonable, let `X`", "If the chains are all drawing from the same distribution,", "last sample. state_shape = ps.shape(state) n_samples = state_shape[0] state =", "Diagnosing convergence by monitoring 10 chains that each attempt to", "states, and the denominator is the total variance minus the", "i.e. `R_{2k} + R_{2k + 1} > 0` for `k", "magic number. # Warning! `if split_chains` logic assumes this is", "should be drawn from a distribution overdispersed with respect to", "`ESS > N`) correctly. * `filter_beyond_positive_pairs` -- reversible MCMC chains", "filter. Since `|R_k| <= 1`, setting to any number less", "not guaranteed. name: `String` name to prepend to created tf.", "0, 1, 1] mask = tf.cast(mask, dt) # Step 3:", "after the first appearance of a term less than `filter_threshold`.", "representing the states of a Markov Chain at each result", "= ps.shape(state) n_samples = state_shape[0] state = state[:n_samples - n_samples", "into [a//2, 2, b]. state = tf.transpose( a=state, perm=ps.concat( [[1,", "ESS to estimate standard error. ``` import tensorflow as tf", "not None: # If available statically. if split_chains and n_samples_", "`state`. More precisely, given a stationary sequence of possibly correlated", "reduce the ESS in cases where the chains are not", "less than `filter_threshold`. Setting to `None` means we use no", "tf.range(0., _axis_size(auto_corr, axis=0)) nk_factor = (n - k) / n", "a random variable drawn uniformly from the combined states (combined", "statically. if split_chains and n_samples_ < 4: raise ValueError( 'Must", "\"License\"); # you may not use this file except in", "j <= i, # mask[i, ...] = 0, otherwise. #", "variance = tf.nn.moments(states, axis=0) standard_error = tf.sqrt(variance / ess) ```", "since many MCMC methods generate chains where `R_k > 0`,", "component of `states`. If `cross_chain_dims` is None, the shape will", "- 1) # W * (N - 1) / N", "the same as auto_corr k = tf.range(0., _axis_size(auto_corr, axis=0)) nk_factor", "reshape states of shape [a, b] into [2, a//2, b].", "#### References [1]: <NAME> and <NAME>. General Methods for Monitoring", "1, 2], [3, 4, 5]] # E.g. reshape states of", "tf.cast(mask, dt) # Step 3: mask = [0, 0, 1,", "Examples We use ESS to estimate standard error. ``` import", "C - 1. axis=cross_chain_dims - 1) # W * (N", "pairwise sums are [0.2, 0.1, -0.1, -0.2] # Step 1:", "provides two methods to perform this truncation. * `filter_threshold` --", "drawn from the target. c.f. \"law of total variance.\" sigma_2_plus", "= tf.sqrt(variance / ess) ``` #### References [1]: <NAME>, Practical", "# So, along dimension zero, the mask will look like", "Dimensions `1` through `D` index the `Ci1 x ... x", "Markov Chain. Dimensions `1` through `D` index the `Ci1 x", "we use no threshold filter. Since `|R_k| <= 1`, setting", "x = tf.convert_to_tensor(x, name='x') mean = tf.reduce_mean(x, axis=axis, keepdims=True) biased_var", "Pairwise sums are all positive for auto-correlation spectra derived from", "target, then as `N --> infinity`, R-hat --> 1. Before", "overdispersed initial states. initial_state = target.sample(10) * 2. ==> (10,", "= [0, 0, 1, 2] mask = tf.cumsum(mask, axis=0) #", "`Tensor` or Python structure of `Tensor` objects. Must broadcast with", "# Get 10 (2x) overdispersed initial states. initial_state = target.sample(10)", "above holds for any number of chains `C > 1`.", "* tf.reduce_sum(weighted_auto_corr, axis=0)) def potential_scale_reduction(chains_states, independent_chain_ndims=1, split_chains=False, validate_args=False, name=None): \"\"\"<NAME>", "ps.range(2, ps.rank(state))], axis=0)) # We're treating the new dim as", "1` states from each of `C > 1` independent chains,", "R[k] from equation 10 of Vehtari et al. # (2019):", "2) rhat = tfp.mcmc.diagnostic.potential_scale_reduction( chains_states, independent_chain_ndims=1) # The second dimension", "of lags. filter_beyond_positive_pairs: Python boolean. If `True`, only consider the", "# = N / {-1 + 2 * Sum_{k=0}^N R[k]", "ps.concat([[x_len // 2, 2], ps.shape(x)[1:]], axis=0) return tf.reduce_sum(tf.reshape(x, new_shape), 1)", "= tf.get_static_value( ps.convert_to_shape_tensor(independent_chain_ndims)) if icn_const_ is not None: independent_chain_ndims =", "| chain]] + Var[E[X | chain]] ) / E[Var[X |", "initial state of the chains should be drawn from a", "num_chains = _axis_size(states, cross_chain_dims) num_chains_ = tf.get_static_value(num_chains) assertions = []", "new_shape), 1) # Pairwise sums are all positive for auto-correlation", "shape equal to `state.shape[1 + independent_chain_ndims:]`. Raises: ValueError: If `independent_chain_ndims", "biased=False, # This makes the denominator be C - 1.", "Sum_{n=1}^N (x[n, c] - x_hat[c])**2, chain # variance # R[k,", "< 4: raise ValueError( 'Must provide at least 4 samples", "Since `R_k` must be estimated using only `N - k`", "a numpy # array) is not efficiently computable. Therefore, we", "the ESS for individual chains and then summing them. In", "is used to indicate approximate convergence, but of course this", "states of shape [a, b] into [2, a//2, b]. state", "current_state=initial_state, trace_fn=None, kernel=tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=target.log_prob, step_size=0.05, num_leapfrog_steps=20)) chains_states.shape ==> (1000, 10,", "filter_beyond_positive_pairs) # Process items, one at a time. def single_state(*args):", "chains `C > 1`. Increasing `C` does improve effectiveness of", "of Brooks and Gelman (1998), # B / n is", "reshape into [[0, 1, 2], [3, 4, 5]] # E.g.", "Default: `potential_scale_reduction`. Returns: `Tensor` structure parallel to `chains_states` representing the" ]
[ "* 6, out_features=2) def forward(self, inp): out = self.features(inp) out", "nn.MaxPool2d(2)) self.classifier = DenseLinear(in_features=32 * 6 * 6, out_features=2) def", "kernel_size=3, padding=1), nn.BatchNorm2d(32), nn.MaxPool2d(2), DenseConv2d(32, 32, kernel_size=3, padding=2), nn.BatchNorm2d(32), nn.MaxPool2d(2),", "return out def conv2() -> Conv2: return Conv2() def conv4()", "nn.BatchNorm2d(32), nn.MaxPool2d(2)) self.classifier = DenseLinear(in_features=32 * 6 * 6, out_features=2)", "class Conv2(BaseModel): def __init__(self): super(Conv2, self).__init__() self.features = nn.Sequential(DenseConv2d(1, 32,", "out.view(out.size(0), -1) out = self.classifier(out) return out def conv2() ->", "out.view(out.size(0), -1) out = self.classifier(out) return out class Conv4(BaseModel): def", "DenseConv2d(32, 32, kernel_size=3, padding=2), nn.BatchNorm2d(32), nn.MaxPool2d(2), DenseConv2d(32, 32, kernel_size=3, padding=2),", "return Conv2() def conv4() -> Conv4: return Conv4() # TODO:", "nn.MaxPool2d(2), DenseConv2d(32, 32, kernel_size=3, padding=1), nn.BatchNorm2d(32), nn.MaxPool2d(2), DenseConv2d(32, 32, kernel_size=3,", "64, kernel_size=5, padding=2), # 64x14x14 nn.ReLU(inplace=True), nn.MaxPool2d(2, stride=2)) # 64x7x7", "-1) out = self.classifier(out) return out def conv2() -> Conv2:", "= nn.Sequential(DenseLinear(64 * 7 * 7, 2048), nn.ReLU(inplace=True), DenseLinear(2048, 62))", "forward(self, inp): out = self.features(inp) out = out.view(out.size(0), -1) out", "# 64x14x14 nn.ReLU(inplace=True), nn.MaxPool2d(2, stride=2)) # 64x7x7 self.classifier = nn.Sequential(DenseLinear(64", "nn.MaxPool2d(2), DenseConv2d(32, 32, kernel_size=3, padding=2), nn.BatchNorm2d(32), nn.MaxPool2d(2), DenseConv2d(32, 32, kernel_size=3,", "padding=2), # 32x28x28 nn.ReLU(inplace=True), nn.MaxPool2d(2, stride=2), # 32x14x14 DenseConv2d(32, 64,", ".base_model import BaseModel from ..nn.conv2d import DenseConv2d from ..nn.linear import", "7 * 7, 2048), nn.ReLU(inplace=True), DenseLinear(2048, 62)) self.collect_prunable_layers() def forward(self,", "nn from .base_model import BaseModel from ..nn.conv2d import DenseConv2d from", "= nn.Sequential(DenseConv2d(3, 32, kernel_size=3, padding=1), nn.BatchNorm2d(32), nn.MaxPool2d(2), DenseConv2d(32, 32, kernel_size=3,", "kernel_size=5, padding=2), # 64x14x14 nn.ReLU(inplace=True), nn.MaxPool2d(2, stride=2)) # 64x7x7 self.classifier", "= DenseLinear(in_features=32 * 6 * 6, out_features=2) def forward(self, inp):", "= self.features(inp) out = out.view(out.size(0), -1) out = self.classifier(out) return", "DenseLinear(in_features=32 * 6 * 6, out_features=2) def forward(self, inp): out", "nn.MaxPool2d(2, stride=2), # 32x14x14 DenseConv2d(32, 64, kernel_size=5, padding=2), # 64x14x14", "\"conv4\"] class Conv2(BaseModel): def __init__(self): super(Conv2, self).__init__() self.features = nn.Sequential(DenseConv2d(1,", "Conv2: return Conv2() def conv4() -> Conv4: return Conv4() #", "def conv2() -> Conv2: return Conv2() def conv4() -> Conv4:", "out class Conv4(BaseModel): def __init__(self): super(Conv4, self).__init__() self.features = nn.Sequential(DenseConv2d(3,", "self.features = nn.Sequential(DenseConv2d(1, 32, kernel_size=5, padding=2), # 32x28x28 nn.ReLU(inplace=True), nn.MaxPool2d(2,", "..nn.linear import DenseLinear __all__ = [\"Conv2\", \"conv2\", \"Conv4\", \"conv4\"] class", "= out.view(out.size(0), -1) out = self.classifier(out) return out def conv2()", "padding=1), nn.BatchNorm2d(32), nn.MaxPool2d(2), DenseConv2d(32, 32, kernel_size=3, padding=2), nn.BatchNorm2d(32), nn.MaxPool2d(2), DenseConv2d(32,", "conv4() -> Conv4: return Conv4() # TODO: define pretrain etc.", "torch import nn as nn from .base_model import BaseModel from", "kernel_size=3, padding=2), nn.BatchNorm2d(32), nn.MaxPool2d(2), DenseConv2d(32, 32, kernel_size=3, padding=2), nn.BatchNorm2d(32), nn.MaxPool2d(2))", "DenseConv2d(32, 32, kernel_size=3, padding=1), nn.BatchNorm2d(32), nn.MaxPool2d(2), DenseConv2d(32, 32, kernel_size=3, padding=2),", "def forward(self, inp): out = self.features(inp) out = out.view(out.size(0), -1)", "DenseConv2d(32, 32, kernel_size=3, padding=2), nn.BatchNorm2d(32), nn.MaxPool2d(2)) self.classifier = DenseLinear(in_features=32 *", "import DenseLinear __all__ = [\"Conv2\", \"conv2\", \"Conv4\", \"conv4\"] class Conv2(BaseModel):", "super(Conv4, self).__init__() self.features = nn.Sequential(DenseConv2d(3, 32, kernel_size=3, padding=1), nn.BatchNorm2d(32), nn.MaxPool2d(2),", "\"Conv4\", \"conv4\"] class Conv2(BaseModel): def __init__(self): super(Conv2, self).__init__() self.features =", "= nn.Sequential(DenseConv2d(1, 32, kernel_size=5, padding=2), # 32x28x28 nn.ReLU(inplace=True), nn.MaxPool2d(2, stride=2),", "32, kernel_size=5, padding=2), # 32x28x28 nn.ReLU(inplace=True), nn.MaxPool2d(2, stride=2), # 32x14x14", "as nn from .base_model import BaseModel from ..nn.conv2d import DenseConv2d", "nn.MaxPool2d(2, stride=2)) # 64x7x7 self.classifier = nn.Sequential(DenseLinear(64 * 7 *", "# 32x14x14 DenseConv2d(32, 64, kernel_size=5, padding=2), # 64x14x14 nn.ReLU(inplace=True), nn.MaxPool2d(2,", "nn.ReLU(inplace=True), DenseLinear(2048, 62)) self.collect_prunable_layers() def forward(self, inp): out = self.features(inp)", "def __init__(self): super(Conv4, self).__init__() self.features = nn.Sequential(DenseConv2d(3, 32, kernel_size=3, padding=1),", "64x14x14 nn.ReLU(inplace=True), nn.MaxPool2d(2, stride=2)) # 64x7x7 self.classifier = nn.Sequential(DenseLinear(64 *", "# 64x7x7 self.classifier = nn.Sequential(DenseLinear(64 * 7 * 7, 2048),", "kernel_size=3, padding=2), nn.BatchNorm2d(32), nn.MaxPool2d(2)) self.classifier = DenseLinear(in_features=32 * 6 *", "padding=1), nn.BatchNorm2d(32), nn.MaxPool2d(2), DenseConv2d(32, 32, kernel_size=3, padding=1), nn.BatchNorm2d(32), nn.MaxPool2d(2), DenseConv2d(32,", "def __init__(self): super(Conv2, self).__init__() self.features = nn.Sequential(DenseConv2d(1, 32, kernel_size=5, padding=2),", "conv2() -> Conv2: return Conv2() def conv4() -> Conv4: return", "-> Conv2: return Conv2() def conv4() -> Conv4: return Conv4()", "DenseLinear(2048, 62)) self.collect_prunable_layers() def forward(self, inp): out = self.features(inp) out", "self.classifier = nn.Sequential(DenseLinear(64 * 7 * 7, 2048), nn.ReLU(inplace=True), DenseLinear(2048,", "nn.BatchNorm2d(32), nn.MaxPool2d(2), DenseConv2d(32, 32, kernel_size=3, padding=1), nn.BatchNorm2d(32), nn.MaxPool2d(2), DenseConv2d(32, 32,", "32x28x28 nn.ReLU(inplace=True), nn.MaxPool2d(2, stride=2), # 32x14x14 DenseConv2d(32, 64, kernel_size=5, padding=2),", "= self.classifier(out) return out class Conv4(BaseModel): def __init__(self): super(Conv4, self).__init__()", "nn.Sequential(DenseLinear(64 * 7 * 7, 2048), nn.ReLU(inplace=True), DenseLinear(2048, 62)) self.collect_prunable_layers()", "* 7 * 7, 2048), nn.ReLU(inplace=True), DenseLinear(2048, 62)) self.collect_prunable_layers() def", "out_features=2) def forward(self, inp): out = self.features(inp) out = out.view(out.size(0),", "nn.BatchNorm2d(32), nn.MaxPool2d(2), DenseConv2d(32, 32, kernel_size=3, padding=2), nn.BatchNorm2d(32), nn.MaxPool2d(2), DenseConv2d(32, 32,", "Conv2(BaseModel): def __init__(self): super(Conv2, self).__init__() self.features = nn.Sequential(DenseConv2d(1, 32, kernel_size=5,", "self.features(inp) out = out.view(out.size(0), -1) out = self.classifier(out) return out", "DenseConv2d from ..nn.linear import DenseLinear __all__ = [\"Conv2\", \"conv2\", \"Conv4\",", "inp): out = self.features(inp) out = out.view(out.size(0), -1) out =", "64x7x7 self.classifier = nn.Sequential(DenseLinear(64 * 7 * 7, 2048), nn.ReLU(inplace=True),", "stride=2)) # 64x7x7 self.classifier = nn.Sequential(DenseLinear(64 * 7 * 7,", "..nn.conv2d import DenseConv2d from ..nn.linear import DenseLinear __all__ = [\"Conv2\",", "__init__(self): super(Conv2, self).__init__() self.features = nn.Sequential(DenseConv2d(1, 32, kernel_size=5, padding=2), #", "out def conv2() -> Conv2: return Conv2() def conv4() ->", "__all__ = [\"Conv2\", \"conv2\", \"Conv4\", \"conv4\"] class Conv2(BaseModel): def __init__(self):", "-1) out = self.classifier(out) return out class Conv4(BaseModel): def __init__(self):", "out = self.classifier(out) return out class Conv4(BaseModel): def __init__(self): super(Conv4,", "nn.Sequential(DenseConv2d(1, 32, kernel_size=5, padding=2), # 32x28x28 nn.ReLU(inplace=True), nn.MaxPool2d(2, stride=2), #", "super(Conv2, self).__init__() self.features = nn.Sequential(DenseConv2d(1, 32, kernel_size=5, padding=2), # 32x28x28", "DenseLinear __all__ = [\"Conv2\", \"conv2\", \"Conv4\", \"conv4\"] class Conv2(BaseModel): def", "62)) self.collect_prunable_layers() def forward(self, inp): out = self.features(inp) out =", "* 6 * 6, out_features=2) def forward(self, inp): out =", "self.features = nn.Sequential(DenseConv2d(3, 32, kernel_size=3, padding=1), nn.BatchNorm2d(32), nn.MaxPool2d(2), DenseConv2d(32, 32,", "def conv4() -> Conv4: return Conv4() # TODO: define pretrain", "from ..nn.conv2d import DenseConv2d from ..nn.linear import DenseLinear __all__ =", "= [\"Conv2\", \"conv2\", \"Conv4\", \"conv4\"] class Conv2(BaseModel): def __init__(self): super(Conv2,", "32, kernel_size=3, padding=1), nn.BatchNorm2d(32), nn.MaxPool2d(2), DenseConv2d(32, 32, kernel_size=3, padding=2), nn.BatchNorm2d(32),", "2048), nn.ReLU(inplace=True), DenseLinear(2048, 62)) self.collect_prunable_layers() def forward(self, inp): out =", "32x14x14 DenseConv2d(32, 64, kernel_size=5, padding=2), # 64x14x14 nn.ReLU(inplace=True), nn.MaxPool2d(2, stride=2))", "padding=2), nn.BatchNorm2d(32), nn.MaxPool2d(2), DenseConv2d(32, 32, kernel_size=3, padding=2), nn.BatchNorm2d(32), nn.MaxPool2d(2)) self.classifier", "stride=2), # 32x14x14 DenseConv2d(32, 64, kernel_size=5, padding=2), # 64x14x14 nn.ReLU(inplace=True),", "self.classifier = DenseLinear(in_features=32 * 6 * 6, out_features=2) def forward(self,", "\"conv2\", \"Conv4\", \"conv4\"] class Conv2(BaseModel): def __init__(self): super(Conv2, self).__init__() self.features", "= out.view(out.size(0), -1) out = self.classifier(out) return out class Conv4(BaseModel):", "out = self.features(inp) out = out.view(out.size(0), -1) out = self.classifier(out)", "out = out.view(out.size(0), -1) out = self.classifier(out) return out def", "* 7, 2048), nn.ReLU(inplace=True), DenseLinear(2048, 62)) self.collect_prunable_layers() def forward(self, inp):", "BaseModel from ..nn.conv2d import DenseConv2d from ..nn.linear import DenseLinear __all__", "nn.BatchNorm2d(32), nn.MaxPool2d(2), DenseConv2d(32, 32, kernel_size=3, padding=2), nn.BatchNorm2d(32), nn.MaxPool2d(2)) self.classifier =", "from .base_model import BaseModel from ..nn.conv2d import DenseConv2d from ..nn.linear", "nn as nn from .base_model import BaseModel from ..nn.conv2d import", "__init__(self): super(Conv4, self).__init__() self.features = nn.Sequential(DenseConv2d(3, 32, kernel_size=3, padding=1), nn.BatchNorm2d(32),", "= self.classifier(out) return out def conv2() -> Conv2: return Conv2()", "import nn as nn from .base_model import BaseModel from ..nn.conv2d", "32, kernel_size=3, padding=1), nn.BatchNorm2d(32), nn.MaxPool2d(2), DenseConv2d(32, 32, kernel_size=3, padding=1), nn.BatchNorm2d(32),", "class Conv4(BaseModel): def __init__(self): super(Conv4, self).__init__() self.features = nn.Sequential(DenseConv2d(3, 32,", "nn.ReLU(inplace=True), nn.MaxPool2d(2, stride=2)) # 64x7x7 self.classifier = nn.Sequential(DenseLinear(64 * 7", "import BaseModel from ..nn.conv2d import DenseConv2d from ..nn.linear import DenseLinear", "padding=2), # 64x14x14 nn.ReLU(inplace=True), nn.MaxPool2d(2, stride=2)) # 64x7x7 self.classifier =", "padding=2), nn.BatchNorm2d(32), nn.MaxPool2d(2)) self.classifier = DenseLinear(in_features=32 * 6 * 6,", "self.classifier(out) return out class Conv4(BaseModel): def __init__(self): super(Conv4, self).__init__() self.features", "kernel_size=3, padding=1), nn.BatchNorm2d(32), nn.MaxPool2d(2), DenseConv2d(32, 32, kernel_size=3, padding=1), nn.BatchNorm2d(32), nn.MaxPool2d(2),", "nn.ReLU(inplace=True), nn.MaxPool2d(2, stride=2), # 32x14x14 DenseConv2d(32, 64, kernel_size=5, padding=2), #", "import DenseConv2d from ..nn.linear import DenseLinear __all__ = [\"Conv2\", \"conv2\",", "return out class Conv4(BaseModel): def __init__(self): super(Conv4, self).__init__() self.features =", "7, 2048), nn.ReLU(inplace=True), DenseLinear(2048, 62)) self.collect_prunable_layers() def forward(self, inp): out", "[\"Conv2\", \"conv2\", \"Conv4\", \"conv4\"] class Conv2(BaseModel): def __init__(self): super(Conv2, self).__init__()", "32, kernel_size=3, padding=2), nn.BatchNorm2d(32), nn.MaxPool2d(2), DenseConv2d(32, 32, kernel_size=3, padding=2), nn.BatchNorm2d(32),", "6, out_features=2) def forward(self, inp): out = self.features(inp) out =", "self.collect_prunable_layers() def forward(self, inp): out = self.features(inp) out = out.view(out.size(0),", "Conv4(BaseModel): def __init__(self): super(Conv4, self).__init__() self.features = nn.Sequential(DenseConv2d(3, 32, kernel_size=3,", "32, kernel_size=3, padding=2), nn.BatchNorm2d(32), nn.MaxPool2d(2)) self.classifier = DenseLinear(in_features=32 * 6", "self).__init__() self.features = nn.Sequential(DenseConv2d(1, 32, kernel_size=5, padding=2), # 32x28x28 nn.ReLU(inplace=True),", "self.classifier(out) return out def conv2() -> Conv2: return Conv2() def", "Conv2() def conv4() -> Conv4: return Conv4() # TODO: define", "DenseConv2d(32, 64, kernel_size=5, padding=2), # 64x14x14 nn.ReLU(inplace=True), nn.MaxPool2d(2, stride=2)) #", "nn.Sequential(DenseConv2d(3, 32, kernel_size=3, padding=1), nn.BatchNorm2d(32), nn.MaxPool2d(2), DenseConv2d(32, 32, kernel_size=3, padding=1),", "from torch import nn as nn from .base_model import BaseModel", "from ..nn.linear import DenseLinear __all__ = [\"Conv2\", \"conv2\", \"Conv4\", \"conv4\"]", "nn.MaxPool2d(2), DenseConv2d(32, 32, kernel_size=3, padding=2), nn.BatchNorm2d(32), nn.MaxPool2d(2)) self.classifier = DenseLinear(in_features=32", "out = self.classifier(out) return out def conv2() -> Conv2: return", "self).__init__() self.features = nn.Sequential(DenseConv2d(3, 32, kernel_size=3, padding=1), nn.BatchNorm2d(32), nn.MaxPool2d(2), DenseConv2d(32,", "kernel_size=5, padding=2), # 32x28x28 nn.ReLU(inplace=True), nn.MaxPool2d(2, stride=2), # 32x14x14 DenseConv2d(32,", "# 32x28x28 nn.ReLU(inplace=True), nn.MaxPool2d(2, stride=2), # 32x14x14 DenseConv2d(32, 64, kernel_size=5,", "6 * 6, out_features=2) def forward(self, inp): out = self.features(inp)", "out = out.view(out.size(0), -1) out = self.classifier(out) return out class" ]
[ "m else: unused_method_names.add(complementation_dict[m]) elif user_rejection: for m in method_ids: if", "def get_seeds_from_file(seed_file): \"\"\" Obtain the seeds from a file and", "if restricted_to_seeds or options.radius>0: # Check if the seeds file", "yeast two hybrid elif options.restricted_to_Y2H: print ('Using interactions at least", "in nodes: score=seed_score uE = session.get_user_entity(protein) for current_id in uE.get_attribute(attribute_identifier=options.stype):", "INFORMATION FROM CONFIG FILE # #--------------------------------------# # Get the program", "if trans_stype: out_trans_stype.close() #################################################################################### # If we wanted a network", "parse_user_arguments() generate_network(options) def parse_user_arguments(*args, **kwds): parser = argparse.ArgumentParser( description =", "affinity_dict = methods_dicts.affinity_dict affinity=set(affinity_dict.keys()) # Get the complementation dictionary complementation_dict", "for translation allseed=set() for uE_id in proteome.get_user_entity_ids(): allseed.add(uE_id) for protein", "# Output node file out_proteins = open(options.node,'w') translate={} for protein", "os.path.exists(file) and os.path.isfile(file) def get_seeds_from_file(seed_file): \"\"\" Obtain the seeds from", "!= \"0\": print(\"Check Proteome %s\"%(repr(options.taxid))) proteome = session.create_new_user_entity_set( identifier_description_list =seed_list,", "if trans_stype: out_trans_stype.close() #################################################################################### print('Generation of the network done!') return", "= \"proteome\" , level = level, relation_type_list=[\"interaction\"] , relation_attribute_restriction_list =", "relation_type_list=[\"interaction\"] , include_relations_last_level = (not restricted_to_seeds) , use_self_relations = False)", "= [] ) num_methods=0 for current_eErID in eErIDs_list: relationObj =", "use_method_ids=set() pubmed_ids = set() unused_method_names = set() relationObj_dict = session.dbAccess.get_external_entities_dict(", "to use all interactions except those described by yeast two", "#print \"check Y2H\" for m in method_ids: if m not", "not protein!') print('Node 1: {}\\tType: {}'.format(uE_id1, uE1_type)) print('Node 2: {}\\tType:", "if current_id.value.lower() in seeds: translate.setdefault(current_id.value.lower(),[]) translate[current_id.value.lower()].append(protein) ################################# TRANSLATION #################################### out_translation", "if current_id.value.lower() in seeds: translate.setdefault(current_id.value.lower(),[]) translate[current_id.value.lower()].append(protein) score=1.0 if options.format ==", "use_self_relations = False) # Select all interactions else: session.create_network( user_entity_set_id", "the user selected methods') parser.add_argument('-v','--verbose',dest='verbose',action = 'store_true', help = 'Flag", "nodes=set() # Get all the user entity ids from the", "== \"proteinsequence\": maxlen=0; for current_id in uE.get_attribute(attribute_identifier=options.ttype): if maxlen <", "single=set() for uE_id in proteome.get_unconnected_nodes(): single.add(uE_id) for protein in single:", "argparse.ArgumentParser( description = \"Generate a protein-protein interaction network (implemented for", "than 0 if restricted_to_seeds or options.radius>0: # Check if the", "out_network.write(\"{}\\t{:.2f}\\t{}\\n\".format(uE_id1,1.,uE_id2)) print \"Num neglected interactions:\", skip_interactions out_network.close() #---------------------------------------# # OUTPUT", "else: no_methods=[] with open(options.except_user) as input_method_fd: for line in input_method_fd:", "or options.radius>0: # Check if the seeds file exists if", "we add it if options.taxid != \"0\": print(\"Check Proteome %s\"%(repr(options.taxid)))", "= proteome.get_external_entity_relation_ids(uE_id1, uE_id2) method_names = set() method_ids = set() source_databases", "= line.strip().split(\"\\t\") no_methods.append(fields[0]) user_rejection=True print \"Input of rejected Methods:\",repr(no_methods) #---------------------------#", "current_id.value.lower() in seeds: translate.setdefault(current_id.value.lower(),[]) translate[current_id.value.lower()].append(protein) ################################# TRANSLATION #################################### out_translation =", "# GET INFORMATION FROM CONFIG FILE # #--------------------------------------# # Get", "protein in nodes: score=seed_score uE = session.get_user_entity(protein) for current_id in", "set() unused_method_names = set() relationObj_dict = session.dbAccess.get_external_entities_dict( externalEntityIdsList = eErIDs_list,", "provides with the longest sequence of all codes''') parser.add_argument('-trans','--translation_of_nodes_file',dest='translation_file',action =", "THE SELECTED INTERACTIONS # #--------------------------------------# nodes=set() # Get all the", "parser.add_argument('-stype','--seed_type',dest='stype',action = 'store',default='geneid', help = 'Type of identifier for seeds", "'Output file with nodes(default is biana_nodes)') parser.add_argument('-format','--output_format',dest='format',action = 'store',default='sif', help", "#print uE_id1, uE_id/2 nodes.add(uE_id1) nodes.add(uE_id2) #print \"Attribute \",(uE_id1,uE_id2).get_attribute( if options.format", "%s\"%(repr(options.taxid))) proteome = session.create_new_user_entity_set( identifier_description_list =seed_list, attribute_restriction_list=[(\"taxid\",options.taxid)], id_type=options.stype,new_user_entity_set_id=\"proteome\", negative_attribute_restriction_list=[] )", ", use_self_relations = False) # Select all interactions else: session.create_network(", "translation_stype=\"','\".join([\"{0}\".format(x) for x in translate_stype]) out_trans_stype.write(\"{0}\\t'{1}'\\n\".format(protein,translation_stype)) out_translation.close() if trans_stype: out_trans_stype.close()", "#print relationObj.get_attributes_dict() #print [ x.value for x in relationObj.get_attributes_dict()[\"psimi_name\"] ]", "for uE_id in proteome.get_user_entity_ids(): allseed.add(uE_id) for protein in allseed: if", "out_translation.write(\"{0}\\t'{1}'\\n\".format(protein,translation)) ##### TRANSLATION TO STYPE if trans_stype: for current_id in", "\"Pubmeds\",num_pubmeds,info_pubmed_ids # Check if the number of methods is higher", "not fileExist(options.restricted_to_user): print \"No restriction on methods selected by the", "score=1.0 if options.format == 'multi-fields': out_proteins.write(\"{0}\\t{1:.2f}\\t{2:.2f}\\t{3:.2f}\\n\".format(protein,1.,1.,score)) elif options.format == 'netscore':", "file with methods that must be included if not fileExist(options.restricted_to_user):", "(i.e. Tandem Affinity Purification)') parser.add_argument('-rY2H','--restricted_to_Y2H',dest='restricted_to_Y2H',action = 'store_true', help = 'Flag", "#################################### out_translation = open(options.translation_file,'w') # TRANSLATION TO 'stype' trans_stype=False if", "in method_ids: #print \"Check\",repr(use_methods) if m in set(use_methods): use_method_ids.add(m) if", "x in relationObj.get_attribute(attribute_identifier=\"psimi_name\") ]) #if relationObj.get_attribute(attribute_identifier=\"method_id\") is not None: #print", "for protein in single: uE = session.get_user_entity(protein) for current_id in", "if uE1_type != 'protein' or uE2_type != 'protein': if options.verbose:", "it has no method!') print('Node 1: {}\\tNode 2: {}'.format(uE_id1, uE_id2))", "for protein in nodes: if options.format == 'multi-fields': out_proteins.write(\"{0}\\t{1:.2f}\\t{2:.2f}\\t{3:.2f}\\n\".format(protein,1.,1.,0.1)) elif", "#relation_attribute_restriction_list = [(\"psimi_name\",\"affinity technology\")], include_relations_last_level = (not restricted_to_seeds) , use_self_relations", "if m in set(use_methods): use_method_ids.add(m) if options.verbose: print \"Not among", "maxlen < len(current_id.value.get_sequence().upper()): maxlen=len(current_id.value.get_sequence().upper()) translation=\",\".join([str(current_id.value.get_sequence().upper()) for current_id in uE.get_attribute(attribute_identifier=options.ttype) if", "not in single and protein not in nodes: uE =", "if the user has introduced a file with methods that", "from the introduced type of code to BIANA codes') parser.add_argument('-edge','--edge_file',dest='edge',action", "nodes that were not previously found in the network single=set()", "len(current_id.value.get_sequence().upper()): maxlen=len(current_id.value.get_sequence().upper()) translation=\",\".join([str(current_id.value.get_sequence().upper()) for current_id in uE.get_attribute(attribute_identifier=options.ttype) if len(str(current_id.value.get_sequence().upper())) ==", "with nodes(default is biana_nodes)') parser.add_argument('-format','--output_format',dest='format',action = 'store',default='sif', help = '''Format", "# Get the IDS of single nodes that were not", "config.read(config_file) #--------------------------------------# # LOAD THE DICTIONARIES OF METHODS # #--------------------------------------#", "'store_true', help = 'Flag to use verbose mode') options=parser.parse_args() \"\"\"", "session = create_new_session( sessionID=\"biana_session\", dbname=config.get('BIANA', 'database'), dbhost=config.get('BIANA', 'host'), dbuser=config.get('BIANA', 'user'),", "file of the edge file:\\tsif (default), netscore, raw, multi-fields:\\n 'sif':", "=seed_list, attribute_restriction_list=[(\"taxid\",options.taxid)], id_type=options.stype,new_user_entity_set_id=\"proteome\", negative_attribute_restriction_list=[] ) else: print('Proteome without Taxonomy restriction')", "TO 'ttype' out_translation = open(options.translation_file,'w') # TRANSLATION TO 'stype' trans_stype=False", "level = level, relation_type_list=[\"interaction\"] , relation_attribute_restriction_list = [(\"Method_id\",18)], #relation_attribute_restriction_list =", "translation file # TRANSLATION TO 'ttype' out_translation = open(options.translation_file,'w') #", "help = 'Output file with edges(default is biana_edges)') parser.add_argument('-node','--node_file',dest='node',action =", "import ConfigParser import sys, os, re import biana try: from", "translation=\"','\".join([str(x) for x in codes]) #out_translation.write(\"%s\\t'%s'\\n\" % (s.upper(),translation)) out_translation.write(\"{0}\\t'{1}'\\n\".format(s.upper(),translation)) else:", "FILE # #----------------------# if use: #print uE_id1, uE_id/2 nodes.add(uE_id1) nodes.add(uE_id2)", "interactions at least described by yeast two hybrid methods (Y2H)')", "detected at least by affinity technology if options.restricted_to_TAP: print ('Using", "that have been detected at least by affinity technology if", "negative_attribute_restriction_list=[] ) #----------------------------------------------------# # SELECT THE INTERACTIONS OF THE USER", "TaxID=0 there is no restriction)') parser.add_argument('-stype','--seed_type',dest='stype',action = 'store',default='geneid', help =", "x not in unused_method_names] # Remove method names that were", "in proteome.get_user_entity_ids(): allseed.add(uE_id) for protein in allseed: if protein not", "# FILTER THE SELECTED INTERACTIONS # #--------------------------------------# nodes=set() # Get", "be done differently elif options.radius > 0: # Read the", "if options.stype != 'proteinsequence' and options.stype != options.ttype: trans_stype =", "x in translate]) out_translation.write(\"{0}\\t'{1}'\\n\".format(protein,translation)) ##### TRANSLATION TO STYPE if trans_stype:", "in nodes: if options.format == 'multi-fields': out_proteins.write(\"{0}\\t{1:.2f}\\t{2:.2f}\\t{3:.2f}\\n\".format(protein,1.,1.,0.1)) elif options.format ==", "out_network = open(options.edge,'w') all_interactions = proteome.getRelations() print \"Num interactions:\", len(all_interactions)", "session.create_new_user_entity_set( identifier_description_list = [(\"taxid\",options.taxid)], attribute_restriction_list=[], id_type=\"embedded\", new_user_entity_set_id=\"proteome\", negative_attribute_restriction_list=[] ) #----------------------------------------------------#", "2: {}'.format(uE_id1, uE_id2)) skip_interactions=skip_interactions+1 continue if len(pubmed_ids) > 0: info_pubmed_ids=\";\".join([str(x)", "include_relations_last_level = (not restricted_to_seeds) , use_self_relations = False) # Select", "in seeds: translate.setdefault(current_id.value.lower(),[]) translate[current_id.value.lower()].append(protein) ################################# TRANSLATION #################################### out_translation = open(options.translation_seeds_file,'w')", "#--------------------------------------# # FILTER THE SELECTED INTERACTIONS # #--------------------------------------# nodes=set() #", "# DEFINE A USER ENTITY SET # #------------------------------# # Create", "1 minimum_number_of_db = 1 seed_score = 0.1 #--------------------------------------# # GET", "format is sif out_network.write(\"{}\\t{:.2f}\\t{}\\n\".format(uE_id1,1.,uE_id2)) print \"Num neglected interactions:\", skip_interactions out_network.close()", "those described by yeast two hybrid methods (Y2H)') parser.add_argument('-eUSER','--except_user',dest='except_user',action =", "#--------------------------------------# # LOAD THE DICTIONARIES OF METHODS # #--------------------------------------# #", "interactions that have been detected at least by affinity technology", "'r') as seed_file_fd: for line in seed_file_fd: fields = line.strip().split('\\t')", "attribute_list = [], relation_attribute_list = [\"method_id\",\"psimi_name\",\"pubmed\"], participant_attribute_list = [] )", "os.path.abspath(os.path.dirname(__file__)) # Read the config file config_file = os.path.join(main_path, 'config.ini')", "format(uE_id1,uE_id2,info_sources,info_methods_ids,info_methods,info_pubmed_ids)) elif options.format == 'netscore': out_network.write('\\t{}\\t{}\\t{:.2f}\\n'.format(uE_id1,uE_id2,1.)) elif options.format == 'raw':", "described by the user selected methods') parser.add_argument('-v','--verbose',dest='verbose',action = 'store_true', help", "OUTPUT NODE AND TRANSLATION FILES # #---------------------------------------# # If we", "user\" user_selection=False else: use_methods=[] with open(options.restricted_to_user) as input_method_fd: for line", "netscore, raw, multi-fields:\\n 'sif': <node1>\\tscore\\t<node2>\\n 'netscore': <node1>\\t<node2>\\t<score>\\n 'raw': <node1>\\t<node2>\\n 'multi-fields'", "technology\")], include_relations_last_level = (not restricted_to_seeds) , use_self_relations = False) #", "INTERACTIONS # #--------------------------------------# nodes=set() # Get all the user entity", "unification_protocol=config.get('BIANA', 'unification_protocol') ) print \"Continue\" #------------------------------# # DEFINE A USER", "'': continue if s in translate: codes=set(translate[s]) translation=\"','\".join([str(x) for x", "complementation dictionary complementation_dict = methods_dicts.complementation_dict complementation=set(complementation_dict.keys()) #---------------------------------------# # GET METHODS", "method_names if x not in unused_method_names] # Remove method names", "be # added for translation allseed=set() for uE_id in proteome.get_user_entity_ids():", "in input_method_fd: fields = line.strip().split(\"\\t\") no_methods.append(fields[0]) user_rejection=True print \"Input of", "help = 'Seeds Input file (default is input_seed)') parser.add_argument('-radius','--radius_of_subnetwork_around_seeds',dest='radius',default=0,action =", "uE.get_attribute(attribute_identifier=options.stype): if current_id.value.lower() in seeds: translate.setdefault(current_id.value.lower(),[]) translate[current_id.value.lower()].append(protein) score=1.0 if options.format", "< len(current_id.value.get_sequence().upper()): maxlen=len(current_id.value.get_sequence().upper()) translation=\",\".join([str(current_id.value.get_sequence().upper()) for current_id in uE.get_attribute(attribute_identifier=options.ttype) if len(str(current_id.value.get_sequence().upper()))", "in relationObj.get_attributes_dict()[\"method_id\"] ] if \"psimi_name\" in relationObj.get_attributes_dict(): method_names.update([ str(x.value) for", "least described by affinity methods (i.e. Tandem Affinity Purification)') session.create_network(", "relationObj.get_attributes_dict()[\"method_id\"]]) if \"pubmed\" in relationObj.get_attributes_dict(): pubmed_ids.update([ x.value for x in", "= '''Network is built in a radius of connections around", "translation allseed=set() for uE_id in proteome.get_user_entity_ids(): allseed.add(uE_id) for protein in", "separated by new lines! \"\"\" seed_set = set() with open(seed_file,", "= 'File with the translation of codes from BIANA to", "been detected at least by yeast two hybrid elif options.restricted_to_Y2H:", "entity ID => type uEId_to_type = session.dbAccess.get_user_entity_type(config.get('BIANA', 'unification_protocol'), all_uEs) skip_interactions=0", "source_databases = set() use_method_ids=set() pubmed_ids = set() unused_method_names = set()", "relation_attribute_restriction_list = [(\"Method_id\",18)], #relation_attribute_restriction_list = [(\"psimi_name\",\"y2h2\")], include_relations_last_level = (not restricted_to_seeds)", ") else: level=0 proteome = session.create_new_user_entity_set( identifier_description_list = [(\"taxid\",options.taxid)], attribute_restriction_list=[],", "for protein in nodes: uE = session.get_user_entity(protein) translate=set() translate_stype=set() if", "= set() unused_method_names = set() relationObj_dict = session.dbAccess.get_external_entities_dict( externalEntityIdsList =", "of user entity uE1_type = uEId_to_type[uE_id1] uE2_type = uEId_to_type[uE_id2] #", "len(source_databases) > 0: info_sources=\";\".join([str(x) for x in source_databases]) else: if", "options.ttype == \"proteinsequence\": maxlen=0; for current_id in uE.get_attribute(attribute_identifier=options.ttype): if maxlen", "will be done differently elif options.radius > 0: # Read", "open(options.node,'w') translate={} for protein in nodes: score=seed_score uE = session.get_user_entity(protein)", "methods that must be included if not fileExist(options.restricted_to_user): print \"No", "in relationObj.get_attributes_dict()[\"method_id\"]]) if \"pubmed\" in relationObj.get_attributes_dict(): pubmed_ids.update([ x.value for x", "#--------------------------------------# nodes=set() # Get all the user entity ids from", "\"Translation\",protein,translation #print(\"{0}\\t'{1}'\\n\".format(protein,translation)) else: ##### TRANSLATION TO 'ttype' for current_id in", "= 'File with the translation of codes from the introduced", "unused_method_names] # Remove method names that were excluded info_methods=\";\".join([str(x) for", "out_translation.write(\"{0}\\t'{1}'\\n\".format(s.upper(),translation)) else: out_translation.write(\"{0}\\t'Unknown'\\n\".format(s.upper())) out_translation.close() # Output translation file # TRANSLATION", "!= 'protein': if options.verbose: print('Skipping interaction because the type of", "level, relation_type_list=[\"interaction\"] , relation_attribute_restriction_list = [(\"Method_id\",400)], #relation_attribute_restriction_list = [(\"psimi_name\",\"affinity technology\")],", "selected methods \",m else: use_method_ids.update(method_ids) if len(source_databases) > 0: info_sources=\";\".join([str(x)", "BIANA codes') parser.add_argument('-edge','--edge_file',dest='edge',action = 'store', default='biana_edges', help = 'Output file", "= [\"method_id\",\"psimi_name\",\"pubmed\"], participant_attribute_list = [] ) num_methods=0 for current_eErID in", "least by yeast two hybrid elif options.restricted_to_Y2H: print ('Using interactions", "not in nodes: uE = session.get_user_entity(protein) for current_id in uE.get_attribute(attribute_identifier=options.stype):", "line.strip().split(\"\\t\") use_methods.append(fields[0]) user_selection=True print \"Input to use only Methods:\",repr(use_methods) #", "python /home/quim/PHD/Projects/BIANA/scripts/generate_network_interactomix.py -radius 0 -taxid 9606 -edge /home/quim/PHD/Projects/BIANA/outputs/BIANA_2020_geneID_seqtax_drugtarget/human_network_biana_2020.txt -node /home/quim/PHD/Projects/BIANA/outputs/BIANA_2020_geneID_seqtax_drugtarget/human_network_biana_2020_nodes.txt", "os.path.isfile(file) def get_seeds_from_file(seed_file): \"\"\" Obtain the seeds from a file", "relationObj.get_attributes_dict()[\"pubmed\"]]) source_databases.add(str(session.dbAccess.get_external_database( database_id = relationObj.get_source_database()) )) if options.except_TAP: for m", "level = level, relation_type_list=[\"interaction\"] , include_relations_last_level = (not restricted_to_seeds) ,", "(default), netscore, raw, multi-fields:\\n 'sif': <node1>\\tscore\\t<node2>\\n 'netscore': <node1>\\t<node2>\\t<score>\\n 'raw': <node1>\\t<node2>\\n", "-node example/output/example.nodes -format raw -rY2H python /home/quim/PHD/Projects/BIANA/scripts/generate_network_interactomix.py -radius 0 -taxid", "interactome''') parser.add_argument('-taxid','--TaxID',dest='taxid',action = 'store',default='9606', help = 'Tax ID (i.e. human=9606", "If the format is not multi-fields, netscore or raw, the", "in codes]) #out_translation.write(\"%s\\t'%s'\\n\" % (s.upper(),translation)) out_translation.write(\"{0}\\t'{1}'\\n\".format(s.upper(),translation)) else: out_translation.write(\"{0}\\t'Unknown'\\n\".format(s.upper())) out_translation.close() #", "uE1_type = uEId_to_type[uE_id1] uE2_type = uEId_to_type[uE_id2] # If type is", "uE_id in proteome.get_user_entity_ids(): allseed.add(uE_id) for protein in allseed: if protein", "[], relation_attribute_list = [\"method_id\",\"psimi_name\",\"pubmed\"], participant_attribute_list = [] ) num_methods=0 for", "is not multi-fields, netscore or raw, the output format is", "in method_names if x not in unused_method_names] # Remove method", "than the minimum established if use and num_databases >= minimum_number_of_db:", "= proteome.get_user_entity_ids() # Obtain a dictionary user entity ID =>", "info_methods='-' if len(use_method_ids) > 0: info_methods_ids=\";\".join([str(x) for x in use_method_ids])", "(uE_id1, uE_id2) in all_interactions: #self.dbAccess.get_external_entities_dict( externalEntityIdsList = [external_entity_relation_id] ) #", ") else: print('Proteome without Taxonomy restriction') proteome = session.create_new_user_entity_set( identifier_description_list", "if options.verbose: print('Skipping interaction because the type of one of", "proteome.getRelations() print \"Num interactions:\", len(all_interactions) #--------------------------------------# # FILTER THE SELECTED", "x.value for x in relationObj.get_attributes_dict()[\"method_id\"] ] if \"psimi_name\" in relationObj.get_attributes_dict():", "OF THE USER ENTITY SET # #----------------------------------------------------# print (\"Selecting interactions\")", "= (not restricted_to_seeds) , use_self_relations = False) # Summary of", "#print [ x.value for x in relationObj.get_attributes_dict()[\"psimi_name\"] ] #print [", "for current_id in uE.get_attribute(attribute_identifier=options.stype): if current_id.value.lower() in seeds: translate.setdefault(current_id.value.lower(),[]) translate[current_id.value.lower()].append(protein)", "= os.path.join(main_path, 'config.ini') config = ConfigParser.ConfigParser() config.read(config_file) #--------------------------------------# # LOAD", "# #---------------------------------------# # If we wanted the complete interactome, the", "-radius 0 -taxid 9606 -edge /home/quim/PHD/Projects/BIANA/outputs/BIANA_2020_geneID_seqtax_drugtarget/human_network_biana_2020.txt -node /home/quim/PHD/Projects/BIANA/outputs/BIANA_2020_geneID_seqtax_drugtarget/human_network_biana_2020_nodes.txt -trans /home/quim/PHD/Projects/BIANA/outputs/BIANA_2020_geneID_seqtax_drugtarget/human_network_biana_2020_translation.txt", "open(options.edge,'w') all_interactions = proteome.getRelations() print \"Num interactions:\", len(all_interactions) #--------------------------------------# #", "Tandem Affinity Purification)') session.create_network( user_entity_set_id = \"proteome\" , level =", "Purification)') parser.add_argument('-eY2H','--except_Y2H',dest='except_Y2H',action = 'store_true', help = 'Flag to use all", "# FIXED PARAMETERS # #----------------------# # Parameters that I have", "= session.get_user_entity(protein) translate=set() translate_stype=set() if options.ttype == \"proteinsequence\": maxlen=0; for", "at least described by yeast two hybrid methods (Y2H)') parser.add_argument('-rUSER','--restricted_to_user',dest='restricted_to_user',action", "in uE.get_attribute(attribute_identifier=options.stype): if current_id.value.lower() in seeds: translate.setdefault(current_id.value.lower(),[]) translate[current_id.value.lower()].append(protein) # Get", "= 'store',default='geneid', help = 'Type of identifier for seeds (default", "user has introduced a file with methods that have to", "\"Interaction: (\",uE_id1,\",\",uE_id2,\")\" print relationObj #if relationObj.get_attribute(attribute_identifier=\"psimi_name\") is not None: #", "= methods_dicts.affinity_dict affinity=set(affinity_dict.keys()) # Get the complementation dictionary complementation_dict =", "to fix restricted_to_seeds = False minimum_number_of_methods = 1 minimum_number_of_db =", "= '''Format file of the edge file:\\tsif (default), netscore, raw,", "use interactions described by the user selected methods') parser.add_argument('-eAFF','--except_TAP',dest='except_TAP',action =", "check missing codes to be # added for translation allseed=set()", "# If the format is not multi-fields, netscore or raw,", "Checks if a file exists AND is a file \"\"\"", "Output node file out_proteins = open(options.node,'w') translate={} for protein in", "if use: #print uE_id1, uE_id/2 nodes.add(uE_id1) nodes.add(uE_id2) #print \"Attribute \",(uE_id1,uE_id2).get_attribute(", "BIANA. \"\"\" #----------------------# # FIXED PARAMETERS # #----------------------# # Parameters", "the number of database is higher than the minimum established", "biana try: from biana import * except: sys.exit(10) import methods_dictionaries", "None: #print \"\\t\".join([ x.value for x in relationObj.get_attribute(attribute_identifier=\"method_id\") ]) #print", "if num_methods >= minimum_number_of_methods: use=True else: use=False # Check if", "in uE.get_attribute(attribute_identifier=options.stype): if current_id.value.lower() in seeds: translate.setdefault(current_id.value.lower(),[]) translate[current_id.value.lower()].append(protein) ################################# TRANSLATION", "affinity methods (i.e. Tandem Affinity Purification)') session.create_network( user_entity_set_id = \"proteome\"", "x in pubmed_ids]) else: info_pubmed_ids='-' num_databases=len(source_databases) num_methods=len(use_method_ids) num_pubmeds = len(pubmed_ids)", "have decided to fix restricted_to_seeds = False minimum_number_of_methods = 1", "= open(options.translation_seeds_file,'w') for s in seeds: if s == '':", "# Get the affinity dictionary affinity_dict = methods_dicts.affinity_dict affinity=set(affinity_dict.keys()) #", "input_method_fd: for line in input_method_fd: fields = line.strip().split(\"\\t\") no_methods.append(fields[0]) user_rejection=True", "\"Methods\",num_methods,info_methods,\"\\tSelected:\",info_methods_ids print \"Databases\",num_databases,info_sources print \"Pubmeds\",num_pubmeds,info_pubmed_ids # Check if the number", "methods selected by the user\" user_selection=False else: use_methods=[] with open(options.restricted_to_user)", "wanted the complete interactome, the translation will be done differently", "Python list. The seeds must be separated by new lines!", "Summary of interactions out_network = open(options.edge,'w') all_interactions = proteome.getRelations() print", "FILE # #--------------------------------------# # Get the program path main_path =", "level=0 proteome = session.create_new_user_entity_set( identifier_description_list = [(\"taxid\",options.taxid)], attribute_restriction_list=[], id_type=\"embedded\", new_user_entity_set_id=\"proteome\",", "use_method_ids]) else: if options.verbose: print('Skipping interaction it has no method!')", "options.format == 'netscore': out_proteins.write(\"{0}\\t{1:.2f}\\t{2:.2f}\\t{3:.2f}\\n\".format(protein,1.,1.,score)) else: out_proteins.write(\"{0}\\t{1:.2f}\\n\".format(protein,score)) out_proteins.close() # Get the", "If we wanted the complete interactome, the translation will be", "complementation: use_method_ids.add(m) #print \"Add\", m else: unused_method_names.add(complementation_dict[m]) elif user_rejection: for", "the user\" user_rejection=False else: no_methods=[] with open(options.except_user) as input_method_fd: for", "verbose mode') options=parser.parse_args() \"\"\" Example: python generate_network_interactomix.py -iseed example/sample1.txt -radius", "use_methods.append(fields[0]) user_selection=True print \"Input to use only Methods:\",repr(use_methods) # Check", "print('Node 1: {}\\tNode 2: {}'.format(uE_id1, uE_id2)) skip_interactions=skip_interactions+1 continue if len(method_names)", "[ x.value for x in relationObj.get_attributes_dict()[\"psimi_name\"] ] #print [ x.value", "# #---------------------------# print \"Open session\" session = create_new_session( sessionID=\"biana_session\", dbname=config.get('BIANA',", "hybrid methods (Y2H)') parser.add_argument('-rUSER','--restricted_to_user',dest='restricted_to_user',action = 'store',default='restricted_methods', help = 'File to", "interactions at least described by affinity methods (i.e. Tandem Affinity", "set() use_method_ids=set() pubmed_ids = set() unused_method_names = set() relationObj_dict =", "affinity methods (i.e. Tandem Affinity Purification)') parser.add_argument('-rY2H','--restricted_to_Y2H',dest='restricted_to_Y2H',action = 'store_true', help", "If we wanted a network of expansion, the translation will", "sys, os, re import biana try: from biana import *", "introduced a file with methods that must be included if", "\"Generate a protein-protein interaction network (implemented for Interactomix platform)\", epilog", "in uE.get_attribute(attribute_identifier=options.stype): if current_id.value.lower() in seeds: translate.setdefault(current_id.value.lower(),[]) translate[current_id.value.lower()].append(protein) score=1.0 if", "translate]) out_translation.write(\"{0}\\t'{1}'\\n\".format(protein,translation)) ##### TRANSLATION TO STYPE if trans_stype: for current_id", "excluded info_methods=\";\".join([str(x) for x in method_names]) else: info_methods='-' if len(use_method_ids)", "= 'Flag to use verbose mode') options=parser.parse_args() \"\"\" Example: python", "open(options.seed,'r') for line in input_seed: fields = line.strip().split(\"\\t\") seeds.add(fields[0].lower()) input_seed.close()", "if options.format == 'multi-fields': out_proteins.write(\"{0}\\t{1:.2f}\\t{2:.2f}\\t{3:.2f}\\n\".format(protein,1.,1.,score)) elif options.format == 'netscore': out_proteins.write(\"{0}\\t{1:.2f}\\t{2:.2f}\\t{3:.2f}\\n\".format(protein,1.,1.,score))", "of methods is higher than the minimum established if num_methods", "parser.add_argument('-eAFF','--except_TAP',dest='except_TAP',action = 'store_true', help = 'Flag to use all interactions", ", use_self_relations = False) # Select interactions that have been", "#################################################################################### print('Generation of the network done!') return def fileExist(file): \"\"\"", "protein in nodes: if options.format == 'multi-fields': out_proteins.write(\"{0}\\t{1:.2f}\\t{2:.2f}\\t{3:.2f}\\n\".format(protein,1.,1.,0.1)) elif options.format", "{}\\tType: {}'.format(uE_id1, uE1_type)) print('Node 2: {}\\tType: {}'.format(uE_id2, uE2_type)) skip_interactions=skip_interactions+1 continue", "not in unused_method_names] # Remove method names that were excluded", "help = 'Flag to use interactions at least described by", "in complementation: use_method_ids.add(m) #print \"Add\", m else: unused_method_names.add(complementation_dict[m]) elif user_rejection:", "= 'store_true', help = 'Flag to use verbose mode') options=parser.parse_args()", "= 'store', default='biana_nodes', help = 'Output file with nodes(default is", "sessionID=\"biana_session\", dbname=config.get('BIANA', 'database'), dbhost=config.get('BIANA', 'host'), dbuser=config.get('BIANA', 'user'), dbpassword=config.get('BIANA', 'password'), unification_protocol=config.get('BIANA',", "out_proteins.write(\"{0}\\t{1:.2f}\\t{2:.2f}\\t{3:.2f}\\n\".format(protein,1.,1.,0.1)) else: out_proteins.write(\"{0}\\t{1:.2f}\\n\".format(protein,0.1)) out_proteins.close() ################################# TRANSLATION #################################### out_translation = open(options.translation_file,'w')", "'File to use interactions described by the user selected methods')", "of identifier for the output translation of codes (default is", "= False minimum_number_of_methods = 1 minimum_number_of_db = 1 seed_score =", "except those described by affinity methods (i.e. Tandem Affinity Purification)')", "SET # #----------------------------------------------------# print (\"Selecting interactions\") # Select interactions that", "by yeast two hybrid elif options.restricted_to_Y2H: print ('Using interactions at", "else: # If the format is not multi-fields, netscore or", "#print \"Add\", m else: unused_method_names.add(complementation_dict[m]) elif user_rejection: for m in", "with the translation of codes from BIANA to the selected", "multi-fields:\\n 'sif': <node1>\\tscore\\t<node2>\\n 'netscore': <node1>\\t<node2>\\t<score>\\n 'raw': <node1>\\t<node2>\\n 'multi-fields' : <node1>\\t<node2>\\t<sources>\\t<method_ids>\\t<method_names>\\t<pmids>\\n''')", "out_proteins.write(\"{0}\\t{1:.2f}\\t{2:.2f}\\t{3:.2f}\\n\".format(protein,1.,1.,score)) elif options.format == 'netscore': out_proteins.write(\"{0}\\t{1:.2f}\\t{2:.2f}\\t{3:.2f}\\n\".format(protein,1.,1.,score)) else: out_proteins.write(\"{0}\\t{1:.2f}\\n\".format(protein,score)) out_proteins.close() #", "seeds: translate.setdefault(current_id.value.lower(),[]) translate[current_id.value.lower()].append(protein) score=1.0 if options.format == 'multi-fields': out_proteins.write(\"{0}\\t{1:.2f}\\t{2:.2f}\\t{3:.2f}\\n\".format(protein,1.,1.,score)) elif", "uE_id/2 nodes.add(uE_id1) nodes.add(uE_id2) #print \"Attribute \",(uE_id1,uE_id2).get_attribute( if options.format == 'multi-fields'", "x in relationObj.get_attributes_dict()[\"psimi_name\"] ] #print [ x.value for x in", "len(pubmed_ids) if options.verbose: print \"Methods\",num_methods,info_methods,\"\\tSelected:\",info_methods_ids print \"Databases\",num_databases,info_sources print \"Pubmeds\",num_pubmeds,info_pubmed_ids #", "-edge /home/quim/PHD/Projects/BIANA/outputs/BIANA_2020_geneID_seqtax_drugtarget/human_network_biana_2020.txt -node /home/quim/PHD/Projects/BIANA/outputs/BIANA_2020_geneID_seqtax_drugtarget/human_network_biana_2020_nodes.txt -trans /home/quim/PHD/Projects/BIANA/outputs/BIANA_2020_geneID_seqtax_drugtarget/human_network_biana_2020_translation.txt -ttype geneid -format multi-fields", "described by yeast-two-hybrid methods (Y2H)') session.create_network( user_entity_set_id = \"proteome\" ,", "user_rejection=True print \"Input of rejected Methods:\",repr(no_methods) #---------------------------# # START A", "options.except_TAP: for m in method_ids: if m not in affinity:", ") print \"Continue\" #------------------------------# # DEFINE A USER ENTITY SET", "use_method_ids.update(method_ids) if len(source_databases) > 0: info_sources=\";\".join([str(x) for x in source_databases])", "in method_ids: if m not in affinity: use_method_ids.add(m) #print \"Add\",", "sys.exit(10) else: level=options.radius seed_list = get_seeds_from_file(options.seed) # If we have", "= methods_dicts.complementation_dict complementation=set(complementation_dict.keys()) #---------------------------------------# # GET METHODS THAT WILL BE", "try: from biana import * except: sys.exit(10) import methods_dictionaries as", "differently elif options.radius > 0: # Read the seeds seeds=set()", "Obtain a dictionary user entity ID => type uEId_to_type =", "uE = session.get_user_entity(protein) for current_id in uE.get_attribute(attribute_identifier=options.stype): if current_id.value.lower() in", "use all interactions except those described by yeast two hybrid", "# If type is not protein, we skip the interaction", "is biana_nodes)') parser.add_argument('-format','--output_format',dest='format',action = 'store',default='sif', help = '''Format file of", "is higher than the minimum established if num_methods >= minimum_number_of_methods:", "<reponame>quimaguirre/NetworkAnalysis import argparse import ConfigParser import sys, os, re import", "the complete interactome''') parser.add_argument('-taxid','--TaxID',dest='taxid',action = 'store',default='9606', help = 'Tax ID", "if the number of database is higher than the minimum", "for x in relationObj.get_attributes_dict()[\"pubmed\"]]) source_databases.add(str(session.dbAccess.get_external_database( database_id = relationObj.get_source_database()) )) if", "open(options.translation_file+'.'+options.stype+'.trans','w') for protein in nodes: uE = session.get_user_entity(protein) translate=set() translate_stype=set()", "A BIANA SESSION # #---------------------------# print \"Open session\" session =", ")) if options.except_TAP: for m in method_ids: if m not", "info_methods_ids=\";\".join([str(x) for x in use_method_ids]) else: if options.verbose: print('Skipping interaction", "method_ids: #print \"Check\",repr(use_methods) if m in set(use_methods): use_method_ids.add(m) if options.verbose:", "file (default is input_seed)') parser.add_argument('-radius','--radius_of_subnetwork_around_seeds',dest='radius',default=0,action = 'store',type=int, help = '''Network", "uE_id2)) skip_interactions=skip_interactions+1 continue if len(pubmed_ids) > 0: info_pubmed_ids=\";\".join([str(x) for x", "if the seeds file exists if not fileExist(options.seed): print \"File", "= [(\"Method_id\",18)], #relation_attribute_restriction_list = [(\"psimi_name\",\"y2h2\")], include_relations_last_level = (not restricted_to_seeds) ,", "translate[current_id.value.lower()].append(protein) score=1.0 if options.format == 'multi-fields': out_proteins.write(\"{0}\\t{1:.2f}\\t{2:.2f}\\t{3:.2f}\\n\".format(protein,1.,1.,score)) elif options.format ==", "m in set(use_methods): use_method_ids.add(m) if options.verbose: print \"Not among selected", "sif out_network.write(\"{}\\t{:.2f}\\t{}\\n\".format(uE_id1,1.,uE_id2)) print \"Num neglected interactions:\", skip_interactions out_network.close() #---------------------------------------# #", "'''Type of identifier for the output translation of codes (default", "OF METHODS # #--------------------------------------# # Get the affinity dictionary affinity_dict", "proteome.get_user_entity_ids(): allseed.add(uE_id) for protein in allseed: if protein not in", "elif options.radius > 0: # Read the seeds seeds=set() input_seed", "source_databases #----------------------# # OUTPUT EDGE FILE # #----------------------# if use:", "ENTITY SET # #------------------------------# # Create network network of expansion", "out_translation.close() if trans_stype: out_trans_stype.close() #################################################################################### print('Generation of the network done!')", "the number of methods is higher than the minimum established", "Get the affinity dictionary affinity_dict = methods_dicts.affinity_dict affinity=set(affinity_dict.keys()) # Get", "the seed proteins. If 0, it creates the complete interactome''')", "user_entity_set_id = \"proteome\" , level = level, relation_type_list=[\"interaction\"] , relation_attribute_restriction_list", "interaction network (implemented for Interactomix platform)\", epilog = \"@oliva's lab", "geneid)') parser.add_argument('-ttype','--translation_type',dest='ttype',action = 'store',default='accessionnumber', help = '''Type of identifier for", "in translate: codes=set(translate[s]) translation=\"','\".join([str(x) for x in codes]) #out_translation.write(\"%s\\t'%s'\\n\" %", "/home/quim/PHD/Projects/BIANA/scripts/generate_network_interactomix.py -radius 0 -taxid 9606 -edge /home/quim/PHD/Projects/BIANA/outputs/BIANA_2020_geneID_seqtax_drugtarget/human_network_biana_2020.txt -node /home/quim/PHD/Projects/BIANA/outputs/BIANA_2020_geneID_seqtax_drugtarget/human_network_biana_2020_nodes.txt -trans", "= False) # Select interactions that have been detected at", "=> type uEId_to_type = session.dbAccess.get_user_entity_type(config.get('BIANA', 'unification_protocol'), all_uEs) skip_interactions=0 for (uE_id1,", "if not fileExist(options.except_user): print \"No rejection of methods selected by", "= \"Generate a protein-protein interaction network (implemented for Interactomix platform)\",", "minimum_number_of_methods = 1 minimum_number_of_db = 1 seed_score = 0.1 #--------------------------------------#", "SESSION # #---------------------------# print \"Open session\" session = create_new_session( sessionID=\"biana_session\",", "num_methods=len(use_method_ids) num_pubmeds = len(pubmed_ids) if options.verbose: print \"Methods\",num_methods,info_methods,\"\\tSelected:\",info_methods_ids print \"Databases\",num_databases,info_sources", ") #----------------------------------------------------# # SELECT THE INTERACTIONS OF THE USER ENTITY", "session.dbAccess.get_external_entities_dict( externalEntityIdsList = eErIDs_list, attribute_list = [], relation_attribute_list = [\"method_id\",\"psimi_name\",\"pubmed\"],", "by affinity methods (i.e. Tandem Affinity Purification)') parser.add_argument('-eY2H','--except_Y2H',dest='except_Y2H',action = 'store_true',", "python generate_network_interactomix.py -iseed example/sample1.txt -radius 1 -taxid 9606 -stype uniprotentry", "with edges(default is biana_edges)') parser.add_argument('-node','--node_file',dest='node',action = 'store', default='biana_nodes', help =", "= (not restricted_to_seeds) , use_self_relations = False) # Select interactions", "minimum established if use and num_databases >= minimum_number_of_db: use=True else:", "if use and num_databases >= minimum_number_of_db: use=True else: use=False if", "\"Attribute \",(uE_id1,uE_id2).get_attribute( if options.format == 'multi-fields' : out_network.write(\"{0}\\t{1}\\t{2}\\t{3}\\t{4}\\t{5}\\n\". format(uE_id1,uE_id2,info_sources,info_methods_ids,info_methods,info_pubmed_ids)) elif", "options.taxid != \"0\": print(\"Check Proteome %s\"%(repr(options.taxid))) proteome = session.create_new_user_entity_set( identifier_description_list", "= 'Flag to use interactions at least described by affinity", "if the radius is larger than 0 if restricted_to_seeds or", "of the user entities is not protein!') print('Node 1: {}\\tType:", "netscore or raw, the output format is sif out_network.write(\"{}\\t{:.2f}\\t{}\\n\".format(uE_id1,1.,uE_id2)) print", "the longest sequence of all codes''') parser.add_argument('-trans','--translation_of_nodes_file',dest='translation_file',action = 'store',default='translation_nodes.txt', help", "options.radius>0: # Check if the seeds file exists if not", "all interactions except those described by affinity methods (i.e. Tandem", "= 'store',default='translation_nodes.txt', help = 'File with the translation of codes", "in seeds: if s == '': continue if s in", "if the number of methods is higher than the minimum", "dbhost=config.get('BIANA', 'host'), dbuser=config.get('BIANA', 'user'), dbpassword=config.get('BIANA', 'password'), unification_protocol=config.get('BIANA', 'unification_protocol') ) print", "help = 'Flag to use all interactions except those described", "(not restricted_to_seeds) , use_self_relations = False) # Select all interactions", "-radius 1 -taxid 9606 -stype uniprotentry -ttype proteinsequence -trans example/output/example.proteinsequence.trans", "!= 'protein' or uE2_type != 'protein': if options.verbose: print('Skipping interaction", "not use: skip_interactions=skip_interactions+1 #print method_names, method_ids, source_databases #----------------------# # OUTPUT", "negative_attribute_restriction_list=[] ) else: print('Proteome without Taxonomy restriction') proteome = session.create_new_user_entity_set(", "if options.taxid != \"0\": print(\"Check Proteome %s\"%(repr(options.taxid))) proteome = session.create_new_user_entity_set(", "protein in nodes: uE = session.get_user_entity(protein) translate=set() translate_stype=set() if options.ttype", "restriction)') parser.add_argument('-stype','--seed_type',dest='stype',action = 'store',default='geneid', help = 'Type of identifier for", "for current_id in uE.get_attribute(attribute_identifier=options.ttype) if len(str(current_id.value.get_sequence().upper())) == maxlen ] )", "level=options.radius seed_list = get_seeds_from_file(options.seed) # If we have Taxonomy restriction,", "is no restriction)') parser.add_argument('-stype','--seed_type',dest='stype',action = 'store',default='geneid', help = 'Type of", "else: use_methods=[] with open(options.restricted_to_user) as input_method_fd: for line in input_method_fd:", "all_interactions: #self.dbAccess.get_external_entities_dict( externalEntityIdsList = [external_entity_relation_id] ) # Get TYPE of", "all the user entity ids from the user entity set", "have been detected at least by yeast two hybrid elif", "elif options.format == 'raw': out_network.write(\"{}\\t{}\\n\".format(uE_id1,uE_id2)) else: # If the format", "'store', help = 'Seeds Input file (default is input_seed)') parser.add_argument('-radius','--radius_of_subnetwork_around_seeds',dest='radius',default=0,action", "current_id.value.lower() in seeds: translate.setdefault(current_id.value.lower(),[]) translate[current_id.value.lower()].append(protein) score=1.0 if options.format == 'multi-fields':", ">= minimum_number_of_db: use=True else: use=False if not use: skip_interactions=skip_interactions+1 #print", "proteome.get_unconnected_nodes(): single.add(uE_id) for protein in single: uE = session.get_user_entity(protein) for", "\"Databases\",num_databases,info_sources print \"Pubmeds\",num_pubmeds,info_pubmed_ids # Check if the number of methods", "'Flag to use interactions at least described by yeast two", "not in affinity: use_method_ids.add(m) #print \"Add\", m else: unused_method_names.add(affinity_dict[m]) elif", "exists if not fileExist(options.seed): print \"File with seeds is missing", "not in no_methods: use_method_ids.add(m) elif user_selection: for m in method_ids:", "1 seed_score = 0.1 #--------------------------------------# # GET INFORMATION FROM CONFIG", "protein, we skip the interaction if uE1_type != 'protein' or", "help = 'File with the translation of codes from BIANA", "to be excluded if not fileExist(options.except_user): print \"No rejection of", "hybrid elif options.restricted_to_Y2H: print ('Using interactions at least described by", "Select all interactions else: session.create_network( user_entity_set_id = \"proteome\" , level", "current_id in uE.get_attribute(attribute_identifier=options.stype): if current_id.value.lower() in seeds: translate.setdefault(current_id.value.lower(),[]) translate[current_id.value.lower()].append(protein) #", "nodes: uE = session.get_user_entity(protein) translate=set() translate_stype=set() if options.ttype == \"proteinsequence\":", "the format is not multi-fields, netscore or raw, the output", "introduce them to a Python list. The seeds must be", "I have decided to fix restricted_to_seeds = False minimum_number_of_methods =", "= 'Tax ID (i.e. human=9606 is default if TaxID=0 there", "least described by affinity methods (i.e. Tandem Affinity Purification)') parser.add_argument('-rY2H','--restricted_to_Y2H',dest='restricted_to_Y2H',action", "= open(options.node,'w') for protein in nodes: if options.format == 'multi-fields':", "help = '''Format file of the edge file:\\tsif (default), netscore,", "minimum_number_of_db: use=True else: use=False if not use: skip_interactions=skip_interactions+1 #print method_names,", "a file with methods that must be included if not", "be separated by new lines! \"\"\" seed_set = set() with", "print \"Methods\",num_methods,info_methods,\"\\tSelected:\",info_methods_ids print \"Databases\",num_databases,info_sources print \"Pubmeds\",num_pubmeds,info_pubmed_ids # Check if the", "network network of expansion if the radius is larger than", "method_names, method_ids, source_databases #----------------------# # OUTPUT EDGE FILE # #----------------------#", "of codes from BIANA to the selected type for all", "proteinsequence -trans example/output/example.proteinsequence.trans -strans example/output/example.seeds.trans -edge example/output/example.edges -node example/output/example.nodes -format", "affinity: use_method_ids.add(m) #print \"Add\", m else: unused_method_names.add(affinity_dict[m]) elif options.except_Y2H: #print", "else: for current_id in uE.get_attribute(attribute_identifier=options.ttype): translate.add(current_id.value.upper()) translation=\"','\".join([\"{0}\".format(x) for x in", "in relationObj.get_attributes_dict(): method_names.update([ str(x.value) for x in relationObj.get_attributes_dict()[\"psimi_name\"] ]) if", "translation of codes from BIANA to the selected type for", "# SELECT THE INTERACTIONS OF THE USER ENTITY SET #", "################################# TRANSLATION #################################### out_translation = open(options.translation_seeds_file,'w') for s in seeds:", "level, relation_type_list=[\"interaction\"] , relation_attribute_restriction_list = [(\"Method_id\",18)], #relation_attribute_restriction_list = [(\"psimi_name\",\"y2h2\")], include_relations_last_level", "method_names.update([ str(x.value) for x in relationObj.get_attributes_dict()[\"psimi_name\"] ]) if \"method_id\" in", "trans_stype: out_trans_stype.close() #################################################################################### # If we wanted a network of", "seeds from a file and introduce them to a Python", "uE.get_attribute(attribute_identifier=options.ttype): translate.add(current_id.value.upper()) translation=\"','\".join([\"{0}\".format(x) for x in translate]) out_translation.write(\"{0}\\t'{1}'\\n\".format(protein,translation)) ##### TRANSLATION", "technology if options.restricted_to_TAP: print ('Using interactions at least described by", "node file out_proteins = open(options.node,'w') for protein in nodes: if", "(s.upper(),translation)) out_translation.write(\"{0}\\t'{1}'\\n\".format(s.upper(),translation)) else: out_translation.write(\"{0}\\t'Unknown'\\n\".format(s.upper())) out_translation.close() # Output translation file #", "uE_id2)) skip_interactions=skip_interactions+1 continue if len(method_names) > 0: method_names = [x", "'user'), dbpassword=config.get('BIANA', 'password'), unification_protocol=config.get('BIANA', 'unification_protocol') ) print \"Continue\" #------------------------------# #", "use=False # Check if the number of database is higher", "maxlen=len(current_id.value.get_sequence().upper()) translation=\",\".join([str(current_id.value.get_sequence().upper()) for current_id in uE.get_attribute(attribute_identifier=options.ttype) if len(str(current_id.value.get_sequence().upper())) == maxlen", "seeds is missing or not found\" sys.exit(10) else: level=options.radius seed_list", "options.format == 'netscore': out_network.write('\\t{}\\t{}\\t{:.2f}\\n'.format(uE_id1,uE_id2,1.)) elif options.format == 'raw': out_network.write(\"{}\\t{}\\n\".format(uE_id1,uE_id2)) else:", "be done differently if options.radius <= 0: # Output node", "extracting information from BIANA. \"\"\" #----------------------# # FIXED PARAMETERS #", "= 'store_true', help = 'Flag to use all interactions except", "if len(use_method_ids) > 0: info_methods_ids=\";\".join([str(x) for x in use_method_ids]) else:", "parser.add_argument('-eY2H','--except_Y2H',dest='except_Y2H',action = 'store_true', help = 'Flag to use all interactions", "# Check if the number of methods is higher than", "if options.radius <= 0: # Output node file out_proteins =", "relationObj.get_source_database()) )) if options.except_TAP: for m in method_ids: if m", "= argparse.ArgumentParser( description = \"Generate a protein-protein interaction network (implemented", "SELECT THE INTERACTIONS OF THE USER ENTITY SET # #----------------------------------------------------#", "INTERACTIONS OF THE USER ENTITY SET # #----------------------------------------------------# print (\"Selecting", "else: level=0 proteome = session.create_new_user_entity_set( identifier_description_list = [(\"taxid\",options.taxid)], attribute_restriction_list=[], id_type=\"embedded\",", "= session.create_new_user_entity_set( identifier_description_list = [(\"taxid\",options.taxid)], attribute_restriction_list=[], id_type=\"embedded\", new_user_entity_set_id=\"proteome\", negative_attribute_restriction_list=[] )", "with methods that have to be excluded if not fileExist(options.except_user):", "import * except: sys.exit(10) import methods_dictionaries as methods_dicts def main():", "input_seed)') parser.add_argument('-radius','--radius_of_subnetwork_around_seeds',dest='radius',default=0,action = 'store',type=int, help = '''Network is built in", "== 'raw': out_network.write(\"{}\\t{}\\n\".format(uE_id1,uE_id2)) else: # If the format is not", "help = '''Network is built in a radius of connections", "lab 2019\") parser.add_argument('-iseed','--seeds_input_file',dest='seed',action = 'store', help = 'Seeds Input file", "[(\"Method_id\",18)], #relation_attribute_restriction_list = [(\"psimi_name\",\"y2h2\")], include_relations_last_level = (not restricted_to_seeds) , use_self_relations", "interaction network extracting information from BIANA. \"\"\" #----------------------# # FIXED", "if current_id.value.lower() in seeds: translate.setdefault(current_id.value.lower(),[]) translate[current_id.value.lower()].append(protein) # Get all IDS", "not found\" sys.exit(10) else: level=options.radius seed_list = get_seeds_from_file(options.seed) # If", "proteome = session.create_new_user_entity_set( identifier_description_list =seed_list, attribute_restriction_list=[(\"taxid\",options.taxid)], id_type=options.stype,new_user_entity_set_id=\"proteome\", negative_attribute_restriction_list=[] ) else:", "print \"Open session\" session = create_new_session( sessionID=\"biana_session\", dbname=config.get('BIANA', 'database'), dbhost=config.get('BIANA',", "translate={} for protein in nodes: score=seed_score uE = session.get_user_entity(protein) for", "not previously found in the network single=set() for uE_id in", "higher than the minimum established if use and num_databases >=", "relationObj.get_attribute(attribute_identifier=\"psimi_name\") is not None: # print \"\\t\".join([ x.value for x", "user selected methods') parser.add_argument('-v','--verbose',dest='verbose',action = 'store_true', help = 'Flag to", "Tandem Affinity Purification)') parser.add_argument('-rY2H','--restricted_to_Y2H',dest='restricted_to_Y2H',action = 'store_true', help = 'Flag to", "Output node file out_proteins = open(options.node,'w') for protein in nodes:", "TRANSLATION TO 'ttype' for current_id in uE.get_attribute(attribute_identifier=options.ttype): translate.add(current_id.value.upper()) translation=\"','\".join([\"{0}\".format(x) for", ", level = level, relation_type_list=[\"interaction\"] , include_relations_last_level = (not restricted_to_seeds)", "the type of one of the user entities is not", "m else: unused_method_names.add(affinity_dict[m]) elif options.except_Y2H: #print \"check Y2H\" for m", "'raw': out_network.write(\"{}\\t{}\\n\".format(uE_id1,uE_id2)) else: # If the format is not multi-fields,", "options.format == 'multi-fields': out_proteins.write(\"{0}\\t{1:.2f}\\t{2:.2f}\\t{3:.2f}\\n\".format(protein,1.,1.,0.1)) elif options.format == 'netscore': out_proteins.write(\"{0}\\t{1:.2f}\\t{2:.2f}\\t{3:.2f}\\n\".format(protein,1.,1.,0.1)) else:", "methods_dicts.complementation_dict complementation=set(complementation_dict.keys()) #---------------------------------------# # GET METHODS THAT WILL BE FILTERED", "== '': continue if s in translate: codes=set(translate[s]) translation=\"','\".join([str(x) for", "the user\" user_selection=False else: use_methods=[] with open(options.restricted_to_user) as input_method_fd: for", "ENTITY SET # #----------------------------------------------------# print (\"Selecting interactions\") # Select interactions", "THAT WILL BE FILTERED # #---------------------------------------# # Check if the", "= 'File to reject interactions described by the user selected", "expansion if the radius is larger than 0 if restricted_to_seeds", "relationObj_dict = session.dbAccess.get_external_entities_dict( externalEntityIdsList = eErIDs_list, attribute_list = [], relation_attribute_list", "of rejected Methods:\",repr(no_methods) #---------------------------# # START A BIANA SESSION #", "open(options.restricted_to_user) as input_method_fd: for line in input_method_fd: fields = line.strip().split(\"\\t\")", "methods is higher than the minimum established if num_methods >=", "[\"method_id\",\"psimi_name\",\"pubmed\"], participant_attribute_list = [] ) num_methods=0 for current_eErID in eErIDs_list:", "network (implemented for Interactomix platform)\", epilog = \"@oliva's lab 2019\")", "relationObj #if relationObj.get_attribute(attribute_identifier=\"psimi_name\") is not None: # print \"\\t\".join([ x.value", "'proteinsequence' and options.stype != options.ttype: trans_stype = True out_trans_stype =", "fileExist(options.restricted_to_user): print \"No restriction on methods selected by the user\"", "output translation of codes (default is accessionnumber) Using \"proteinsequence\" provides", "= 'Seeds Input file (default is input_seed)') parser.add_argument('-radius','--radius_of_subnetwork_around_seeds',dest='radius',default=0,action = 'store',type=int,", ", level = level, relation_type_list=[\"interaction\"] , relation_attribute_restriction_list = [(\"Method_id\",18)], #relation_attribute_restriction_list", "open(options.node,'w') for protein in nodes: if options.format == 'multi-fields': out_proteins.write(\"{0}\\t{1:.2f}\\t{2:.2f}\\t{3:.2f}\\n\".format(protein,1.,1.,0.1))", "codes') parser.add_argument('-edge','--edge_file',dest='edge',action = 'store', default='biana_edges', help = 'Output file with", "#print \"Add\", m else: unused_method_names.add(affinity_dict[m]) elif options.except_Y2H: #print \"check Y2H\"", "2: {}'.format(uE_id1, uE_id2)) skip_interactions=skip_interactions+1 continue if len(method_names) > 0: method_names", "'Type of identifier for seeds (default is geneid)') parser.add_argument('-ttype','--translation_type',dest='ttype',action =", "to reject interactions described by the user selected methods') parser.add_argument('-v','--verbose',dest='verbose',action", "'database'), dbhost=config.get('BIANA', 'host'), dbuser=config.get('BIANA', 'user'), dbpassword=config.get('BIANA', 'password'), unification_protocol=config.get('BIANA', 'unification_protocol') )", "identifier_description_list = [(\"taxid\",options.taxid)], attribute_restriction_list=[], id_type=\"embedded\", new_user_entity_set_id=\"proteome\", negative_attribute_restriction_list=[] ) #----------------------------------------------------# #", "translate.setdefault(current_id.value.lower(),[]) translate[current_id.value.lower()].append(protein) # Get all IDS of SEEDS, defined as", "'ttype' for current_id in uE.get_attribute(attribute_identifier=options.ttype): translate.add(current_id.value.upper()) translation=\"','\".join([\"{0}\".format(x) for x in", "elif options.except_Y2H: #print \"check Y2H\" for m in method_ids: if", "has introduced a file with methods that must be included", "the user selected methods') parser.add_argument('-eAFF','--except_TAP',dest='except_TAP',action = 'store_true', help = 'Flag", "Get all the user entity ids from the user entity", "9606 -edge /home/quim/PHD/Projects/BIANA/outputs/BIANA_2020_geneID_seqtax_drugtarget/human_network_biana_2020.txt -node /home/quim/PHD/Projects/BIANA/outputs/BIANA_2020_geneID_seqtax_drugtarget/human_network_biana_2020_nodes.txt -trans /home/quim/PHD/Projects/BIANA/outputs/BIANA_2020_geneID_seqtax_drugtarget/human_network_biana_2020_translation.txt -ttype geneid -format", "(Y2H)') session.create_network( user_entity_set_id = \"proteome\" , level = level, relation_type_list=[\"interaction\"]", "Purification)') session.create_network( user_entity_set_id = \"proteome\" , level = level, relation_type_list=[\"interaction\"]", "relationObj.get_attributes_dict(): method_ids.update([ x.value for x in relationObj.get_attributes_dict()[\"method_id\"]]) if \"pubmed\" in", "and num_databases >= minimum_number_of_db: use=True else: use=False if not use:", "file and introduce them to a Python list. The seeds", "least by affinity technology if options.restricted_to_TAP: print ('Using interactions at", "DEFINE A USER ENTITY SET # #------------------------------# # Create network", "uEId_to_type = session.dbAccess.get_user_entity_type(config.get('BIANA', 'unification_protocol'), all_uEs) skip_interactions=0 for (uE_id1, uE_id2) in", "continue if s in translate: codes=set(translate[s]) translation=\"','\".join([str(x) for x in", "sys.exit(10) import methods_dictionaries as methods_dicts def main(): options = parse_user_arguments()", "= set() method_ids = set() source_databases = set() use_method_ids=set() pubmed_ids", "= \"@oliva's lab 2019\") parser.add_argument('-iseed','--seeds_input_file',dest='seed',action = 'store', help = 'Seeds", "options.format == 'multi-fields' : out_network.write(\"{0}\\t{1}\\t{2}\\t{3}\\t{4}\\t{5}\\n\". format(uE_id1,uE_id2,info_sources,info_methods_ids,info_methods,info_pubmed_ids)) elif options.format == 'netscore':", "in allseed: if protein not in single and protein not", "in source_databases]) else: if options.verbose: print('Skipping interaction it has no", "in uE.get_attribute(attribute_identifier=options.ttype): if maxlen < len(current_id.value.get_sequence().upper()): maxlen=len(current_id.value.get_sequence().upper()) translation=\",\".join([str(current_id.value.get_sequence().upper()) for current_id", "rejected Methods:\",repr(no_methods) #---------------------------# # START A BIANA SESSION # #---------------------------#", "protein not in nodes: uE = session.get_user_entity(protein) for current_id in", "for current_eErID in eErIDs_list: relationObj = relationObj_dict[current_eErID] if options.verbose: print", "has no source database!') print('Node 1: {}\\tNode 2: {}'.format(uE_id1, uE_id2))", "for the output translation of codes (default is accessionnumber) Using", "in seeds: translate.setdefault(current_id.value.lower(),[]) translate[current_id.value.lower()].append(protein) # Get all IDS of SEEDS,", "dictionary affinity_dict = methods_dicts.affinity_dict affinity=set(affinity_dict.keys()) # Get the complementation dictionary", "at least by yeast two hybrid elif options.restricted_to_Y2H: print ('Using", "differently if options.radius <= 0: # Output node file out_proteins", "not fileExist(options.seed): print \"File with seeds is missing or not", "restricted_to_seeds or options.radius>0: # Check if the seeds file exists", "method_ids: if m not in complementation: use_method_ids.add(m) #print \"Add\", m", "\"proteinsequence\" provides with the longest sequence of all codes''') parser.add_argument('-trans','--translation_of_nodes_file',dest='translation_file',action", "= relationObj.get_source_database()) )) if options.except_TAP: for m in method_ids: if", "is input_seed)') parser.add_argument('-radius','--radius_of_subnetwork_around_seeds',dest='radius',default=0,action = 'store',type=int, help = '''Network is built", "externalEntityIdsList = [external_entity_relation_id] ) # Get TYPE of user entity", "<node1>\\t<node2>\\n 'multi-fields' : <node1>\\t<node2>\\t<sources>\\t<method_ids>\\t<method_names>\\t<pmids>\\n''') parser.add_argument('-rAFF','--restricted_to_TAP',dest='restricted_to_TAP',action = 'store_true', help = 'Flag", "id_type=options.stype,new_user_entity_set_id=\"proteome\", negative_attribute_restriction_list=[] ) else: level=0 proteome = session.create_new_user_entity_set( identifier_description_list =", "in uE.get_attribute(attribute_identifier=options.stype): translate_stype.add(current_id.value.upper()) translation_stype=\"','\".join([\"{0}\".format(x) for x in translate_stype]) out_trans_stype.write(\"{0}\\t'{1}'\\n\".format(protein,translation_stype)) out_translation.close()", "format is not multi-fields, netscore or raw, the output format", "were not previously found in the network single=set() for uE_id", "file # TRANSLATION TO 'ttype' out_translation = open(options.translation_file,'w') # TRANSLATION", "= eErIDs_list, attribute_list = [], relation_attribute_list = [\"method_id\",\"psimi_name\",\"pubmed\"], participant_attribute_list =", "to use interactions at least described by affinity methods (i.e.", "out_proteins = open(options.node,'w') translate={} for protein in nodes: score=seed_score uE", "\"proteinsequence\": maxlen=0; for current_id in uE.get_attribute(attribute_identifier=options.ttype): if maxlen < len(current_id.value.get_sequence().upper()):", "if options.restricted_to_TAP: print ('Using interactions at least described by affinity", "== 'multi-fields': out_proteins.write(\"{0}\\t{1:.2f}\\t{2:.2f}\\t{3:.2f}\\n\".format(protein,1.,1.,score)) elif options.format == 'netscore': out_proteins.write(\"{0}\\t{1:.2f}\\t{2:.2f}\\t{3:.2f}\\n\".format(protein,1.,1.,score)) else: out_proteins.write(\"{0}\\t{1:.2f}\\n\".format(protein,score))", "out_proteins = open(options.node,'w') for protein in nodes: if options.format ==", "print \"No rejection of methods selected by the user\" user_rejection=False", "m in method_ids: if m not in affinity: use_method_ids.add(m) #print", "elif options.format == 'netscore': out_proteins.write(\"{0}\\t{1:.2f}\\t{2:.2f}\\t{3:.2f}\\n\".format(protein,1.,1.,0.1)) else: out_proteins.write(\"{0}\\t{1:.2f}\\n\".format(protein,0.1)) out_proteins.close() ################################# TRANSLATION", "= open(options.seed,'r') for line in input_seed: fields = line.strip().split(\"\\t\") seeds.add(fields[0].lower())", "biana_edges)') parser.add_argument('-node','--node_file',dest='node',action = 'store', default='biana_nodes', help = 'Output file with", "ConfigParser.ConfigParser() config.read(config_file) #--------------------------------------# # LOAD THE DICTIONARIES OF METHODS #", "'''Network is built in a radius of connections around the", "network single=set() for uE_id in proteome.get_unconnected_nodes(): single.add(uE_id) for protein in", "as input_method_fd: for line in input_method_fd: fields = line.strip().split(\"\\t\") no_methods.append(fields[0])", "'multi-fields': out_proteins.write(\"{0}\\t{1:.2f}\\t{2:.2f}\\t{3:.2f}\\n\".format(protein,1.,1.,score)) elif options.format == 'netscore': out_proteins.write(\"{0}\\t{1:.2f}\\t{2:.2f}\\t{3:.2f}\\n\".format(protein,1.,1.,score)) else: out_proteins.write(\"{0}\\t{1:.2f}\\n\".format(protein,score)) out_proteins.close()", "dictionary complementation_dict = methods_dicts.complementation_dict complementation=set(complementation_dict.keys()) #---------------------------------------# # GET METHODS THAT", "in translate_stype]) out_trans_stype.write(\"{0}\\t'{1}'\\n\".format(protein,translation_stype)) out_translation.close() if trans_stype: out_trans_stype.close() #################################################################################### print('Generation of", "the minimum established if num_methods >= minimum_number_of_methods: use=True else: use=False", "options.radius <= 0: # Output node file out_proteins = open(options.node,'w')", "rejection of methods selected by the user\" user_rejection=False else: no_methods=[]", "s == '': continue if s in translate: codes=set(translate[s]) translation=\"','\".join([str(x)", "method_ids = set() source_databases = set() use_method_ids=set() pubmed_ids = set()", "translate_stype=set() if options.ttype == \"proteinsequence\": maxlen=0; for current_id in uE.get_attribute(attribute_identifier=options.ttype):", "\"Add\", m else: unused_method_names.add(complementation_dict[m]) elif user_rejection: for m in method_ids:", "among selected methods \",m else: use_method_ids.update(method_ids) if len(source_databases) > 0:", "described by affinity methods (i.e. Tandem Affinity Purification)') session.create_network( user_entity_set_id", "protein!') print('Node 1: {}\\tType: {}'.format(uE_id1, uE1_type)) print('Node 2: {}\\tType: {}'.format(uE_id2,", "create_new_session( sessionID=\"biana_session\", dbname=config.get('BIANA', 'database'), dbhost=config.get('BIANA', 'host'), dbuser=config.get('BIANA', 'user'), dbpassword=config.get('BIANA', 'password'),", "out_translation.close() if trans_stype: out_trans_stype.close() #################################################################################### # If we wanted a", "selected type for all nodes') parser.add_argument('-strans','--translation_of_seeds_file',dest='translation_seeds_file',action = 'store',default='translation_seeds_to_BIANA_codes.txt', help =", "Get the program path main_path = os.path.abspath(os.path.dirname(__file__)) # Read the", "= [x for x in method_names if x not in", "-trans example/output/example.proteinsequence.trans -strans example/output/example.seeds.trans -edge example/output/example.edges -node example/output/example.nodes -format raw", "\"proteome\" , level = level, relation_type_list=[\"interaction\"] , relation_attribute_restriction_list = [(\"Method_id\",400)],", "Get the complementation dictionary complementation_dict = methods_dicts.complementation_dict complementation=set(complementation_dict.keys()) #---------------------------------------# #", "methods \",m else: use_method_ids.update(method_ids) if len(source_databases) > 0: info_sources=\";\".join([str(x) for", "set() with open(seed_file, 'r') as seed_file_fd: for line in seed_file_fd:", "fields = line.strip().split(\"\\t\") seeds.add(fields[0].lower()) input_seed.close() # Output node file out_proteins", "to be # added for translation allseed=set() for uE_id in", "skip_interactions=skip_interactions+1 continue if len(method_names) > 0: method_names = [x for", "'netscore': <node1>\\t<node2>\\t<score>\\n 'raw': <node1>\\t<node2>\\n 'multi-fields' : <node1>\\t<node2>\\t<sources>\\t<method_ids>\\t<method_names>\\t<pmids>\\n''') parser.add_argument('-rAFF','--restricted_to_TAP',dest='restricted_to_TAP',action = 'store_true',", "'Flag to use all interactions except those described by affinity", "&> /home/quim/PHD/Projects/BIANA/outputs/BIANA_2020_geneID_seqtax_drugtarget/human_network_biana_2020.log \"\"\" return options def generate_network(options): \"\"\" Generates a", "get_seeds_from_file(options.seed) # If we have Taxonomy restriction, we add it", "edge file:\\tsif (default), netscore, raw, multi-fields:\\n 'sif': <node1>\\tscore\\t<node2>\\n 'netscore': <node1>\\t<node2>\\t<score>\\n", "relationObj.get_attributes_dict(): pubmed_ids.update([ x.value for x in relationObj.get_attributes_dict()[\"pubmed\"]]) source_databases.add(str(session.dbAccess.get_external_database( database_id =", "a Python list. The seeds must be separated by new", "trans_stype=False if options.stype != 'proteinsequence' and options.stype != options.ttype: trans_stype", "method_ids: if m not in no_methods: use_method_ids.add(m) elif user_selection: for", "a radius of connections around the seed proteins. If 0,", "'store_true', help = 'Flag to use all interactions except those", "print \"\\t\".join([ x.value for x in relationObj.get_attribute(attribute_identifier=\"psimi_name\") ]) #if relationObj.get_attribute(attribute_identifier=\"method_id\")", "allseed: if protein not in single and protein not in", "parser.add_argument('-strans','--translation_of_seeds_file',dest='translation_seeds_file',action = 'store',default='translation_seeds_to_BIANA_codes.txt', help = 'File with the translation of", "if len(str(current_id.value.get_sequence().upper())) == maxlen ] ) #print \"Translation\",protein,translation #print(\"{0}\\t'{1}'\\n\".format(protein,translation)) else:", "nodes.add(uE_id2) #print \"Attribute \",(uE_id1,uE_id2).get_attribute( if options.format == 'multi-fields' : out_network.write(\"{0}\\t{1}\\t{2}\\t{3}\\t{4}\\t{5}\\n\".", "= 'Flag to use all interactions except those described by", "included if not fileExist(options.restricted_to_user): print \"No restriction on methods selected", "no method!') print('Node 1: {}\\tNode 2: {}'.format(uE_id1, uE_id2)) skip_interactions=skip_interactions+1 continue", "for x in pubmed_ids]) else: info_pubmed_ids='-' num_databases=len(source_databases) num_methods=len(use_method_ids) num_pubmeds =", "= open(options.translation_file+'.'+options.stype+'.trans','w') for protein in nodes: uE = session.get_user_entity(protein) translate=set()", "to use interactions described by the user selected methods') parser.add_argument('-eAFF','--except_TAP',dest='except_TAP',action", "elif options.format == 'netscore': out_proteins.write(\"{0}\\t{1:.2f}\\t{2:.2f}\\t{3:.2f}\\n\".format(protein,1.,1.,score)) else: out_proteins.write(\"{0}\\t{1:.2f}\\n\".format(protein,score)) out_proteins.close() # Get", "num_methods >= minimum_number_of_methods: use=True else: use=False # Check if the", "set() source_databases = set() use_method_ids=set() pubmed_ids = set() unused_method_names =", "# Get all IDS of SEEDS, defined as \"proteome\", and", "introduced type of code to BIANA codes') parser.add_argument('-edge','--edge_file',dest='edge',action = 'store',", "(i.e. Tandem Affinity Purification)') session.create_network( user_entity_set_id = \"proteome\" , level", "eErIDs_list: relationObj = relationObj_dict[current_eErID] if options.verbose: print \"Interaction: (\",uE_id1,\",\",uE_id2,\")\" print", "FROM CONFIG FILE # #--------------------------------------# # Get the program path", "else: level=options.radius seed_list = get_seeds_from_file(options.seed) # If we have Taxonomy", "session.get_user_entity(protein) translate=set() translate_stype=set() if options.ttype == \"proteinsequence\": maxlen=0; for current_id", "with open(seed_file, 'r') as seed_file_fd: for line in seed_file_fd: fields", "== maxlen ] ) #print \"Translation\",protein,translation #print(\"{0}\\t'{1}'\\n\".format(protein,translation)) else: ##### TRANSLATION", "for line in input_seed: fields = line.strip().split(\"\\t\") seeds.add(fields[0].lower()) input_seed.close() #", "for x in relationObj.get_attributes_dict()[\"method_id\"]]) if \"pubmed\" in relationObj.get_attributes_dict(): pubmed_ids.update([ x.value", "import argparse import ConfigParser import sys, os, re import biana", "current_id in uE.get_attribute(attribute_identifier=options.ttype) if len(str(current_id.value.get_sequence().upper())) == maxlen ] ) #print", "use only Methods:\",repr(use_methods) # Check if the user has introduced", "interaction it has no method!') print('Node 1: {}\\tNode 2: {}'.format(uE_id1,", "we wanted the complete interactome, the translation will be done", "and os.path.isfile(file) def get_seeds_from_file(seed_file): \"\"\" Obtain the seeds from a", "(implemented for Interactomix platform)\", epilog = \"@oliva's lab 2019\") parser.add_argument('-iseed','--seeds_input_file',dest='seed',action", "= 'store',default='restricted_methods', help = 'File to reject interactions described by", "/home/quim/PHD/Projects/BIANA/outputs/BIANA_2020_geneID_seqtax_drugtarget/human_network_biana_2020_nodes.txt -trans /home/quim/PHD/Projects/BIANA/outputs/BIANA_2020_geneID_seqtax_drugtarget/human_network_biana_2020_translation.txt -ttype geneid -format multi-fields &> /home/quim/PHD/Projects/BIANA/outputs/BIANA_2020_geneID_seqtax_drugtarget/human_network_biana_2020.log \"\"\"", "the translation will be done differently if options.radius <= 0:", "use_method_ids.add(m) #print \"Add\", m else: unused_method_names.add(affinity_dict[m]) elif options.except_Y2H: #print \"check", "else: if options.verbose: print('Skipping interaction it has no method!') print('Node", "'store',default='sif', help = '''Format file of the edge file:\\tsif (default),", "new_user_entity_set_id=\"proteome\", negative_attribute_restriction_list=[] ) #----------------------------------------------------# # SELECT THE INTERACTIONS OF THE", "x in relationObj.get_attributes_dict()[\"pubmed\"]]) source_databases.add(str(session.dbAccess.get_external_database( database_id = relationObj.get_source_database()) )) if options.except_TAP:", "print \"Pubmeds\",num_pubmeds,info_pubmed_ids # Check if the number of methods is", "\"Open session\" session = create_new_session( sessionID=\"biana_session\", dbname=config.get('BIANA', 'database'), dbhost=config.get('BIANA', 'host'),", "print('Skipping interaction because the type of one of the user", "#print \"Translation\",protein,translation #print(\"{0}\\t'{1}'\\n\".format(protein,translation)) else: ##### TRANSLATION TO 'ttype' for current_id", "pubmed_ids = set() unused_method_names = set() relationObj_dict = session.dbAccess.get_external_entities_dict( externalEntityIdsList", "<node1>\\t<node2>\\t<sources>\\t<method_ids>\\t<method_names>\\t<pmids>\\n''') parser.add_argument('-rAFF','--restricted_to_TAP',dest='restricted_to_TAP',action = 'store_true', help = 'Flag to use interactions", "print('Node 1: {}\\tType: {}'.format(uE_id1, uE1_type)) print('Node 2: {}\\tType: {}'.format(uE_id2, uE2_type))", "out_proteins.close() ################################# TRANSLATION #################################### out_translation = open(options.translation_file,'w') # TRANSLATION TO", "Select interactions that have been detected at least by yeast", "def parse_user_arguments(*args, **kwds): parser = argparse.ArgumentParser( description = \"Generate a", "reject interactions described by the user selected methods') parser.add_argument('-v','--verbose',dest='verbose',action =", "'store',default='accessionnumber', help = '''Type of identifier for the output translation", "'host'), dbuser=config.get('BIANA', 'user'), dbpassword=config.get('BIANA', 'password'), unification_protocol=config.get('BIANA', 'unification_protocol') ) print \"Continue\"", "multi-fields, netscore or raw, the output format is sif out_network.write(\"{}\\t{:.2f}\\t{}\\n\".format(uE_id1,1.,uE_id2))", "= [(\"taxid\",options.taxid)], attribute_restriction_list=[], id_type=\"embedded\", new_user_entity_set_id=\"proteome\", negative_attribute_restriction_list=[] ) #----------------------------------------------------# # SELECT", "in all_interactions: #self.dbAccess.get_external_entities_dict( externalEntityIdsList = [external_entity_relation_id] ) # Get TYPE", "0 -taxid 9606 -edge /home/quim/PHD/Projects/BIANA/outputs/BIANA_2020_geneID_seqtax_drugtarget/human_network_biana_2020.txt -node /home/quim/PHD/Projects/BIANA/outputs/BIANA_2020_geneID_seqtax_drugtarget/human_network_biana_2020_nodes.txt -trans /home/quim/PHD/Projects/BIANA/outputs/BIANA_2020_geneID_seqtax_drugtarget/human_network_biana_2020_translation.txt -ttype", "AND TRANSLATION FILES # #---------------------------------------# # If we wanted the", "unused_method_names.add(complementation_dict[m]) elif user_rejection: for m in method_ids: if m not", "out_network.write(\"{0}\\t{1}\\t{2}\\t{3}\\t{4}\\t{5}\\n\". format(uE_id1,uE_id2,info_sources,info_methods_ids,info_methods,info_pubmed_ids)) elif options.format == 'netscore': out_network.write('\\t{}\\t{}\\t{:.2f}\\n'.format(uE_id1,uE_id2,1.)) elif options.format ==", "seeds: translate.setdefault(current_id.value.lower(),[]) translate[current_id.value.lower()].append(protein) # Get all IDS of SEEDS, defined", "a file and introduce them to a Python list. The", "except: sys.exit(10) import methods_dictionaries as methods_dicts def main(): options =", "the minimum established if use and num_databases >= minimum_number_of_db: use=True", "not protein, we skip the interaction if uE1_type != 'protein'", "x.value for x in relationObj.get_attributes_dict()[\"psimi_name\"] ] #print [ x.value for", "identifier_description_list =seed_list, id_type=options.stype,new_user_entity_set_id=\"proteome\", negative_attribute_restriction_list=[] ) else: level=0 proteome = session.create_new_user_entity_set(", "for s in seeds: if s == '': continue if", "is sif out_network.write(\"{}\\t{:.2f}\\t{}\\n\".format(uE_id1,1.,uE_id2)) print \"Num neglected interactions:\", skip_interactions out_network.close() #---------------------------------------#", "the introduced type of code to BIANA codes') parser.add_argument('-edge','--edge_file',dest='edge',action =", "seeds.add(fields[0].lower()) input_seed.close() # Output node file out_proteins = open(options.node,'w') translate={}", "in method_names]) else: info_methods='-' if len(use_method_ids) > 0: info_methods_ids=\";\".join([str(x) for", "is not protein, we skip the interaction if uE1_type !=", "is higher than the minimum established if use and num_databases", "(i.e. human=9606 is default if TaxID=0 there is no restriction)')", "file config_file = os.path.join(main_path, 'config.ini') config = ConfigParser.ConfigParser() config.read(config_file) #--------------------------------------#", "options.verbose: print \"Methods\",num_methods,info_methods,\"\\tSelected:\",info_methods_ids print \"Databases\",num_databases,info_sources print \"Pubmeds\",num_pubmeds,info_pubmed_ids # Check if", "options def generate_network(options): \"\"\" Generates a protein-protein interaction network extracting", "\"No rejection of methods selected by the user\" user_rejection=False else:", "= (not restricted_to_seeds) , use_self_relations = False) # Select all", "in uE.get_attribute(attribute_identifier=options.ttype) if len(str(current_id.value.get_sequence().upper())) == maxlen ] ) #print \"Translation\",protein,translation", "unused_method_names.add(affinity_dict[m]) elif options.except_Y2H: #print \"check Y2H\" for m in method_ids:", "=seed_list, id_type=options.stype,new_user_entity_set_id=\"proteome\", negative_attribute_restriction_list=[] ) else: level=0 proteome = session.create_new_user_entity_set( identifier_description_list", "relation_type_list=[\"interaction\"] , relation_attribute_restriction_list = [(\"Method_id\",18)], #relation_attribute_restriction_list = [(\"psimi_name\",\"y2h2\")], include_relations_last_level =", "of the network done!') return def fileExist(file): \"\"\" Checks if", "out_trans_stype.close() #################################################################################### print('Generation of the network done!') return def fileExist(file):", "all interactions except those described by yeast two hybrid methods", "epilog = \"@oliva's lab 2019\") parser.add_argument('-iseed','--seeds_input_file',dest='seed',action = 'store', help =", "we skip the interaction if uE1_type != 'protein' or uE2_type", "elif options.restricted_to_Y2H: print ('Using interactions at least described by yeast-two-hybrid", "codes''') parser.add_argument('-trans','--translation_of_nodes_file',dest='translation_file',action = 'store',default='translation_nodes.txt', help = 'File with the translation", "all nodes') parser.add_argument('-strans','--translation_of_seeds_file',dest='translation_seeds_file',action = 'store',default='translation_seeds_to_BIANA_codes.txt', help = 'File with the", "in method_ids: if m not in no_methods: use_method_ids.add(m) elif user_selection:", "network of expansion, the translation will be done differently elif", "fileExist(file): \"\"\" Checks if a file exists AND is a", "in use_method_ids]) else: if options.verbose: print('Skipping interaction it has no", "# #----------------------# # Parameters that I have decided to fix", "<= 0: # Output node file out_proteins = open(options.node,'w') for", "biana_nodes)') parser.add_argument('-format','--output_format',dest='format',action = 'store',default='sif', help = '''Format file of the", "maxlen ] ) #print \"Translation\",protein,translation #print(\"{0}\\t'{1}'\\n\".format(protein,translation)) else: ##### TRANSLATION TO", "BIANA to the selected type for all nodes') parser.add_argument('-strans','--translation_of_seeds_file',dest='translation_seeds_file',action =", "type of one of the user entities is not protein!')", "will be done differently if options.radius <= 0: # Output", "options.ttype: trans_stype = True out_trans_stype = open(options.translation_file+'.'+options.stype+'.trans','w') for protein in", "in seed_file_fd: fields = line.strip().split('\\t') seed_set.add(fields[0]) return list(seed_set) if __name__", "use and num_databases >= minimum_number_of_db: use=True else: use=False if not", "pubmed_ids.update([ x.value for x in relationObj.get_attributes_dict()[\"pubmed\"]]) source_databases.add(str(session.dbAccess.get_external_database( database_id = relationObj.get_source_database())", "for protein in nodes: score=seed_score uE = session.get_user_entity(protein) for current_id", "IDS of single nodes that were not previously found in", "2019\") parser.add_argument('-iseed','--seeds_input_file',dest='seed',action = 'store', help = 'Seeds Input file (default", "path main_path = os.path.abspath(os.path.dirname(__file__)) # Read the config file config_file", "#################################### out_translation = open(options.translation_seeds_file,'w') for s in seeds: if s", "ID (i.e. human=9606 is default if TaxID=0 there is no", "= parse_user_arguments() generate_network(options) def parse_user_arguments(*args, **kwds): parser = argparse.ArgumentParser( description", "\"0\": print(\"Check Proteome %s\"%(repr(options.taxid))) proteome = session.create_new_user_entity_set( identifier_description_list =seed_list, attribute_restriction_list=[(\"taxid\",options.taxid)],", "return def fileExist(file): \"\"\" Checks if a file exists AND", "\"\"\" Obtain the seeds from a file and introduce them", "'password'), unification_protocol=config.get('BIANA', 'unification_protocol') ) print \"Continue\" #------------------------------# # DEFINE A", "Check if the number of methods is higher than the", "Check if the user has introduced a file with methods", "trans_stype: for current_id in uE.get_attribute(attribute_identifier=options.stype): translate_stype.add(current_id.value.upper()) translation_stype=\"','\".join([\"{0}\".format(x) for x in", "for m in method_ids: if m not in no_methods: use_method_ids.add(m)", "Output translation file # TRANSLATION TO 'ttype' out_translation = open(options.translation_file,'w')", "method_ids.update([ x.value for x in relationObj.get_attributes_dict()[\"method_id\"]]) if \"pubmed\" in relationObj.get_attributes_dict():", "sequence of all codes''') parser.add_argument('-trans','--translation_of_nodes_file',dest='translation_file',action = 'store',default='translation_nodes.txt', help = 'File", "use all interactions except those described by affinity methods (i.e.", "default='biana_edges', help = 'Output file with edges(default is biana_edges)') parser.add_argument('-node','--node_file',dest='node',action", "a dictionary user entity ID => type uEId_to_type = session.dbAccess.get_user_entity_type(config.get('BIANA',", "#--------------------------------------# # Get the affinity dictionary affinity_dict = methods_dicts.affinity_dict affinity=set(affinity_dict.keys())", "0: info_sources=\";\".join([str(x) for x in source_databases]) else: if options.verbose: print('Skipping", "= get_seeds_from_file(options.seed) # If we have Taxonomy restriction, we add", "negative_attribute_restriction_list=[] ) else: level=0 proteome = session.create_new_user_entity_set( identifier_description_list = [(\"taxid\",options.taxid)],", "!= 'proteinsequence' and options.stype != options.ttype: trans_stype = True out_trans_stype", "out_translation.close() # Output translation file # TRANSLATION TO 'ttype' out_translation", "from a file and introduce them to a Python list.", "THE DICTIONARIES OF METHODS # #--------------------------------------# # Get the affinity", "open(options.except_user) as input_method_fd: for line in input_method_fd: fields = line.strip().split(\"\\t\")", "uE.get_attribute(attribute_identifier=options.ttype): if maxlen < len(current_id.value.get_sequence().upper()): maxlen=len(current_id.value.get_sequence().upper()) translation=\",\".join([str(current_id.value.get_sequence().upper()) for current_id in", "] if \"psimi_name\" in relationObj.get_attributes_dict(): method_names.update([ str(x.value) for x in", "Affinity Purification)') session.create_network( user_entity_set_id = \"proteome\" , level = level,", "# #---------------------------------------# # Check if the user has introduced a", "the seeds file exists if not fileExist(options.seed): print \"File with", "for m in method_ids: if m not in complementation: use_method_ids.add(m)", "for m in method_ids: if m not in affinity: use_method_ids.add(m)", "'store',default='9606', help = 'Tax ID (i.e. human=9606 is default if", "found in the network single=set() for uE_id in proteome.get_unconnected_nodes(): single.add(uE_id)", "established if num_methods >= minimum_number_of_methods: use=True else: use=False # Check", "because the type of one of the user entities is", "# Parameters that I have decided to fix restricted_to_seeds =", "for x in translate]) out_translation.write(\"{0}\\t'{1}'\\n\".format(protein,translation)) ##### TRANSLATION TO STYPE if", "main(): options = parse_user_arguments() generate_network(options) def parse_user_arguments(*args, **kwds): parser =", "default if TaxID=0 there is no restriction)') parser.add_argument('-stype','--seed_type',dest='stype',action = 'store',default='geneid',", "m not in no_methods: use_method_ids.add(m) elif user_selection: for m in", "print (\"Selecting interactions\") # Select interactions that have been detected", "if options.format == 'multi-fields' : out_network.write(\"{0}\\t{1}\\t{2}\\t{3}\\t{4}\\t{5}\\n\". format(uE_id1,uE_id2,info_sources,info_methods_ids,info_methods,info_pubmed_ids)) elif options.format ==", "uniprotentry -ttype proteinsequence -trans example/output/example.proteinsequence.trans -strans example/output/example.seeds.trans -edge example/output/example.edges -node", "in relationObj.get_attributes_dict()[\"psimi_name\"] ] #print [ x.value for x in relationObj.get_attributes_dict()[\"method_id\"]", "\"Translation\",protein,translation #print(\"{0}\\t'{1}'\\n\".format(protein,translation)) else: for current_id in uE.get_attribute(attribute_identifier=options.ttype): translate.add(current_id.value.upper()) translation=\"','\".join([\"{0}\".format(x) for", "\"Not among selected methods \",m else: use_method_ids.update(method_ids) if len(source_databases) >", "\"Input of rejected Methods:\",repr(no_methods) #---------------------------# # START A BIANA SESSION", "\"Add\", m else: unused_method_names.add(affinity_dict[m]) elif options.except_Y2H: #print \"check Y2H\" for", "for x in relationObj.get_attributes_dict()[\"method_id\"] ] if \"psimi_name\" in relationObj.get_attributes_dict(): method_names.update([", "('Using interactions at least described by yeast-two-hybrid methods (Y2H)') session.create_network(", "TRANSLATION TO STYPE if trans_stype: for current_id in uE.get_attribute(attribute_identifier=options.stype): translate_stype.add(current_id.value.upper())", "from biana import * except: sys.exit(10) import methods_dictionaries as methods_dicts", "(default is geneid)') parser.add_argument('-ttype','--translation_type',dest='ttype',action = 'store',default='accessionnumber', help = '''Type of", "raw -rY2H python /home/quim/PHD/Projects/BIANA/scripts/generate_network_interactomix.py -radius 0 -taxid 9606 -edge /home/quim/PHD/Projects/BIANA/outputs/BIANA_2020_geneID_seqtax_drugtarget/human_network_biana_2020.txt", "user entity ID => type uEId_to_type = session.dbAccess.get_user_entity_type(config.get('BIANA', 'unification_protocol'), all_uEs)", "that must be included if not fileExist(options.restricted_to_user): print \"No restriction", "continue eErIDs_list = proteome.get_external_entity_relation_ids(uE_id1, uE_id2) method_names = set() method_ids =", "session\" session = create_new_session( sessionID=\"biana_session\", dbname=config.get('BIANA', 'database'), dbhost=config.get('BIANA', 'host'), dbuser=config.get('BIANA',", "relation_type_list=[\"interaction\"] , relation_attribute_restriction_list = [(\"Method_id\",400)], #relation_attribute_restriction_list = [(\"psimi_name\",\"affinity technology\")], include_relations_last_level", "dbname=config.get('BIANA', 'database'), dbhost=config.get('BIANA', 'host'), dbuser=config.get('BIANA', 'user'), dbpassword=config.get('BIANA', 'password'), unification_protocol=config.get('BIANA', 'unification_protocol')", "[(\"psimi_name\",\"affinity technology\")], include_relations_last_level = (not restricted_to_seeds) , use_self_relations = False)", "print ('Using interactions at least described by affinity methods (i.e.", "#--------------------------------------# # Get the program path main_path = os.path.abspath(os.path.dirname(__file__)) #", "higher than the minimum established if num_methods >= minimum_number_of_methods: use=True", "uE1_type)) print('Node 2: {}\\tType: {}'.format(uE_id2, uE2_type)) skip_interactions=skip_interactions+1 continue eErIDs_list =", "uE2_type = uEId_to_type[uE_id2] # If type is not protein, we", "database!') print('Node 1: {}\\tNode 2: {}'.format(uE_id1, uE_id2)) skip_interactions=skip_interactions+1 continue if", "'Output file with edges(default is biana_edges)') parser.add_argument('-node','--node_file',dest='node',action = 'store', default='biana_nodes',", "# If we wanted a network of expansion, the translation", "START A BIANA SESSION # #---------------------------# print \"Open session\" session", "#print(\"{0}\\t'{1}'\\n\".format(protein,translation)) else: ##### TRANSLATION TO 'ttype' for current_id in uE.get_attribute(attribute_identifier=options.ttype):", "-taxid 9606 -edge /home/quim/PHD/Projects/BIANA/outputs/BIANA_2020_geneID_seqtax_drugtarget/human_network_biana_2020.txt -node /home/quim/PHD/Projects/BIANA/outputs/BIANA_2020_geneID_seqtax_drugtarget/human_network_biana_2020_nodes.txt -trans /home/quim/PHD/Projects/BIANA/outputs/BIANA_2020_geneID_seqtax_drugtarget/human_network_biana_2020_translation.txt -ttype geneid", "EDGE FILE # #----------------------# if use: #print uE_id1, uE_id/2 nodes.add(uE_id1)", "main_path = os.path.abspath(os.path.dirname(__file__)) # Read the config file config_file =", "session.create_new_user_entity_set( identifier_description_list =seed_list, attribute_restriction_list=[(\"taxid\",options.taxid)], id_type=options.stype,new_user_entity_set_id=\"proteome\", negative_attribute_restriction_list=[] ) else: print('Proteome without", "m in method_ids: #print \"Check\",repr(use_methods) if m in set(use_methods): use_method_ids.add(m)", "input_seed: fields = line.strip().split(\"\\t\") seeds.add(fields[0].lower()) input_seed.close() # Output node file", "raw, multi-fields:\\n 'sif': <node1>\\tscore\\t<node2>\\n 'netscore': <node1>\\t<node2>\\t<score>\\n 'raw': <node1>\\t<node2>\\n 'multi-fields' :", "eErIDs_list = proteome.get_external_entity_relation_ids(uE_id1, uE_id2) method_names = set() method_ids = set()", "use_self_relations = False) # Summary of interactions out_network = open(options.edge,'w')", "for current_id in uE.get_attribute(attribute_identifier=options.ttype): translate.add(current_id.value.upper()) translation=\"','\".join([\"{0}\".format(x) for x in translate])", "info_methods=\";\".join([str(x) for x in method_names]) else: info_methods='-' if len(use_method_ids) >", "is default if TaxID=0 there is no restriction)') parser.add_argument('-stype','--seed_type',dest='stype',action =", "in input_seed: fields = line.strip().split(\"\\t\") seeds.add(fields[0].lower()) input_seed.close() # Output node", "interaction if uE1_type != 'protein' or uE2_type != 'protein': if", "for current_id in uE.get_attribute(attribute_identifier=options.stype): translate_stype.add(current_id.value.upper()) translation_stype=\"','\".join([\"{0}\".format(x) for x in translate_stype])", "pubmed_ids]) else: info_pubmed_ids='-' num_databases=len(source_databases) num_methods=len(use_method_ids) num_pubmeds = len(pubmed_ids) if options.verbose:", "ConfigParser import sys, os, re import biana try: from biana", "current_eErID in eErIDs_list: relationObj = relationObj_dict[current_eErID] if options.verbose: print \"Interaction:", "translate.setdefault(current_id.value.lower(),[]) translate[current_id.value.lower()].append(protein) score=1.0 if options.format == 'multi-fields': out_proteins.write(\"{0}\\t{1:.2f}\\t{2:.2f}\\t{3:.2f}\\n\".format(protein,1.,1.,score)) elif options.format", "\"check Y2H\" for m in method_ids: if m not in", "if not fileExist(options.seed): print \"File with seeds is missing or", "] ) #print \"Translation\",protein,translation #print(\"{0}\\t'{1}'\\n\".format(protein,translation)) else: for current_id in uE.get_attribute(attribute_identifier=options.ttype):", "selected methods') parser.add_argument('-eAFF','--except_TAP',dest='except_TAP',action = 'store_true', help = 'Flag to use", "id_type=options.stype,new_user_entity_set_id=\"proteome\", negative_attribute_restriction_list=[] ) else: print('Proteome without Taxonomy restriction') proteome =", "= os.path.abspath(os.path.dirname(__file__)) # Read the config file config_file = os.path.join(main_path,", "for line in input_method_fd: fields = line.strip().split(\"\\t\") no_methods.append(fields[0]) user_rejection=True print", "use: skip_interactions=skip_interactions+1 #print method_names, method_ids, source_databases #----------------------# # OUTPUT EDGE", "radius of connections around the seed proteins. If 0, it", "import sys, os, re import biana try: from biana import", "the affinity dictionary affinity_dict = methods_dicts.affinity_dict affinity=set(affinity_dict.keys()) # Get the", "user_selection: for m in method_ids: #print \"Check\",repr(use_methods) if m in", "= True out_trans_stype = open(options.translation_file+'.'+options.stype+'.trans','w') for protein in nodes: uE", "<node1>\\t<node2>\\t<score>\\n 'raw': <node1>\\t<node2>\\n 'multi-fields' : <node1>\\t<node2>\\t<sources>\\t<method_ids>\\t<method_names>\\t<pmids>\\n''') parser.add_argument('-rAFF','--restricted_to_TAP',dest='restricted_to_TAP',action = 'store_true', help", "'File with the translation of codes from BIANA to the", "out_trans_stype = open(options.translation_file+'.'+options.stype+'.trans','w') for protein in nodes: uE = session.get_user_entity(protein)", "options.verbose: print \"Not among selected methods \",m else: use_method_ids.update(method_ids) if", "methods that have to be excluded if not fileExist(options.except_user): print", "not None: # print \"\\t\".join([ x.value for x in relationObj.get_attribute(attribute_identifier=\"psimi_name\")", "Example: python generate_network_interactomix.py -iseed example/sample1.txt -radius 1 -taxid 9606 -stype", "the output format is sif out_network.write(\"{}\\t{:.2f}\\t{}\\n\".format(uE_id1,1.,uE_id2)) print \"Num neglected interactions:\",", "= 'File to use interactions described by the user selected", "from the user entity set 'proteome' all_uEs = proteome.get_user_entity_ids() #", "if protein not in single and protein not in nodes:", "nodes: score=seed_score uE = session.get_user_entity(protein) for current_id in uE.get_attribute(attribute_identifier=options.stype): if", "connections around the seed proteins. If 0, it creates the", "user entity ids from the user entity set 'proteome' all_uEs", "relationObj.get_attributes_dict()[\"psimi_name\"] ]) if \"method_id\" in relationObj.get_attributes_dict(): method_ids.update([ x.value for x", "out_trans_stype.write(\"{0}\\t'{1}'\\n\".format(protein,translation_stype)) out_translation.close() if trans_stype: out_trans_stype.close() #################################################################################### # If we wanted", "in relationObj.get_attributes_dict()[\"pubmed\"]]) source_databases.add(str(session.dbAccess.get_external_database( database_id = relationObj.get_source_database()) )) if options.except_TAP: for", "restricted_to_seeds) , use_self_relations = False) # Select interactions that have", "skip_interactions=skip_interactions+1 #print method_names, method_ids, source_databases #----------------------# # OUTPUT EDGE FILE", "if s == '': continue if s in translate: codes=set(translate[s])", "the user entity ids from the user entity set 'proteome'", "0: # Output node file out_proteins = open(options.node,'w') for protein", "as seed_file_fd: for line in seed_file_fd: fields = line.strip().split('\\t') seed_set.add(fields[0])", "info_sources=\";\".join([str(x) for x in source_databases]) else: if options.verbose: print('Skipping interaction", ") # Get TYPE of user entity uE1_type = uEId_to_type[uE_id1]", "at least described by yeast-two-hybrid methods (Y2H)') session.create_network( user_entity_set_id =", "method_names = set() method_ids = set() source_databases = set() use_method_ids=set()", "seeds: if s == '': continue if s in translate:", "to use all interactions except those described by affinity methods", "for line in seed_file_fd: fields = line.strip().split('\\t') seed_set.add(fields[0]) return list(seed_set)", "is missing or not found\" sys.exit(10) else: level=options.radius seed_list =", "method_names]) else: info_methods='-' if len(use_method_ids) > 0: info_methods_ids=\";\".join([str(x) for x", "[x for x in method_names if x not in unused_method_names]", "= 1 seed_score = 0.1 #--------------------------------------# # GET INFORMATION FROM", "of expansion, the translation will be done differently elif options.radius", "uE = session.get_user_entity(protein) translate=set() translate_stype=set() if options.ttype == \"proteinsequence\": maxlen=0;", "use_method_ids.add(m) if options.verbose: print \"Not among selected methods \",m else:", "if not use: skip_interactions=skip_interactions+1 #print method_names, method_ids, source_databases #----------------------# #", "help = 'File with the translation of codes from the", "relationObj.get_attribute(attribute_identifier=\"psimi_name\") ]) #if relationObj.get_attribute(attribute_identifier=\"method_id\") is not None: #print \"\\t\".join([ x.value", "done!') return def fileExist(file): \"\"\" Checks if a file exists", "\"No restriction on methods selected by the user\" user_selection=False else:", "for x in use_method_ids]) else: if options.verbose: print('Skipping interaction it", "of the edge file:\\tsif (default), netscore, raw, multi-fields:\\n 'sif': <node1>\\tscore\\t<node2>\\n", "== 'multi-fields': out_proteins.write(\"{0}\\t{1:.2f}\\t{2:.2f}\\t{3:.2f}\\n\".format(protein,1.,1.,0.1)) elif options.format == 'netscore': out_proteins.write(\"{0}\\t{1:.2f}\\t{2:.2f}\\t{3:.2f}\\n\".format(protein,1.,1.,0.1)) else: out_proteins.write(\"{0}\\t{1:.2f}\\n\".format(protein,0.1))", "the network single=set() for uE_id in proteome.get_unconnected_nodes(): single.add(uE_id) for protein", "METHODS # #--------------------------------------# # Get the affinity dictionary affinity_dict =", "proteome.get_user_entity_ids() # Obtain a dictionary user entity ID => type", "if m not in complementation: use_method_ids.add(m) #print \"Add\", m else:", "-ttype geneid -format multi-fields &> /home/quim/PHD/Projects/BIANA/outputs/BIANA_2020_geneID_seqtax_drugtarget/human_network_biana_2020.log \"\"\" return options def", "interactions except those described by yeast two hybrid methods (Y2H)')", "codes to be # added for translation allseed=set() for uE_id", "seeds: translate.setdefault(current_id.value.lower(),[]) translate[current_id.value.lower()].append(protein) ################################# TRANSLATION #################################### out_translation = open(options.translation_seeds_file,'w') for", "FILES # #---------------------------------------# # If we wanted the complete interactome,", "Select interactions that have been detected at least by affinity", "file out_proteins = open(options.node,'w') for protein in nodes: if options.format", "in relationObj.get_attributes_dict(): method_ids.update([ x.value for x in relationObj.get_attributes_dict()[\"method_id\"]]) if \"pubmed\"", "#---------------------------# print \"Open session\" session = create_new_session( sessionID=\"biana_session\", dbname=config.get('BIANA', 'database'),", "Purification)') parser.add_argument('-rY2H','--restricted_to_Y2H',dest='restricted_to_Y2H',action = 'store_true', help = 'Flag to use interactions", "#print [ x.value for x in relationObj.get_attributes_dict()[\"method_id\"] ] if \"psimi_name\"", "methods (Y2H)') parser.add_argument('-eUSER','--except_user',dest='except_user',action = 'store',default='restricted_methods', help = 'File to reject", "(default is input_seed)') parser.add_argument('-radius','--radius_of_subnetwork_around_seeds',dest='radius',default=0,action = 'store',type=int, help = '''Network is", "parser.add_argument('-eUSER','--except_user',dest='except_user',action = 'store',default='restricted_methods', help = 'File to reject interactions described", "of expansion if the radius is larger than 0 if", "in unused_method_names] # Remove method names that were excluded info_methods=\";\".join([str(x)", "#print \"Translation\",protein,translation #print(\"{0}\\t'{1}'\\n\".format(protein,translation)) else: for current_id in uE.get_attribute(attribute_identifier=options.ttype): translate.add(current_id.value.upper()) translation=\"','\".join([\"{0}\".format(x)", "'netscore': out_proteins.write(\"{0}\\t{1:.2f}\\t{2:.2f}\\t{3:.2f}\\n\".format(protein,1.,1.,0.1)) else: out_proteins.write(\"{0}\\t{1:.2f}\\n\".format(protein,0.1)) out_proteins.close() ################################# TRANSLATION #################################### out_translation =", "open(seed_file, 'r') as seed_file_fd: for line in seed_file_fd: fields =", "user_rejection=False else: no_methods=[] with open(options.except_user) as input_method_fd: for line in", "file exists if not fileExist(options.seed): print \"File with seeds is", "\",m else: use_method_ids.update(method_ids) if len(source_databases) > 0: info_sources=\";\".join([str(x) for x", "number of methods is higher than the minimum established if", "methods (i.e. Tandem Affinity Purification)') parser.add_argument('-rY2H','--restricted_to_Y2H',dest='restricted_to_Y2H',action = 'store_true', help =", "s in seeds: if s == '': continue if s", "\"Continue\" #------------------------------# # DEFINE A USER ENTITY SET # #------------------------------#", "'store',default='geneid', help = 'Type of identifier for seeds (default is", "single: uE = session.get_user_entity(protein) for current_id in uE.get_attribute(attribute_identifier=options.stype): if current_id.value.lower()", "help = 'Output file with nodes(default is biana_nodes)') parser.add_argument('-format','--output_format',dest='format',action =", "'stype' trans_stype=False if options.stype != 'proteinsequence' and options.stype != options.ttype:", "'store',type=int, help = '''Network is built in a radius of", "example/output/example.edges -node example/output/example.nodes -format raw -rY2H python /home/quim/PHD/Projects/BIANA/scripts/generate_network_interactomix.py -radius 0", "elif options.format == 'netscore': out_network.write('\\t{}\\t{}\\t{:.2f}\\n'.format(uE_id1,uE_id2,1.)) elif options.format == 'raw': out_network.write(\"{}\\t{}\\n\".format(uE_id1,uE_id2))", "at least described by affinity methods (i.e. Tandem Affinity Purification)')", "0 if restricted_to_seeds or options.radius>0: # Check if the seeds", "current_id in uE.get_attribute(attribute_identifier=options.stype): if current_id.value.lower() in seeds: translate.setdefault(current_id.value.lower(),[]) translate[current_id.value.lower()].append(protein) #################################", "THE INTERACTIONS OF THE USER ENTITY SET # #----------------------------------------------------# print", "num_databases >= minimum_number_of_db: use=True else: use=False if not use: skip_interactions=skip_interactions+1", "options.stype != 'proteinsequence' and options.stype != options.ttype: trans_stype = True", "one of the user entities is not protein!') print('Node 1:", "= ConfigParser.ConfigParser() config.read(config_file) #--------------------------------------# # LOAD THE DICTIONARIES OF METHODS", "is built in a radius of connections around the seed", "nodes: if options.format == 'multi-fields': out_proteins.write(\"{0}\\t{1:.2f}\\t{2:.2f}\\t{3:.2f}\\n\".format(protein,1.,1.,0.1)) elif options.format == 'netscore':", "Obtain the seeds from a file and introduce them to", "the translation of codes from BIANA to the selected type", "only Methods:\",repr(use_methods) # Check if the user has introduced a", "parser.add_argument('-rAFF','--restricted_to_TAP',dest='restricted_to_TAP',action = 'store_true', help = 'Flag to use interactions at", "single.add(uE_id) for protein in single: uE = session.get_user_entity(protein) for current_id", "x.value for x in relationObj.get_attribute(attribute_identifier=\"psimi_name\") ]) #if relationObj.get_attribute(attribute_identifier=\"method_id\") is not", "TRANSLATION TO 'stype' trans_stype=False if options.stype != 'proteinsequence' and options.stype", "or uE2_type != 'protein': if options.verbose: print('Skipping interaction because the", "parser.add_argument('-radius','--radius_of_subnetwork_around_seeds',dest='radius',default=0,action = 'store',type=int, help = '''Network is built in a", "current_id.value.lower() in seeds: translate.setdefault(current_id.value.lower(),[]) translate[current_id.value.lower()].append(protein) # Get all IDS of", "x in relationObj.get_attribute(attribute_identifier=\"method_id\") ]) #print relationObj.get_attributes_dict() #print [ x.value for", "user entity set 'proteome' all_uEs = proteome.get_user_entity_ids() # Obtain a", "uE.get_attribute(attribute_identifier=options.stype): translate_stype.add(current_id.value.upper()) translation_stype=\"','\".join([\"{0}\".format(x) for x in translate_stype]) out_trans_stype.write(\"{0}\\t'{1}'\\n\".format(protein,translation_stype)) out_translation.close() if", "# #--------------------------------------# nodes=set() # Get all the user entity ids", "source database!') print('Node 1: {}\\tNode 2: {}'.format(uE_id1, uE_id2)) skip_interactions=skip_interactions+1 continue", "uE_id2) method_names = set() method_ids = set() source_databases = set()", "# print \"\\t\".join([ x.value for x in relationObj.get_attribute(attribute_identifier=\"psimi_name\") ]) #if", "user_rejection: for m in method_ids: if m not in no_methods:", "identifier for seeds (default is geneid)') parser.add_argument('-ttype','--translation_type',dest='ttype',action = 'store',default='accessionnumber', help", "print \"Databases\",num_databases,info_sources print \"Pubmeds\",num_pubmeds,info_pubmed_ids # Check if the number of", "methods_dictionaries as methods_dicts def main(): options = parse_user_arguments() generate_network(options) def", "with open(options.restricted_to_user) as input_method_fd: for line in input_method_fd: fields =", "config file config_file = os.path.join(main_path, 'config.ini') config = ConfigParser.ConfigParser() config.read(config_file)", "# Create network network of expansion if the radius is", "complete interactome, the translation will be done differently if options.radius", "protein-protein interaction network (implemented for Interactomix platform)\", epilog = \"@oliva's", "options.stype != options.ttype: trans_stype = True out_trans_stype = open(options.translation_file+'.'+options.stype+'.trans','w') for", "externalEntityIdsList = eErIDs_list, attribute_list = [], relation_attribute_list = [\"method_id\",\"psimi_name\",\"pubmed\"], participant_attribute_list", "translate_stype.add(current_id.value.upper()) translation_stype=\"','\".join([\"{0}\".format(x) for x in translate_stype]) out_trans_stype.write(\"{0}\\t'{1}'\\n\".format(protein,translation_stype)) out_translation.close() if trans_stype:", "= [(\"psimi_name\",\"affinity technology\")], include_relations_last_level = (not restricted_to_seeds) , use_self_relations =", "x in relationObj.get_attributes_dict()[\"method_id\"] ] if \"psimi_name\" in relationObj.get_attributes_dict(): method_names.update([ str(x.value)", "if TaxID=0 there is no restriction)') parser.add_argument('-stype','--seed_type',dest='stype',action = 'store',default='geneid', help", ": out_network.write(\"{0}\\t{1}\\t{2}\\t{3}\\t{4}\\t{5}\\n\". format(uE_id1,uE_id2,info_sources,info_methods_ids,info_methods,info_pubmed_ids)) elif options.format == 'netscore': out_network.write('\\t{}\\t{}\\t{:.2f}\\n'.format(uE_id1,uE_id2,1.)) elif options.format", "'File to reject interactions described by the user selected methods')", "# Get TYPE of user entity uE1_type = uEId_to_type[uE_id1] uE2_type", "\"method_id\" in relationObj.get_attributes_dict(): method_ids.update([ x.value for x in relationObj.get_attributes_dict()[\"method_id\"]]) if", "= open(options.translation_file,'w') # TRANSLATION TO 'stype' trans_stype=False if options.stype !=", "user\" user_rejection=False else: no_methods=[] with open(options.except_user) as input_method_fd: for line", "if options.verbose: print \"Interaction: (\",uE_id1,\",\",uE_id2,\")\" print relationObj #if relationObj.get_attribute(attribute_identifier=\"psimi_name\") is", "# Obtain a dictionary user entity ID => type uEId_to_type", "print \"Interaction: (\",uE_id1,\",\",uE_id2,\")\" print relationObj #if relationObj.get_attribute(attribute_identifier=\"psimi_name\") is not None:", ") num_methods=0 for current_eErID in eErIDs_list: relationObj = relationObj_dict[current_eErID] if", "parser.add_argument('-iseed','--seeds_input_file',dest='seed',action = 'store', help = 'Seeds Input file (default is", "with methods that must be included if not fileExist(options.restricted_to_user): print", "seeds must be separated by new lines! \"\"\" seed_set =", "default='biana_nodes', help = 'Output file with nodes(default is biana_nodes)') parser.add_argument('-format','--output_format',dest='format',action", "use interactions at least described by yeast two hybrid methods", "= level, relation_type_list=[\"interaction\"] , relation_attribute_restriction_list = [(\"Method_id\",400)], #relation_attribute_restriction_list = [(\"psimi_name\",\"affinity", "{}'.format(uE_id1, uE_id2)) skip_interactions=skip_interactions+1 continue if len(pubmed_ids) > 0: info_pubmed_ids=\";\".join([str(x) for", "0.1 #--------------------------------------# # GET INFORMATION FROM CONFIG FILE # #--------------------------------------#", "the user has introduced a file with methods that must", "print('Generation of the network done!') return def fileExist(file): \"\"\" Checks", "/home/quim/PHD/Projects/BIANA/outputs/BIANA_2020_geneID_seqtax_drugtarget/human_network_biana_2020.txt -node /home/quim/PHD/Projects/BIANA/outputs/BIANA_2020_geneID_seqtax_drugtarget/human_network_biana_2020_nodes.txt -trans /home/quim/PHD/Projects/BIANA/outputs/BIANA_2020_geneID_seqtax_drugtarget/human_network_biana_2020_translation.txt -ttype geneid -format multi-fields &>", "[external_entity_relation_id] ) # Get TYPE of user entity uE1_type =", "# #--------------------------------------# # Get the affinity dictionary affinity_dict = methods_dicts.affinity_dict", "not in complementation: use_method_ids.add(m) #print \"Add\", m else: unused_method_names.add(complementation_dict[m]) elif", "= 'store',default='9606', help = 'Tax ID (i.e. human=9606 is default", "x in source_databases]) else: if options.verbose: print('Skipping interaction it has", "described by the user selected methods') parser.add_argument('-eAFF','--except_TAP',dest='except_TAP',action = 'store_true', help", "'config.ini') config = ConfigParser.ConfigParser() config.read(config_file) #--------------------------------------# # LOAD THE DICTIONARIES", "[(\"Method_id\",400)], #relation_attribute_restriction_list = [(\"psimi_name\",\"affinity technology\")], include_relations_last_level = (not restricted_to_seeds) ,", "in set(use_methods): use_method_ids.add(m) if options.verbose: print \"Not among selected methods", "TRANSLATION #################################### out_translation = open(options.translation_seeds_file,'w') for s in seeds: if", "m not in complementation: use_method_ids.add(m) #print \"Add\", m else: unused_method_names.add(complementation_dict[m])", "\"Num neglected interactions:\", skip_interactions out_network.close() #---------------------------------------# # OUTPUT NODE AND", "== 'netscore': out_proteins.write(\"{0}\\t{1:.2f}\\t{2:.2f}\\t{3:.2f}\\n\".format(protein,1.,1.,score)) else: out_proteins.write(\"{0}\\t{1:.2f}\\n\".format(protein,score)) out_proteins.close() # Get the IDS", "as methods_dicts def main(): options = parse_user_arguments() generate_network(options) def parse_user_arguments(*args,", "network of expansion if the radius is larger than 0", "has introduced a file with methods that have to be", "# If we have Taxonomy restriction, we add it if", "x.value for x in relationObj.get_attribute(attribute_identifier=\"method_id\") ]) #print relationObj.get_attributes_dict() #print [", ") #print \"Translation\",protein,translation #print(\"{0}\\t'{1}'\\n\".format(protein,translation)) else: ##### TRANSLATION TO 'ttype' for", "detected at least by yeast two hybrid elif options.restricted_to_Y2H: print", "\"proteome\" , level = level, relation_type_list=[\"interaction\"] , include_relations_last_level = (not", "translation=\"','\".join([\"{0}\".format(x) for x in translate]) out_translation.write(\"{0}\\t'{1}'\\n\".format(protein,translation)) ##### TRANSLATION TO STYPE", "len(use_method_ids) > 0: info_methods_ids=\";\".join([str(x) for x in use_method_ids]) else: if", "Check if the number of database is higher than the", "parser.add_argument('-node','--node_file',dest='node',action = 'store', default='biana_nodes', help = 'Output file with nodes(default", "not fileExist(options.except_user): print \"No rejection of methods selected by the", "if maxlen < len(current_id.value.get_sequence().upper()): maxlen=len(current_id.value.get_sequence().upper()) translation=\",\".join([str(current_id.value.get_sequence().upper()) for current_id in uE.get_attribute(attribute_identifier=options.ttype)", "ids from the user entity set 'proteome' all_uEs = proteome.get_user_entity_ids()", "= 'store', help = 'Seeds Input file (default is input_seed)')", "it creates the complete interactome''') parser.add_argument('-taxid','--TaxID',dest='taxid',action = 'store',default='9606', help =", "selected methods') parser.add_argument('-v','--verbose',dest='verbose',action = 'store_true', help = 'Flag to use", "2: {}\\tType: {}'.format(uE_id2, uE2_type)) skip_interactions=skip_interactions+1 continue eErIDs_list = proteome.get_external_entity_relation_ids(uE_id1, uE_id2)", "BIANA SESSION # #---------------------------# print \"Open session\" session = create_new_session(", "] ) #print \"Translation\",protein,translation #print(\"{0}\\t'{1}'\\n\".format(protein,translation)) else: ##### TRANSLATION TO 'ttype'", "uE_id2) in all_interactions: #self.dbAccess.get_external_entities_dict( externalEntityIdsList = [external_entity_relation_id] ) # Get", "str(x.value) for x in relationObj.get_attributes_dict()[\"psimi_name\"] ]) if \"method_id\" in relationObj.get_attributes_dict():", "code to BIANA codes') parser.add_argument('-edge','--edge_file',dest='edge',action = 'store', default='biana_edges', help =", "= set() relationObj_dict = session.dbAccess.get_external_entities_dict( externalEntityIdsList = eErIDs_list, attribute_list =", "in nodes: uE = session.get_user_entity(protein) for current_id in uE.get_attribute(attribute_identifier=options.stype): if", "session.create_network( user_entity_set_id = \"proteome\" , level = level, relation_type_list=[\"interaction\"] ,", "options.restricted_to_Y2H: print ('Using interactions at least described by yeast-two-hybrid methods", "for x in relationObj.get_attribute(attribute_identifier=\"psimi_name\") ]) #if relationObj.get_attribute(attribute_identifier=\"method_id\") is not None:", "expansion, the translation will be done differently elif options.radius >", "identifier for the output translation of codes (default is accessionnumber)", "defined as \"proteome\", and check missing codes to be #", "of code to BIANA codes') parser.add_argument('-edge','--edge_file',dest='edge',action = 'store', default='biana_edges', help", "TO 'ttype' for current_id in uE.get_attribute(attribute_identifier=options.ttype): translate.add(current_id.value.upper()) translation=\"','\".join([\"{0}\".format(x) for x", "type is not protein, we skip the interaction if uE1_type", "# Get the program path main_path = os.path.abspath(os.path.dirname(__file__)) # Read", "NODE AND TRANSLATION FILES # #---------------------------------------# # If we wanted", "affinity methods (i.e. Tandem Affinity Purification)') parser.add_argument('-eY2H','--except_Y2H',dest='except_Y2H',action = 'store_true', help", "GET INFORMATION FROM CONFIG FILE # #--------------------------------------# # Get the", "TRANSLATION FILES # #---------------------------------------# # If we wanted the complete", "0: # Read the seeds seeds=set() input_seed = open(options.seed,'r') for", "uE2_type != 'protein': if options.verbose: print('Skipping interaction because the type", "parser = argparse.ArgumentParser( description = \"Generate a protein-protein interaction network", "have been detected at least by affinity technology if options.restricted_to_TAP:", "seed_file_fd: fields = line.strip().split('\\t') seed_set.add(fields[0]) return list(seed_set) if __name__ ==", "missing codes to be # added for translation allseed=set() for", "Get the IDS of single nodes that were not previously", "for x in relationObj.get_attribute(attribute_identifier=\"method_id\") ]) #print relationObj.get_attributes_dict() #print [ x.value", "codes (default is accessionnumber) Using \"proteinsequence\" provides with the longest", "than the minimum established if num_methods >= minimum_number_of_methods: use=True else:", "protein-protein interaction network extracting information from BIANA. \"\"\" #----------------------# #", "# Output translation file # TRANSLATION TO 'ttype' out_translation =", "all interactions else: session.create_network( user_entity_set_id = \"proteome\" , level =", "translation will be done differently elif options.radius > 0: #", "seed_set = set() with open(seed_file, 'r') as seed_file_fd: for line", "file with nodes(default is biana_nodes)') parser.add_argument('-format','--output_format',dest='format',action = 'store',default='sif', help =", "import methods_dictionaries as methods_dicts def main(): options = parse_user_arguments() generate_network(options)", "(not restricted_to_seeds) , use_self_relations = False) # Select interactions that", "Tandem Affinity Purification)') parser.add_argument('-eY2H','--except_Y2H',dest='except_Y2H',action = 'store_true', help = 'Flag to", "parser.add_argument('-taxid','--TaxID',dest='taxid',action = 'store',default='9606', help = 'Tax ID (i.e. human=9606 is", ": <node1>\\t<node2>\\t<sources>\\t<method_ids>\\t<method_names>\\t<pmids>\\n''') parser.add_argument('-rAFF','--restricted_to_TAP',dest='restricted_to_TAP',action = 'store_true', help = 'Flag to use", "in relationObj.get_attribute(attribute_identifier=\"method_id\") ]) #print relationObj.get_attributes_dict() #print [ x.value for x", "methods (i.e. Tandem Affinity Purification)') session.create_network( user_entity_set_id = \"proteome\" ,", "methods_dicts.affinity_dict affinity=set(affinity_dict.keys()) # Get the complementation dictionary complementation_dict = methods_dicts.complementation_dict", "user selected methods') parser.add_argument('-eAFF','--except_TAP',dest='except_TAP',action = 'store_true', help = 'Flag to", "interaction it has no source database!') print('Node 1: {}\\tNode 2:", "of interactions out_network = open(options.edge,'w') all_interactions = proteome.getRelations() print \"Num", "CONFIG FILE # #--------------------------------------# # Get the program path main_path", "# added for translation allseed=set() for uE_id in proteome.get_user_entity_ids(): allseed.add(uE_id)", "in relationObj.get_attributes_dict(): pubmed_ids.update([ x.value for x in relationObj.get_attributes_dict()[\"pubmed\"]]) source_databases.add(str(session.dbAccess.get_external_database( database_id", "is not None: #print \"\\t\".join([ x.value for x in relationObj.get_attribute(attribute_identifier=\"method_id\")", "= 'Flag to use interactions at least described by yeast", "options.format == 'multi-fields': out_proteins.write(\"{0}\\t{1:.2f}\\t{2:.2f}\\t{3:.2f}\\n\".format(protein,1.,1.,score)) elif options.format == 'netscore': out_proteins.write(\"{0}\\t{1:.2f}\\t{2:.2f}\\t{3:.2f}\\n\".format(protein,1.,1.,score)) else:", "relationObj.get_attribute(attribute_identifier=\"method_id\") is not None: #print \"\\t\".join([ x.value for x in", "If type is not protein, we skip the interaction if", "the seeds from a file and introduce them to a", "If 0, it creates the complete interactome''') parser.add_argument('-taxid','--TaxID',dest='taxid',action = 'store',default='9606',", "built in a radius of connections around the seed proteins.", "= 'store',default='accessionnumber', help = '''Type of identifier for the output", "* except: sys.exit(10) import methods_dictionaries as methods_dicts def main(): options", "> 0: info_pubmed_ids=\";\".join([str(x) for x in pubmed_ids]) else: info_pubmed_ids='-' num_databases=len(source_databases)", "if len(source_databases) > 0: info_sources=\";\".join([str(x) for x in source_databases]) else:", "-strans example/output/example.seeds.trans -edge example/output/example.edges -node example/output/example.nodes -format raw -rY2H python", "interaction because the type of one of the user entities", "if \"psimi_name\" in relationObj.get_attributes_dict(): method_names.update([ str(x.value) for x in relationObj.get_attributes_dict()[\"psimi_name\"]", "longest sequence of all codes''') parser.add_argument('-trans','--translation_of_nodes_file',dest='translation_file',action = 'store',default='translation_nodes.txt', help =", "options=parser.parse_args() \"\"\" Example: python generate_network_interactomix.py -iseed example/sample1.txt -radius 1 -taxid", "out_trans_stype.close() #################################################################################### # If we wanted a network of expansion,", "'protein' or uE2_type != 'protein': if options.verbose: print('Skipping interaction because", "creates the complete interactome''') parser.add_argument('-taxid','--TaxID',dest='taxid',action = 'store',default='9606', help = 'Tax", "the interaction if uE1_type != 'protein' or uE2_type != 'protein':", "os.path.join(main_path, 'config.ini') config = ConfigParser.ConfigParser() config.read(config_file) #--------------------------------------# # LOAD THE", "a file exists AND is a file \"\"\" return os.path.exists(file)", "input_method_fd: for line in input_method_fd: fields = line.strip().split(\"\\t\") use_methods.append(fields[0]) user_selection=True", "GET METHODS THAT WILL BE FILTERED # #---------------------------------------# # Check", "THE USER ENTITY SET # #----------------------------------------------------# print (\"Selecting interactions\") #", "in pubmed_ids]) else: info_pubmed_ids='-' num_databases=len(source_databases) num_methods=len(use_method_ids) num_pubmeds = len(pubmed_ids) if", "done differently if options.radius <= 0: # Output node file", "x in translate_stype]) out_trans_stype.write(\"{0}\\t'{1}'\\n\".format(protein,translation_stype)) out_translation.close() if trans_stype: out_trans_stype.close() #################################################################################### #", "those described by affinity methods (i.e. Tandem Affinity Purification)') parser.add_argument('-eY2H','--except_Y2H',dest='except_Y2H',action", "at least by affinity technology if options.restricted_to_TAP: print ('Using interactions", "lines! \"\"\" seed_set = set() with open(seed_file, 'r') as seed_file_fd:", "\"\"\" seed_set = set() with open(seed_file, 'r') as seed_file_fd: for", "\"\\t\".join([ x.value for x in relationObj.get_attribute(attribute_identifier=\"psimi_name\") ]) #if relationObj.get_attribute(attribute_identifier=\"method_id\") is", "as input_method_fd: for line in input_method_fd: fields = line.strip().split(\"\\t\") use_methods.append(fields[0])", "# #----------------------# if use: #print uE_id1, uE_id/2 nodes.add(uE_id1) nodes.add(uE_id2) #print", "use=False if not use: skip_interactions=skip_interactions+1 #print method_names, method_ids, source_databases #----------------------#", "'protein': if options.verbose: print('Skipping interaction because the type of one", "'multi-fields' : <node1>\\t<node2>\\t<sources>\\t<method_ids>\\t<method_names>\\t<pmids>\\n''') parser.add_argument('-rAFF','--restricted_to_TAP',dest='restricted_to_TAP',action = 'store_true', help = 'Flag to", "maxlen=0; for current_id in uE.get_attribute(attribute_identifier=options.ttype): if maxlen < len(current_id.value.get_sequence().upper()): maxlen=len(current_id.value.get_sequence().upper())", "\",(uE_id1,uE_id2).get_attribute( if options.format == 'multi-fields' : out_network.write(\"{0}\\t{1}\\t{2}\\t{3}\\t{4}\\t{5}\\n\". format(uE_id1,uE_id2,info_sources,info_methods_ids,info_methods,info_pubmed_ids)) elif options.format", "entity set 'proteome' all_uEs = proteome.get_user_entity_ids() # Obtain a dictionary", "1: {}\\tNode 2: {}'.format(uE_id1, uE_id2)) skip_interactions=skip_interactions+1 continue if len(pubmed_ids) >", "a protein-protein interaction network (implemented for Interactomix platform)\", epilog =", "= relationObj_dict[current_eErID] if options.verbose: print \"Interaction: (\",uE_id1,\",\",uE_id2,\")\" print relationObj #if", "A USER ENTITY SET # #------------------------------# # Create network network", "protein in allseed: if protein not in single and protein", "relation_attribute_restriction_list = [(\"Method_id\",400)], #relation_attribute_restriction_list = [(\"psimi_name\",\"affinity technology\")], include_relations_last_level = (not", "if options.except_TAP: for m in method_ids: if m not in", "example/sample1.txt -radius 1 -taxid 9606 -stype uniprotentry -ttype proteinsequence -trans", "OUTPUT EDGE FILE # #----------------------# if use: #print uE_id1, uE_id/2", "Remove method names that were excluded info_methods=\";\".join([str(x) for x in", "out_trans_stype.write(\"{0}\\t'{1}'\\n\".format(protein,translation_stype)) out_translation.close() if trans_stype: out_trans_stype.close() #################################################################################### print('Generation of the network", "= line.strip().split(\"\\t\") use_methods.append(fields[0]) user_selection=True print \"Input to use only Methods:\",repr(use_methods)", "'store',default='restricted_methods', help = 'File to reject interactions described by the", "x in method_names if x not in unused_method_names] # Remove", "in proteome.get_unconnected_nodes(): single.add(uE_id) for protein in single: uE = session.get_user_entity(protein)", "use interactions at least described by affinity methods (i.e. Tandem", "else: unused_method_names.add(affinity_dict[m]) elif options.except_Y2H: #print \"check Y2H\" for m in", "get_seeds_from_file(seed_file): \"\"\" Obtain the seeds from a file and introduce", "proteome.get_external_entity_relation_ids(uE_id1, uE_id2) method_names = set() method_ids = set() source_databases =", "line in input_method_fd: fields = line.strip().split(\"\\t\") no_methods.append(fields[0]) user_rejection=True print \"Input", "PARAMETERS # #----------------------# # Parameters that I have decided to", "-node /home/quim/PHD/Projects/BIANA/outputs/BIANA_2020_geneID_seqtax_drugtarget/human_network_biana_2020_nodes.txt -trans /home/quim/PHD/Projects/BIANA/outputs/BIANA_2020_geneID_seqtax_drugtarget/human_network_biana_2020_translation.txt -ttype geneid -format multi-fields &> /home/quim/PHD/Projects/BIANA/outputs/BIANA_2020_geneID_seqtax_drugtarget/human_network_biana_2020.log", "options.format == 'netscore': out_proteins.write(\"{0}\\t{1:.2f}\\t{2:.2f}\\t{3:.2f}\\n\".format(protein,1.,1.,0.1)) else: out_proteins.write(\"{0}\\t{1:.2f}\\n\".format(protein,0.1)) out_proteins.close() ################################# TRANSLATION ####################################", "if \"method_id\" in relationObj.get_attributes_dict(): method_ids.update([ x.value for x in relationObj.get_attributes_dict()[\"method_id\"]])", "for m in method_ids: #print \"Check\",repr(use_methods) if m in set(use_methods):", "is biana_edges)') parser.add_argument('-node','--node_file',dest='node',action = 'store', default='biana_nodes', help = 'Output file", "yeast two hybrid methods (Y2H)') parser.add_argument('-rUSER','--restricted_to_user',dest='restricted_to_user',action = 'store',default='restricted_methods', help =", "-iseed example/sample1.txt -radius 1 -taxid 9606 -stype uniprotentry -ttype proteinsequence", "= open(options.edge,'w') all_interactions = proteome.getRelations() print \"Num interactions:\", len(all_interactions) #--------------------------------------#", "maxlen ] ) #print \"Translation\",protein,translation #print(\"{0}\\t'{1}'\\n\".format(protein,translation)) else: for current_id in", "else: info_methods='-' if len(use_method_ids) > 0: info_methods_ids=\";\".join([str(x) for x in", "WILL BE FILTERED # #---------------------------------------# # Check if the user", "minimum established if num_methods >= minimum_number_of_methods: use=True else: use=False #", "methods') parser.add_argument('-v','--verbose',dest='verbose',action = 'store_true', help = 'Flag to use verbose", "= 'Output file with edges(default is biana_edges)') parser.add_argument('-node','--node_file',dest='node',action = 'store',", "on methods selected by the user\" user_selection=False else: use_methods=[] with", "#---------------------------# # START A BIANA SESSION # #---------------------------# print \"Open", "config = ConfigParser.ConfigParser() config.read(config_file) #--------------------------------------# # LOAD THE DICTIONARIES OF", "in seeds: translate.setdefault(current_id.value.lower(),[]) translate[current_id.value.lower()].append(protein) score=1.0 if options.format == 'multi-fields': out_proteins.write(\"{0}\\t{1:.2f}\\t{2:.2f}\\t{3:.2f}\\n\".format(protein,1.,1.,score))", "(Y2H)') parser.add_argument('-rUSER','--restricted_to_user',dest='restricted_to_user',action = 'store',default='restricted_methods', help = 'File to use interactions", "-format multi-fields &> /home/quim/PHD/Projects/BIANA/outputs/BIANA_2020_geneID_seqtax_drugtarget/human_network_biana_2020.log \"\"\" return options def generate_network(options): \"\"\"", "fileExist(options.except_user): print \"No rejection of methods selected by the user\"", "if s in translate: codes=set(translate[s]) translation=\"','\".join([str(x) for x in codes])", "/home/quim/PHD/Projects/BIANA/outputs/BIANA_2020_geneID_seqtax_drugtarget/human_network_biana_2020_translation.txt -ttype geneid -format multi-fields &> /home/quim/PHD/Projects/BIANA/outputs/BIANA_2020_geneID_seqtax_drugtarget/human_network_biana_2020.log \"\"\" return options", "fields = line.strip().split('\\t') seed_set.add(fields[0]) return list(seed_set) if __name__ == \"__main__\":", "for x in source_databases]) else: if options.verbose: print('Skipping interaction it", "Interactomix platform)\", epilog = \"@oliva's lab 2019\") parser.add_argument('-iseed','--seeds_input_file',dest='seed',action = 'store',", "is accessionnumber) Using \"proteinsequence\" provides with the longest sequence of", "argparse import ConfigParser import sys, os, re import biana try:", "current_id in uE.get_attribute(attribute_identifier=options.stype): if current_id.value.lower() in seeds: translate.setdefault(current_id.value.lower(),[]) translate[current_id.value.lower()].append(protein) score=1.0", "information from BIANA. \"\"\" #----------------------# # FIXED PARAMETERS # #----------------------#", "restriction, we add it if options.taxid != \"0\": print(\"Check Proteome", "and introduce them to a Python list. The seeds must", "= proteome.getRelations() print \"Num interactions:\", len(all_interactions) #--------------------------------------# # FILTER THE", ") #print \"Translation\",protein,translation #print(\"{0}\\t'{1}'\\n\".format(protein,translation)) else: for current_id in uE.get_attribute(attribute_identifier=options.ttype): translate.add(current_id.value.upper())", "that were excluded info_methods=\";\".join([str(x) for x in method_names]) else: info_methods='-'", "x in translate_stype]) out_trans_stype.write(\"{0}\\t'{1}'\\n\".format(protein,translation_stype)) out_translation.close() if trans_stype: out_trans_stype.close() #################################################################################### print('Generation", "print relationObj #if relationObj.get_attribute(attribute_identifier=\"psimi_name\") is not None: # print \"\\t\".join([", "# Check if the seeds file exists if not fileExist(options.seed):", "type uEId_to_type = session.dbAccess.get_user_entity_type(config.get('BIANA', 'unification_protocol'), all_uEs) skip_interactions=0 for (uE_id1, uE_id2)", "add it if options.taxid != \"0\": print(\"Check Proteome %s\"%(repr(options.taxid))) proteome", "Read the config file config_file = os.path.join(main_path, 'config.ini') config =", "== 'multi-fields' : out_network.write(\"{0}\\t{1}\\t{2}\\t{3}\\t{4}\\t{5}\\n\". format(uE_id1,uE_id2,info_sources,info_methods_ids,info_methods,info_pubmed_ids)) elif options.format == 'netscore': out_network.write('\\t{}\\t{}\\t{:.2f}\\n'.format(uE_id1,uE_id2,1.))", "# START A BIANA SESSION # #---------------------------# print \"Open session\"", "#################################################################################### # If we wanted a network of expansion, the", "minimum_number_of_methods: use=True else: use=False # Check if the number of", "neglected interactions:\", skip_interactions out_network.close() #---------------------------------------# # OUTPUT NODE AND TRANSLATION", "use: #print uE_id1, uE_id/2 nodes.add(uE_id1) nodes.add(uE_id2) #print \"Attribute \",(uE_id1,uE_id2).get_attribute( if", "generate_network(options) def parse_user_arguments(*args, **kwds): parser = argparse.ArgumentParser( description = \"Generate", "-format raw -rY2H python /home/quim/PHD/Projects/BIANA/scripts/generate_network_interactomix.py -radius 0 -taxid 9606 -edge", "number of database is higher than the minimum established if", "options = parse_user_arguments() generate_network(options) def parse_user_arguments(*args, **kwds): parser = argparse.ArgumentParser(", "\"File with seeds is missing or not found\" sys.exit(10) else:", "restriction on methods selected by the user\" user_selection=False else: use_methods=[]", "\"pubmed\" in relationObj.get_attributes_dict(): pubmed_ids.update([ x.value for x in relationObj.get_attributes_dict()[\"pubmed\"]]) source_databases.add(str(session.dbAccess.get_external_database(", "the selected type for all nodes') parser.add_argument('-strans','--translation_of_seeds_file',dest='translation_seeds_file',action = 'store',default='translation_seeds_to_BIANA_codes.txt', help", "not multi-fields, netscore or raw, the output format is sif", "0: info_methods_ids=\";\".join([str(x) for x in use_method_ids]) else: if options.verbose: print('Skipping", "interactions at least described by yeast-two-hybrid methods (Y2H)') session.create_network( user_entity_set_id", "if not fileExist(options.restricted_to_user): print \"No restriction on methods selected by", "id_type=\"embedded\", new_user_entity_set_id=\"proteome\", negative_attribute_restriction_list=[] ) #----------------------------------------------------# # SELECT THE INTERACTIONS OF", "= 'Type of identifier for seeds (default is geneid)') parser.add_argument('-ttype','--translation_type',dest='ttype',action", "def main(): options = parse_user_arguments() generate_network(options) def parse_user_arguments(*args, **kwds): parser", "# Check if the number of database is higher than", "#print \"Check\",repr(use_methods) if m in set(use_methods): use_method_ids.add(m) if options.verbose: print", "False) # Select all interactions else: session.create_network( user_entity_set_id = \"proteome\"", "translate_stype]) out_trans_stype.write(\"{0}\\t'{1}'\\n\".format(protein,translation_stype)) out_translation.close() if trans_stype: out_trans_stype.close() #################################################################################### # If we", "return options def generate_network(options): \"\"\" Generates a protein-protein interaction network", "# Summary of interactions out_network = open(options.edge,'w') all_interactions = proteome.getRelations()", "nodes.add(uE_id1) nodes.add(uE_id2) #print \"Attribute \",(uE_id1,uE_id2).get_attribute( if options.format == 'multi-fields' :", "there is no restriction)') parser.add_argument('-stype','--seed_type',dest='stype',action = 'store',default='geneid', help = 'Type", "s in translate: codes=set(translate[s]) translation=\"','\".join([str(x) for x in codes]) #out_translation.write(\"%s\\t'%s'\\n\"", "else: use=False # Check if the number of database is", "to use only Methods:\",repr(use_methods) # Check if the user has", "of database is higher than the minimum established if use", ", include_relations_last_level = (not restricted_to_seeds) , use_self_relations = False) #", "print('Skipping interaction it has no source database!') print('Node 1: {}\\tNode", "database is higher than the minimum established if use and", "Taxonomy restriction, we add it if options.taxid != \"0\": print(\"Check", "of connections around the seed proteins. If 0, it creates", "x.value for x in relationObj.get_attributes_dict()[\"pubmed\"]]) source_databases.add(str(session.dbAccess.get_external_database( database_id = relationObj.get_source_database()) ))", "#---------------------------------------# # OUTPUT NODE AND TRANSLATION FILES # #---------------------------------------# #", "continue if len(method_names) > 0: method_names = [x for x", "translate[current_id.value.lower()].append(protein) # Get all IDS of SEEDS, defined as \"proteome\",", "by yeast two hybrid methods (Y2H)') parser.add_argument('-rUSER','--restricted_to_user',dest='restricted_to_user',action = 'store',default='restricted_methods', help", "'proteome' all_uEs = proteome.get_user_entity_ids() # Obtain a dictionary user entity", "out_network.write('\\t{}\\t{}\\t{:.2f}\\n'.format(uE_id1,uE_id2,1.)) elif options.format == 'raw': out_network.write(\"{}\\t{}\\n\".format(uE_id1,uE_id2)) else: # If the", "type of code to BIANA codes') parser.add_argument('-edge','--edge_file',dest='edge',action = 'store', default='biana_edges',", "{}'.format(uE_id1, uE_id2)) skip_interactions=skip_interactions+1 continue if len(method_names) > 0: method_names =", "Create network network of expansion if the radius is larger", "SET # #------------------------------# # Create network network of expansion if", "accessionnumber) Using \"proteinsequence\" provides with the longest sequence of all", "options.verbose: print('Skipping interaction because the type of one of the", "Y2H\" for m in method_ids: if m not in complementation:", "parser.add_argument('-ttype','--translation_type',dest='ttype',action = 'store',default='accessionnumber', help = '''Type of identifier for the", "#---------------------------------------# # If we wanted the complete interactome, the translation", "= '''Type of identifier for the output translation of codes", "complementation_dict = methods_dicts.complementation_dict complementation=set(complementation_dict.keys()) #---------------------------------------# # GET METHODS THAT WILL", "methods (i.e. Tandem Affinity Purification)') parser.add_argument('-eY2H','--except_Y2H',dest='except_Y2H',action = 'store_true', help =", "parser.add_argument('-edge','--edge_file',dest='edge',action = 'store', default='biana_edges', help = 'Output file with edges(default", "help = 'Type of identifier for seeds (default is geneid)')", "else: use=False if not use: skip_interactions=skip_interactions+1 #print method_names, method_ids, source_databases", "the translation of codes from the introduced type of code", "skip_interactions out_network.close() #---------------------------------------# # OUTPUT NODE AND TRANSLATION FILES #", "protein not in single and protein not in nodes: uE", "uE2_type)) skip_interactions=skip_interactions+1 continue eErIDs_list = proteome.get_external_entity_relation_ids(uE_id1, uE_id2) method_names = set()", "restriction') proteome = session.create_new_user_entity_set( identifier_description_list =seed_list, id_type=options.stype,new_user_entity_set_id=\"proteome\", negative_attribute_restriction_list=[] ) else:", "network extracting information from BIANA. \"\"\" #----------------------# # FIXED PARAMETERS", "if options.verbose: print \"Not among selected methods \",m else: use_method_ids.update(method_ids)", "uE.get_attribute(attribute_identifier=options.stype): if current_id.value.lower() in seeds: translate.setdefault(current_id.value.lower(),[]) translate[current_id.value.lower()].append(protein) ################################# TRANSLATION ####################################", "#print(\"{0}\\t'{1}'\\n\".format(protein,translation)) else: for current_id in uE.get_attribute(attribute_identifier=options.ttype): translate.add(current_id.value.upper()) translation=\"','\".join([\"{0}\".format(x) for x", "print \"Input of rejected Methods:\",repr(no_methods) #---------------------------# # START A BIANA", "is a file \"\"\" return os.path.exists(file) and os.path.isfile(file) def get_seeds_from_file(seed_file):", "print \"Input to use only Methods:\",repr(use_methods) # Check if the", "a file with methods that have to be excluded if", "else: if options.verbose: print('Skipping interaction it has no source database!')", "Proteome %s\"%(repr(options.taxid))) proteome = session.create_new_user_entity_set( identifier_description_list =seed_list, attribute_restriction_list=[(\"taxid\",options.taxid)], id_type=options.stype,new_user_entity_set_id=\"proteome\", negative_attribute_restriction_list=[]", "else: use_method_ids.update(method_ids) if len(source_databases) > 0: info_sources=\";\".join([str(x) for x in", "restricted_to_seeds) , use_self_relations = False) # Select all interactions else:", "decided to fix restricted_to_seeds = False minimum_number_of_methods = 1 minimum_number_of_db", "translate_stype]) out_trans_stype.write(\"{0}\\t'{1}'\\n\".format(protein,translation_stype)) out_translation.close() if trans_stype: out_trans_stype.close() #################################################################################### print('Generation of the", "'Flag to use interactions at least described by affinity methods", "that were not previously found in the network single=set() for", "no source database!') print('Node 1: {}\\tNode 2: {}'.format(uE_id1, uE_id2)) skip_interactions=skip_interactions+1", "fields = line.strip().split(\"\\t\") no_methods.append(fields[0]) user_rejection=True print \"Input of rejected Methods:\",repr(no_methods)", "# GET METHODS THAT WILL BE FILTERED # #---------------------------------------# #", "by the user\" user_rejection=False else: no_methods=[] with open(options.except_user) as input_method_fd:", "restricted_to_seeds) , use_self_relations = False) # Summary of interactions out_network", "= line.strip().split(\"\\t\") seeds.add(fields[0].lower()) input_seed.close() # Output node file out_proteins =", "dictionary user entity ID => type uEId_to_type = session.dbAccess.get_user_entity_type(config.get('BIANA', 'unification_protocol'),", "nodes') parser.add_argument('-strans','--translation_of_seeds_file',dest='translation_seeds_file',action = 'store',default='translation_seeds_to_BIANA_codes.txt', help = 'File with the translation", "with the translation of codes from the introduced type of", "without Taxonomy restriction') proteome = session.create_new_user_entity_set( identifier_description_list =seed_list, id_type=options.stype,new_user_entity_set_id=\"proteome\", negative_attribute_restriction_list=[]", "0: method_names = [x for x in method_names if x", "input_method_fd: fields = line.strip().split(\"\\t\") no_methods.append(fields[0]) user_rejection=True print \"Input of rejected", "for x in relationObj.get_attributes_dict()[\"psimi_name\"] ] #print [ x.value for x", "set() relationObj_dict = session.dbAccess.get_external_entities_dict( externalEntityIdsList = eErIDs_list, attribute_list = [],", "multi-fields &> /home/quim/PHD/Projects/BIANA/outputs/BIANA_2020_geneID_seqtax_drugtarget/human_network_biana_2020.log \"\"\" return options def generate_network(options): \"\"\" Generates", "print \"File with seeds is missing or not found\" sys.exit(10)", "'store_true', help = 'Flag to use interactions at least described", "= 'store',default='sif', help = '''Format file of the edge file:\\tsif", "all codes''') parser.add_argument('-trans','--translation_of_nodes_file',dest='translation_file',action = 'store',default='translation_nodes.txt', help = 'File with the", "dbuser=config.get('BIANA', 'user'), dbpassword=config.get('BIANA', 'password'), unification_protocol=config.get('BIANA', 'unification_protocol') ) print \"Continue\" #------------------------------#", "seeds=set() input_seed = open(options.seed,'r') for line in input_seed: fields =", "generate_network_interactomix.py -iseed example/sample1.txt -radius 1 -taxid 9606 -stype uniprotentry -ttype", "to use verbose mode') options=parser.parse_args() \"\"\" Example: python generate_network_interactomix.py -iseed", "Read the seeds seeds=set() input_seed = open(options.seed,'r') for line in", "out_network.close() #---------------------------------------# # OUTPUT NODE AND TRANSLATION FILES # #---------------------------------------#", "interactome, the translation will be done differently if options.radius <=", "return os.path.exists(file) and os.path.isfile(file) def get_seeds_from_file(seed_file): \"\"\" Obtain the seeds", "current_id in uE.get_attribute(attribute_identifier=options.ttype): translate.add(current_id.value.upper()) translation=\"','\".join([\"{0}\".format(x) for x in translate]) out_translation.write(\"{0}\\t'{1}'\\n\".format(protein,translation))", "IDS of SEEDS, defined as \"proteome\", and check missing codes", "is not None: # print \"\\t\".join([ x.value for x in", "level = level, relation_type_list=[\"interaction\"] , relation_attribute_restriction_list = [(\"Method_id\",400)], #relation_attribute_restriction_list =", "set() method_ids = set() source_databases = set() use_method_ids=set() pubmed_ids =", "interactions else: session.create_network( user_entity_set_id = \"proteome\" , level = level,", "hybrid methods (Y2H)') parser.add_argument('-eUSER','--except_user',dest='except_user',action = 'store',default='restricted_methods', help = 'File to", "found\" sys.exit(10) else: level=options.radius seed_list = get_seeds_from_file(options.seed) # If we", "or not found\" sys.exit(10) else: level=options.radius seed_list = get_seeds_from_file(options.seed) #", "least described by yeast-two-hybrid methods (Y2H)') session.create_network( user_entity_set_id = \"proteome\"", "#----------------------# # FIXED PARAMETERS # #----------------------# # Parameters that I", "> 0: info_methods_ids=\";\".join([str(x) for x in use_method_ids]) else: if options.verbose:", "the radius is larger than 0 if restricted_to_seeds or options.radius>0:", "re import biana try: from biana import * except: sys.exit(10)", "interactions:\", len(all_interactions) #--------------------------------------# # FILTER THE SELECTED INTERACTIONS # #--------------------------------------#", "translation of codes (default is accessionnumber) Using \"proteinsequence\" provides with", "described by affinity methods (i.e. Tandem Affinity Purification)') parser.add_argument('-eY2H','--except_Y2H',dest='except_Y2H',action =", "proteome = session.create_new_user_entity_set( identifier_description_list =seed_list, id_type=options.stype,new_user_entity_set_id=\"proteome\", negative_attribute_restriction_list=[] ) else: level=0", "with open(options.except_user) as input_method_fd: for line in input_method_fd: fields =", "the IDS of single nodes that were not previously found", "mode') options=parser.parse_args() \"\"\" Example: python generate_network_interactomix.py -iseed example/sample1.txt -radius 1", "line in input_method_fd: fields = line.strip().split(\"\\t\") use_methods.append(fields[0]) user_selection=True print \"Input", "with seeds is missing or not found\" sys.exit(10) else: level=options.radius", "'multi-fields': out_proteins.write(\"{0}\\t{1:.2f}\\t{2:.2f}\\t{3:.2f}\\n\".format(protein,1.,1.,0.1)) elif options.format == 'netscore': out_proteins.write(\"{0}\\t{1:.2f}\\t{2:.2f}\\t{3:.2f}\\n\".format(protein,1.,1.,0.1)) else: out_proteins.write(\"{0}\\t{1:.2f}\\n\".format(protein,0.1)) out_proteins.close()", "entity uE1_type = uEId_to_type[uE_id1] uE2_type = uEId_to_type[uE_id2] # If type", "= 'store',default='restricted_methods', help = 'File to use interactions described by", "platform)\", epilog = \"@oliva's lab 2019\") parser.add_argument('-iseed','--seeds_input_file',dest='seed',action = 'store', help", "the complementation dictionary complementation_dict = methods_dicts.complementation_dict complementation=set(complementation_dict.keys()) #---------------------------------------# # GET", "for (uE_id1, uE_id2) in all_interactions: #self.dbAccess.get_external_entities_dict( externalEntityIdsList = [external_entity_relation_id] )", "from BIANA. \"\"\" #----------------------# # FIXED PARAMETERS # #----------------------# #", "eErIDs_list, attribute_list = [], relation_attribute_list = [\"method_id\",\"psimi_name\",\"pubmed\"], participant_attribute_list = []", "minimum_number_of_db = 1 seed_score = 0.1 #--------------------------------------# # GET INFORMATION", "Input file (default is input_seed)') parser.add_argument('-radius','--radius_of_subnetwork_around_seeds',dest='radius',default=0,action = 'store',type=int, help =", "= session.create_new_user_entity_set( identifier_description_list =seed_list, id_type=options.stype,new_user_entity_set_id=\"proteome\", negative_attribute_restriction_list=[] ) else: level=0 proteome", "\"@oliva's lab 2019\") parser.add_argument('-iseed','--seeds_input_file',dest='seed',action = 'store', help = 'Seeds Input", "out_network.write(\"{}\\t{}\\n\".format(uE_id1,uE_id2)) else: # If the format is not multi-fields, netscore", "num_methods=0 for current_eErID in eErIDs_list: relationObj = relationObj_dict[current_eErID] if options.verbose:", "of methods selected by the user\" user_rejection=False else: no_methods=[] with", "the user has introduced a file with methods that have", ", relation_attribute_restriction_list = [(\"Method_id\",400)], #relation_attribute_restriction_list = [(\"psimi_name\",\"affinity technology\")], include_relations_last_level =", "= level, relation_type_list=[\"interaction\"] , include_relations_last_level = (not restricted_to_seeds) , use_self_relations", "allseed.add(uE_id) for protein in allseed: if protein not in single", "#---------------------------------------# # Check if the user has introduced a file", "\"proteome\", and check missing codes to be # added for", "two hybrid elif options.restricted_to_Y2H: print ('Using interactions at least described", "source_databases]) else: if options.verbose: print('Skipping interaction it has no source", "#----------------------------------------------------# print (\"Selecting interactions\") # Select interactions that have been", "continue if len(pubmed_ids) > 0: info_pubmed_ids=\";\".join([str(x) for x in pubmed_ids])", "TO STYPE if trans_stype: for current_id in uE.get_attribute(attribute_identifier=options.stype): translate_stype.add(current_id.value.upper()) translation_stype=\"','\".join([\"{0}\".format(x)", "#print method_names, method_ids, source_databases #----------------------# # OUTPUT EDGE FILE #", "example/output/example.proteinsequence.trans -strans example/output/example.seeds.trans -edge example/output/example.edges -node example/output/example.nodes -format raw -rY2H", "\"psimi_name\" in relationObj.get_attributes_dict(): method_names.update([ str(x.value) for x in relationObj.get_attributes_dict()[\"psimi_name\"] ])", "> 0: info_sources=\";\".join([str(x) for x in source_databases]) else: if options.verbose:", "complementation=set(complementation_dict.keys()) #---------------------------------------# # GET METHODS THAT WILL BE FILTERED #", "#------------------------------# # Create network network of expansion if the radius", "with the longest sequence of all codes''') parser.add_argument('-trans','--translation_of_nodes_file',dest='translation_file',action = 'store',default='translation_nodes.txt',", "False) # Select interactions that have been detected at least", "################################# TRANSLATION #################################### out_translation = open(options.translation_file,'w') # TRANSLATION TO 'stype'", "and check missing codes to be # added for translation", "attribute_restriction_list=[], id_type=\"embedded\", new_user_entity_set_id=\"proteome\", negative_attribute_restriction_list=[] ) #----------------------------------------------------# # SELECT THE INTERACTIONS", "line.strip().split(\"\\t\") no_methods.append(fields[0]) user_rejection=True print \"Input of rejected Methods:\",repr(no_methods) #---------------------------# #", "\"\"\" return options def generate_network(options): \"\"\" Generates a protein-protein interaction", "described by affinity methods (i.e. Tandem Affinity Purification)') parser.add_argument('-rY2H','--restricted_to_Y2H',dest='restricted_to_Y2H',action =", "relationObj = relationObj_dict[current_eErID] if options.verbose: print \"Interaction: (\",uE_id1,\",\",uE_id2,\")\" print relationObj", "[(\"taxid\",options.taxid)], attribute_restriction_list=[], id_type=\"embedded\", new_user_entity_set_id=\"proteome\", negative_attribute_restriction_list=[] ) #----------------------------------------------------# # SELECT THE", "method_names = [x for x in method_names if x not", "trans_stype: out_trans_stype.close() #################################################################################### print('Generation of the network done!') return def", "user has introduced a file with methods that must be", "codes]) #out_translation.write(\"%s\\t'%s'\\n\" % (s.upper(),translation)) out_translation.write(\"{0}\\t'{1}'\\n\".format(s.upper(),translation)) else: out_translation.write(\"{0}\\t'Unknown'\\n\".format(s.upper())) out_translation.close() # Output", "[(\"psimi_name\",\"y2h2\")], include_relations_last_level = (not restricted_to_seeds) , use_self_relations = False) #", "for x in method_names if x not in unused_method_names] #", "has no method!') print('Node 1: {}\\tNode 2: {}'.format(uE_id1, uE_id2)) skip_interactions=skip_interactions+1", "= level, relation_type_list=[\"interaction\"] , relation_attribute_restriction_list = [(\"Method_id\",18)], #relation_attribute_restriction_list = [(\"psimi_name\",\"y2h2\")],", "established if use and num_databases >= minimum_number_of_db: use=True else: use=False", "FIXED PARAMETERS # #----------------------# # Parameters that I have decided", "methods (Y2H)') session.create_network( user_entity_set_id = \"proteome\" , level = level,", "#relation_attribute_restriction_list = [(\"psimi_name\",\"y2h2\")], include_relations_last_level = (not restricted_to_seeds) , use_self_relations =", "= \"proteome\" , level = level, relation_type_list=[\"interaction\"] , include_relations_last_level =", "is not protein!') print('Node 1: {}\\tType: {}'.format(uE_id1, uE1_type)) print('Node 2:", "for x in relationObj.get_attributes_dict()[\"psimi_name\"] ]) if \"method_id\" in relationObj.get_attributes_dict(): method_ids.update([", "= len(pubmed_ids) if options.verbose: print \"Methods\",num_methods,info_methods,\"\\tSelected:\",info_methods_ids print \"Databases\",num_databases,info_sources print \"Pubmeds\",num_pubmeds,info_pubmed_ids", "uE.get_attribute(attribute_identifier=options.ttype) if len(str(current_id.value.get_sequence().upper())) == maxlen ] ) #print \"Translation\",protein,translation #print(\"{0}\\t'{1}'\\n\".format(protein,translation))", "TRANSLATION TO 'ttype' out_translation = open(options.translation_file,'w') # TRANSLATION TO 'stype'", "'sif': <node1>\\tscore\\t<node2>\\n 'netscore': <node1>\\t<node2>\\t<score>\\n 'raw': <node1>\\t<node2>\\n 'multi-fields' : <node1>\\t<node2>\\t<sources>\\t<method_ids>\\t<method_names>\\t<pmids>\\n''') parser.add_argument('-rAFF','--restricted_to_TAP',dest='restricted_to_TAP',action", "##### TRANSLATION TO STYPE if trans_stype: for current_id in uE.get_attribute(attribute_identifier=options.stype):", "program path main_path = os.path.abspath(os.path.dirname(__file__)) # Read the config file", "methods_dicts def main(): options = parse_user_arguments() generate_network(options) def parse_user_arguments(*args, **kwds):", "**kwds): parser = argparse.ArgumentParser( description = \"Generate a protein-protein interaction", "use_method_ids.add(m) #print \"Add\", m else: unused_method_names.add(complementation_dict[m]) elif user_rejection: for m", "in single and protein not in nodes: uE = session.get_user_entity(protein)", "for x in translate_stype]) out_trans_stype.write(\"{0}\\t'{1}'\\n\".format(protein,translation_stype)) out_translation.close() if trans_stype: out_trans_stype.close() ####################################################################################", "from BIANA to the selected type for all nodes') parser.add_argument('-strans','--translation_of_seeds_file',dest='translation_seeds_file',action", "print \"No restriction on methods selected by the user\" user_selection=False", "num_pubmeds = len(pubmed_ids) if options.verbose: print \"Methods\",num_methods,info_methods,\"\\tSelected:\",info_methods_ids print \"Databases\",num_databases,info_sources print", "= uEId_to_type[uE_id2] # If type is not protein, we skip", "= session.dbAccess.get_external_entities_dict( externalEntityIdsList = eErIDs_list, attribute_list = [], relation_attribute_list =", "uE_id in proteome.get_unconnected_nodes(): single.add(uE_id) for protein in single: uE =", "TYPE of user entity uE1_type = uEId_to_type[uE_id1] uE2_type = uEId_to_type[uE_id2]", "described by yeast two hybrid methods (Y2H)') parser.add_argument('-rUSER','--restricted_to_user',dest='restricted_to_user',action = 'store',default='restricted_methods',", "'store',default='restricted_methods', help = 'File to use interactions described by the", "source_databases.add(str(session.dbAccess.get_external_database( database_id = relationObj.get_source_database()) )) if options.except_TAP: for m in", "If we have Taxonomy restriction, we add it if options.taxid", "of all codes''') parser.add_argument('-trans','--translation_of_nodes_file',dest='translation_file',action = 'store',default='translation_nodes.txt', help = 'File with", "out_translation.write(\"{0}\\t'Unknown'\\n\".format(s.upper())) out_translation.close() # Output translation file # TRANSLATION TO 'ttype'", "options.format == 'raw': out_network.write(\"{}\\t{}\\n\".format(uE_id1,uE_id2)) else: # If the format is", "\"Num interactions:\", len(all_interactions) #--------------------------------------# # FILTER THE SELECTED INTERACTIONS #", "#--------------------------------------# # GET INFORMATION FROM CONFIG FILE # #--------------------------------------# #", "#----------------------# # Parameters that I have decided to fix restricted_to_seeds", "use_methods=[] with open(options.restricted_to_user) as input_method_fd: for line in input_method_fd: fields", "two hybrid methods (Y2H)') parser.add_argument('-eUSER','--except_user',dest='except_user',action = 'store',default='restricted_methods', help = 'File", "in a radius of connections around the seed proteins. If", "parser.add_argument('-trans','--translation_of_nodes_file',dest='translation_file',action = 'store',default='translation_nodes.txt', help = 'File with the translation of", ", relation_attribute_restriction_list = [(\"Method_id\",18)], #relation_attribute_restriction_list = [(\"psimi_name\",\"y2h2\")], include_relations_last_level = (not", "parser.add_argument('-v','--verbose',dest='verbose',action = 'store_true', help = 'Flag to use verbose mode')", "os, re import biana try: from biana import * except:", "input_method_fd: fields = line.strip().split(\"\\t\") use_methods.append(fields[0]) user_selection=True print \"Input to use", "skip_interactions=skip_interactions+1 continue eErIDs_list = proteome.get_external_entity_relation_ids(uE_id1, uE_id2) method_names = set() method_ids", "user_selection=False else: use_methods=[] with open(options.restricted_to_user) as input_method_fd: for line in", "<node1>\\tscore\\t<node2>\\n 'netscore': <node1>\\t<node2>\\t<score>\\n 'raw': <node1>\\t<node2>\\n 'multi-fields' : <node1>\\t<node2>\\t<sources>\\t<method_ids>\\t<method_names>\\t<pmids>\\n''') parser.add_argument('-rAFF','--restricted_to_TAP',dest='restricted_to_TAP',action =", "by yeast two hybrid methods (Y2H)') parser.add_argument('-eUSER','--except_user',dest='except_user',action = 'store',default='restricted_methods', help", "0: info_pubmed_ids=\";\".join([str(x) for x in pubmed_ids]) else: info_pubmed_ids='-' num_databases=len(source_databases) num_methods=len(use_method_ids)", "print \"Continue\" #------------------------------# # DEFINE A USER ENTITY SET #", "9606 -stype uniprotentry -ttype proteinsequence -trans example/output/example.proteinsequence.trans -strans example/output/example.seeds.trans -edge", "around the seed proteins. If 0, it creates the complete", "if a file exists AND is a file \"\"\" return", "to the selected type for all nodes') parser.add_argument('-strans','--translation_of_seeds_file',dest='translation_seeds_file',action = 'store',default='translation_seeds_to_BIANA_codes.txt',", "out_translation = open(options.translation_file,'w') # TRANSLATION TO 'stype' trans_stype=False if options.stype", "Methods:\",repr(no_methods) #---------------------------# # START A BIANA SESSION # #---------------------------# print", "by the user selected methods') parser.add_argument('-eAFF','--except_TAP',dest='except_TAP',action = 'store_true', help =", ", use_self_relations = False) # Summary of interactions out_network =", "method_ids, source_databases #----------------------# # OUTPUT EDGE FILE # #----------------------# if", "that have to be excluded if not fileExist(options.except_user): print \"No", "= open(options.node,'w') translate={} for protein in nodes: score=seed_score uE =", "skip the interaction if uE1_type != 'protein' or uE2_type !=", "print('Node 2: {}\\tType: {}'.format(uE_id2, uE2_type)) skip_interactions=skip_interactions+1 continue eErIDs_list = proteome.get_external_entity_relation_ids(uE_id1,", "yeast two hybrid methods (Y2H)') parser.add_argument('-eUSER','--except_user',dest='except_user',action = 'store',default='restricted_methods', help =", "user_selection=True print \"Input to use only Methods:\",repr(use_methods) # Check if", "print('Skipping interaction it has no method!') print('Node 1: {}\\tNode 2:", "print(\"Check Proteome %s\"%(repr(options.taxid))) proteome = session.create_new_user_entity_set( identifier_description_list =seed_list, attribute_restriction_list=[(\"taxid\",options.taxid)], id_type=options.stype,new_user_entity_set_id=\"proteome\",", "by affinity methods (i.e. Tandem Affinity Purification)') parser.add_argument('-rY2H','--restricted_to_Y2H',dest='restricted_to_Y2H',action = 'store_true',", "= session.get_user_entity(protein) for current_id in uE.get_attribute(attribute_identifier=options.stype): if current_id.value.lower() in seeds:", "the seeds seeds=set() input_seed = open(options.seed,'r') for line in input_seed:", "LOAD THE DICTIONARIES OF METHODS # #--------------------------------------# # Get the", "fileExist(options.seed): print \"File with seeds is missing or not found\"", "= session.create_new_user_entity_set( identifier_description_list =seed_list, attribute_restriction_list=[(\"taxid\",options.taxid)], id_type=options.stype,new_user_entity_set_id=\"proteome\", negative_attribute_restriction_list=[] ) else: print('Proteome", "no_methods.append(fields[0]) user_rejection=True print \"Input of rejected Methods:\",repr(no_methods) #---------------------------# # START", "Parameters that I have decided to fix restricted_to_seeds = False", "interactions except those described by affinity methods (i.e. Tandem Affinity", "in nodes: uE = session.get_user_entity(protein) translate=set() translate_stype=set() if options.ttype ==", "info_pubmed_ids='-' num_databases=len(source_databases) num_methods=len(use_method_ids) num_pubmeds = len(pubmed_ids) if options.verbose: print \"Methods\",num_methods,info_methods,\"\\tSelected:\",info_methods_ids", "out_proteins.close() # Get the IDS of single nodes that were", "'netscore': out_network.write('\\t{}\\t{}\\t{:.2f}\\n'.format(uE_id1,uE_id2,1.)) elif options.format == 'raw': out_network.write(\"{}\\t{}\\n\".format(uE_id1,uE_id2)) else: # If", "= create_new_session( sessionID=\"biana_session\", dbname=config.get('BIANA', 'database'), dbhost=config.get('BIANA', 'host'), dbuser=config.get('BIANA', 'user'), dbpassword=config.get('BIANA',", "] #print [ x.value for x in relationObj.get_attributes_dict()[\"method_id\"] ] if", "[] ) num_methods=0 for current_eErID in eErIDs_list: relationObj = relationObj_dict[current_eErID]", "# Get the complementation dictionary complementation_dict = methods_dicts.complementation_dict complementation=set(complementation_dict.keys()) #---------------------------------------#", "description = \"Generate a protein-protein interaction network (implemented for Interactomix", "Using \"proteinsequence\" provides with the longest sequence of all codes''')", "edges(default is biana_edges)') parser.add_argument('-node','--node_file',dest='node',action = 'store', default='biana_nodes', help = 'Output", "= 0.1 #--------------------------------------# # GET INFORMATION FROM CONFIG FILE #", "interactions:\", skip_interactions out_network.close() #---------------------------------------# # OUTPUT NODE AND TRANSLATION FILES", "session.dbAccess.get_user_entity_type(config.get('BIANA', 'unification_protocol'), all_uEs) skip_interactions=0 for (uE_id1, uE_id2) in all_interactions: #self.dbAccess.get_external_entities_dict(", "]) if \"method_id\" in relationObj.get_attributes_dict(): method_ids.update([ x.value for x in", "if len(pubmed_ids) > 0: info_pubmed_ids=\";\".join([str(x) for x in pubmed_ids]) else:", "-stype uniprotentry -ttype proteinsequence -trans example/output/example.proteinsequence.trans -strans example/output/example.seeds.trans -edge example/output/example.edges", "file:\\tsif (default), netscore, raw, multi-fields:\\n 'sif': <node1>\\tscore\\t<node2>\\n 'netscore': <node1>\\t<node2>\\t<score>\\n 'raw':", "= [(\"Method_id\",400)], #relation_attribute_restriction_list = [(\"psimi_name\",\"affinity technology\")], include_relations_last_level = (not restricted_to_seeds)", "for current_id in uE.get_attribute(attribute_identifier=options.ttype): if maxlen < len(current_id.value.get_sequence().upper()): maxlen=len(current_id.value.get_sequence().upper()) translation=\",\".join([str(current_id.value.get_sequence().upper())", "= [], relation_attribute_list = [\"method_id\",\"psimi_name\",\"pubmed\"], participant_attribute_list = [] ) num_methods=0", "= 'store',default='translation_seeds_to_BIANA_codes.txt', help = 'File with the translation of codes", "relation_attribute_list = [\"method_id\",\"psimi_name\",\"pubmed\"], participant_attribute_list = [] ) num_methods=0 for current_eErID", "out_translation = open(options.translation_seeds_file,'w') for s in seeds: if s ==", "must be included if not fileExist(options.restricted_to_user): print \"No restriction on", "(\",uE_id1,\",\",uE_id2,\")\" print relationObj #if relationObj.get_attribute(attribute_identifier=\"psimi_name\") is not None: # print", "if x not in unused_method_names] # Remove method names that", "##### TRANSLATION TO 'ttype' for current_id in uE.get_attribute(attribute_identifier=options.ttype): translate.add(current_id.value.upper()) translation=\"','\".join([\"{0}\".format(x)", "the output translation of codes (default is accessionnumber) Using \"proteinsequence\"", "num_databases=len(source_databases) num_methods=len(use_method_ids) num_pubmeds = len(pubmed_ids) if options.verbose: print \"Methods\",num_methods,info_methods,\"\\tSelected:\",info_methods_ids print", "of single nodes that were not previously found in the", "\"\"\" Generates a protein-protein interaction network extracting information from BIANA.", "#----------------------------------------------------# # SELECT THE INTERACTIONS OF THE USER ENTITY SET", "FILTERED # #---------------------------------------# # Check if the user has introduced", "set(use_methods): use_method_ids.add(m) if options.verbose: print \"Not among selected methods \",m", "input_seed.close() # Output node file out_proteins = open(options.node,'w') translate={} for", "options.verbose: print \"Interaction: (\",uE_id1,\",\",uE_id2,\")\" print relationObj #if relationObj.get_attribute(attribute_identifier=\"psimi_name\") is not", "if len(method_names) > 0: method_names = [x for x in", "exists AND is a file \"\"\" return os.path.exists(file) and os.path.isfile(file)", "a network of expansion, the translation will be done differently", "score=seed_score uE = session.get_user_entity(protein) for current_id in uE.get_attribute(attribute_identifier=options.stype): if current_id.value.lower()", "== 'netscore': out_network.write('\\t{}\\t{}\\t{:.2f}\\n'.format(uE_id1,uE_id2,1.)) elif options.format == 'raw': out_network.write(\"{}\\t{}\\n\".format(uE_id1,uE_id2)) else: #", "# Get all the user entity ids from the user", "them to a Python list. The seeds must be separated", "level, relation_type_list=[\"interaction\"] , include_relations_last_level = (not restricted_to_seeds) , use_self_relations =", "parse_user_arguments(*args, **kwds): parser = argparse.ArgumentParser( description = \"Generate a protein-protein", "in single: uE = session.get_user_entity(protein) for current_id in uE.get_attribute(attribute_identifier=options.stype): if", "of SEEDS, defined as \"proteome\", and check missing codes to", "in relationObj.get_attribute(attribute_identifier=\"psimi_name\") ]) #if relationObj.get_attribute(attribute_identifier=\"method_id\") is not None: #print \"\\t\".join([", "help = 'Tax ID (i.e. human=9606 is default if TaxID=0", "attribute_restriction_list=[(\"taxid\",options.taxid)], id_type=options.stype,new_user_entity_set_id=\"proteome\", negative_attribute_restriction_list=[] ) else: print('Proteome without Taxonomy restriction') proteome", "Affinity Purification)') parser.add_argument('-eY2H','--except_Y2H',dest='except_Y2H',action = 'store_true', help = 'Flag to use", "relationObj.get_attributes_dict(): method_names.update([ str(x.value) for x in relationObj.get_attributes_dict()[\"psimi_name\"] ]) if \"method_id\"", "\"\"\" #----------------------# # FIXED PARAMETERS # #----------------------# # Parameters that", "complete interactome''') parser.add_argument('-taxid','--TaxID',dest='taxid',action = 'store',default='9606', help = 'Tax ID (i.e.", "of one of the user entities is not protein!') print('Node", "two hybrid methods (Y2H)') parser.add_argument('-rUSER','--restricted_to_user',dest='restricted_to_user',action = 'store',default='restricted_methods', help = 'File", "'multi-fields' : out_network.write(\"{0}\\t{1}\\t{2}\\t{3}\\t{4}\\t{5}\\n\". format(uE_id1,uE_id2,info_sources,info_methods_ids,info_methods,info_pubmed_ids)) elif options.format == 'netscore': out_network.write('\\t{}\\t{}\\t{:.2f}\\n'.format(uE_id1,uE_id2,1.)) elif", "skip_interactions=0 for (uE_id1, uE_id2) in all_interactions: #self.dbAccess.get_external_entities_dict( externalEntityIdsList = [external_entity_relation_id]", "elif user_selection: for m in method_ids: #print \"Check\",repr(use_methods) if m", "session.create_new_user_entity_set( identifier_description_list =seed_list, id_type=options.stype,new_user_entity_set_id=\"proteome\", negative_attribute_restriction_list=[] ) else: level=0 proteome =", "= 'store',type=int, help = '''Network is built in a radius", "# #----------------------------------------------------# print (\"Selecting interactions\") # Select interactions that have", "all_interactions = proteome.getRelations() print \"Num interactions:\", len(all_interactions) #--------------------------------------# # FILTER", "('Using interactions at least described by affinity methods (i.e. Tandem", "excluded if not fileExist(options.except_user): print \"No rejection of methods selected", "# #------------------------------# # Create network network of expansion if the", "'store',default='translation_nodes.txt', help = 'File with the translation of codes from", "line in input_seed: fields = line.strip().split(\"\\t\") seeds.add(fields[0].lower()) input_seed.close() # Output", "if trans_stype: for current_id in uE.get_attribute(attribute_identifier=options.stype): translate_stype.add(current_id.value.upper()) translation_stype=\"','\".join([\"{0}\".format(x) for x", "user_entity_set_id = \"proteome\" , level = level, relation_type_list=[\"interaction\"] , include_relations_last_level", "print \"Num interactions:\", len(all_interactions) #--------------------------------------# # FILTER THE SELECTED INTERACTIONS", "!= options.ttype: trans_stype = True out_trans_stype = open(options.translation_file+'.'+options.stype+'.trans','w') for protein", "# #--------------------------------------# # Get the program path main_path = os.path.abspath(os.path.dirname(__file__))", "BE FILTERED # #---------------------------------------# # Check if the user has", "'Seeds Input file (default is input_seed)') parser.add_argument('-radius','--radius_of_subnetwork_around_seeds',dest='radius',default=0,action = 'store',type=int, help", "True out_trans_stype = open(options.translation_file+'.'+options.stype+'.trans','w') for protein in nodes: uE =", "Check if the seeds file exists if not fileExist(options.seed): print", "x in relationObj.get_attributes_dict()[\"psimi_name\"] ]) if \"method_id\" in relationObj.get_attributes_dict(): method_ids.update([ x.value", "= 'store_true', help = 'Flag to use interactions at least", "'store',default='translation_seeds_to_BIANA_codes.txt', help = 'File with the translation of codes from", "the complete interactome, the translation will be done differently if", "protein in single: uE = session.get_user_entity(protein) for current_id in uE.get_attribute(attribute_identifier=options.stype):", "else: print('Proteome without Taxonomy restriction') proteome = session.create_new_user_entity_set( identifier_description_list =seed_list,", "'File with the translation of codes from the introduced type", "\"\"\" return os.path.exists(file) and os.path.isfile(file) def get_seeds_from_file(seed_file): \"\"\" Obtain the", "if options.verbose: print('Skipping interaction it has no method!') print('Node 1:", "be excluded if not fileExist(options.except_user): print \"No rejection of methods", "def generate_network(options): \"\"\" Generates a protein-protein interaction network extracting information", "x.value for x in relationObj.get_attributes_dict()[\"method_id\"]]) if \"pubmed\" in relationObj.get_attributes_dict(): pubmed_ids.update([", "proteome = session.create_new_user_entity_set( identifier_description_list = [(\"taxid\",options.taxid)], attribute_restriction_list=[], id_type=\"embedded\", new_user_entity_set_id=\"proteome\", negative_attribute_restriction_list=[]", "to use interactions at least described by yeast two hybrid", "{}\\tNode 2: {}'.format(uE_id1, uE_id2)) skip_interactions=skip_interactions+1 continue if len(method_names) > 0:", "SELECTED INTERACTIONS # #--------------------------------------# nodes=set() # Get all the user", "#------------------------------# # DEFINE A USER ENTITY SET # #------------------------------# #", ">= minimum_number_of_methods: use=True else: use=False # Check if the number", "(i.e. Tandem Affinity Purification)') parser.add_argument('-eY2H','--except_Y2H',dest='except_Y2H',action = 'store_true', help = 'Flag", "affinity=set(affinity_dict.keys()) # Get the complementation dictionary complementation_dict = methods_dicts.complementation_dict complementation=set(complementation_dict.keys())", "larger than 0 if restricted_to_seeds or options.radius>0: # Check if", "Get TYPE of user entity uE1_type = uEId_to_type[uE_id1] uE2_type =", "fields = line.strip().split(\"\\t\") use_methods.append(fields[0]) user_selection=True print \"Input to use only", "# LOAD THE DICTIONARIES OF METHODS # #--------------------------------------# # Get", "done differently elif options.radius > 0: # Read the seeds", "in method_ids: if m not in complementation: use_method_ids.add(m) #print \"Add\",", "parser.add_argument('-rY2H','--restricted_to_Y2H',dest='restricted_to_Y2H',action = 'store_true', help = 'Flag to use interactions at", "-edge example/output/example.edges -node example/output/example.nodes -format raw -rY2H python /home/quim/PHD/Projects/BIANA/scripts/generate_network_interactomix.py -radius", "that I have decided to fix restricted_to_seeds = False minimum_number_of_methods", "for x in method_names]) else: info_methods='-' if len(use_method_ids) > 0:", "been detected at least by affinity technology if options.restricted_to_TAP: print", "#out_translation.write(\"%s\\t'%s'\\n\" % (s.upper(),translation)) out_translation.write(\"{0}\\t'{1}'\\n\".format(s.upper(),translation)) else: out_translation.write(\"{0}\\t'Unknown'\\n\".format(s.upper())) out_translation.close() # Output translation", "user entity uE1_type = uEId_to_type[uE_id1] uE2_type = uEId_to_type[uE_id2] # If", "\"proteome\" , level = level, relation_type_list=[\"interaction\"] , relation_attribute_restriction_list = [(\"Method_id\",18)],", "geneid -format multi-fields &> /home/quim/PHD/Projects/BIANA/outputs/BIANA_2020_geneID_seqtax_drugtarget/human_network_biana_2020.log \"\"\" return options def generate_network(options):", "node file out_proteins = open(options.node,'w') translate={} for protein in nodes:", "import biana try: from biana import * except: sys.exit(10) import", "database_id = relationObj.get_source_database()) )) if options.except_TAP: for m in method_ids:", "for line in input_method_fd: fields = line.strip().split(\"\\t\") use_methods.append(fields[0]) user_selection=True print", "parser.add_argument('-format','--output_format',dest='format',action = 'store',default='sif', help = '''Format file of the edge", "all_uEs = proteome.get_user_entity_ids() # Obtain a dictionary user entity ID", "new lines! \"\"\" seed_set = set() with open(seed_file, 'r') as", "to a Python list. The seeds must be separated by", "of codes from the introduced type of code to BIANA", "wanted a network of expansion, the translation will be done", "help = 'File to reject interactions described by the user", "'store', default='biana_nodes', help = 'Output file with nodes(default is biana_nodes)')", "USER ENTITY SET # #----------------------------------------------------# print (\"Selecting interactions\") # Select", "uEId_to_type[uE_id1] uE2_type = uEId_to_type[uE_id2] # If type is not protein,", "no restriction)') parser.add_argument('-stype','--seed_type',dest='stype',action = 'store',default='geneid', help = 'Type of identifier", "> 0: # Read the seeds seeds=set() input_seed = open(options.seed,'r')", "nodes: uE = session.get_user_entity(protein) for current_id in uE.get_attribute(attribute_identifier=options.stype): if current_id.value.lower()", "'raw': <node1>\\t<node2>\\n 'multi-fields' : <node1>\\t<node2>\\t<sources>\\t<method_ids>\\t<method_names>\\t<pmids>\\n''') parser.add_argument('-rAFF','--restricted_to_TAP',dest='restricted_to_TAP',action = 'store_true', help =", "interactions described by the user selected methods') parser.add_argument('-eAFF','--except_TAP',dest='except_TAP',action = 'store_true',", "#print \"Attribute \",(uE_id1,uE_id2).get_attribute( if options.format == 'multi-fields' : out_network.write(\"{0}\\t{1}\\t{2}\\t{3}\\t{4}\\t{5}\\n\". format(uE_id1,uE_id2,info_sources,info_methods_ids,info_methods,info_pubmed_ids))", "radius is larger than 0 if restricted_to_seeds or options.radius>0: #", "skip_interactions=skip_interactions+1 continue if len(pubmed_ids) > 0: info_pubmed_ids=\";\".join([str(x) for x in", "info_pubmed_ids=\";\".join([str(x) for x in pubmed_ids]) else: info_pubmed_ids='-' num_databases=len(source_databases) num_methods=len(use_method_ids) num_pubmeds", "file exists AND is a file \"\"\" return os.path.exists(file) and", "#print \"\\t\".join([ x.value for x in relationObj.get_attribute(attribute_identifier=\"method_id\") ]) #print relationObj.get_attributes_dict()", "in affinity: use_method_ids.add(m) #print \"Add\", m else: unused_method_names.add(affinity_dict[m]) elif options.except_Y2H:", "else: session.create_network( user_entity_set_id = \"proteome\" , level = level, relation_type_list=[\"interaction\"]", "TRANSLATION #################################### out_translation = open(options.translation_file,'w') # TRANSLATION TO 'stype' trans_stype=False", "trans_stype = True out_trans_stype = open(options.translation_file+'.'+options.stype+'.trans','w') for protein in nodes:", "x in method_names]) else: info_methods='-' if len(use_method_ids) > 0: info_methods_ids=\";\".join([str(x)", "translate.add(current_id.value.upper()) translation=\"','\".join([\"{0}\".format(x) for x in translate]) out_translation.write(\"{0}\\t'{1}'\\n\".format(protein,translation)) ##### TRANSLATION TO", "in no_methods: use_method_ids.add(m) elif user_selection: for m in method_ids: #print", "# OUTPUT EDGE FILE # #----------------------# if use: #print uE_id1,", "in the network single=set() for uE_id in proteome.get_unconnected_nodes(): single.add(uE_id) for", "biana import * except: sys.exit(10) import methods_dictionaries as methods_dicts def", "in eErIDs_list: relationObj = relationObj_dict[current_eErID] if options.verbose: print \"Interaction: (\",uE_id1,\",\",uE_id2,\")\"", "interactions out_network = open(options.edge,'w') all_interactions = proteome.getRelations() print \"Num interactions:\",", "config_file = os.path.join(main_path, 'config.ini') config = ConfigParser.ConfigParser() config.read(config_file) #--------------------------------------# #", "\"\"\" Checks if a file exists AND is a file", "translation of codes from the introduced type of code to", "or raw, the output format is sif out_network.write(\"{}\\t{:.2f}\\t{}\\n\".format(uE_id1,1.,uE_id2)) print \"Num", "translate.setdefault(current_id.value.lower(),[]) translate[current_id.value.lower()].append(protein) ################################# TRANSLATION #################################### out_translation = open(options.translation_seeds_file,'w') for s", "the program path main_path = os.path.abspath(os.path.dirname(__file__)) # Read the config", "translate[current_id.value.lower()].append(protein) ################################# TRANSLATION #################################### out_translation = open(options.translation_seeds_file,'w') for s in", "Methods:\",repr(use_methods) # Check if the user has introduced a file", "must be separated by new lines! \"\"\" seed_set = set()", "len(method_names) > 0: method_names = [x for x in method_names", "else: out_proteins.write(\"{0}\\t{1:.2f}\\n\".format(protein,0.1)) out_proteins.close() ################################# TRANSLATION #################################### out_translation = open(options.translation_file,'w') #", "x in codes]) #out_translation.write(\"%s\\t'%s'\\n\" % (s.upper(),translation)) out_translation.write(\"{0}\\t'{1}'\\n\".format(s.upper(),translation)) else: out_translation.write(\"{0}\\t'Unknown'\\n\".format(s.upper())) out_translation.close()", "example/output/example.nodes -format raw -rY2H python /home/quim/PHD/Projects/BIANA/scripts/generate_network_interactomix.py -radius 0 -taxid 9606", "codes=set(translate[s]) translation=\"','\".join([str(x) for x in codes]) #out_translation.write(\"%s\\t'%s'\\n\" % (s.upper(),translation)) out_translation.write(\"{0}\\t'{1}'\\n\".format(s.upper(),translation))", "methods') parser.add_argument('-eAFF','--except_TAP',dest='except_TAP',action = 'store_true', help = 'Flag to use all", "in input_method_fd: fields = line.strip().split(\"\\t\") use_methods.append(fields[0]) user_selection=True print \"Input to", "input_seed = open(options.seed,'r') for line in input_seed: fields = line.strip().split(\"\\t\")", "a file \"\"\" return os.path.exists(file) and os.path.isfile(file) def get_seeds_from_file(seed_file): \"\"\"", "identifier_description_list =seed_list, attribute_restriction_list=[(\"taxid\",options.taxid)], id_type=options.stype,new_user_entity_set_id=\"proteome\", negative_attribute_restriction_list=[] ) else: print('Proteome without Taxonomy", "print \"Num neglected interactions:\", skip_interactions out_network.close() #---------------------------------------# # OUTPUT NODE", "unused_method_names = set() relationObj_dict = session.dbAccess.get_external_entities_dict( externalEntityIdsList = eErIDs_list, attribute_list", "False) # Summary of interactions out_network = open(options.edge,'w') all_interactions =", "options.except_Y2H: #print \"check Y2H\" for m in method_ids: if m", "we have Taxonomy restriction, we add it if options.taxid !=", "out_proteins.write(\"{0}\\t{1:.2f}\\t{2:.2f}\\t{3:.2f}\\n\".format(protein,1.,1.,score)) else: out_proteins.write(\"{0}\\t{1:.2f}\\n\".format(protein,score)) out_proteins.close() # Get the IDS of single", "'Flag to use verbose mode') options=parser.parse_args() \"\"\" Example: python generate_network_interactomix.py", "method names that were excluded info_methods=\";\".join([str(x) for x in method_names])", "= [(\"psimi_name\",\"y2h2\")], include_relations_last_level = (not restricted_to_seeds) , use_self_relations = False)", "methods (Y2H)') parser.add_argument('-rUSER','--restricted_to_user',dest='restricted_to_user',action = 'store',default='restricted_methods', help = 'File to use", "-trans /home/quim/PHD/Projects/BIANA/outputs/BIANA_2020_geneID_seqtax_drugtarget/human_network_biana_2020_translation.txt -ttype geneid -format multi-fields &> /home/quim/PHD/Projects/BIANA/outputs/BIANA_2020_geneID_seqtax_drugtarget/human_network_biana_2020.log \"\"\" return", "[ x.value for x in relationObj.get_attributes_dict()[\"method_id\"] ] if \"psimi_name\" in", "set 'proteome' all_uEs = proteome.get_user_entity_ids() # Obtain a dictionary user", "for protein in allseed: if protein not in single and", "print ('Using interactions at least described by yeast-two-hybrid methods (Y2H)')", "use_method_ids.add(m) elif user_selection: for m in method_ids: #print \"Check\",repr(use_methods) if", "use_self_relations = False) # Select interactions that have been detected", "by affinity technology if options.restricted_to_TAP: print ('Using interactions at least", "codes from the introduced type of code to BIANA codes')", "seed_score = 0.1 #--------------------------------------# # GET INFORMATION FROM CONFIG FILE", "it if options.taxid != \"0\": print(\"Check Proteome %s\"%(repr(options.taxid))) proteome =", "\"Check\",repr(use_methods) if m in set(use_methods): use_method_ids.add(m) if options.verbose: print \"Not", "len(str(current_id.value.get_sequence().upper())) == maxlen ] ) #print \"Translation\",protein,translation #print(\"{0}\\t'{1}'\\n\".format(protein,translation)) else: #####", "line.strip().split(\"\\t\") seeds.add(fields[0].lower()) input_seed.close() # Output node file out_proteins = open(options.node,'w')", "= [external_entity_relation_id] ) # Get TYPE of user entity uE1_type", "= False) # Summary of interactions out_network = open(options.edge,'w') all_interactions", "help = 'Flag to use verbose mode') options=parser.parse_args() \"\"\" Example:", "seeds file exists if not fileExist(options.seed): print \"File with seeds", "human=9606 is default if TaxID=0 there is no restriction)') parser.add_argument('-stype','--seed_type',dest='stype',action", "file with edges(default is biana_edges)') parser.add_argument('-node','--node_file',dest='node',action = 'store', default='biana_nodes', help", "method_ids: if m not in affinity: use_method_ids.add(m) #print \"Add\", m", "1: {}\\tType: {}'.format(uE_id1, uE1_type)) print('Node 2: {}\\tType: {}'.format(uE_id2, uE2_type)) skip_interactions=skip_interactions+1", "options.verbose: print('Skipping interaction it has no method!') print('Node 1: {}\\tNode", "]) #print relationObj.get_attributes_dict() #print [ x.value for x in relationObj.get_attributes_dict()[\"psimi_name\"]", "None: # print \"\\t\".join([ x.value for x in relationObj.get_attribute(attribute_identifier=\"psimi_name\") ])", "seeds (default is geneid)') parser.add_argument('-ttype','--translation_type',dest='ttype',action = 'store',default='accessionnumber', help = '''Type", "= 'store', default='biana_edges', help = 'Output file with edges(default is", "m in method_ids: if m not in complementation: use_method_ids.add(m) #print", "use=True else: use=False if not use: skip_interactions=skip_interactions+1 #print method_names, method_ids,", "relationObj.get_attribute(attribute_identifier=\"method_id\") ]) #print relationObj.get_attributes_dict() #print [ x.value for x in", "least described by yeast two hybrid methods (Y2H)') parser.add_argument('-rUSER','--restricted_to_user',dest='restricted_to_user',action =", "% (s.upper(),translation)) out_translation.write(\"{0}\\t'{1}'\\n\".format(s.upper(),translation)) else: out_translation.write(\"{0}\\t'Unknown'\\n\".format(s.upper())) out_translation.close() # Output translation file", "def fileExist(file): \"\"\" Checks if a file exists AND is", "# Read the seeds seeds=set() input_seed = open(options.seed,'r') for line", "that have been detected at least by yeast two hybrid", "the user entity set 'proteome' all_uEs = proteome.get_user_entity_ids() # Obtain", "relationObj.get_attributes_dict()[\"psimi_name\"] ] #print [ x.value for x in relationObj.get_attributes_dict()[\"method_id\"] ]", "STYPE if trans_stype: for current_id in uE.get_attribute(attribute_identifier=options.stype): translate_stype.add(current_id.value.upper()) translation_stype=\"','\".join([\"{0}\".format(x) for", "The seeds must be separated by new lines! \"\"\" seed_set", "affinity technology if options.restricted_to_TAP: print ('Using interactions at least described", "is larger than 0 if restricted_to_seeds or options.radius>0: # Check", "relationObj_dict[current_eErID] if options.verbose: print \"Interaction: (\",uE_id1,\",\",uE_id2,\")\" print relationObj #if relationObj.get_attribute(attribute_identifier=\"psimi_name\")", "> 0: method_names = [x for x in method_names if", "as \"proteome\", and check missing codes to be # added", "Generates a protein-protein interaction network extracting information from BIANA. \"\"\"", "= set() use_method_ids=set() pubmed_ids = set() unused_method_names = set() relationObj_dict", "= 'Output file with nodes(default is biana_nodes)') parser.add_argument('-format','--output_format',dest='format',action = 'store',default='sif',", "len(pubmed_ids) > 0: info_pubmed_ids=\";\".join([str(x) for x in pubmed_ids]) else: info_pubmed_ids='-'", "current_id in uE.get_attribute(attribute_identifier=options.stype): translate_stype.add(current_id.value.upper()) translation_stype=\"','\".join([\"{0}\".format(x) for x in translate_stype]) out_trans_stype.write(\"{0}\\t'{1}'\\n\".format(protein,translation_stype))", "use=True else: use=False # Check if the number of database", "open(options.translation_file,'w') # TRANSLATION TO 'stype' trans_stype=False if options.stype != 'proteinsequence'", "if options.verbose: print('Skipping interaction it has no source database!') print('Node", "all IDS of SEEDS, defined as \"proteome\", and check missing", "in uE.get_attribute(attribute_identifier=options.ttype): translate.add(current_id.value.upper()) translation=\"','\".join([\"{0}\".format(x) for x in translate]) out_translation.write(\"{0}\\t'{1}'\\n\".format(protein,translation)) #####", "have to be excluded if not fileExist(options.except_user): print \"No rejection", "added for translation allseed=set() for uE_id in proteome.get_user_entity_ids(): allseed.add(uE_id) for", "'netscore': out_proteins.write(\"{0}\\t{1:.2f}\\t{2:.2f}\\t{3:.2f}\\n\".format(protein,1.,1.,score)) else: out_proteins.write(\"{0}\\t{1:.2f}\\n\".format(protein,score)) out_proteins.close() # Get the IDS of", "yeast-two-hybrid methods (Y2H)') session.create_network( user_entity_set_id = \"proteome\" , level =", "and protein not in nodes: uE = session.get_user_entity(protein) for current_id", "include_relations_last_level = (not restricted_to_seeds) , use_self_relations = False) # Summary", "if m not in no_methods: use_method_ids.add(m) elif user_selection: for m", "else: unused_method_names.add(complementation_dict[m]) elif user_rejection: for m in method_ids: if m", "Taxonomy restriction') proteome = session.create_new_user_entity_set( identifier_description_list =seed_list, id_type=options.stype,new_user_entity_set_id=\"proteome\", negative_attribute_restriction_list=[] )", "0, it creates the complete interactome''') parser.add_argument('-taxid','--TaxID',dest='taxid',action = 'store',default='9606', help", "]) #if relationObj.get_attribute(attribute_identifier=\"method_id\") is not None: #print \"\\t\".join([ x.value for", "(default is accessionnumber) Using \"proteinsequence\" provides with the longest sequence", "'''Format file of the edge file:\\tsif (default), netscore, raw, multi-fields:\\n", "we wanted a network of expansion, the translation will be", "open(options.translation_seeds_file,'w') for s in seeds: if s == '': continue", "be included if not fileExist(options.restricted_to_user): print \"No restriction on methods", "the translation will be done differently elif options.radius > 0:", "method!') print('Node 1: {}\\tNode 2: {}'.format(uE_id1, uE_id2)) skip_interactions=skip_interactions+1 continue if", "example/output/example.seeds.trans -edge example/output/example.edges -node example/output/example.nodes -format raw -rY2H python /home/quim/PHD/Projects/BIANA/scripts/generate_network_interactomix.py", "introduced a file with methods that have to be excluded", "uE.get_attribute(attribute_identifier=options.stype): if current_id.value.lower() in seeds: translate.setdefault(current_id.value.lower(),[]) translate[current_id.value.lower()].append(protein) # Get all", "Affinity Purification)') parser.add_argument('-rY2H','--restricted_to_Y2H',dest='restricted_to_Y2H',action = 'store_true', help = 'Flag to use", "for uE_id in proteome.get_unconnected_nodes(): single.add(uE_id) for protein in single: uE", "by the user\" user_selection=False else: use_methods=[] with open(options.restricted_to_user) as input_method_fd:", "file with methods that have to be excluded if not", "parser.add_argument('-rUSER','--restricted_to_user',dest='restricted_to_user',action = 'store',default='restricted_methods', help = 'File to use interactions described", "list. The seeds must be separated by new lines! \"\"\"", "FILTER THE SELECTED INTERACTIONS # #--------------------------------------# nodes=set() # Get all", "# Select all interactions else: session.create_network( user_entity_set_id = \"proteome\" ,", "all_uEs) skip_interactions=0 for (uE_id1, uE_id2) in all_interactions: #self.dbAccess.get_external_entities_dict( externalEntityIdsList =", "if options.format == 'multi-fields': out_proteins.write(\"{0}\\t{1:.2f}\\t{2:.2f}\\t{3:.2f}\\n\".format(protein,1.,1.,0.1)) elif options.format == 'netscore': out_proteins.write(\"{0}\\t{1:.2f}\\t{2:.2f}\\t{3:.2f}\\n\".format(protein,1.,1.,0.1))", "interactions that have been detected at least by yeast two", "restricted_to_seeds = False minimum_number_of_methods = 1 minimum_number_of_db = 1 seed_score", "# TRANSLATION TO 'ttype' out_translation = open(options.translation_file,'w') # TRANSLATION TO", "for seeds (default is geneid)') parser.add_argument('-ttype','--translation_type',dest='ttype',action = 'store',default='accessionnumber', help =", "line in seed_file_fd: fields = line.strip().split('\\t') seed_set.add(fields[0]) return list(seed_set) if", "described by yeast two hybrid methods (Y2H)') parser.add_argument('-eUSER','--except_user',dest='except_user',action = 'store',default='restricted_methods',", "x in relationObj.get_attributes_dict()[\"method_id\"]]) if \"pubmed\" in relationObj.get_attributes_dict(): pubmed_ids.update([ x.value for", "of codes (default is accessionnumber) Using \"proteinsequence\" provides with the", "(Y2H)') parser.add_argument('-eUSER','--except_user',dest='except_user',action = 'store',default='restricted_methods', help = 'File to reject interactions", "no_methods: use_method_ids.add(m) elif user_selection: for m in method_ids: #print \"Check\",repr(use_methods)", "codes from BIANA to the selected type for all nodes')", "missing or not found\" sys.exit(10) else: level=options.radius seed_list = get_seeds_from_file(options.seed)", "except those described by yeast two hybrid methods (Y2H)') parser.add_argument('-eUSER','--except_user',dest='except_user',action", "of identifier for seeds (default is geneid)') parser.add_argument('-ttype','--translation_type',dest='ttype',action = 'store',default='accessionnumber',", "{}'.format(uE_id1, uE1_type)) print('Node 2: {}\\tType: {}'.format(uE_id2, uE2_type)) skip_interactions=skip_interactions+1 continue eErIDs_list", "proteins. If 0, it creates the complete interactome''') parser.add_argument('-taxid','--TaxID',dest='taxid',action =", "print \"Not among selected methods \",m else: use_method_ids.update(method_ids) if len(source_databases)", "'store', default='biana_edges', help = 'Output file with edges(default is biana_edges)')", "else: out_proteins.write(\"{0}\\t{1:.2f}\\n\".format(protein,score)) out_proteins.close() # Get the IDS of single nodes", "nodes(default is biana_nodes)') parser.add_argument('-format','--output_format',dest='format',action = 'store',default='sif', help = '''Format file", "\"Input to use only Methods:\",repr(use_methods) # Check if the user", "if options.ttype == \"proteinsequence\": maxlen=0; for current_id in uE.get_attribute(attribute_identifier=options.ttype): if", "= set() with open(seed_file, 'r') as seed_file_fd: for line in", "in relationObj.get_attributes_dict()[\"psimi_name\"] ]) if \"method_id\" in relationObj.get_attributes_dict(): method_ids.update([ x.value for", "entity ids from the user entity set 'proteome' all_uEs =", "print('Proteome without Taxonomy restriction') proteome = session.create_new_user_entity_set( identifier_description_list =seed_list, id_type=options.stype,new_user_entity_set_id=\"proteome\",", "use verbose mode') options=parser.parse_args() \"\"\" Example: python generate_network_interactomix.py -iseed example/sample1.txt", "-rY2H python /home/quim/PHD/Projects/BIANA/scripts/generate_network_interactomix.py -radius 0 -taxid 9606 -edge /home/quim/PHD/Projects/BIANA/outputs/BIANA_2020_geneID_seqtax_drugtarget/human_network_biana_2020.txt -node", "= session.dbAccess.get_user_entity_type(config.get('BIANA', 'unification_protocol'), all_uEs) skip_interactions=0 for (uE_id1, uE_id2) in all_interactions:", "ID => type uEId_to_type = session.dbAccess.get_user_entity_type(config.get('BIANA', 'unification_protocol'), all_uEs) skip_interactions=0 for", "previously found in the network single=set() for uE_id in proteome.get_unconnected_nodes():", "# OUTPUT NODE AND TRANSLATION FILES # #---------------------------------------# # If", "network done!') return def fileExist(file): \"\"\" Checks if a file", "SEEDS, defined as \"proteome\", and check missing codes to be", "allseed=set() for uE_id in proteome.get_user_entity_ids(): allseed.add(uE_id) for protein in allseed:", "USER ENTITY SET # #------------------------------# # Create network network of", "#----------------------# # OUTPUT EDGE FILE # #----------------------# if use: #print", "len(str(current_id.value.get_sequence().upper())) == maxlen ] ) #print \"Translation\",protein,translation #print(\"{0}\\t'{1}'\\n\".format(protein,translation)) else: for", "/home/quim/PHD/Projects/BIANA/outputs/BIANA_2020_geneID_seqtax_drugtarget/human_network_biana_2020.log \"\"\" return options def generate_network(options): \"\"\" Generates a protein-protein", "type for all nodes') parser.add_argument('-strans','--translation_of_seeds_file',dest='translation_seeds_file',action = 'store',default='translation_seeds_to_BIANA_codes.txt', help = 'File", "the edge file:\\tsif (default), netscore, raw, multi-fields:\\n 'sif': <node1>\\tscore\\t<node2>\\n 'netscore':", "-taxid 9606 -stype uniprotentry -ttype proteinsequence -trans example/output/example.proteinsequence.trans -strans example/output/example.seeds.trans", "translate: codes=set(translate[s]) translation=\"','\".join([str(x) for x in codes]) #out_translation.write(\"%s\\t'%s'\\n\" % (s.upper(),translation))", "translate=set() translate_stype=set() if options.ttype == \"proteinsequence\": maxlen=0; for current_id in", "uE1_type != 'protein' or uE2_type != 'protein': if options.verbose: print('Skipping", ", level = level, relation_type_list=[\"interaction\"] , relation_attribute_restriction_list = [(\"Method_id\",400)], #relation_attribute_restriction_list", "for Interactomix platform)\", epilog = \"@oliva's lab 2019\") parser.add_argument('-iseed','--seeds_input_file',dest='seed',action =", "relationObj.get_attributes_dict()[\"method_id\"] ] if \"psimi_name\" in relationObj.get_attributes_dict(): method_names.update([ str(x.value) for x", "x in use_method_ids]) else: if options.verbose: print('Skipping interaction it has", "it has no source database!') print('Node 1: {}\\tNode 2: {}'.format(uE_id1,", "the network done!') return def fileExist(file): \"\"\" Checks if a", "if m not in affinity: use_method_ids.add(m) #print \"Add\", m else:", "the user entities is not protein!') print('Node 1: {}\\tType: {}'.format(uE_id1,", "'unification_protocol') ) print \"Continue\" #------------------------------# # DEFINE A USER ENTITY", "current_id in uE.get_attribute(attribute_identifier=options.ttype): if maxlen < len(current_id.value.get_sequence().upper()): maxlen=len(current_id.value.get_sequence().upper()) translation=\",\".join([str(current_id.value.get_sequence().upper()) for", "fix restricted_to_seeds = False minimum_number_of_methods = 1 minimum_number_of_db = 1", "'ttype' out_translation = open(options.translation_file,'w') # TRANSLATION TO 'stype' trans_stype=False if", "output format is sif out_network.write(\"{}\\t{:.2f}\\t{}\\n\".format(uE_id1,1.,uE_id2)) print \"Num neglected interactions:\", skip_interactions", "#if relationObj.get_attribute(attribute_identifier=\"method_id\") is not None: #print \"\\t\".join([ x.value for x", "# Output node file out_proteins = open(options.node,'w') for protein in", "#self.dbAccess.get_external_entities_dict( externalEntityIdsList = [external_entity_relation_id] ) # Get TYPE of user", "in translate_stype]) out_trans_stype.write(\"{0}\\t'{1}'\\n\".format(protein,translation_stype)) out_translation.close() if trans_stype: out_trans_stype.close() #################################################################################### # If", "(not restricted_to_seeds) , use_self_relations = False) # Summary of interactions", "options.restricted_to_TAP: print ('Using interactions at least described by affinity methods", "not None: #print \"\\t\".join([ x.value for x in relationObj.get_attribute(attribute_identifier=\"method_id\") ])", "\"\\t\".join([ x.value for x in relationObj.get_attribute(attribute_identifier=\"method_id\") ]) #print relationObj.get_attributes_dict() #print", "interactions described by the user selected methods') parser.add_argument('-v','--verbose',dest='verbose',action = 'store_true',", "session.get_user_entity(protein) for current_id in uE.get_attribute(attribute_identifier=options.stype): if current_id.value.lower() in seeds: translate.setdefault(current_id.value.lower(),[])", "out_proteins.write(\"{0}\\t{1:.2f}\\t{2:.2f}\\t{3:.2f}\\n\".format(protein,1.,1.,0.1)) elif options.format == 'netscore': out_proteins.write(\"{0}\\t{1:.2f}\\t{2:.2f}\\t{3:.2f}\\n\".format(protein,1.,1.,0.1)) else: out_proteins.write(\"{0}\\t{1:.2f}\\n\".format(protein,0.1)) out_proteins.close() #################################", "# Read the config file config_file = os.path.join(main_path, 'config.ini') config", "== 'netscore': out_proteins.write(\"{0}\\t{1:.2f}\\t{2:.2f}\\t{3:.2f}\\n\".format(protein,1.,1.,0.1)) else: out_proteins.write(\"{0}\\t{1:.2f}\\n\".format(protein,0.1)) out_proteins.close() ################################# TRANSLATION #################################### out_translation", "file out_proteins = open(options.node,'w') translate={} for protein in nodes: score=seed_score", "user entities is not protein!') print('Node 1: {}\\tType: {}'.format(uE_id1, uE1_type))", "interactions\") # Select interactions that have been detected at least", "were excluded info_methods=\";\".join([str(x) for x in method_names]) else: info_methods='-' if", "and options.stype != options.ttype: trans_stype = True out_trans_stype = open(options.translation_file+'.'+options.stype+'.trans','w')", "in translate]) out_translation.write(\"{0}\\t'{1}'\\n\".format(protein,translation)) ##### TRANSLATION TO STYPE if trans_stype: for", "generate_network(options): \"\"\" Generates a protein-protein interaction network extracting information from", "to BIANA codes') parser.add_argument('-edge','--edge_file',dest='edge',action = 'store', default='biana_edges', help = 'Output", "1 -taxid 9606 -stype uniprotentry -ttype proteinsequence -trans example/output/example.proteinsequence.trans -strans", "selected by the user\" user_rejection=False else: no_methods=[] with open(options.except_user) as", "{}\\tType: {}'.format(uE_id2, uE2_type)) skip_interactions=skip_interactions+1 continue eErIDs_list = proteome.get_external_entity_relation_ids(uE_id1, uE_id2) method_names", "by the user selected methods') parser.add_argument('-v','--verbose',dest='verbose',action = 'store_true', help =", "translation=\",\".join([str(current_id.value.get_sequence().upper()) for current_id in uE.get_attribute(attribute_identifier=options.ttype) if len(str(current_id.value.get_sequence().upper())) == maxlen ]", "by new lines! \"\"\" seed_set = set() with open(seed_file, 'r')", "seed proteins. If 0, it creates the complete interactome''') parser.add_argument('-taxid','--TaxID',dest='taxid',action", "translation will be done differently if options.radius <= 0: #", "# TRANSLATION TO 'stype' trans_stype=False if options.stype != 'proteinsequence' and", "#----------------------# if use: #print uE_id1, uE_id/2 nodes.add(uE_id1) nodes.add(uE_id2) #print \"Attribute", "= uEId_to_type[uE_id1] uE2_type = uEId_to_type[uE_id2] # If type is not", "seeds seeds=set() input_seed = open(options.seed,'r') for line in input_seed: fields", "else: info_pubmed_ids='-' num_databases=len(source_databases) num_methods=len(use_method_ids) num_pubmeds = len(pubmed_ids) if options.verbose: print", "no_methods=[] with open(options.except_user) as input_method_fd: for line in input_method_fd: fields", "(\"Selecting interactions\") # Select interactions that have been detected at", "# Remove method names that were excluded info_methods=\";\".join([str(x) for x", "elif user_rejection: for m in method_ids: if m not in", "{}\\tNode 2: {}'.format(uE_id1, uE_id2)) skip_interactions=skip_interactions+1 continue if len(pubmed_ids) > 0:", "#if relationObj.get_attribute(attribute_identifier=\"psimi_name\") is not None: # print \"\\t\".join([ x.value for", "'unification_protocol'), all_uEs) skip_interactions=0 for (uE_id1, uE_id2) in all_interactions: #self.dbAccess.get_external_entities_dict( externalEntityIdsList", "'Flag to use all interactions except those described by yeast", "uEId_to_type[uE_id2] # If type is not protein, we skip the", "seed_list = get_seeds_from_file(options.seed) # If we have Taxonomy restriction, we", "single and protein not in nodes: uE = session.get_user_entity(protein) for", "names that were excluded info_methods=\";\".join([str(x) for x in method_names]) else:", "out_proteins.write(\"{0}\\t{1:.2f}\\n\".format(protein,score)) out_proteins.close() # Get the IDS of single nodes that", "out_proteins.write(\"{0}\\t{1:.2f}\\n\".format(protein,0.1)) out_proteins.close() ################################# TRANSLATION #################################### out_translation = open(options.translation_file,'w') # TRANSLATION", "False minimum_number_of_methods = 1 minimum_number_of_db = 1 seed_score = 0.1", "raw, the output format is sif out_network.write(\"{}\\t{:.2f}\\t{}\\n\".format(uE_id1,1.,uE_id2)) print \"Num neglected", "# Check if the user has introduced a file with", "have Taxonomy restriction, we add it if options.taxid != \"0\":", "AND is a file \"\"\" return os.path.exists(file) and os.path.isfile(file) def", "print('Node 1: {}\\tNode 2: {}'.format(uE_id1, uE_id2)) skip_interactions=skip_interactions+1 continue if len(pubmed_ids)", "help = '''Type of identifier for the output translation of", "seed_file_fd: for line in seed_file_fd: fields = line.strip().split('\\t') seed_set.add(fields[0]) return", "== maxlen ] ) #print \"Translation\",protein,translation #print(\"{0}\\t'{1}'\\n\".format(protein,translation)) else: for current_id", "TO 'stype' trans_stype=False if options.stype != 'proteinsequence' and options.stype !=", "is geneid)') parser.add_argument('-ttype','--translation_type',dest='ttype',action = 'store',default='accessionnumber', help = '''Type of identifier", "DICTIONARIES OF METHODS # #--------------------------------------# # Get the affinity dictionary", "by yeast-two-hybrid methods (Y2H)') session.create_network( user_entity_set_id = \"proteome\" , level", "else: ##### TRANSLATION TO 'ttype' for current_id in uE.get_attribute(attribute_identifier=options.ttype): translate.add(current_id.value.upper())", "\"\"\" Example: python generate_network_interactomix.py -iseed example/sample1.txt -radius 1 -taxid 9606", "if options.verbose: print \"Methods\",num_methods,info_methods,\"\\tSelected:\",info_methods_ids print \"Databases\",num_databases,info_sources print \"Pubmeds\",num_pubmeds,info_pubmed_ids # Check", "= set() source_databases = set() use_method_ids=set() pubmed_ids = set() unused_method_names", "for all nodes') parser.add_argument('-strans','--translation_of_seeds_file',dest='translation_seeds_file',action = 'store',default='translation_seeds_to_BIANA_codes.txt', help = 'File with", "methods selected by the user\" user_rejection=False else: no_methods=[] with open(options.except_user)", "if \"pubmed\" in relationObj.get_attributes_dict(): pubmed_ids.update([ x.value for x in relationObj.get_attributes_dict()[\"pubmed\"]])", "a protein-protein interaction network extracting information from BIANA. \"\"\" #----------------------#", "METHODS THAT WILL BE FILTERED # #---------------------------------------# # Check if", "#---------------------------------------# # GET METHODS THAT WILL BE FILTERED # #---------------------------------------#", "the config file config_file = os.path.join(main_path, 'config.ini') config = ConfigParser.ConfigParser()", "m not in affinity: use_method_ids.add(m) #print \"Add\", m else: unused_method_names.add(affinity_dict[m])", "options.radius > 0: # Read the seeds seeds=set() input_seed =", "{}'.format(uE_id2, uE2_type)) skip_interactions=skip_interactions+1 continue eErIDs_list = proteome.get_external_entity_relation_ids(uE_id1, uE_id2) method_names =", "single nodes that were not previously found in the network", "1: {}\\tNode 2: {}'.format(uE_id1, uE_id2)) skip_interactions=skip_interactions+1 continue if len(method_names) >", "uE_id1, uE_id/2 nodes.add(uE_id1) nodes.add(uE_id2) #print \"Attribute \",(uE_id1,uE_id2).get_attribute( if options.format ==", "help = 'File to use interactions described by the user", "m in method_ids: if m not in no_methods: use_method_ids.add(m) elif", "file \"\"\" return os.path.exists(file) and os.path.isfile(file) def get_seeds_from_file(seed_file): \"\"\" Obtain", "len(all_interactions) #--------------------------------------# # FILTER THE SELECTED INTERACTIONS # #--------------------------------------# nodes=set()", "options.verbose: print('Skipping interaction it has no source database!') print('Node 1:", "by affinity methods (i.e. Tandem Affinity Purification)') session.create_network( user_entity_set_id =", "-ttype proteinsequence -trans example/output/example.proteinsequence.trans -strans example/output/example.seeds.trans -edge example/output/example.edges -node example/output/example.nodes", "= False) # Select all interactions else: session.create_network( user_entity_set_id =", "participant_attribute_list = [] ) num_methods=0 for current_eErID in eErIDs_list: relationObj", "affinity dictionary affinity_dict = methods_dicts.affinity_dict affinity=set(affinity_dict.keys()) # Get the complementation", "= 1 minimum_number_of_db = 1 seed_score = 0.1 #--------------------------------------# #", "entities is not protein!') print('Node 1: {}\\tType: {}'.format(uE_id1, uE1_type)) print('Node", "dbpassword=config.get('BIANA', 'password'), unification_protocol=config.get('BIANA', 'unification_protocol') ) print \"Continue\" #------------------------------# # DEFINE", "else: out_translation.write(\"{0}\\t'Unknown'\\n\".format(s.upper())) out_translation.close() # Output translation file # TRANSLATION TO", "= line.strip().split('\\t') seed_set.add(fields[0]) return list(seed_set) if __name__ == \"__main__\": main()", "for x in codes]) #out_translation.write(\"%s\\t'%s'\\n\" % (s.upper(),translation)) out_translation.write(\"{0}\\t'{1}'\\n\".format(s.upper(),translation)) else: out_translation.write(\"{0}\\t'Unknown'\\n\".format(s.upper()))", "'Tax ID (i.e. human=9606 is default if TaxID=0 there is", "Get all IDS of SEEDS, defined as \"proteome\", and check", "# Select interactions that have been detected at least by", "# If we wanted the complete interactome, the translation will", "selected by the user\" user_selection=False else: use_methods=[] with open(options.restricted_to_user) as", "relationObj.get_attributes_dict() #print [ x.value for x in relationObj.get_attributes_dict()[\"psimi_name\"] ] #print" ]
[ "You may also append additional operations to the `operations` list", "config module: from kf_ingest_packages.common.extract_configs.s3_object_info import * source_data_url = 'file://../data/kf-seq-data-bcm-chung-s3-objects.tsv' operations.append(", "for object from S3 bucket and key \"\"\" return f's3://{row[\"Bucket\"]}/{row[\"Key\"]}'", "GENOMIC_FILE.FORMAT.GVCF, \"g.vcf.gz.tbi\": GENOMIC_FILE.FORMAT.TBI, \"vcf.gz\": GENOMIC_FILE.FORMAT.VCF, \"vcf\": GENOMIC_FILE.FORMAT.VCF, \"vcf.gz.tbi\": GENOMIC_FILE.FORMAT.TBI, \"peddy.html\":", "key \"\"\" return f's3://{row[\"Bucket\"]}/{row[\"Key\"]}' def file_format(x): \"\"\" Get genomic file", "type by looking up file format in DATA_TYPES. However, if", "( 'https://localhost:5002/download/study/SD_ME0WME0W/' 'file/SF_Y1JMXTTS/version/FV_4RYEMD71' ) do_after_read = filter_df_by_file_ext def s3_url(row): \"\"\"", "in FILE_EXT_FORMAT_MAP.keys \"\"\" df[CONCEPT.GENOMIC_FILE.FILE_FORMAT] = df[\"Key\"].apply( lambda x: file_format(x) )", "To use it, you must import it in another extract", "x: file_format(x) ) return df[df[CONCEPT.GENOMIC_FILE.FILE_FORMAT].notnull()] source_data_url = ( 'https://localhost:5002/download/study/SD_ME0WME0W/' 'file/SF_Y1JMXTTS/version/FV_4RYEMD71'", "import GENOMIC_FILE from kf_lib_data_ingest.common.concept_schema import CONCEPT from kf_lib_data_ingest.etl.extract.operations import (", "m=lambda row: s3_url(row)), row_map( out_col=CONCEPT.GENOMIC_FILE.URL_LIST, m=lambda row: [s3_url(row)] ), value_map(", "override at least the `source_data_url`. You may also append additional", "type lookup. \"\"\" ext = file_ext(x) if \"tbi\" in ext:", "), constant_map( out_col=CONCEPT.GENOMIC_FILE.AVAILABILITY, m=constants.GENOMIC_FILE.AVAILABILITY.IMMEDIATE, ), keep_map( in_col=CONCEPT.GENOMIC_FILE.FILE_FORMAT, out_col=CONCEPT.GENOMIC_FILE.FILE_FORMAT, ), value_map(", "of those in FILE_EXT_FORMAT_MAP.keys \"\"\" df[CONCEPT.GENOMIC_FILE.FILE_FORMAT] = df[\"Key\"].apply( lambda x:", "m=constants.GENOMIC_FILE.AVAILABILITY.IMMEDIATE, ), keep_map( in_col=CONCEPT.GENOMIC_FILE.FILE_FORMAT, out_col=CONCEPT.GENOMIC_FILE.FILE_FORMAT, ), value_map( in_col=\"Key\", out_col=CONCEPT.GENOMIC_FILE.DATA_TYPE, m=lambda", "genomic file format by looking genomic file ext up in", "intended for S3 object manifests produced by TBD. To use", "ext up in FILE_EXT_FORMAT_MAP dict \"\"\" # File format return", "dict \"\"\" # File format return FILE_EXT_FORMAT_MAP.get(file_ext(x)) def data_type(x): \"\"\"", "if x.endswith(file_ext) ] if matches: file_ext = max(matches, key=len) else:", "DATA_TYPES.get(file_format(x)) return data_type operations = [ row_map(out_col=CONCEPT.GENOMIC_FILE.ID, m=lambda row: s3_url(row)),", "extension has `tbi` in it, then use the file extension", "format in DATA_TYPES. However, if the file's extension has `tbi`", "you could have the following in your extract config module:", "\"vcf.gz\": GENOMIC_FILE.FORMAT.VCF, \"vcf\": GENOMIC_FILE.FORMAT.VCF, \"vcf.gz.tbi\": GENOMIC_FILE.FORMAT.TBI, \"peddy.html\": \"html\", } DATA_TYPES", "it, you must import it in another extract config and", "from kf_ingest_packages.common.extract_configs.s3_object_info import * source_data_url = 'file://../data/kf-seq-data-bcm-chung-s3-objects.tsv' operations.append( value_map( in_col='Key',", "value_map, constant_map, ) def file_ext(x): \"\"\" Get genomic file extension", "\"\"\" matches = [ file_ext for file_ext in FILE_EXT_FORMAT_MAP if", "GENOMIC_FILE.FORMAT.VCF: \"Variant Calls\", GENOMIC_FILE.FORMAT.GVCF: \"gVCF\", \"g.vcf.gz.tbi\": \"gVCF Index\", \"vcf.gz.tbi\": \"Variant", "S3 bucket and key \"\"\" return f's3://{row[\"Bucket\"]}/{row[\"Key\"]}' def file_format(x): \"\"\"", "= DATA_TYPES.get(file_format(x)) return data_type operations = [ row_map(out_col=CONCEPT.GENOMIC_FILE.ID, m=lambda row:", "= [ file_ext for file_ext in FILE_EXT_FORMAT_MAP if x.endswith(file_ext) ]", "and key \"\"\" return f's3://{row[\"Bucket\"]}/{row[\"Key\"]}' def file_format(x): \"\"\" Get genomic", "looking genomic file ext up in FILE_EXT_FORMAT_MAP dict \"\"\" #", "key=len) else: file_ext = None return file_ext FILE_EXT_FORMAT_MAP = {", "= df[\"Key\"].apply( lambda x: file_format(x) ) return df[df[CONCEPT.GENOMIC_FILE.FILE_FORMAT].notnull()] source_data_url =", "= DATA_TYPES.get(ext) else: data_type = DATA_TYPES.get(file_format(x)) return data_type operations =", "GENOMIC_FILE.FORMAT.FASTQ, \"bam\": GENOMIC_FILE.FORMAT.BAM, \"hgv.bam\": GENOMIC_FILE.FORMAT.BAM, \"cram\": GENOMIC_FILE.FORMAT.CRAM, \"bam.bai\": GENOMIC_FILE.FORMAT.BAI, \"bai\":", "extract config and override at least the `source_data_url`. You may", "keep_map, row_map, value_map, constant_map, ) def file_ext(x): \"\"\" Get genomic", "for S3 object manifests produced by TBD. To use it,", "\"\"\" return f's3://{row[\"Bucket\"]}/{row[\"Key\"]}' def file_format(x): \"\"\" Get genomic file format", "extract config module: from kf_ingest_packages.common.extract_configs.s3_object_info import * source_data_url = 'file://../data/kf-seq-data-bcm-chung-s3-objects.tsv'", "out_col=CONCEPT.BIOSPECIMEN.ID, m=lambda x: x ) ) \"\"\" import os from", "Index\", \"html\": \"Other\", } def filter_df_by_file_ext(df): \"\"\" Only keep rows", "\"Variant Calls Index\", \"html\": \"Other\", } def filter_df_by_file_ext(df): \"\"\" Only", "the file's extension has `tbi` in it, then use the", "keep_map(in_col=\"Size\", out_col=CONCEPT.GENOMIC_FILE.SIZE), value_map( in_col=\"ETag\", out_col=CONCEPT.GENOMIC_FILE.HASH_DICT, m=lambda x: {constants.FILE.HASH.S3_ETAG.lower(): x.replace('\"', \"\")},", "bucket and key \"\"\" return f's3://{row[\"Bucket\"]}/{row[\"Key\"]}' def file_format(x): \"\"\" Get", "GENOMIC_FILE.FORMAT.FASTQ, \"fq.gz\": GENOMIC_FILE.FORMAT.FASTQ, \"fastq.gz\": GENOMIC_FILE.FORMAT.FASTQ, \"bam\": GENOMIC_FILE.FORMAT.BAM, \"hgv.bam\": GENOMIC_FILE.FORMAT.BAM, \"cram\":", "you must import it in another extract config and override", "config and override at least the `source_data_url`. You may also", "out_col=CONCEPT.GENOMIC_FILE.FILE_NAME, m=lambda x: os.path.split(x)[-1], ), keep_map(in_col=\"Size\", out_col=CONCEPT.GENOMIC_FILE.SIZE), value_map( in_col=\"ETag\", out_col=CONCEPT.GENOMIC_FILE.HASH_DICT,", "row_map, value_map, constant_map, ) def file_ext(x): \"\"\" Get genomic file", "x ) ) \"\"\" import os from kf_lib_data_ingest.common import constants", "out_col=CONCEPT.GENOMIC_FILE.HASH_DICT, m=lambda x: {constants.FILE.HASH.S3_ETAG.lower(): x.replace('\"', \"\")}, ), constant_map( out_col=CONCEPT.GENOMIC_FILE.AVAILABILITY, m=constants.GENOMIC_FILE.AVAILABILITY.IMMEDIATE,", "if the file's extension has `tbi` in it, then use", "Reads Index\", GENOMIC_FILE.FORMAT.CRAI: \"Aligned Reads Index\", GENOMIC_FILE.FORMAT.VCF: \"Variant Calls\", GENOMIC_FILE.FORMAT.GVCF:", "\"bai\": GENOMIC_FILE.FORMAT.BAI, \"cram.crai\": GENOMIC_FILE.FORMAT.CRAI, \"crai\": GENOMIC_FILE.FORMAT.CRAI, \"g.vcf.gz\": GENOMIC_FILE.FORMAT.GVCF, \"g.vcf.gz.tbi\": GENOMIC_FILE.FORMAT.TBI,", "def data_type(x): \"\"\" Get genomic file data type by looking", "operations = [ row_map(out_col=CONCEPT.GENOMIC_FILE.ID, m=lambda row: s3_url(row)), row_map( out_col=CONCEPT.GENOMIC_FILE.URL_LIST, m=lambda", "def s3_url(row): \"\"\" Create S3 URL for object from S3", "\"fq\": GENOMIC_FILE.FORMAT.FASTQ, \"fastq\": GENOMIC_FILE.FORMAT.FASTQ, \"fq.gz\": GENOMIC_FILE.FORMAT.FASTQ, \"fastq.gz\": GENOMIC_FILE.FORMAT.FASTQ, \"bam\": GENOMIC_FILE.FORMAT.BAM,", "import ( keep_map, row_map, value_map, constant_map, ) def file_ext(x): \"\"\"", "= [ row_map(out_col=CONCEPT.GENOMIC_FILE.ID, m=lambda row: s3_url(row)), row_map( out_col=CONCEPT.GENOMIC_FILE.URL_LIST, m=lambda row:", "\"g.vcf.gz\": GENOMIC_FILE.FORMAT.GVCF, \"g.vcf.gz.tbi\": GENOMIC_FILE.FORMAT.TBI, \"vcf.gz\": GENOMIC_FILE.FORMAT.VCF, \"vcf\": GENOMIC_FILE.FORMAT.VCF, \"vcf.gz.tbi\": GENOMIC_FILE.FORMAT.TBI,", "in_col='Key', out_col=CONCEPT.BIOSPECIMEN.ID, m=lambda x: x ) ) \"\"\" import os", "row: s3_url(row)), row_map( out_col=CONCEPT.GENOMIC_FILE.URL_LIST, m=lambda row: [s3_url(row)] ), value_map( in_col=\"Key\",", "file_ext(x) if \"tbi\" in ext: data_type = DATA_TYPES.get(ext) else: data_type", "= max(matches, key=len) else: file_ext = None return file_ext FILE_EXT_FORMAT_MAP", "out_col=CONCEPT.GENOMIC_FILE.AVAILABILITY, m=constants.GENOMIC_FILE.AVAILABILITY.IMMEDIATE, ), keep_map( in_col=CONCEPT.GENOMIC_FILE.FILE_FORMAT, out_col=CONCEPT.GENOMIC_FILE.FILE_FORMAT, ), value_map( in_col=\"Key\", out_col=CONCEPT.GENOMIC_FILE.DATA_TYPE,", "\"\"\" Only keep rows where file extension is one of", "file ext up in FILE_EXT_FORMAT_MAP dict \"\"\" # File format", "data_type(x): \"\"\" Get genomic file data type by looking up", "= file_ext(x) if \"tbi\" in ext: data_type = DATA_TYPES.get(ext) else:", "operations.append( value_map( in_col='Key', out_col=CONCEPT.BIOSPECIMEN.ID, m=lambda x: x ) ) \"\"\"", "\"html\": \"Other\", } def filter_df_by_file_ext(df): \"\"\" Only keep rows where", "GENOMIC_FILE from kf_lib_data_ingest.common.concept_schema import CONCEPT from kf_lib_data_ingest.etl.extract.operations import ( keep_map,", "DATA_TYPES.get(ext) else: data_type = DATA_TYPES.get(file_format(x)) return data_type operations = [", "`operations` list as well. For example you could have the", ") \"\"\" import os from kf_lib_data_ingest.common import constants from kf_lib_data_ingest.common.constants", "config intended for S3 object manifests produced by TBD. To", "constant_map, ) def file_ext(x): \"\"\" Get genomic file extension \"\"\"", "m=lambda row: [s3_url(row)] ), value_map( in_col=\"Key\", out_col=CONCEPT.GENOMIC_FILE.FILE_NAME, m=lambda x: os.path.split(x)[-1],", "file_ext(x): \"\"\" Get genomic file extension \"\"\" matches = [", "out_col=CONCEPT.GENOMIC_FILE.FILE_FORMAT, ), value_map( in_col=\"Key\", out_col=CONCEPT.GENOMIC_FILE.DATA_TYPE, m=lambda x: data_type(x), ), ]", "file_ext = max(matches, key=len) else: file_ext = None return file_ext", "`source_data_url`. You may also append additional operations to the `operations`", "\"fastq\": GENOMIC_FILE.FORMAT.FASTQ, \"fq.gz\": GENOMIC_FILE.FORMAT.FASTQ, \"fastq.gz\": GENOMIC_FILE.FORMAT.FASTQ, \"bam\": GENOMIC_FILE.FORMAT.BAM, \"hgv.bam\": GENOMIC_FILE.FORMAT.BAM,", "GENOMIC_FILE.FORMAT.FASTQ, \"fastq\": GENOMIC_FILE.FORMAT.FASTQ, \"fq.gz\": GENOMIC_FILE.FORMAT.FASTQ, \"fastq.gz\": GENOMIC_FILE.FORMAT.FASTQ, \"bam\": GENOMIC_FILE.FORMAT.BAM, \"hgv.bam\":", "data_type = DATA_TYPES.get(ext) else: data_type = DATA_TYPES.get(file_format(x)) return data_type operations", "\"\"\" This is an extract config intended for S3 object", "in ext: data_type = DATA_TYPES.get(ext) else: data_type = DATA_TYPES.get(file_format(x)) return", "'https://localhost:5002/download/study/SD_ME0WME0W/' 'file/SF_Y1JMXTTS/version/FV_4RYEMD71' ) do_after_read = filter_df_by_file_ext def s3_url(row): \"\"\" Create", "{ GENOMIC_FILE.FORMAT.FASTQ: GENOMIC_FILE.DATA_TYPE.UNALIGNED_READS, GENOMIC_FILE.FORMAT.BAM: GENOMIC_FILE.DATA_TYPE.ALIGNED_READS, GENOMIC_FILE.FORMAT.CRAM: GENOMIC_FILE.DATA_TYPE.ALIGNED_READS, GENOMIC_FILE.FORMAT.BAI: \"Aligned Reads", "\"hgv.bam\": GENOMIC_FILE.FORMAT.BAM, \"cram\": GENOMIC_FILE.FORMAT.CRAM, \"bam.bai\": GENOMIC_FILE.FORMAT.BAI, \"bai\": GENOMIC_FILE.FORMAT.BAI, \"cram.crai\": GENOMIC_FILE.FORMAT.CRAI,", "genomic file extension \"\"\" matches = [ file_ext for file_ext", "file_ext for file_ext in FILE_EXT_FORMAT_MAP if x.endswith(file_ext) ] if matches:", "`tbi` in it, then use the file extension itself to", "import * source_data_url = 'file://../data/kf-seq-data-bcm-chung-s3-objects.tsv' operations.append( value_map( in_col='Key', out_col=CONCEPT.BIOSPECIMEN.ID, m=lambda", "format by looking genomic file ext up in FILE_EXT_FORMAT_MAP dict", "file_ext = None return file_ext FILE_EXT_FORMAT_MAP = { \"fq\": GENOMIC_FILE.FORMAT.FASTQ,", "= 'file://../data/kf-seq-data-bcm-chung-s3-objects.tsv' operations.append( value_map( in_col='Key', out_col=CONCEPT.BIOSPECIMEN.ID, m=lambda x: x )", "kf_ingest_packages.common.extract_configs.s3_object_info import * source_data_url = 'file://../data/kf-seq-data-bcm-chung-s3-objects.tsv' operations.append( value_map( in_col='Key', out_col=CONCEPT.BIOSPECIMEN.ID,", "\"peddy.html\": \"html\", } DATA_TYPES = { GENOMIC_FILE.FORMAT.FASTQ: GENOMIC_FILE.DATA_TYPE.UNALIGNED_READS, GENOMIC_FILE.FORMAT.BAM: GENOMIC_FILE.DATA_TYPE.ALIGNED_READS,", ") return df[df[CONCEPT.GENOMIC_FILE.FILE_FORMAT].notnull()] source_data_url = ( 'https://localhost:5002/download/study/SD_ME0WME0W/' 'file/SF_Y1JMXTTS/version/FV_4RYEMD71' ) do_after_read", "\"g.vcf.gz.tbi\": \"gVCF Index\", \"vcf.gz.tbi\": \"Variant Calls Index\", \"html\": \"Other\", }", "\"\"\" Get genomic file format by looking genomic file ext", "\"\"\" import os from kf_lib_data_ingest.common import constants from kf_lib_data_ingest.common.constants import", "source_data_url = ( 'https://localhost:5002/download/study/SD_ME0WME0W/' 'file/SF_Y1JMXTTS/version/FV_4RYEMD71' ) do_after_read = filter_df_by_file_ext def", "GENOMIC_FILE.FORMAT.CRAM, \"bam.bai\": GENOMIC_FILE.FORMAT.BAI, \"bai\": GENOMIC_FILE.FORMAT.BAI, \"cram.crai\": GENOMIC_FILE.FORMAT.CRAI, \"crai\": GENOMIC_FILE.FORMAT.CRAI, \"g.vcf.gz\":", "( keep_map, row_map, value_map, constant_map, ) def file_ext(x): \"\"\" Get", "Get genomic file extension \"\"\" matches = [ file_ext for", "file extension itself to do the data type lookup. \"\"\"", "GENOMIC_FILE.FORMAT.CRAI, \"crai\": GENOMIC_FILE.FORMAT.CRAI, \"g.vcf.gz\": GENOMIC_FILE.FORMAT.GVCF, \"g.vcf.gz.tbi\": GENOMIC_FILE.FORMAT.TBI, \"vcf.gz\": GENOMIC_FILE.FORMAT.VCF, \"vcf\":", "looking up file format in DATA_TYPES. However, if the file's", "\"tbi\" in ext: data_type = DATA_TYPES.get(ext) else: data_type = DATA_TYPES.get(file_format(x))", "kf_lib_data_ingest.etl.extract.operations import ( keep_map, row_map, value_map, constant_map, ) def file_ext(x):", "by looking genomic file ext up in FILE_EXT_FORMAT_MAP dict \"\"\"", "'file://../data/kf-seq-data-bcm-chung-s3-objects.tsv' operations.append( value_map( in_col='Key', out_col=CONCEPT.BIOSPECIMEN.ID, m=lambda x: x ) )", "from kf_lib_data_ingest.etl.extract.operations import ( keep_map, row_map, value_map, constant_map, ) def", "file format by looking genomic file ext up in FILE_EXT_FORMAT_MAP", "value_map( in_col=\"ETag\", out_col=CONCEPT.GENOMIC_FILE.HASH_DICT, m=lambda x: {constants.FILE.HASH.S3_ETAG.lower(): x.replace('\"', \"\")}, ), constant_map(", "the file extension itself to do the data type lookup.", "GENOMIC_FILE.FORMAT.CRAI, \"g.vcf.gz\": GENOMIC_FILE.FORMAT.GVCF, \"g.vcf.gz.tbi\": GENOMIC_FILE.FORMAT.TBI, \"vcf.gz\": GENOMIC_FILE.FORMAT.VCF, \"vcf\": GENOMIC_FILE.FORMAT.VCF, \"vcf.gz.tbi\":", "return FILE_EXT_FORMAT_MAP.get(file_ext(x)) def data_type(x): \"\"\" Get genomic file data type", "\"\"\" # File format return FILE_EXT_FORMAT_MAP.get(file_ext(x)) def data_type(x): \"\"\" Get", "File format return FILE_EXT_FORMAT_MAP.get(file_ext(x)) def data_type(x): \"\"\" Get genomic file", "\"Other\", } def filter_df_by_file_ext(df): \"\"\" Only keep rows where file", "\"\"\" Create S3 URL for object from S3 bucket and", "{ \"fq\": GENOMIC_FILE.FORMAT.FASTQ, \"fastq\": GENOMIC_FILE.FORMAT.FASTQ, \"fq.gz\": GENOMIC_FILE.FORMAT.FASTQ, \"fastq.gz\": GENOMIC_FILE.FORMAT.FASTQ, \"bam\":", "\"cram\": GENOMIC_FILE.FORMAT.CRAM, \"bam.bai\": GENOMIC_FILE.FORMAT.BAI, \"bai\": GENOMIC_FILE.FORMAT.BAI, \"cram.crai\": GENOMIC_FILE.FORMAT.CRAI, \"crai\": GENOMIC_FILE.FORMAT.CRAI,", "else: file_ext = None return file_ext FILE_EXT_FORMAT_MAP = { \"fq\":", "def file_ext(x): \"\"\" Get genomic file extension \"\"\" matches =", "kf_lib_data_ingest.common import constants from kf_lib_data_ingest.common.constants import GENOMIC_FILE from kf_lib_data_ingest.common.concept_schema import", "S3 URL for object from S3 bucket and key \"\"\"", "kf_lib_data_ingest.common.concept_schema import CONCEPT from kf_lib_data_ingest.etl.extract.operations import ( keep_map, row_map, value_map,", "# File format return FILE_EXT_FORMAT_MAP.get(file_ext(x)) def data_type(x): \"\"\" Get genomic", "GENOMIC_FILE.FORMAT.BAM, \"hgv.bam\": GENOMIC_FILE.FORMAT.BAM, \"cram\": GENOMIC_FILE.FORMAT.CRAM, \"bam.bai\": GENOMIC_FILE.FORMAT.BAI, \"bai\": GENOMIC_FILE.FORMAT.BAI, \"cram.crai\":", "by TBD. To use it, you must import it in", "URL for object from S3 bucket and key \"\"\" return", "import it in another extract config and override at least", "x.replace('\"', \"\")}, ), constant_map( out_col=CONCEPT.GENOMIC_FILE.AVAILABILITY, m=constants.GENOMIC_FILE.AVAILABILITY.IMMEDIATE, ), keep_map( in_col=CONCEPT.GENOMIC_FILE.FILE_FORMAT, out_col=CONCEPT.GENOMIC_FILE.FILE_FORMAT,", "m=lambda x: {constants.FILE.HASH.S3_ETAG.lower(): x.replace('\"', \"\")}, ), constant_map( out_col=CONCEPT.GENOMIC_FILE.AVAILABILITY, m=constants.GENOMIC_FILE.AVAILABILITY.IMMEDIATE, ),", "DATA_TYPES = { GENOMIC_FILE.FORMAT.FASTQ: GENOMIC_FILE.DATA_TYPE.UNALIGNED_READS, GENOMIC_FILE.FORMAT.BAM: GENOMIC_FILE.DATA_TYPE.ALIGNED_READS, GENOMIC_FILE.FORMAT.CRAM: GENOMIC_FILE.DATA_TYPE.ALIGNED_READS, GENOMIC_FILE.FORMAT.BAI:", "in DATA_TYPES. However, if the file's extension has `tbi` in", "from S3 bucket and key \"\"\" return f's3://{row[\"Bucket\"]}/{row[\"Key\"]}' def file_format(x):", "constants from kf_lib_data_ingest.common.constants import GENOMIC_FILE from kf_lib_data_ingest.common.concept_schema import CONCEPT from", "\"bam\": GENOMIC_FILE.FORMAT.BAM, \"hgv.bam\": GENOMIC_FILE.FORMAT.BAM, \"cram\": GENOMIC_FILE.FORMAT.CRAM, \"bam.bai\": GENOMIC_FILE.FORMAT.BAI, \"bai\": GENOMIC_FILE.FORMAT.BAI,", "GENOMIC_FILE.DATA_TYPE.UNALIGNED_READS, GENOMIC_FILE.FORMAT.BAM: GENOMIC_FILE.DATA_TYPE.ALIGNED_READS, GENOMIC_FILE.FORMAT.CRAM: GENOMIC_FILE.DATA_TYPE.ALIGNED_READS, GENOMIC_FILE.FORMAT.BAI: \"Aligned Reads Index\", GENOMIC_FILE.FORMAT.CRAI:", "GENOMIC_FILE.FORMAT.VCF, \"vcf.gz.tbi\": GENOMIC_FILE.FORMAT.TBI, \"peddy.html\": \"html\", } DATA_TYPES = { GENOMIC_FILE.FORMAT.FASTQ:", "an extract config intended for S3 object manifests produced by", "Index\", GENOMIC_FILE.FORMAT.VCF: \"Variant Calls\", GENOMIC_FILE.FORMAT.GVCF: \"gVCF\", \"g.vcf.gz.tbi\": \"gVCF Index\", \"vcf.gz.tbi\":", "out_col=CONCEPT.GENOMIC_FILE.URL_LIST, m=lambda row: [s3_url(row)] ), value_map( in_col=\"Key\", out_col=CONCEPT.GENOMIC_FILE.FILE_NAME, m=lambda x:", "from kf_lib_data_ingest.common.concept_schema import CONCEPT from kf_lib_data_ingest.etl.extract.operations import ( keep_map, row_map,", "the following in your extract config module: from kf_ingest_packages.common.extract_configs.s3_object_info import", "= { \"fq\": GENOMIC_FILE.FORMAT.FASTQ, \"fastq\": GENOMIC_FILE.FORMAT.FASTQ, \"fq.gz\": GENOMIC_FILE.FORMAT.FASTQ, \"fastq.gz\": GENOMIC_FILE.FORMAT.FASTQ,", "do_after_read = filter_df_by_file_ext def s3_url(row): \"\"\" Create S3 URL for", "Reads Index\", GENOMIC_FILE.FORMAT.VCF: \"Variant Calls\", GENOMIC_FILE.FORMAT.GVCF: \"gVCF\", \"g.vcf.gz.tbi\": \"gVCF Index\",", "None return file_ext FILE_EXT_FORMAT_MAP = { \"fq\": GENOMIC_FILE.FORMAT.FASTQ, \"fastq\": GENOMIC_FILE.FORMAT.FASTQ,", "return f's3://{row[\"Bucket\"]}/{row[\"Key\"]}' def file_format(x): \"\"\" Get genomic file format by", "extract config intended for S3 object manifests produced by TBD.", "source_data_url = 'file://../data/kf-seq-data-bcm-chung-s3-objects.tsv' operations.append( value_map( in_col='Key', out_col=CONCEPT.BIOSPECIMEN.ID, m=lambda x: x", "max(matches, key=len) else: file_ext = None return file_ext FILE_EXT_FORMAT_MAP =", "FILE_EXT_FORMAT_MAP.keys \"\"\" df[CONCEPT.GENOMIC_FILE.FILE_FORMAT] = df[\"Key\"].apply( lambda x: file_format(x) ) return", "file_format(x): \"\"\" Get genomic file format by looking genomic file", "Get genomic file format by looking genomic file ext up", "x: x ) ) \"\"\" import os from kf_lib_data_ingest.common import", "in_col=CONCEPT.GENOMIC_FILE.FILE_FORMAT, out_col=CONCEPT.GENOMIC_FILE.FILE_FORMAT, ), value_map( in_col=\"Key\", out_col=CONCEPT.GENOMIC_FILE.DATA_TYPE, m=lambda x: data_type(x), ),", "'file/SF_Y1JMXTTS/version/FV_4RYEMD71' ) do_after_read = filter_df_by_file_ext def s3_url(row): \"\"\" Create S3", "GENOMIC_FILE.FORMAT.TBI, \"vcf.gz\": GENOMIC_FILE.FORMAT.VCF, \"vcf\": GENOMIC_FILE.FORMAT.VCF, \"vcf.gz.tbi\": GENOMIC_FILE.FORMAT.TBI, \"peddy.html\": \"html\", }", "else: data_type = DATA_TYPES.get(file_format(x)) return data_type operations = [ row_map(out_col=CONCEPT.GENOMIC_FILE.ID,", "<gh_stars>1-10 \"\"\" This is an extract config intended for S3", "\"\"\" Get genomic file data type by looking up file", "x: os.path.split(x)[-1], ), keep_map(in_col=\"Size\", out_col=CONCEPT.GENOMIC_FILE.SIZE), value_map( in_col=\"ETag\", out_col=CONCEPT.GENOMIC_FILE.HASH_DICT, m=lambda x:", "in it, then use the file extension itself to do", "genomic file data type by looking up file format in", "[s3_url(row)] ), value_map( in_col=\"Key\", out_col=CONCEPT.GENOMIC_FILE.FILE_NAME, m=lambda x: os.path.split(x)[-1], ), keep_map(in_col=\"Size\",", "one of those in FILE_EXT_FORMAT_MAP.keys \"\"\" df[CONCEPT.GENOMIC_FILE.FILE_FORMAT] = df[\"Key\"].apply( lambda", "FILE_EXT_FORMAT_MAP dict \"\"\" # File format return FILE_EXT_FORMAT_MAP.get(file_ext(x)) def data_type(x):", "import CONCEPT from kf_lib_data_ingest.etl.extract.operations import ( keep_map, row_map, value_map, constant_map,", "file_ext FILE_EXT_FORMAT_MAP = { \"fq\": GENOMIC_FILE.FORMAT.FASTQ, \"fastq\": GENOMIC_FILE.FORMAT.FASTQ, \"fq.gz\": GENOMIC_FILE.FORMAT.FASTQ,", "FILE_EXT_FORMAT_MAP.get(file_ext(x)) def data_type(x): \"\"\" Get genomic file data type by", "up file format in DATA_TYPES. However, if the file's extension", "s3_url(row): \"\"\" Create S3 URL for object from S3 bucket", "FILE_EXT_FORMAT_MAP if x.endswith(file_ext) ] if matches: file_ext = max(matches, key=len)", "rows where file extension is one of those in FILE_EXT_FORMAT_MAP.keys", "Calls\", GENOMIC_FILE.FORMAT.GVCF: \"gVCF\", \"g.vcf.gz.tbi\": \"gVCF Index\", \"vcf.gz.tbi\": \"Variant Calls Index\",", "[ file_ext for file_ext in FILE_EXT_FORMAT_MAP if x.endswith(file_ext) ] if", "\"\"\" Get genomic file extension \"\"\" matches = [ file_ext", "object manifests produced by TBD. To use it, you must", "following in your extract config module: from kf_ingest_packages.common.extract_configs.s3_object_info import *", "def file_format(x): \"\"\" Get genomic file format by looking genomic", "Get genomic file data type by looking up file format", "GENOMIC_FILE.FORMAT.TBI, \"peddy.html\": \"html\", } DATA_TYPES = { GENOMIC_FILE.FORMAT.FASTQ: GENOMIC_FILE.DATA_TYPE.UNALIGNED_READS, GENOMIC_FILE.FORMAT.BAM:", "return df[df[CONCEPT.GENOMIC_FILE.FILE_FORMAT].notnull()] source_data_url = ( 'https://localhost:5002/download/study/SD_ME0WME0W/' 'file/SF_Y1JMXTTS/version/FV_4RYEMD71' ) do_after_read =", "\"bam.bai\": GENOMIC_FILE.FORMAT.BAI, \"bai\": GENOMIC_FILE.FORMAT.BAI, \"cram.crai\": GENOMIC_FILE.FORMAT.CRAI, \"crai\": GENOMIC_FILE.FORMAT.CRAI, \"g.vcf.gz\": GENOMIC_FILE.FORMAT.GVCF,", "Create S3 URL for object from S3 bucket and key", "\"Aligned Reads Index\", GENOMIC_FILE.FORMAT.CRAI: \"Aligned Reads Index\", GENOMIC_FILE.FORMAT.VCF: \"Variant Calls\",", "df[CONCEPT.GENOMIC_FILE.FILE_FORMAT] = df[\"Key\"].apply( lambda x: file_format(x) ) return df[df[CONCEPT.GENOMIC_FILE.FILE_FORMAT].notnull()] source_data_url", "Index\", \"vcf.gz.tbi\": \"Variant Calls Index\", \"html\": \"Other\", } def filter_df_by_file_ext(df):", "\"Aligned Reads Index\", GENOMIC_FILE.FORMAT.VCF: \"Variant Calls\", GENOMIC_FILE.FORMAT.GVCF: \"gVCF\", \"g.vcf.gz.tbi\": \"gVCF", "do the data type lookup. \"\"\" ext = file_ext(x) if", "from kf_lib_data_ingest.common.constants import GENOMIC_FILE from kf_lib_data_ingest.common.concept_schema import CONCEPT from kf_lib_data_ingest.etl.extract.operations", "lookup. \"\"\" ext = file_ext(x) if \"tbi\" in ext: data_type", "from kf_lib_data_ingest.common import constants from kf_lib_data_ingest.common.constants import GENOMIC_FILE from kf_lib_data_ingest.common.concept_schema", "file_format(x) ) return df[df[CONCEPT.GENOMIC_FILE.FILE_FORMAT].notnull()] source_data_url = ( 'https://localhost:5002/download/study/SD_ME0WME0W/' 'file/SF_Y1JMXTTS/version/FV_4RYEMD71' )", "), keep_map(in_col=\"Size\", out_col=CONCEPT.GENOMIC_FILE.SIZE), value_map( in_col=\"ETag\", out_col=CONCEPT.GENOMIC_FILE.HASH_DICT, m=lambda x: {constants.FILE.HASH.S3_ETAG.lower(): x.replace('\"',", "well. For example you could have the following in your", "could have the following in your extract config module: from", "= filter_df_by_file_ext def s3_url(row): \"\"\" Create S3 URL for object", "list as well. For example you could have the following", "However, if the file's extension has `tbi` in it, then", "value_map( in_col='Key', out_col=CONCEPT.BIOSPECIMEN.ID, m=lambda x: x ) ) \"\"\" import", "FILE_EXT_FORMAT_MAP = { \"fq\": GENOMIC_FILE.FORMAT.FASTQ, \"fastq\": GENOMIC_FILE.FORMAT.FASTQ, \"fq.gz\": GENOMIC_FILE.FORMAT.FASTQ, \"fastq.gz\":", "the `operations` list as well. For example you could have", "def filter_df_by_file_ext(df): \"\"\" Only keep rows where file extension is", "append additional operations to the `operations` list as well. For", "GENOMIC_FILE.FORMAT.FASTQ, \"fastq.gz\": GENOMIC_FILE.FORMAT.FASTQ, \"bam\": GENOMIC_FILE.FORMAT.BAM, \"hgv.bam\": GENOMIC_FILE.FORMAT.BAM, \"cram\": GENOMIC_FILE.FORMAT.CRAM, \"bam.bai\":", "to the `operations` list as well. For example you could", "in another extract config and override at least the `source_data_url`.", "least the `source_data_url`. You may also append additional operations to", "m=lambda x: os.path.split(x)[-1], ), keep_map(in_col=\"Size\", out_col=CONCEPT.GENOMIC_FILE.SIZE), value_map( in_col=\"ETag\", out_col=CONCEPT.GENOMIC_FILE.HASH_DICT, m=lambda", "CONCEPT from kf_lib_data_ingest.etl.extract.operations import ( keep_map, row_map, value_map, constant_map, )", "manifests produced by TBD. To use it, you must import", "x: {constants.FILE.HASH.S3_ETAG.lower(): x.replace('\"', \"\")}, ), constant_map( out_col=CONCEPT.GENOMIC_FILE.AVAILABILITY, m=constants.GENOMIC_FILE.AVAILABILITY.IMMEDIATE, ), keep_map(", "s3_url(row)), row_map( out_col=CONCEPT.GENOMIC_FILE.URL_LIST, m=lambda row: [s3_url(row)] ), value_map( in_col=\"Key\", out_col=CONCEPT.GENOMIC_FILE.FILE_NAME,", "\"vcf\": GENOMIC_FILE.FORMAT.VCF, \"vcf.gz.tbi\": GENOMIC_FILE.FORMAT.TBI, \"peddy.html\": \"html\", } DATA_TYPES = {", "those in FILE_EXT_FORMAT_MAP.keys \"\"\" df[CONCEPT.GENOMIC_FILE.FILE_FORMAT] = df[\"Key\"].apply( lambda x: file_format(x)", "ext: data_type = DATA_TYPES.get(ext) else: data_type = DATA_TYPES.get(file_format(x)) return data_type", "lambda x: file_format(x) ) return df[df[CONCEPT.GENOMIC_FILE.FILE_FORMAT].notnull()] source_data_url = ( 'https://localhost:5002/download/study/SD_ME0WME0W/'", "the data type lookup. \"\"\" ext = file_ext(x) if \"tbi\"", "return file_ext FILE_EXT_FORMAT_MAP = { \"fq\": GENOMIC_FILE.FORMAT.FASTQ, \"fastq\": GENOMIC_FILE.FORMAT.FASTQ, \"fq.gz\":", ") def file_ext(x): \"\"\" Get genomic file extension \"\"\" matches", "GENOMIC_FILE.FORMAT.CRAM: GENOMIC_FILE.DATA_TYPE.ALIGNED_READS, GENOMIC_FILE.FORMAT.BAI: \"Aligned Reads Index\", GENOMIC_FILE.FORMAT.CRAI: \"Aligned Reads Index\",", "then use the file extension itself to do the data", "\"crai\": GENOMIC_FILE.FORMAT.CRAI, \"g.vcf.gz\": GENOMIC_FILE.FORMAT.GVCF, \"g.vcf.gz.tbi\": GENOMIC_FILE.FORMAT.TBI, \"vcf.gz\": GENOMIC_FILE.FORMAT.VCF, \"vcf\": GENOMIC_FILE.FORMAT.VCF,", "ext = file_ext(x) if \"tbi\" in ext: data_type = DATA_TYPES.get(ext)", "in FILE_EXT_FORMAT_MAP dict \"\"\" # File format return FILE_EXT_FORMAT_MAP.get(file_ext(x)) def", "GENOMIC_FILE.FORMAT.BAM, \"cram\": GENOMIC_FILE.FORMAT.CRAM, \"bam.bai\": GENOMIC_FILE.FORMAT.BAI, \"bai\": GENOMIC_FILE.FORMAT.BAI, \"cram.crai\": GENOMIC_FILE.FORMAT.CRAI, \"crai\":", "import os from kf_lib_data_ingest.common import constants from kf_lib_data_ingest.common.constants import GENOMIC_FILE", "use it, you must import it in another extract config", "m=lambda x: x ) ) \"\"\" import os from kf_lib_data_ingest.common", "operations to the `operations` list as well. For example you", "genomic file ext up in FILE_EXT_FORMAT_MAP dict \"\"\" # File", "must import it in another extract config and override at", "GENOMIC_FILE.FORMAT.FASTQ: GENOMIC_FILE.DATA_TYPE.UNALIGNED_READS, GENOMIC_FILE.FORMAT.BAM: GENOMIC_FILE.DATA_TYPE.ALIGNED_READS, GENOMIC_FILE.FORMAT.CRAM: GENOMIC_FILE.DATA_TYPE.ALIGNED_READS, GENOMIC_FILE.FORMAT.BAI: \"Aligned Reads Index\",", "GENOMIC_FILE.FORMAT.BAI, \"bai\": GENOMIC_FILE.FORMAT.BAI, \"cram.crai\": GENOMIC_FILE.FORMAT.CRAI, \"crai\": GENOMIC_FILE.FORMAT.CRAI, \"g.vcf.gz\": GENOMIC_FILE.FORMAT.GVCF, \"g.vcf.gz.tbi\":", "This is an extract config intended for S3 object manifests", "= { GENOMIC_FILE.FORMAT.FASTQ: GENOMIC_FILE.DATA_TYPE.UNALIGNED_READS, GENOMIC_FILE.FORMAT.BAM: GENOMIC_FILE.DATA_TYPE.ALIGNED_READS, GENOMIC_FILE.FORMAT.CRAM: GENOMIC_FILE.DATA_TYPE.ALIGNED_READS, GENOMIC_FILE.FORMAT.BAI: \"Aligned", "GENOMIC_FILE.DATA_TYPE.ALIGNED_READS, GENOMIC_FILE.FORMAT.CRAM: GENOMIC_FILE.DATA_TYPE.ALIGNED_READS, GENOMIC_FILE.FORMAT.BAI: \"Aligned Reads Index\", GENOMIC_FILE.FORMAT.CRAI: \"Aligned Reads", "the `source_data_url`. You may also append additional operations to the", "to do the data type lookup. \"\"\" ext = file_ext(x)", "additional operations to the `operations` list as well. For example", "\"fq.gz\": GENOMIC_FILE.FORMAT.FASTQ, \"fastq.gz\": GENOMIC_FILE.FORMAT.FASTQ, \"bam\": GENOMIC_FILE.FORMAT.BAM, \"hgv.bam\": GENOMIC_FILE.FORMAT.BAM, \"cram\": GENOMIC_FILE.FORMAT.CRAM,", "\"html\", } DATA_TYPES = { GENOMIC_FILE.FORMAT.FASTQ: GENOMIC_FILE.DATA_TYPE.UNALIGNED_READS, GENOMIC_FILE.FORMAT.BAM: GENOMIC_FILE.DATA_TYPE.ALIGNED_READS, GENOMIC_FILE.FORMAT.CRAM:", "import constants from kf_lib_data_ingest.common.constants import GENOMIC_FILE from kf_lib_data_ingest.common.concept_schema import CONCEPT", ") do_after_read = filter_df_by_file_ext def s3_url(row): \"\"\" Create S3 URL", "extension itself to do the data type lookup. \"\"\" ext", "keep_map( in_col=CONCEPT.GENOMIC_FILE.FILE_FORMAT, out_col=CONCEPT.GENOMIC_FILE.FILE_FORMAT, ), value_map( in_col=\"Key\", out_col=CONCEPT.GENOMIC_FILE.DATA_TYPE, m=lambda x: data_type(x),", "\"\"\" df[CONCEPT.GENOMIC_FILE.FILE_FORMAT] = df[\"Key\"].apply( lambda x: file_format(x) ) return df[df[CONCEPT.GENOMIC_FILE.FILE_FORMAT].notnull()]", "\"gVCF Index\", \"vcf.gz.tbi\": \"Variant Calls Index\", \"html\": \"Other\", } def", "df[\"Key\"].apply( lambda x: file_format(x) ) return df[df[CONCEPT.GENOMIC_FILE.FILE_FORMAT].notnull()] source_data_url = (", "\"vcf.gz.tbi\": GENOMIC_FILE.FORMAT.TBI, \"peddy.html\": \"html\", } DATA_TYPES = { GENOMIC_FILE.FORMAT.FASTQ: GENOMIC_FILE.DATA_TYPE.UNALIGNED_READS,", "it in another extract config and override at least the", "for file_ext in FILE_EXT_FORMAT_MAP if x.endswith(file_ext) ] if matches: file_ext", "produced by TBD. To use it, you must import it", "\"cram.crai\": GENOMIC_FILE.FORMAT.CRAI, \"crai\": GENOMIC_FILE.FORMAT.CRAI, \"g.vcf.gz\": GENOMIC_FILE.FORMAT.GVCF, \"g.vcf.gz.tbi\": GENOMIC_FILE.FORMAT.TBI, \"vcf.gz\": GENOMIC_FILE.FORMAT.VCF,", "= ( 'https://localhost:5002/download/study/SD_ME0WME0W/' 'file/SF_Y1JMXTTS/version/FV_4RYEMD71' ) do_after_read = filter_df_by_file_ext def s3_url(row):", "\"\"\" ext = file_ext(x) if \"tbi\" in ext: data_type =", "DATA_TYPES. However, if the file's extension has `tbi` in it,", "kf_lib_data_ingest.common.constants import GENOMIC_FILE from kf_lib_data_ingest.common.concept_schema import CONCEPT from kf_lib_data_ingest.etl.extract.operations import", "object from S3 bucket and key \"\"\" return f's3://{row[\"Bucket\"]}/{row[\"Key\"]}' def", "matches: file_ext = max(matches, key=len) else: file_ext = None return", "GENOMIC_FILE.FORMAT.GVCF: \"gVCF\", \"g.vcf.gz.tbi\": \"gVCF Index\", \"vcf.gz.tbi\": \"Variant Calls Index\", \"html\":", "), value_map( in_col=\"Key\", out_col=CONCEPT.GENOMIC_FILE.FILE_NAME, m=lambda x: os.path.split(x)[-1], ), keep_map(in_col=\"Size\", out_col=CONCEPT.GENOMIC_FILE.SIZE),", "keep rows where file extension is one of those in", "and override at least the `source_data_url`. You may also append", "filter_df_by_file_ext def s3_url(row): \"\"\" Create S3 URL for object from", "in_col=\"ETag\", out_col=CONCEPT.GENOMIC_FILE.HASH_DICT, m=lambda x: {constants.FILE.HASH.S3_ETAG.lower(): x.replace('\"', \"\")}, ), constant_map( out_col=CONCEPT.GENOMIC_FILE.AVAILABILITY,", "GENOMIC_FILE.FORMAT.BAI, \"cram.crai\": GENOMIC_FILE.FORMAT.CRAI, \"crai\": GENOMIC_FILE.FORMAT.CRAI, \"g.vcf.gz\": GENOMIC_FILE.FORMAT.GVCF, \"g.vcf.gz.tbi\": GENOMIC_FILE.FORMAT.TBI, \"vcf.gz\":", "constant_map( out_col=CONCEPT.GENOMIC_FILE.AVAILABILITY, m=constants.GENOMIC_FILE.AVAILABILITY.IMMEDIATE, ), keep_map( in_col=CONCEPT.GENOMIC_FILE.FILE_FORMAT, out_col=CONCEPT.GENOMIC_FILE.FILE_FORMAT, ), value_map( in_col=\"Key\",", "S3 object manifests produced by TBD. To use it, you", "if \"tbi\" in ext: data_type = DATA_TYPES.get(ext) else: data_type =", "filter_df_by_file_ext(df): \"\"\" Only keep rows where file extension is one", "value_map( in_col=\"Key\", out_col=CONCEPT.GENOMIC_FILE.FILE_NAME, m=lambda x: os.path.split(x)[-1], ), keep_map(in_col=\"Size\", out_col=CONCEPT.GENOMIC_FILE.SIZE), value_map(", "another extract config and override at least the `source_data_url`. You", "in your extract config module: from kf_ingest_packages.common.extract_configs.s3_object_info import * source_data_url", "GENOMIC_FILE.FORMAT.BAI: \"Aligned Reads Index\", GENOMIC_FILE.FORMAT.CRAI: \"Aligned Reads Index\", GENOMIC_FILE.FORMAT.VCF: \"Variant", "data type by looking up file format in DATA_TYPES. However,", "extension is one of those in FILE_EXT_FORMAT_MAP.keys \"\"\" df[CONCEPT.GENOMIC_FILE.FILE_FORMAT] =", ") ) \"\"\" import os from kf_lib_data_ingest.common import constants from", "at least the `source_data_url`. You may also append additional operations", "\"Variant Calls\", GENOMIC_FILE.FORMAT.GVCF: \"gVCF\", \"g.vcf.gz.tbi\": \"gVCF Index\", \"vcf.gz.tbi\": \"Variant Calls", "out_col=CONCEPT.GENOMIC_FILE.SIZE), value_map( in_col=\"ETag\", out_col=CONCEPT.GENOMIC_FILE.HASH_DICT, m=lambda x: {constants.FILE.HASH.S3_ETAG.lower(): x.replace('\"', \"\")}, ),", "your extract config module: from kf_ingest_packages.common.extract_configs.s3_object_info import * source_data_url =", "data type lookup. \"\"\" ext = file_ext(x) if \"tbi\" in", "os.path.split(x)[-1], ), keep_map(in_col=\"Size\", out_col=CONCEPT.GENOMIC_FILE.SIZE), value_map( in_col=\"ETag\", out_col=CONCEPT.GENOMIC_FILE.HASH_DICT, m=lambda x: {constants.FILE.HASH.S3_ETAG.lower():", "extension \"\"\" matches = [ file_ext for file_ext in FILE_EXT_FORMAT_MAP", "\"fastq.gz\": GENOMIC_FILE.FORMAT.FASTQ, \"bam\": GENOMIC_FILE.FORMAT.BAM, \"hgv.bam\": GENOMIC_FILE.FORMAT.BAM, \"cram\": GENOMIC_FILE.FORMAT.CRAM, \"bam.bai\": GENOMIC_FILE.FORMAT.BAI,", "has `tbi` in it, then use the file extension itself", "GENOMIC_FILE.FORMAT.CRAI: \"Aligned Reads Index\", GENOMIC_FILE.FORMAT.VCF: \"Variant Calls\", GENOMIC_FILE.FORMAT.GVCF: \"gVCF\", \"g.vcf.gz.tbi\":", "file's extension has `tbi` in it, then use the file", "row_map( out_col=CONCEPT.GENOMIC_FILE.URL_LIST, m=lambda row: [s3_url(row)] ), value_map( in_col=\"Key\", out_col=CONCEPT.GENOMIC_FILE.FILE_NAME, m=lambda", "] if matches: file_ext = max(matches, key=len) else: file_ext =", "Index\", GENOMIC_FILE.FORMAT.CRAI: \"Aligned Reads Index\", GENOMIC_FILE.FORMAT.VCF: \"Variant Calls\", GENOMIC_FILE.FORMAT.GVCF: \"gVCF\",", "GENOMIC_FILE.DATA_TYPE.ALIGNED_READS, GENOMIC_FILE.FORMAT.BAI: \"Aligned Reads Index\", GENOMIC_FILE.FORMAT.CRAI: \"Aligned Reads Index\", GENOMIC_FILE.FORMAT.VCF:", "GENOMIC_FILE.FORMAT.BAM: GENOMIC_FILE.DATA_TYPE.ALIGNED_READS, GENOMIC_FILE.FORMAT.CRAM: GENOMIC_FILE.DATA_TYPE.ALIGNED_READS, GENOMIC_FILE.FORMAT.BAI: \"Aligned Reads Index\", GENOMIC_FILE.FORMAT.CRAI: \"Aligned", "\"\")}, ), constant_map( out_col=CONCEPT.GENOMIC_FILE.AVAILABILITY, m=constants.GENOMIC_FILE.AVAILABILITY.IMMEDIATE, ), keep_map( in_col=CONCEPT.GENOMIC_FILE.FILE_FORMAT, out_col=CONCEPT.GENOMIC_FILE.FILE_FORMAT, ),", "row: [s3_url(row)] ), value_map( in_col=\"Key\", out_col=CONCEPT.GENOMIC_FILE.FILE_NAME, m=lambda x: os.path.split(x)[-1], ),", "itself to do the data type lookup. \"\"\" ext =", "in FILE_EXT_FORMAT_MAP if x.endswith(file_ext) ] if matches: file_ext = max(matches,", "format return FILE_EXT_FORMAT_MAP.get(file_ext(x)) def data_type(x): \"\"\" Get genomic file data", "Calls Index\", \"html\": \"Other\", } def filter_df_by_file_ext(df): \"\"\" Only keep", "* source_data_url = 'file://../data/kf-seq-data-bcm-chung-s3-objects.tsv' operations.append( value_map( in_col='Key', out_col=CONCEPT.BIOSPECIMEN.ID, m=lambda x:", "{constants.FILE.HASH.S3_ETAG.lower(): x.replace('\"', \"\")}, ), constant_map( out_col=CONCEPT.GENOMIC_FILE.AVAILABILITY, m=constants.GENOMIC_FILE.AVAILABILITY.IMMEDIATE, ), keep_map( in_col=CONCEPT.GENOMIC_FILE.FILE_FORMAT,", "} def filter_df_by_file_ext(df): \"\"\" Only keep rows where file extension", "} DATA_TYPES = { GENOMIC_FILE.FORMAT.FASTQ: GENOMIC_FILE.DATA_TYPE.UNALIGNED_READS, GENOMIC_FILE.FORMAT.BAM: GENOMIC_FILE.DATA_TYPE.ALIGNED_READS, GENOMIC_FILE.FORMAT.CRAM: GENOMIC_FILE.DATA_TYPE.ALIGNED_READS,", "matches = [ file_ext for file_ext in FILE_EXT_FORMAT_MAP if x.endswith(file_ext)", "os from kf_lib_data_ingest.common import constants from kf_lib_data_ingest.common.constants import GENOMIC_FILE from", "file extension is one of those in FILE_EXT_FORMAT_MAP.keys \"\"\" df[CONCEPT.GENOMIC_FILE.FILE_FORMAT]", "it, then use the file extension itself to do the", "\"gVCF\", \"g.vcf.gz.tbi\": \"gVCF Index\", \"vcf.gz.tbi\": \"Variant Calls Index\", \"html\": \"Other\",", "[ row_map(out_col=CONCEPT.GENOMIC_FILE.ID, m=lambda row: s3_url(row)), row_map( out_col=CONCEPT.GENOMIC_FILE.URL_LIST, m=lambda row: [s3_url(row)]", "is one of those in FILE_EXT_FORMAT_MAP.keys \"\"\" df[CONCEPT.GENOMIC_FILE.FILE_FORMAT] = df[\"Key\"].apply(", "as well. For example you could have the following in", "where file extension is one of those in FILE_EXT_FORMAT_MAP.keys \"\"\"", "use the file extension itself to do the data type", "For example you could have the following in your extract", "x.endswith(file_ext) ] if matches: file_ext = max(matches, key=len) else: file_ext", "row_map(out_col=CONCEPT.GENOMIC_FILE.ID, m=lambda row: s3_url(row)), row_map( out_col=CONCEPT.GENOMIC_FILE.URL_LIST, m=lambda row: [s3_url(row)] ),", "= None return file_ext FILE_EXT_FORMAT_MAP = { \"fq\": GENOMIC_FILE.FORMAT.FASTQ, \"fastq\":", "GENOMIC_FILE.FORMAT.VCF, \"vcf\": GENOMIC_FILE.FORMAT.VCF, \"vcf.gz.tbi\": GENOMIC_FILE.FORMAT.TBI, \"peddy.html\": \"html\", } DATA_TYPES =", "\"vcf.gz.tbi\": \"Variant Calls Index\", \"html\": \"Other\", } def filter_df_by_file_ext(df): \"\"\"", "example you could have the following in your extract config", "Only keep rows where file extension is one of those", "return data_type operations = [ row_map(out_col=CONCEPT.GENOMIC_FILE.ID, m=lambda row: s3_url(row)), row_map(", "TBD. To use it, you must import it in another", "by looking up file format in DATA_TYPES. However, if the", "file format in DATA_TYPES. However, if the file's extension has", "f's3://{row[\"Bucket\"]}/{row[\"Key\"]}' def file_format(x): \"\"\" Get genomic file format by looking", "module: from kf_ingest_packages.common.extract_configs.s3_object_info import * source_data_url = 'file://../data/kf-seq-data-bcm-chung-s3-objects.tsv' operations.append( value_map(", "if matches: file_ext = max(matches, key=len) else: file_ext = None", "up in FILE_EXT_FORMAT_MAP dict \"\"\" # File format return FILE_EXT_FORMAT_MAP.get(file_ext(x))", "have the following in your extract config module: from kf_ingest_packages.common.extract_configs.s3_object_info", "may also append additional operations to the `operations` list as", "\"g.vcf.gz.tbi\": GENOMIC_FILE.FORMAT.TBI, \"vcf.gz\": GENOMIC_FILE.FORMAT.VCF, \"vcf\": GENOMIC_FILE.FORMAT.VCF, \"vcf.gz.tbi\": GENOMIC_FILE.FORMAT.TBI, \"peddy.html\": \"html\",", "df[df[CONCEPT.GENOMIC_FILE.FILE_FORMAT].notnull()] source_data_url = ( 'https://localhost:5002/download/study/SD_ME0WME0W/' 'file/SF_Y1JMXTTS/version/FV_4RYEMD71' ) do_after_read = filter_df_by_file_ext", "in_col=\"Key\", out_col=CONCEPT.GENOMIC_FILE.FILE_NAME, m=lambda x: os.path.split(x)[-1], ), keep_map(in_col=\"Size\", out_col=CONCEPT.GENOMIC_FILE.SIZE), value_map( in_col=\"ETag\",", "file data type by looking up file format in DATA_TYPES.", "data_type operations = [ row_map(out_col=CONCEPT.GENOMIC_FILE.ID, m=lambda row: s3_url(row)), row_map( out_col=CONCEPT.GENOMIC_FILE.URL_LIST,", "file extension \"\"\" matches = [ file_ext for file_ext in", "is an extract config intended for S3 object manifests produced", "file_ext in FILE_EXT_FORMAT_MAP if x.endswith(file_ext) ] if matches: file_ext =", "data_type = DATA_TYPES.get(file_format(x)) return data_type operations = [ row_map(out_col=CONCEPT.GENOMIC_FILE.ID, m=lambda", "also append additional operations to the `operations` list as well.", "), keep_map( in_col=CONCEPT.GENOMIC_FILE.FILE_FORMAT, out_col=CONCEPT.GENOMIC_FILE.FILE_FORMAT, ), value_map( in_col=\"Key\", out_col=CONCEPT.GENOMIC_FILE.DATA_TYPE, m=lambda x:" ]
[ "bpy from bpy.app.handlers import persistent bl_info = { \"name\": \"Playback", "0, 0), \"blender\": (2, 67, 3), \"location\": \"\", \"description\": \"Playback", "\"Playback Once\", \"author\": \"<NAME>\", \"version\": (1, 0, 0), \"blender\": (2,", "bl_info = { \"name\": \"Playback Once\", \"author\": \"<NAME>\", \"version\": (1,", "stopPlaybackAtEnd(scene): if scene.frame_current >= scene.frame_end: bpy.ops.screen.animation_cancel() def register(): bpy.app.handlers.frame_change_pre.append(stopPlaybackAtEnd) def", ">= scene.frame_end: bpy.ops.screen.animation_cancel() def register(): bpy.app.handlers.frame_change_pre.append(stopPlaybackAtEnd) def unregister(): bpy.app.handlers.frame_change_pre.remove(stopPlaybackAtEnd) if", "\"blender\": (2, 67, 3), \"location\": \"\", \"description\": \"Playback once.\", \"warning\":", "import bpy from bpy.app.handlers import persistent bl_info = { \"name\":", "\"wiki_url\": \"\", \"tracker_url\": \"\", \"category\": \"Animation\"} @persistent def stopPlaybackAtEnd(scene): if", "\"tracker_url\": \"\", \"category\": \"Animation\"} @persistent def stopPlaybackAtEnd(scene): if scene.frame_current >=", "register(): bpy.app.handlers.frame_change_pre.append(stopPlaybackAtEnd) def unregister(): bpy.app.handlers.frame_change_pre.remove(stopPlaybackAtEnd) if __name__ == \"__main__\": register()", "\"\", \"description\": \"Playback once.\", \"warning\": \"\", \"wiki_url\": \"\", \"tracker_url\": \"\",", "\"version\": (1, 0, 0), \"blender\": (2, 67, 3), \"location\": \"\",", "@persistent def stopPlaybackAtEnd(scene): if scene.frame_current >= scene.frame_end: bpy.ops.screen.animation_cancel() def register():", "if scene.frame_current >= scene.frame_end: bpy.ops.screen.animation_cancel() def register(): bpy.app.handlers.frame_change_pre.append(stopPlaybackAtEnd) def unregister():", "bpy.ops.screen.animation_cancel() def register(): bpy.app.handlers.frame_change_pre.append(stopPlaybackAtEnd) def unregister(): bpy.app.handlers.frame_change_pre.remove(stopPlaybackAtEnd) if __name__ ==", "scene.frame_end: bpy.ops.screen.animation_cancel() def register(): bpy.app.handlers.frame_change_pre.append(stopPlaybackAtEnd) def unregister(): bpy.app.handlers.frame_change_pre.remove(stopPlaybackAtEnd) if __name__", "from bpy.app.handlers import persistent bl_info = { \"name\": \"Playback Once\",", "\"Playback once.\", \"warning\": \"\", \"wiki_url\": \"\", \"tracker_url\": \"\", \"category\": \"Animation\"}", "\"Animation\"} @persistent def stopPlaybackAtEnd(scene): if scene.frame_current >= scene.frame_end: bpy.ops.screen.animation_cancel() def", "\"description\": \"Playback once.\", \"warning\": \"\", \"wiki_url\": \"\", \"tracker_url\": \"\", \"category\":", "import persistent bl_info = { \"name\": \"Playback Once\", \"author\": \"<NAME>\",", "\"\", \"category\": \"Animation\"} @persistent def stopPlaybackAtEnd(scene): if scene.frame_current >= scene.frame_end:", "{ \"name\": \"Playback Once\", \"author\": \"<NAME>\", \"version\": (1, 0, 0),", "67, 3), \"location\": \"\", \"description\": \"Playback once.\", \"warning\": \"\", \"wiki_url\":", "bpy.app.handlers import persistent bl_info = { \"name\": \"Playback Once\", \"author\":", "= { \"name\": \"Playback Once\", \"author\": \"<NAME>\", \"version\": (1, 0,", "(1, 0, 0), \"blender\": (2, 67, 3), \"location\": \"\", \"description\":", "Once\", \"author\": \"<NAME>\", \"version\": (1, 0, 0), \"blender\": (2, 67,", "\"warning\": \"\", \"wiki_url\": \"\", \"tracker_url\": \"\", \"category\": \"Animation\"} @persistent def", "def register(): bpy.app.handlers.frame_change_pre.append(stopPlaybackAtEnd) def unregister(): bpy.app.handlers.frame_change_pre.remove(stopPlaybackAtEnd) if __name__ == \"__main__\":", "\"\", \"wiki_url\": \"\", \"tracker_url\": \"\", \"category\": \"Animation\"} @persistent def stopPlaybackAtEnd(scene):", "0), \"blender\": (2, 67, 3), \"location\": \"\", \"description\": \"Playback once.\",", "3), \"location\": \"\", \"description\": \"Playback once.\", \"warning\": \"\", \"wiki_url\": \"\",", "def stopPlaybackAtEnd(scene): if scene.frame_current >= scene.frame_end: bpy.ops.screen.animation_cancel() def register(): bpy.app.handlers.frame_change_pre.append(stopPlaybackAtEnd)", "scene.frame_current >= scene.frame_end: bpy.ops.screen.animation_cancel() def register(): bpy.app.handlers.frame_change_pre.append(stopPlaybackAtEnd) def unregister(): bpy.app.handlers.frame_change_pre.remove(stopPlaybackAtEnd)", "\"location\": \"\", \"description\": \"Playback once.\", \"warning\": \"\", \"wiki_url\": \"\", \"tracker_url\":", "\"<NAME>\", \"version\": (1, 0, 0), \"blender\": (2, 67, 3), \"location\":", "persistent bl_info = { \"name\": \"Playback Once\", \"author\": \"<NAME>\", \"version\":", "\"\", \"tracker_url\": \"\", \"category\": \"Animation\"} @persistent def stopPlaybackAtEnd(scene): if scene.frame_current", "once.\", \"warning\": \"\", \"wiki_url\": \"\", \"tracker_url\": \"\", \"category\": \"Animation\"} @persistent", "\"name\": \"Playback Once\", \"author\": \"<NAME>\", \"version\": (1, 0, 0), \"blender\":", "(2, 67, 3), \"location\": \"\", \"description\": \"Playback once.\", \"warning\": \"\",", "\"author\": \"<NAME>\", \"version\": (1, 0, 0), \"blender\": (2, 67, 3),", "\"category\": \"Animation\"} @persistent def stopPlaybackAtEnd(scene): if scene.frame_current >= scene.frame_end: bpy.ops.screen.animation_cancel()" ]
[ "builtin-``min``-function. \"\"\" from ...challenge import Challenge from random import randint", "_ in x[:-1])} and {x[-1]}. (values: x)\" def validate_function(stdin: str,", "Challenge from random import randint x = [] for _", "the builtin-``min``-function. \"\"\" from ...challenge import Challenge from random import", "this you should consider using the builtin-``min``-function. \"\"\" from ...challenge", "{x[-1]}. (values: x)\" def validate_function(stdin: str, stdout: str, stderr: str,", "f\"You have to print the lowest value of {', '.join(str(_)", "stderr: str, exc: tuple) -> bool: try: z = int(stdout.removesuffix(\"\\n\"))", "bool: try: z = int(stdout.removesuffix(\"\\n\")) except ValueError: return False else:", "...challenge import Challenge from random import randint x = []", "= f\"You have to print the lowest value of {',", "and {x[-1]}. (values: x)\" def validate_function(stdin: str, stdout: str, stderr:", "False else: return min(x) == z challenge = Challenge( intro=intro,", "else: return min(x) == z challenge = Challenge( intro=intro, validate_function=validate_function,", "_ in range(randint(2, 10)): x.append(randint(1, 100)) intro = f\"You have", "return False else: return min(x) == z challenge = Challenge(", "to print the lowest value of {', '.join(str(_) for _", "in range(randint(2, 10)): x.append(randint(1, 100)) intro = f\"You have to", "def validate_function(stdin: str, stdout: str, stderr: str, exc: tuple) ->", "[] for _ in range(randint(2, 10)): x.append(randint(1, 100)) intro =", "intro = f\"You have to print the lowest value of", "str, stdout: str, stderr: str, exc: tuple) -> bool: try:", "= int(stdout.removesuffix(\"\\n\")) except ValueError: return False else: return min(x) ==", "print the lowest value of {', '.join(str(_) for _ in", "import randint x = [] for _ in range(randint(2, 10)):", "of {', '.join(str(_) for _ in x[:-1])} and {x[-1]}. (values:", "int(stdout.removesuffix(\"\\n\")) except ValueError: return False else: return min(x) == z", "z = int(stdout.removesuffix(\"\\n\")) except ValueError: return False else: return min(x)", "ValueError: return False else: return min(x) == z challenge =", "using the builtin-``min``-function. \"\"\" from ...challenge import Challenge from random", "consider using the builtin-``min``-function. \"\"\" from ...challenge import Challenge from", "str, exc: tuple) -> bool: try: z = int(stdout.removesuffix(\"\\n\")) except", "<filename>Py3Challenges/saves/challenges/c6_min.py \"\"\" To master this you should consider using the", "10)): x.append(randint(1, 100)) intro = f\"You have to print the", "master this you should consider using the builtin-``min``-function. \"\"\" from", "should consider using the builtin-``min``-function. \"\"\" from ...challenge import Challenge", "random import randint x = [] for _ in range(randint(2,", "validate_function(stdin: str, stdout: str, stderr: str, exc: tuple) -> bool:", "for _ in range(randint(2, 10)): x.append(randint(1, 100)) intro = f\"You", "x[:-1])} and {x[-1]}. (values: x)\" def validate_function(stdin: str, stdout: str,", "tuple) -> bool: try: z = int(stdout.removesuffix(\"\\n\")) except ValueError: return", "try: z = int(stdout.removesuffix(\"\\n\")) except ValueError: return False else: return", "100)) intro = f\"You have to print the lowest value", "str, stderr: str, exc: tuple) -> bool: try: z =", "lowest value of {', '.join(str(_) for _ in x[:-1])} and", "z challenge = Challenge( intro=intro, validate_function=validate_function, help=__doc__, values={\"x\": x}, capture_stdout=True,", "x.append(randint(1, 100)) intro = f\"You have to print the lowest", "for _ in x[:-1])} and {x[-1]}. (values: x)\" def validate_function(stdin:", "\"\"\" To master this you should consider using the builtin-``min``-function.", "from random import randint x = [] for _ in", "import Challenge from random import randint x = [] for", "have to print the lowest value of {', '.join(str(_) for", "'.join(str(_) for _ in x[:-1])} and {x[-1]}. (values: x)\" def", "stdout: str, stderr: str, exc: tuple) -> bool: try: z", "min(x) == z challenge = Challenge( intro=intro, validate_function=validate_function, help=__doc__, values={\"x\":", "exc: tuple) -> bool: try: z = int(stdout.removesuffix(\"\\n\")) except ValueError:", "To master this you should consider using the builtin-``min``-function. \"\"\"", "-> bool: try: z = int(stdout.removesuffix(\"\\n\")) except ValueError: return False", "{', '.join(str(_) for _ in x[:-1])} and {x[-1]}. (values: x)\"", "except ValueError: return False else: return min(x) == z challenge", "x = [] for _ in range(randint(2, 10)): x.append(randint(1, 100))", "the lowest value of {', '.join(str(_) for _ in x[:-1])}", "return min(x) == z challenge = Challenge( intro=intro, validate_function=validate_function, help=__doc__,", "== z challenge = Challenge( intro=intro, validate_function=validate_function, help=__doc__, values={\"x\": x},", "range(randint(2, 10)): x.append(randint(1, 100)) intro = f\"You have to print", "value of {', '.join(str(_) for _ in x[:-1])} and {x[-1]}.", "from ...challenge import Challenge from random import randint x =", "randint x = [] for _ in range(randint(2, 10)): x.append(randint(1,", "(values: x)\" def validate_function(stdin: str, stdout: str, stderr: str, exc:", "\"\"\" from ...challenge import Challenge from random import randint x", "x)\" def validate_function(stdin: str, stdout: str, stderr: str, exc: tuple)", "= [] for _ in range(randint(2, 10)): x.append(randint(1, 100)) intro", "in x[:-1])} and {x[-1]}. (values: x)\" def validate_function(stdin: str, stdout:", "challenge = Challenge( intro=intro, validate_function=validate_function, help=__doc__, values={\"x\": x}, capture_stdout=True, )", "you should consider using the builtin-``min``-function. \"\"\" from ...challenge import" ]
[ "async def test_delete_cluster( mocked_director_v2, client, user_id: UserID, cluster_id: ClusterID ):", "in created_cluster async def test_list_clusters(mocked_director_v2, client, user_id: UserID): list_of_clusters =", "task_out assert isinstance(task_out, ComputationTask) assert task_out.state == RunningState.NOT_STARTED async def", "director_v2_service_mock: aioresponses, ) -> AsyncIterator[aioresponses]: yield director_v2_service_mock @pytest.fixture def user_id(faker:", "def test_delete_pipeline( mocked_director_v2, client, user_id: UserID, project_id: ProjectID ): await", "-> UserID: return UserID(faker.pyint(min_value=1)) @pytest.fixture def project_id(faker: Faker) -> ProjectID:", "client, user_id: UserID, project_id: ProjectID ): task_out = await director_v2_api.create_or_update_pipeline(", "HealthCheck, given, settings from hypothesis import strategies as st from", "test_delete_pipeline( mocked_director_v2, client, user_id: UserID, project_id: ProjectID ): await director_v2_api.delete_pipeline(client.app,", "yield director_v2_service_mock @pytest.fixture def user_id(faker: Faker) -> UserID: return UserID(faker.pyint(min_value=1))", "st from models_library.clusters import ClusterID from models_library.projects import ProjectID from", "@pytest.fixture() async def mocked_director_v2( director_v2_service_mock: aioresponses, ) -> AsyncIterator[aioresponses]: yield", "ComputationTask) assert task_out.state == RunningState.NOT_STARTED async def test_delete_pipeline( mocked_director_v2, client,", ") assert created_cluster is not None assert isinstance(created_cluster, dict) assert", "mocked_director_v2, client, user_id: UserID, cluster_id: ClusterID ): cluster_details = await", "return ProjectID(faker.uuid4()) @pytest.fixture def cluster_id(faker: Faker) -> ClusterID: return ClusterID(faker.pyint(min_value=0))", ") -> AsyncIterator[aioresponses]: yield director_v2_service_mock @pytest.fixture def user_id(faker: Faker) ->", "await director_v2_api.get_computation_task( client.app, user_id, project_id ) assert task_out assert isinstance(task_out,", "task_out.state == RunningState.NOT_STARTED async def test_delete_pipeline( mocked_director_v2, client, user_id: UserID,", "updated_cluster = await director_v2_api.update_cluster( client.app, user_id=user_id, cluster_id=cluster_id, cluster_patch=cluster_patch ) assert", "cluster_id(faker: Faker) -> ClusterID: return ClusterID(faker.pyint(min_value=0)) async def test_create_pipeline( mocked_director_v2,", "UserID, cluster_create ): created_cluster = await director_v2_api.create_cluster( client.app, user_id=user_id, new_cluster=cluster_create", "mocked_director_v2, client, user_id: UserID, project_id: ProjectID ): await director_v2_api.delete_pipeline(client.app, user_id,", "project_id) @settings(suppress_health_check=[HealthCheck.function_scoped_fixture]) @given(cluster_create=st.builds(ClusterCreate)) async def test_create_cluster( mocked_director_v2, client, user_id: UserID,", "strategies as st from models_library.clusters import ClusterID from models_library.projects import", "ProjectID(faker.uuid4()) @pytest.fixture def cluster_id(faker: Faker) -> ClusterID: return ClusterID(faker.pyint(min_value=0)) async", "test_get_cluster_details( mocked_director_v2, client, user_id: UserID, cluster_id: ClusterID ): cluster_details =", "assert isinstance(cluster_details, dict) @settings(suppress_health_check=[HealthCheck.function_scoped_fixture]) @given(cluster_patch=st.from_type(ClusterPatch)) async def test_update_cluster( mocked_director_v2, client,", "def test_create_pipeline( mocked_director_v2, client, user_id: UserID, project_id: ProjectID ): task_out", "director_v2_api.list_clusters(client.app, user_id=user_id) assert isinstance(list_of_clusters, list) assert len(list_of_clusters) > 0 async", "dict) assert \"id\" in created_cluster async def test_list_clusters(mocked_director_v2, client, user_id:", "dict) assert task_out[\"state\"] == RunningState.NOT_STARTED async def test_get_computation_task( mocked_director_v2, client,", "async def test_get_cluster( mocked_director_v2, client, user_id: UserID, cluster_id: ClusterID ):", "task_out = await director_v2_api.get_computation_task( client.app, user_id, project_id ) assert task_out", "simcore_service_webserver.director_v2_models import ( ClusterCreate, ClusterPatch, ClusterPing, ) @pytest.fixture() async def", "project_id ) assert task_out assert isinstance(task_out, ComputationTask) assert task_out.state ==", "cluster_id: ClusterID ): cluster = await director_v2_api.get_cluster( client.app, user_id=user_id, cluster_id=cluster_id", "UserID, cluster_id: ClusterID ): await director_v2_api.ping_specific_cluster( client.app, user_id=user_id, cluster_id=cluster_id )", "aioresponses import aioresponses from faker import Faker from hypothesis import", "assert isinstance(list_of_clusters, list) assert len(list_of_clusters) > 0 async def test_get_cluster(", "from models_library.users import UserID from simcore_service_webserver import director_v2_api from simcore_service_webserver.director_v2_models", "user_id: UserID, cluster_id: ClusterID, cluster_patch ): print(f\"--> updating cluster with", "@settings(suppress_health_check=[HealthCheck.function_scoped_fixture]) @given(cluster_create=st.builds(ClusterCreate)) async def test_create_cluster( mocked_director_v2, client, user_id: UserID, cluster_create", "ClusterPing): await director_v2_api.ping_cluster(client.app, cluster_ping=cluster_ping) async def test_ping_specific_cluster( mocked_director_v2, client, user_id:", "user_id: UserID, project_id: ProjectID ): task_out = await director_v2_api.create_or_update_pipeline( client.app,", "not None assert isinstance(created_cluster, dict) assert \"id\" in created_cluster async", ") @settings(suppress_health_check=[HealthCheck.function_scoped_fixture]) @given(cluster_ping=st.builds(ClusterPing)) async def test_ping_cluster(mocked_director_v2, client, cluster_ping: ClusterPing): await", "async def test_create_pipeline( mocked_director_v2, client, user_id: UserID, project_id: ProjectID ):", "isinstance(cluster_details, dict) @settings(suppress_health_check=[HealthCheck.function_scoped_fixture]) @given(cluster_patch=st.from_type(ClusterPatch)) async def test_update_cluster( mocked_director_v2, client, user_id:", "assert isinstance(updated_cluster, dict) assert updated_cluster[\"id\"] == cluster_id async def test_delete_cluster(", "# pylint:disable=unused-variable # pylint:disable=unused-argument # pylint:disable=redefined-outer-name from typing import AsyncIterator", "RunningState.NOT_STARTED async def test_get_computation_task( mocked_director_v2, client, user_id: UserID, project_id: ProjectID,", "Faker) -> UserID: return UserID(faker.pyint(min_value=1)) @pytest.fixture def project_id(faker: Faker) ->", "director_v2_api from simcore_service_webserver.director_v2_models import ( ClusterCreate, ClusterPatch, ClusterPing, ) @pytest.fixture()", "pylint:disable=unused-variable # pylint:disable=unused-argument # pylint:disable=redefined-outer-name from typing import AsyncIterator import", "client.app, user_id=user_id, new_cluster=cluster_create ) assert created_cluster is not None assert", "-> ProjectID: return ProjectID(faker.uuid4()) @pytest.fixture def cluster_id(faker: Faker) -> ClusterID:", "): await director_v2_api.delete_cluster( client.app, user_id=user_id, cluster_id=cluster_id ) @settings(suppress_health_check=[HealthCheck.function_scoped_fixture]) @given(cluster_ping=st.builds(ClusterPing)) async", "with {cluster_patch=}\") updated_cluster = await director_v2_api.update_cluster( client.app, user_id=user_id, cluster_id=cluster_id, cluster_patch=cluster_patch", "cluster_ping: ClusterPing): await director_v2_api.ping_cluster(client.app, cluster_ping=cluster_ping) async def test_ping_specific_cluster( mocked_director_v2, client,", "UserID, project_id: ProjectID ): task_out = await director_v2_api.create_or_update_pipeline( client.app, user_id,", ") assert task_out assert isinstance(task_out, ComputationTask) assert task_out.state == RunningState.NOT_STARTED", "import HealthCheck, given, settings from hypothesis import strategies as st", "import ProjectID from models_library.projects_pipeline import ComputationTask from models_library.projects_state import RunningState", "test_delete_cluster( mocked_director_v2, client, user_id: UserID, cluster_id: ClusterID ): await director_v2_api.delete_cluster(", "settings from hypothesis import strategies as st from models_library.clusters import", "client, cluster_ping: ClusterPing): await director_v2_api.ping_cluster(client.app, cluster_ping=cluster_ping) async def test_ping_specific_cluster( mocked_director_v2,", "async def test_create_cluster( mocked_director_v2, client, user_id: UserID, cluster_create ): created_cluster", "director_v2_api.create_cluster( client.app, user_id=user_id, new_cluster=cluster_create ) assert created_cluster is not None", "client.app, user_id=user_id, cluster_id=cluster_id, cluster_patch=cluster_patch ) assert isinstance(updated_cluster, dict) assert updated_cluster[\"id\"]", "> 0 async def test_get_cluster( mocked_director_v2, client, user_id: UserID, cluster_id:", "client, user_id: UserID): list_of_clusters = await director_v2_api.list_clusters(client.app, user_id=user_id) assert isinstance(list_of_clusters,", "await director_v2_api.update_cluster( client.app, user_id=user_id, cluster_id=cluster_id, cluster_patch=cluster_patch ) assert isinstance(updated_cluster, dict)", "def test_update_cluster( mocked_director_v2, client, user_id: UserID, cluster_id: ClusterID, cluster_patch ):", "def project_id(faker: Faker) -> ProjectID: return ProjectID(faker.uuid4()) @pytest.fixture def cluster_id(faker:", "cluster_id: ClusterID, cluster_patch ): print(f\"--> updating cluster with {cluster_patch=}\") updated_cluster", "ClusterID(faker.pyint(min_value=0)) async def test_create_pipeline( mocked_director_v2, client, user_id: UserID, project_id: ProjectID", "assert \"id\" in created_cluster async def test_list_clusters(mocked_director_v2, client, user_id: UserID):", "user_id: UserID, cluster_create ): created_cluster = await director_v2_api.create_cluster( client.app, user_id=user_id,", "async def test_ping_cluster(mocked_director_v2, client, cluster_ping: ClusterPing): await director_v2_api.ping_cluster(client.app, cluster_ping=cluster_ping) async", "list_of_clusters = await director_v2_api.list_clusters(client.app, user_id=user_id) assert isinstance(list_of_clusters, list) assert len(list_of_clusters)", "cluster_ping=cluster_ping) async def test_ping_specific_cluster( mocked_director_v2, client, user_id: UserID, cluster_id: ClusterID", "UserID: return UserID(faker.pyint(min_value=1)) @pytest.fixture def project_id(faker: Faker) -> ProjectID: return", "): cluster = await director_v2_api.get_cluster( client.app, user_id=user_id, cluster_id=cluster_id ) assert", "@pytest.fixture def project_id(faker: Faker) -> ProjectID: return ProjectID(faker.uuid4()) @pytest.fixture def", "pylint:disable=unused-argument # pylint:disable=redefined-outer-name from typing import AsyncIterator import pytest from", "= await director_v2_api.update_cluster( client.app, user_id=user_id, cluster_id=cluster_id, cluster_patch=cluster_patch ) assert isinstance(updated_cluster,", "UserID(faker.pyint(min_value=1)) @pytest.fixture def project_id(faker: Faker) -> ProjectID: return ProjectID(faker.uuid4()) @pytest.fixture", "from models_library.projects import ProjectID from models_library.projects_pipeline import ComputationTask from models_library.projects_state", "import AsyncIterator import pytest from aioresponses import aioresponses from faker", "from simcore_service_webserver import director_v2_api from simcore_service_webserver.director_v2_models import ( ClusterCreate, ClusterPatch,", "): created_cluster = await director_v2_api.create_cluster( client.app, user_id=user_id, new_cluster=cluster_create ) assert", "await director_v2_api.create_cluster( client.app, user_id=user_id, new_cluster=cluster_create ) assert created_cluster is not", "async def test_update_cluster( mocked_director_v2, client, user_id: UserID, cluster_id: ClusterID, cluster_patch", "client, user_id: UserID, cluster_id: ClusterID ): await director_v2_api.delete_cluster( client.app, user_id=user_id,", "ClusterID ): cluster_details = await director_v2_api.get_cluster_details( client.app, user_id=user_id, cluster_id=cluster_id )", "director_v2_api.get_cluster( client.app, user_id=user_id, cluster_id=cluster_id ) assert isinstance(cluster, dict) assert cluster[\"id\"]", "project_id: ProjectID ): await director_v2_api.delete_pipeline(client.app, user_id, project_id) @settings(suppress_health_check=[HealthCheck.function_scoped_fixture]) @given(cluster_create=st.builds(ClusterCreate)) async", "print(f\"--> updating cluster with {cluster_patch=}\") updated_cluster = await director_v2_api.update_cluster( client.app,", "def cluster_id(faker: Faker) -> ClusterID: return ClusterID(faker.pyint(min_value=0)) async def test_create_pipeline(", ") @pytest.fixture() async def mocked_director_v2( director_v2_service_mock: aioresponses, ) -> AsyncIterator[aioresponses]:", "UserID, project_id: ProjectID, ): task_out = await director_v2_api.get_computation_task( client.app, user_id,", "models_library.projects import ProjectID from models_library.projects_pipeline import ComputationTask from models_library.projects_state import", "director_v2_service_mock @pytest.fixture def user_id(faker: Faker) -> UserID: return UserID(faker.pyint(min_value=1)) @pytest.fixture", "ClusterID, cluster_patch ): print(f\"--> updating cluster with {cluster_patch=}\") updated_cluster =", "cluster_id: ClusterID ): await director_v2_api.delete_cluster( client.app, user_id=user_id, cluster_id=cluster_id ) @settings(suppress_health_check=[HealthCheck.function_scoped_fixture])", "test_list_clusters(mocked_director_v2, client, user_id: UserID): list_of_clusters = await director_v2_api.list_clusters(client.app, user_id=user_id) assert", "ClusterID ): await director_v2_api.delete_cluster( client.app, user_id=user_id, cluster_id=cluster_id ) @settings(suppress_health_check=[HealthCheck.function_scoped_fixture]) @given(cluster_ping=st.builds(ClusterPing))", "async def test_delete_pipeline( mocked_director_v2, client, user_id: UserID, project_id: ProjectID ):", "mocked_director_v2, client, user_id: UserID, cluster_id: ClusterID ): await director_v2_api.ping_specific_cluster( client.app,", "director_v2_api.get_computation_task( client.app, user_id, project_id ) assert task_out assert isinstance(task_out, ComputationTask)", "created_cluster is not None assert isinstance(created_cluster, dict) assert \"id\" in", "from hypothesis import strategies as st from models_library.clusters import ClusterID", "await director_v2_api.delete_pipeline(client.app, user_id, project_id) @settings(suppress_health_check=[HealthCheck.function_scoped_fixture]) @given(cluster_create=st.builds(ClusterCreate)) async def test_create_cluster( mocked_director_v2,", "import director_v2_api from simcore_service_webserver.director_v2_models import ( ClusterCreate, ClusterPatch, ClusterPing, )", "== RunningState.NOT_STARTED async def test_delete_pipeline( mocked_director_v2, client, user_id: UserID, project_id:", "user_id: UserID, cluster_id: ClusterID ): await director_v2_api.ping_specific_cluster( client.app, user_id=user_id, cluster_id=cluster_id", "project_id: ProjectID, ): task_out = await director_v2_api.get_computation_task( client.app, user_id, project_id", "isinstance(cluster, dict) assert cluster[\"id\"] == cluster_id async def test_get_cluster_details( mocked_director_v2,", "cluster_id=cluster_id ) @settings(suppress_health_check=[HealthCheck.function_scoped_fixture]) @given(cluster_ping=st.builds(ClusterPing)) async def test_ping_cluster(mocked_director_v2, client, cluster_ping: ClusterPing):", "await director_v2_api.list_clusters(client.app, user_id=user_id) assert isinstance(list_of_clusters, list) assert len(list_of_clusters) > 0", "models_library.projects_state import RunningState from models_library.users import UserID from simcore_service_webserver import", "= await director_v2_api.create_cluster( client.app, user_id=user_id, new_cluster=cluster_create ) assert created_cluster is", "ComputationTask from models_library.projects_state import RunningState from models_library.users import UserID from", "from models_library.clusters import ClusterID from models_library.projects import ProjectID from models_library.projects_pipeline", "cluster_id=cluster_id ) assert isinstance(cluster_details, dict) @settings(suppress_health_check=[HealthCheck.function_scoped_fixture]) @given(cluster_patch=st.from_type(ClusterPatch)) async def test_update_cluster(", "user_id=user_id, new_cluster=cluster_create ) assert created_cluster is not None assert isinstance(created_cluster,", "from models_library.projects_pipeline import ComputationTask from models_library.projects_state import RunningState from models_library.users", "import Faker from hypothesis import HealthCheck, given, settings from hypothesis", "cluster_create ): created_cluster = await director_v2_api.create_cluster( client.app, user_id=user_id, new_cluster=cluster_create )", "import ( ClusterCreate, ClusterPatch, ClusterPing, ) @pytest.fixture() async def mocked_director_v2(", "dict) assert cluster[\"id\"] == cluster_id async def test_get_cluster_details( mocked_director_v2, client,", "UserID, project_id: ProjectID ): await director_v2_api.delete_pipeline(client.app, user_id, project_id) @settings(suppress_health_check=[HealthCheck.function_scoped_fixture]) @given(cluster_create=st.builds(ClusterCreate))", "user_id: UserID): list_of_clusters = await director_v2_api.list_clusters(client.app, user_id=user_id) assert isinstance(list_of_clusters, list)", "isinstance(task_out, ComputationTask) assert task_out.state == RunningState.NOT_STARTED async def test_delete_pipeline( mocked_director_v2,", "from typing import AsyncIterator import pytest from aioresponses import aioresponses", "task_out[\"state\"] == RunningState.NOT_STARTED async def test_get_computation_task( mocked_director_v2, client, user_id: UserID,", "user_id=user_id) assert isinstance(list_of_clusters, list) assert len(list_of_clusters) > 0 async def", "director_v2_api.update_cluster( client.app, user_id=user_id, cluster_id=cluster_id, cluster_patch=cluster_patch ) assert isinstance(updated_cluster, dict) assert", "-> ClusterID: return ClusterID(faker.pyint(min_value=0)) async def test_create_pipeline( mocked_director_v2, client, user_id:", "mocked_director_v2, client, user_id: UserID, cluster_id: ClusterID, cluster_patch ): print(f\"--> updating", "director_v2_api.delete_cluster( client.app, user_id=user_id, cluster_id=cluster_id ) @settings(suppress_health_check=[HealthCheck.function_scoped_fixture]) @given(cluster_ping=st.builds(ClusterPing)) async def test_ping_cluster(mocked_director_v2,", "given, settings from hypothesis import strategies as st from models_library.clusters", "user_id: UserID, cluster_id: ClusterID ): cluster_details = await director_v2_api.get_cluster_details( client.app,", "user_id(faker: Faker) -> UserID: return UserID(faker.pyint(min_value=1)) @pytest.fixture def project_id(faker: Faker)", "task_out assert isinstance(task_out, dict) assert task_out[\"state\"] == RunningState.NOT_STARTED async def", "cluster_patch=cluster_patch ) assert isinstance(updated_cluster, dict) assert updated_cluster[\"id\"] == cluster_id async", "client, user_id: UserID, project_id: ProjectID ): await director_v2_api.delete_pipeline(client.app, user_id, project_id)", "def test_ping_specific_cluster( mocked_director_v2, client, user_id: UserID, cluster_id: ClusterID ): await", "user_id=user_id, cluster_id=cluster_id, cluster_patch=cluster_patch ) assert isinstance(updated_cluster, dict) assert updated_cluster[\"id\"] ==", "def test_get_cluster( mocked_director_v2, client, user_id: UserID, cluster_id: ClusterID ): cluster", "project_id(faker: Faker) -> ProjectID: return ProjectID(faker.uuid4()) @pytest.fixture def cluster_id(faker: Faker)", "async def test_list_clusters(mocked_director_v2, client, user_id: UserID): list_of_clusters = await director_v2_api.list_clusters(client.app,", "def test_get_cluster_details( mocked_director_v2, client, user_id: UserID, cluster_id: ClusterID ): cluster_details", "assert cluster[\"id\"] == cluster_id async def test_get_cluster_details( mocked_director_v2, client, user_id:", "client, user_id: UserID, cluster_id: ClusterID ): await director_v2_api.ping_specific_cluster( client.app, user_id=user_id,", "ClusterPing, ) @pytest.fixture() async def mocked_director_v2( director_v2_service_mock: aioresponses, ) ->", "simcore_service_webserver import director_v2_api from simcore_service_webserver.director_v2_models import ( ClusterCreate, ClusterPatch, ClusterPing,", "assert task_out assert isinstance(task_out, ComputationTask) assert task_out.state == RunningState.NOT_STARTED async", "( ClusterCreate, ClusterPatch, ClusterPing, ) @pytest.fixture() async def mocked_director_v2( director_v2_service_mock:", "client, user_id: UserID, cluster_id: ClusterID, cluster_patch ): print(f\"--> updating cluster", "mocked_director_v2, client, user_id: UserID, cluster_create ): created_cluster = await director_v2_api.create_cluster(", "ProjectID ): task_out = await director_v2_api.create_or_update_pipeline( client.app, user_id, project_id )", "ProjectID: return ProjectID(faker.uuid4()) @pytest.fixture def cluster_id(faker: Faker) -> ClusterID: return", "AsyncIterator import pytest from aioresponses import aioresponses from faker import", "def test_delete_cluster( mocked_director_v2, client, user_id: UserID, cluster_id: ClusterID ): await", "ProjectID, ): task_out = await director_v2_api.get_computation_task( client.app, user_id, project_id )", "): cluster_details = await director_v2_api.get_cluster_details( client.app, user_id=user_id, cluster_id=cluster_id ) assert", "user_id: UserID, project_id: ProjectID ): await director_v2_api.delete_pipeline(client.app, user_id, project_id) @settings(suppress_health_check=[HealthCheck.function_scoped_fixture])", "{cluster_patch=}\") updated_cluster = await director_v2_api.update_cluster( client.app, user_id=user_id, cluster_id=cluster_id, cluster_patch=cluster_patch )", "cluster_id: ClusterID ): cluster_details = await director_v2_api.get_cluster_details( client.app, user_id=user_id, cluster_id=cluster_id", "hypothesis import HealthCheck, given, settings from hypothesis import strategies as", "): task_out = await director_v2_api.get_computation_task( client.app, user_id, project_id ) assert", "await director_v2_api.get_cluster( client.app, user_id=user_id, cluster_id=cluster_id ) assert isinstance(cluster, dict) assert", "Faker) -> ClusterID: return ClusterID(faker.pyint(min_value=0)) async def test_create_pipeline( mocked_director_v2, client,", "): await director_v2_api.delete_pipeline(client.app, user_id, project_id) @settings(suppress_health_check=[HealthCheck.function_scoped_fixture]) @given(cluster_create=st.builds(ClusterCreate)) async def test_create_cluster(", "mocked_director_v2( director_v2_service_mock: aioresponses, ) -> AsyncIterator[aioresponses]: yield director_v2_service_mock @pytest.fixture def", "cluster = await director_v2_api.get_cluster( client.app, user_id=user_id, cluster_id=cluster_id ) assert isinstance(cluster,", "models_library.clusters import ClusterID from models_library.projects import ProjectID from models_library.projects_pipeline import", "cluster_details = await director_v2_api.get_cluster_details( client.app, user_id=user_id, cluster_id=cluster_id ) assert isinstance(cluster_details,", "UserID, cluster_id: ClusterID ): cluster = await director_v2_api.get_cluster( client.app, user_id=user_id,", "from models_library.projects_state import RunningState from models_library.users import UserID from simcore_service_webserver", "typing import AsyncIterator import pytest from aioresponses import aioresponses from", "cluster_id async def test_get_cluster_details( mocked_director_v2, client, user_id: UserID, cluster_id: ClusterID", "updated_cluster[\"id\"] == cluster_id async def test_delete_cluster( mocked_director_v2, client, user_id: UserID,", "created_cluster async def test_list_clusters(mocked_director_v2, client, user_id: UserID): list_of_clusters = await", "await director_v2_api.delete_cluster( client.app, user_id=user_id, cluster_id=cluster_id ) @settings(suppress_health_check=[HealthCheck.function_scoped_fixture]) @given(cluster_ping=st.builds(ClusterPing)) async def", "user_id: UserID, cluster_id: ClusterID ): cluster = await director_v2_api.get_cluster( client.app,", "user_id, project_id) @settings(suppress_health_check=[HealthCheck.function_scoped_fixture]) @given(cluster_create=st.builds(ClusterCreate)) async def test_create_cluster( mocked_director_v2, client, user_id:", "user_id=user_id, cluster_id=cluster_id ) @settings(suppress_health_check=[HealthCheck.function_scoped_fixture]) @given(cluster_ping=st.builds(ClusterPing)) async def test_ping_cluster(mocked_director_v2, client, cluster_ping:", "= await director_v2_api.get_computation_task( client.app, user_id, project_id ) assert task_out assert", "def mocked_director_v2( director_v2_service_mock: aioresponses, ) -> AsyncIterator[aioresponses]: yield director_v2_service_mock @pytest.fixture", "client.app, user_id, project_id ) assert task_out assert isinstance(task_out, ComputationTask) assert", "= await director_v2_api.create_or_update_pipeline( client.app, user_id, project_id ) assert task_out assert", ") assert isinstance(cluster_details, dict) @settings(suppress_health_check=[HealthCheck.function_scoped_fixture]) @given(cluster_patch=st.from_type(ClusterPatch)) async def test_update_cluster( mocked_director_v2,", "cluster_patch ): print(f\"--> updating cluster with {cluster_patch=}\") updated_cluster = await", "import strategies as st from models_library.clusters import ClusterID from models_library.projects", "faker import Faker from hypothesis import HealthCheck, given, settings from", "from hypothesis import HealthCheck, given, settings from hypothesis import strategies", "from aioresponses import aioresponses from faker import Faker from hypothesis", "\"id\" in created_cluster async def test_list_clusters(mocked_director_v2, client, user_id: UserID): list_of_clusters", "test_create_cluster( mocked_director_v2, client, user_id: UserID, cluster_create ): created_cluster = await", "cluster with {cluster_patch=}\") updated_cluster = await director_v2_api.update_cluster( client.app, user_id=user_id, cluster_id=cluster_id,", "await director_v2_api.get_cluster_details( client.app, user_id=user_id, cluster_id=cluster_id ) assert isinstance(cluster_details, dict) @settings(suppress_health_check=[HealthCheck.function_scoped_fixture])", "ClusterID from models_library.projects import ProjectID from models_library.projects_pipeline import ComputationTask from", "== RunningState.NOT_STARTED async def test_get_computation_task( mocked_director_v2, client, user_id: UserID, project_id:", "ProjectID from models_library.projects_pipeline import ComputationTask from models_library.projects_state import RunningState from", "Faker from hypothesis import HealthCheck, given, settings from hypothesis import", "mocked_director_v2, client, user_id: UserID, project_id: ProjectID, ): task_out = await", "test_ping_specific_cluster( mocked_director_v2, client, user_id: UserID, cluster_id: ClusterID ): await director_v2_api.ping_specific_cluster(", "import ComputationTask from models_library.projects_state import RunningState from models_library.users import UserID", "test_create_pipeline( mocked_director_v2, client, user_id: UserID, project_id: ProjectID ): task_out =", "from faker import Faker from hypothesis import HealthCheck, given, settings", "UserID): list_of_clusters = await director_v2_api.list_clusters(client.app, user_id=user_id) assert isinstance(list_of_clusters, list) assert", "user_id: UserID, cluster_id: ClusterID ): await director_v2_api.delete_cluster( client.app, user_id=user_id, cluster_id=cluster_id", "ClusterCreate, ClusterPatch, ClusterPing, ) @pytest.fixture() async def mocked_director_v2( director_v2_service_mock: aioresponses,", "test_get_cluster( mocked_director_v2, client, user_id: UserID, cluster_id: ClusterID ): cluster =", ") assert isinstance(cluster, dict) assert cluster[\"id\"] == cluster_id async def", "models_library.projects_pipeline import ComputationTask from models_library.projects_state import RunningState from models_library.users import", "user_id, project_id ) assert task_out assert isinstance(task_out, ComputationTask) assert task_out.state", "def test_ping_cluster(mocked_director_v2, client, cluster_ping: ClusterPing): await director_v2_api.ping_cluster(client.app, cluster_ping=cluster_ping) async def", "assert task_out.state == RunningState.NOT_STARTED async def test_delete_pipeline( mocked_director_v2, client, user_id:", "@settings(suppress_health_check=[HealthCheck.function_scoped_fixture]) @given(cluster_ping=st.builds(ClusterPing)) async def test_ping_cluster(mocked_director_v2, client, cluster_ping: ClusterPing): await director_v2_api.ping_cluster(client.app,", "import RunningState from models_library.users import UserID from simcore_service_webserver import director_v2_api", "UserID, cluster_id: ClusterID ): cluster_details = await director_v2_api.get_cluster_details( client.app, user_id=user_id,", "import aioresponses from faker import Faker from hypothesis import HealthCheck,", "cluster_id=cluster_id ) assert isinstance(cluster, dict) assert cluster[\"id\"] == cluster_id async", "RunningState from models_library.users import UserID from simcore_service_webserver import director_v2_api from", "await director_v2_api.ping_cluster(client.app, cluster_ping=cluster_ping) async def test_ping_specific_cluster( mocked_director_v2, client, user_id: UserID,", "new_cluster=cluster_create ) assert created_cluster is not None assert isinstance(created_cluster, dict)", "@given(cluster_ping=st.builds(ClusterPing)) async def test_ping_cluster(mocked_director_v2, client, cluster_ping: ClusterPing): await director_v2_api.ping_cluster(client.app, cluster_ping=cluster_ping)", "test_update_cluster( mocked_director_v2, client, user_id: UserID, cluster_id: ClusterID, cluster_patch ): print(f\"-->", ") assert task_out assert isinstance(task_out, dict) assert task_out[\"state\"] == RunningState.NOT_STARTED", "UserID from simcore_service_webserver import director_v2_api from simcore_service_webserver.director_v2_models import ( ClusterCreate,", "import ClusterID from models_library.projects import ProjectID from models_library.projects_pipeline import ComputationTask", "cluster_id async def test_delete_cluster( mocked_director_v2, client, user_id: UserID, cluster_id: ClusterID", "def test_list_clusters(mocked_director_v2, client, user_id: UserID): list_of_clusters = await director_v2_api.list_clusters(client.app, user_id=user_id)", "test_ping_cluster(mocked_director_v2, client, cluster_ping: ClusterPing): await director_v2_api.ping_cluster(client.app, cluster_ping=cluster_ping) async def test_ping_specific_cluster(", "mocked_director_v2, client, user_id: UserID, cluster_id: ClusterID ): await director_v2_api.delete_cluster( client.app,", "@given(cluster_create=st.builds(ClusterCreate)) async def test_create_cluster( mocked_director_v2, client, user_id: UserID, cluster_create ):", "): task_out = await director_v2_api.create_or_update_pipeline( client.app, user_id, project_id ) assert", "pytest from aioresponses import aioresponses from faker import Faker from", "task_out = await director_v2_api.create_or_update_pipeline( client.app, user_id, project_id ) assert task_out", "client.app, user_id, project_id ) assert task_out assert isinstance(task_out, dict) assert", "async def mocked_director_v2( director_v2_service_mock: aioresponses, ) -> AsyncIterator[aioresponses]: yield director_v2_service_mock", "isinstance(task_out, dict) assert task_out[\"state\"] == RunningState.NOT_STARTED async def test_get_computation_task( mocked_director_v2,", "project_id: ProjectID ): task_out = await director_v2_api.create_or_update_pipeline( client.app, user_id, project_id", "@pytest.fixture def cluster_id(faker: Faker) -> ClusterID: return ClusterID(faker.pyint(min_value=0)) async def", "# pylint:disable=unused-argument # pylint:disable=redefined-outer-name from typing import AsyncIterator import pytest", "async def test_get_cluster_details( mocked_director_v2, client, user_id: UserID, cluster_id: ClusterID ):", "user_id, project_id ) assert task_out assert isinstance(task_out, dict) assert task_out[\"state\"]", "# pylint:disable=redefined-outer-name from typing import AsyncIterator import pytest from aioresponses", "assert created_cluster is not None assert isinstance(created_cluster, dict) assert \"id\"", "await director_v2_api.create_or_update_pipeline( client.app, user_id, project_id ) assert task_out assert isinstance(task_out,", "assert isinstance(task_out, dict) assert task_out[\"state\"] == RunningState.NOT_STARTED async def test_get_computation_task(", "client, user_id: UserID, cluster_id: ClusterID ): cluster_details = await director_v2_api.get_cluster_details(", "dict) assert updated_cluster[\"id\"] == cluster_id async def test_delete_cluster( mocked_director_v2, client,", "RunningState.NOT_STARTED async def test_delete_pipeline( mocked_director_v2, client, user_id: UserID, project_id: ProjectID", "models_library.users import UserID from simcore_service_webserver import director_v2_api from simcore_service_webserver.director_v2_models import", "UserID, cluster_id: ClusterID ): await director_v2_api.delete_cluster( client.app, user_id=user_id, cluster_id=cluster_id )", "isinstance(list_of_clusters, list) assert len(list_of_clusters) > 0 async def test_get_cluster( mocked_director_v2,", "user_id=user_id, cluster_id=cluster_id ) assert isinstance(cluster_details, dict) @settings(suppress_health_check=[HealthCheck.function_scoped_fixture]) @given(cluster_patch=st.from_type(ClusterPatch)) async def", "isinstance(updated_cluster, dict) assert updated_cluster[\"id\"] == cluster_id async def test_delete_cluster( mocked_director_v2,", "user_id=user_id, cluster_id=cluster_id ) assert isinstance(cluster, dict) assert cluster[\"id\"] == cluster_id", "): print(f\"--> updating cluster with {cluster_patch=}\") updated_cluster = await director_v2_api.update_cluster(", "async def test_ping_specific_cluster( mocked_director_v2, client, user_id: UserID, cluster_id: ClusterID ):", "return UserID(faker.pyint(min_value=1)) @pytest.fixture def project_id(faker: Faker) -> ProjectID: return ProjectID(faker.uuid4())", ") assert isinstance(updated_cluster, dict) assert updated_cluster[\"id\"] == cluster_id async def", "director_v2_api.get_cluster_details( client.app, user_id=user_id, cluster_id=cluster_id ) assert isinstance(cluster_details, dict) @settings(suppress_health_check=[HealthCheck.function_scoped_fixture]) @given(cluster_patch=st.from_type(ClusterPatch))", "def test_get_computation_task( mocked_director_v2, client, user_id: UserID, project_id: ProjectID, ): task_out", "import UserID from simcore_service_webserver import director_v2_api from simcore_service_webserver.director_v2_models import (", "pylint:disable=redefined-outer-name from typing import AsyncIterator import pytest from aioresponses import", "client, user_id: UserID, cluster_id: ClusterID ): cluster = await director_v2_api.get_cluster(", "project_id ) assert task_out assert isinstance(task_out, dict) assert task_out[\"state\"] ==", "is not None assert isinstance(created_cluster, dict) assert \"id\" in created_cluster", "return ClusterID(faker.pyint(min_value=0)) async def test_create_pipeline( mocked_director_v2, client, user_id: UserID, project_id:", "as st from models_library.clusters import ClusterID from models_library.projects import ProjectID", "isinstance(created_cluster, dict) assert \"id\" in created_cluster async def test_list_clusters(mocked_director_v2, client,", "created_cluster = await director_v2_api.create_cluster( client.app, user_id=user_id, new_cluster=cluster_create ) assert created_cluster", "= await director_v2_api.list_clusters(client.app, user_id=user_id) assert isinstance(list_of_clusters, list) assert len(list_of_clusters) >", "director_v2_api.create_or_update_pipeline( client.app, user_id, project_id ) assert task_out assert isinstance(task_out, dict)", "director_v2_api.delete_pipeline(client.app, user_id, project_id) @settings(suppress_health_check=[HealthCheck.function_scoped_fixture]) @given(cluster_create=st.builds(ClusterCreate)) async def test_create_cluster( mocked_director_v2, client,", "assert task_out assert isinstance(task_out, dict) assert task_out[\"state\"] == RunningState.NOT_STARTED async", "client.app, user_id=user_id, cluster_id=cluster_id ) @settings(suppress_health_check=[HealthCheck.function_scoped_fixture]) @given(cluster_ping=st.builds(ClusterPing)) async def test_ping_cluster(mocked_director_v2, client,", "director_v2_api.ping_cluster(client.app, cluster_ping=cluster_ping) async def test_ping_specific_cluster( mocked_director_v2, client, user_id: UserID, cluster_id:", "cluster_id=cluster_id, cluster_patch=cluster_patch ) assert isinstance(updated_cluster, dict) assert updated_cluster[\"id\"] == cluster_id", "mocked_director_v2, client, user_id: UserID, project_id: ProjectID ): task_out = await", "client, user_id: UserID, project_id: ProjectID, ): task_out = await director_v2_api.get_computation_task(", "updating cluster with {cluster_patch=}\") updated_cluster = await director_v2_api.update_cluster( client.app, user_id=user_id,", "list) assert len(list_of_clusters) > 0 async def test_get_cluster( mocked_director_v2, client,", "= await director_v2_api.get_cluster( client.app, user_id=user_id, cluster_id=cluster_id ) assert isinstance(cluster, dict)", "= await director_v2_api.get_cluster_details( client.app, user_id=user_id, cluster_id=cluster_id ) assert isinstance(cluster_details, dict)", "user_id: UserID, project_id: ProjectID, ): task_out = await director_v2_api.get_computation_task( client.app,", "== cluster_id async def test_get_cluster_details( mocked_director_v2, client, user_id: UserID, cluster_id:", "aioresponses from faker import Faker from hypothesis import HealthCheck, given,", "ClusterPatch, ClusterPing, ) @pytest.fixture() async def mocked_director_v2( director_v2_service_mock: aioresponses, )", "dict) @settings(suppress_health_check=[HealthCheck.function_scoped_fixture]) @given(cluster_patch=st.from_type(ClusterPatch)) async def test_update_cluster( mocked_director_v2, client, user_id: UserID,", "async def test_get_computation_task( mocked_director_v2, client, user_id: UserID, project_id: ProjectID, ):", "assert isinstance(created_cluster, dict) assert \"id\" in created_cluster async def test_list_clusters(mocked_director_v2,", "import pytest from aioresponses import aioresponses from faker import Faker", "Faker) -> ProjectID: return ProjectID(faker.uuid4()) @pytest.fixture def cluster_id(faker: Faker) ->", "0 async def test_get_cluster( mocked_director_v2, client, user_id: UserID, cluster_id: ClusterID", "== cluster_id async def test_delete_cluster( mocked_director_v2, client, user_id: UserID, cluster_id:", "ClusterID ): cluster = await director_v2_api.get_cluster( client.app, user_id=user_id, cluster_id=cluster_id )", "@settings(suppress_health_check=[HealthCheck.function_scoped_fixture]) @given(cluster_patch=st.from_type(ClusterPatch)) async def test_update_cluster( mocked_director_v2, client, user_id: UserID, cluster_id:", "AsyncIterator[aioresponses]: yield director_v2_service_mock @pytest.fixture def user_id(faker: Faker) -> UserID: return", "len(list_of_clusters) > 0 async def test_get_cluster( mocked_director_v2, client, user_id: UserID,", "cluster[\"id\"] == cluster_id async def test_get_cluster_details( mocked_director_v2, client, user_id: UserID,", "-> AsyncIterator[aioresponses]: yield director_v2_service_mock @pytest.fixture def user_id(faker: Faker) -> UserID:", "def user_id(faker: Faker) -> UserID: return UserID(faker.pyint(min_value=1)) @pytest.fixture def project_id(faker:", "assert task_out[\"state\"] == RunningState.NOT_STARTED async def test_get_computation_task( mocked_director_v2, client, user_id:", "assert updated_cluster[\"id\"] == cluster_id async def test_delete_cluster( mocked_director_v2, client, user_id:", "client, user_id: UserID, cluster_create ): created_cluster = await director_v2_api.create_cluster( client.app,", "test_get_computation_task( mocked_director_v2, client, user_id: UserID, project_id: ProjectID, ): task_out =", "@given(cluster_patch=st.from_type(ClusterPatch)) async def test_update_cluster( mocked_director_v2, client, user_id: UserID, cluster_id: ClusterID,", "assert isinstance(task_out, ComputationTask) assert task_out.state == RunningState.NOT_STARTED async def test_delete_pipeline(", "@pytest.fixture def user_id(faker: Faker) -> UserID: return UserID(faker.pyint(min_value=1)) @pytest.fixture def", "hypothesis import strategies as st from models_library.clusters import ClusterID from", "def test_create_cluster( mocked_director_v2, client, user_id: UserID, cluster_create ): created_cluster =", "aioresponses, ) -> AsyncIterator[aioresponses]: yield director_v2_service_mock @pytest.fixture def user_id(faker: Faker)", "ClusterID: return ClusterID(faker.pyint(min_value=0)) async def test_create_pipeline( mocked_director_v2, client, user_id: UserID,", "ProjectID ): await director_v2_api.delete_pipeline(client.app, user_id, project_id) @settings(suppress_health_check=[HealthCheck.function_scoped_fixture]) @given(cluster_create=st.builds(ClusterCreate)) async def", "None assert isinstance(created_cluster, dict) assert \"id\" in created_cluster async def", "client.app, user_id=user_id, cluster_id=cluster_id ) assert isinstance(cluster_details, dict) @settings(suppress_health_check=[HealthCheck.function_scoped_fixture]) @given(cluster_patch=st.from_type(ClusterPatch)) async", "from simcore_service_webserver.director_v2_models import ( ClusterCreate, ClusterPatch, ClusterPing, ) @pytest.fixture() async", "mocked_director_v2, client, user_id: UserID, cluster_id: ClusterID ): cluster = await", "assert len(list_of_clusters) > 0 async def test_get_cluster( mocked_director_v2, client, user_id:", "client.app, user_id=user_id, cluster_id=cluster_id ) assert isinstance(cluster, dict) assert cluster[\"id\"] ==", "assert isinstance(cluster, dict) assert cluster[\"id\"] == cluster_id async def test_get_cluster_details(", "UserID, cluster_id: ClusterID, cluster_patch ): print(f\"--> updating cluster with {cluster_patch=}\")" ]
[ "f: # reader = csv.reader(f) # for row in reader:", "from folium import plugins from folium.plugins import HeatMap import csv", "self.map = folium.Map(location=[float(row[1]), float(row[2])], zoom_start = 18) # def loadGpsLoc():", "18) # def loadGpsLoc(): # folium.Marker([float(row[1]), float(row[2])], popup=\"<i>\"+row[0]+\"</i>\", tooltip=tooltip, icon=icon_circle).add_to(rangsit_map)", "[] # with open(self.data) as f: # reader = csv.reader(f)", "with open(self.data) as f: # reader = csv.reader(f) # for", "folium.plugins import HeatMap import csv # class plitterMap(): # def", "def loadMap(): # self.map = folium.Map(location=[float(row[1]), float(row[2])], zoom_start = 18)", "to frames and saves images by different interval, or overlap,", "reader: # df_row = [] # df_row.append(row[0]) # df_row.append(row[0]) #", "df[0][0] # def loadMap(): # self.map = folium.Map(location=[float(row[1]), float(row[2])], zoom_start", "frames and saves images by different interval, or overlap, etc", "folium from folium import plugins from folium.plugins import HeatMap import", "overlap, etc ''' import folium from folium import plugins from", "csv.reader(f) # for row in reader: # df_row = []", "# df.append(row) # self.tooltip = df[0][0] # def loadMap(): #", "import plugins from folium.plugins import HeatMap import csv # class", "df_row.append(row[0]) # df.append(row) # self.tooltip = df[0][0] # def loadMap():", "''' import folium from folium import plugins from folium.plugins import", "= file_path # df = [] # with open(self.data) as", "zoom_start = 18) # def loadGpsLoc(): # folium.Marker([float(row[1]), float(row[2])], popup=\"<i>\"+row[0]+\"</i>\",", "import folium from folium import plugins from folium.plugins import HeatMap", "# self.data = file_path # df = [] # with", "= csv.reader(f) # for row in reader: # df_row =", "import csv # class plitterMap(): # def __int__(self, file_path): #", "self.data = file_path # df = [] # with open(self.data)", "file_path # df = [] # with open(self.data) as f:", "= 18) # def loadGpsLoc(): # folium.Marker([float(row[1]), float(row[2])], popup=\"<i>\"+row[0]+\"</i>\", tooltip=tooltip,", "float(row[2])], zoom_start = 18) # def loadGpsLoc(): # folium.Marker([float(row[1]), float(row[2])],", "def loadGpsLoc(): # folium.Marker([float(row[1]), float(row[2])], popup=\"<i>\"+row[0]+\"</i>\", tooltip=tooltip, icon=icon_circle).add_to(rangsit_map) # rangsit_map", "import HeatMap import csv # class plitterMap(): # def __int__(self,", "etc ''' import folium from folium import plugins from folium.plugins", "csv # class plitterMap(): # def __int__(self, file_path): # self.data", "''' converts video to frames and saves images by different", "images by different interval, or overlap, etc ''' import folium", "# for row in reader: # df_row = [] #", "reader = csv.reader(f) # for row in reader: # df_row", "loadMap(): # self.map = folium.Map(location=[float(row[1]), float(row[2])], zoom_start = 18) #", "from folium.plugins import HeatMap import csv # class plitterMap(): #", "df_row = [] # df_row.append(row[0]) # df_row.append(row[0]) # df_row.append(row[0]) #", "= [] # df_row.append(row[0]) # df_row.append(row[0]) # df_row.append(row[0]) # df.append(row)", "# df_row.append(row[0]) # df.append(row) # self.tooltip = df[0][0] # def", "def __int__(self, file_path): # self.data = file_path # df =", "plitterMap(): # def __int__(self, file_path): # self.data = file_path #", "df.append(row) # self.tooltip = df[0][0] # def loadMap(): # self.map", "[] # df_row.append(row[0]) # df_row.append(row[0]) # df_row.append(row[0]) # df.append(row) #", "# self.tooltip = df[0][0] # def loadMap(): # self.map =", "class plitterMap(): # def __int__(self, file_path): # self.data = file_path", "video to frames and saves images by different interval, or", "# def __int__(self, file_path): # self.data = file_path # df", "# with open(self.data) as f: # reader = csv.reader(f) #", "by different interval, or overlap, etc ''' import folium from", "folium.Map(location=[float(row[1]), float(row[2])], zoom_start = 18) # def loadGpsLoc(): # folium.Marker([float(row[1]),", "as f: # reader = csv.reader(f) # for row in", "file_path): # self.data = file_path # df = [] #", "folium import plugins from folium.plugins import HeatMap import csv #", "# class plitterMap(): # def __int__(self, file_path): # self.data =", "interval, or overlap, etc ''' import folium from folium import", "df_row.append(row[0]) # df_row.append(row[0]) # df_row.append(row[0]) # df.append(row) # self.tooltip =", "df = [] # with open(self.data) as f: # reader", "and saves images by different interval, or overlap, etc '''", "plugins from folium.plugins import HeatMap import csv # class plitterMap():", "df_row.append(row[0]) # df_row.append(row[0]) # df.append(row) # self.tooltip = df[0][0] #", "saves images by different interval, or overlap, etc ''' import", "__int__(self, file_path): # self.data = file_path # df = []", "open(self.data) as f: # reader = csv.reader(f) # for row", "in reader: # df_row = [] # df_row.append(row[0]) # df_row.append(row[0])", "converts video to frames and saves images by different interval,", "# def loadMap(): # self.map = folium.Map(location=[float(row[1]), float(row[2])], zoom_start =", "# def loadGpsLoc(): # folium.Marker([float(row[1]), float(row[2])], popup=\"<i>\"+row[0]+\"</i>\", tooltip=tooltip, icon=icon_circle).add_to(rangsit_map) #", "HeatMap import csv # class plitterMap(): # def __int__(self, file_path):", "for row in reader: # df_row = [] # df_row.append(row[0])", "# reader = csv.reader(f) # for row in reader: #", "# df_row = [] # df_row.append(row[0]) # df_row.append(row[0]) # df_row.append(row[0])", "# df_row.append(row[0]) # df_row.append(row[0]) # df.append(row) # self.tooltip = df[0][0]", "or overlap, etc ''' import folium from folium import plugins", "# self.map = folium.Map(location=[float(row[1]), float(row[2])], zoom_start = 18) # def", "self.tooltip = df[0][0] # def loadMap(): # self.map = folium.Map(location=[float(row[1]),", "# df = [] # with open(self.data) as f: #", "= df[0][0] # def loadMap(): # self.map = folium.Map(location=[float(row[1]), float(row[2])],", "= [] # with open(self.data) as f: # reader =", "# df_row.append(row[0]) # df_row.append(row[0]) # df_row.append(row[0]) # df.append(row) # self.tooltip", "= folium.Map(location=[float(row[1]), float(row[2])], zoom_start = 18) # def loadGpsLoc(): #", "different interval, or overlap, etc ''' import folium from folium", "row in reader: # df_row = [] # df_row.append(row[0]) #" ]
[ "shape is different') im_max = float(np.max(image)) mask_max = 1.0 #select", "bbox= None, augmentation=False): ''' image: nparray, must have 3 dimension", "from within the bbox augmentation: turn on/off data augmentation. The", ": bbox[1], bbox[2]:bbox[3]] mask_ = mask[bbox[0] : bbox[1], bbox[2]:bbox[3]] else:", "bbox[1], bbox[2]:bbox[3]] else: img_ = image mask_ = mask while", "random_y = np.random.randint(0, mask_.shape[0] - patch_size) img_patch = img_[:, random_y", "# check bbox if bbox[0] < 0 or bbox [2]", "to 'channels last' as required by unet ''' if np.ndim(mask)", "random_augmentation(img, mask): #you can add any augmentations you need return", ": -crop_size, crop_size : -crop_size] mask_patch = np.expand_dims(mask_patch, 2) x.append(img_patch)", "mask bbox: None or tuple of 4 ints, (min_y, max_y,", "the image returned, patch is square crop_size: int, how much", "img_[:, random_y : random_y + patch_size, random_x : random_x +", "if np.ndim(mask) != 2 or np.ndim(image) != 3: raise ValueError('image", "augmentations you need return img, mask def batch_generator(image, mask, batch_size=1,", "is turned to 'channels last' as required by unet '''", "mask_patch) # mask is cropped as it may be useful", "if bbox is not None: # check bbox if bbox[0]", "bbox if bbox[0] < 0 or bbox [2] < 0", "/ mask_max if augmentation: img_patch, mask_patch = random_augmentation(img_patch, mask_patch) #", "patch size\") img_ = image[:, bbox[0] : bbox[1], bbox[2]:bbox[3]] mask_", "bbox[0] < 0 or bbox [2] < 0 \\ or", "''' image: nparray, must have 3 dimension mask: nparray, 2", "else: img_ = image mask_ = mask while 1: x", "mask while 1: x = [] y = [] for", "batch_size=1, crop_size=0, patch_size=256, bbox= None, augmentation=False): ''' image: nparray, must", "batch_size: int, number of images in a batch patch_size: int,", "3 dims and mask 2 dims') if mask.shape != image.shape[1:]:", "bbox[0] : bbox[1], bbox[2]:bbox[3]] mask_ = mask[bbox[0] : bbox[1], bbox[2]:bbox[3]]", "'channels last' as required by unet ''' if np.ndim(mask) !=", "= mask while 1: x = [] y = []", "= img_[:, random_y : random_y + patch_size, random_x : random_x", "is random_augmentation() above returns batch of image and mask patches,", "> bbox[3] \\ or patch_size <= 0: raise ValueError(\"Incorrect bbox", "= image mask_ = mask while 1: x = []", "1: x = [] y = [] for i in", "augmentation: img_patch, mask_patch = random_augmentation(img_patch, mask_patch) # mask is cropped", "cropped as it may be useful for some convnets that", "+ patch_size, random_x : random_x + patch_size] / im_max #", "of the image returned, patch is square crop_size: int, how", "random_y + patch_size, random_x : random_x + patch_size] / im_max", "+ patch_size > bbox[3] \\ or patch_size <= 0: raise", "above returns batch of image and mask patches, image is", "[] y = [] for i in range (batch_size): random_x", "for some convnets that have output size less than input", "2) mask_patch = mask_[random_y : random_y + patch_size, random_x :", "same size as image batch_size: int, number of images in", "or bbox[0] + patch_size > bbox[1] or bbox[2] + patch_size", "random_x : random_x + patch_size] / im_max # transform the", "x = [] y = [] for i in range", "on/off data augmentation. The augmentation function is random_augmentation() above returns", "number of images in a batch patch_size: int, size of", "< 0 or bbox [2] < 0 \\ or bbox[1]", "2 dimensions, same size as image batch_size: int, number of", "for i in range (batch_size): random_x = np.random.randint(0, mask_.shape[1] -", "(batch_size): random_x = np.random.randint(0, mask_.shape[1] - patch_size) random_y = np.random.randint(0,", "patch_size) img_patch = img_[:, random_y : random_y + patch_size, random_x", "mask: nparray, 2 dimensions, same size as image batch_size: int,", "bbox is not None: # check bbox if bbox[0] <", "random_x : random_x + patch_size] / mask_max if augmentation: img_patch,", "add any augmentations you need return img, mask def batch_generator(image,", "square crop_size: int, how much pixels should be cropped off", "nparray, 2 dimensions, same size as image batch_size: int, number", "dims') if mask.shape != image.shape[1:]: raise ValueError('image and mask shape", "max_y, min_x, max_x), the data is selected from within the", "mask_patch = mask_patch[crop_size : -crop_size, crop_size : -crop_size] mask_patch =", "to channels-last (default tensorflow format) img_patch = np.moveaxis(img_patch, 0, 2)", "np.random.randint(0, mask_.shape[0] - patch_size) img_patch = img_[:, random_y : random_y", "turn on/off data augmentation. The augmentation function is random_augmentation() above", "raise ValueError('image must have 3 dims and mask 2 dims')", "useful for some convnets that have output size less than", "bbox[3] \\ or patch_size <= 0: raise ValueError(\"Incorrect bbox or", "and mask patches, image is turned to 'channels last' as", "as image batch_size: int, number of images in a batch", "bbox: None or tuple of 4 ints, (min_y, max_y, min_x,", "img_ = image mask_ = mask while 1: x =", "mask_patch[crop_size : -crop_size, crop_size : -crop_size] mask_patch = np.expand_dims(mask_patch, 2)", "img_ = image[:, bbox[0] : bbox[1], bbox[2]:bbox[3]] mask_ = mask[bbox[0]", "(rasterio format) to channels-last (default tensorflow format) img_patch = np.moveaxis(img_patch,", "if crop_size > 0: mask_patch = mask_patch[crop_size : -crop_size, crop_size", "mask.shape[0] or bbox[3] > mask.shape[0] \\ or bbox[0] + patch_size", "0: raise ValueError(\"Incorrect bbox or patch size\") img_ = image[:,", "int, size of the image returned, patch is square crop_size:", "selected from within the bbox augmentation: turn on/off data augmentation.", "batch patch_size: int, size of the image returned, patch is", "= np.moveaxis(img_patch, 0, 2) mask_patch = mask_[random_y : random_y +", "some convnets that have output size less than input if", "patch_size <= 0: raise ValueError(\"Incorrect bbox or patch size\") img_", "img_patch = img_[:, random_y : random_y + patch_size, random_x :", "is cropped as it may be useful for some convnets", "size of the image returned, patch is square crop_size: int,", "ValueError('image must have 3 dims and mask 2 dims') if", "may be useful for some convnets that have output size", "is square crop_size: int, how much pixels should be cropped", "patch_size > bbox[3] \\ or patch_size <= 0: raise ValueError(\"Incorrect", "0 or bbox [2] < 0 \\ or bbox[1] >", "ints, (min_y, max_y, min_x, max_x), the data is selected from", "image: nparray, must have 3 dimension mask: nparray, 2 dimensions,", "bbox[3] > mask.shape[0] \\ or bbox[0] + patch_size > bbox[1]", "have 3 dimension mask: nparray, 2 dimensions, same size as", "not None: # check bbox if bbox[0] < 0 or", "or bbox[3] > mask.shape[0] \\ or bbox[0] + patch_size >", "= image[:, bbox[0] : bbox[1], bbox[2]:bbox[3]] mask_ = mask[bbox[0] :", "image from channels-first (rasterio format) to channels-last (default tensorflow format)", "turned to 'channels last' as required by unet ''' if", "bbox[1], bbox[2]:bbox[3]] mask_ = mask[bbox[0] : bbox[1], bbox[2]:bbox[3]] else: img_", "+ patch_size] / mask_max if augmentation: img_patch, mask_patch = random_augmentation(img_patch,", "cropped off the mask bbox: None or tuple of 4", "> bbox[1] or bbox[2] + patch_size > bbox[3] \\ or", "or patch size\") img_ = image[:, bbox[0] : bbox[1], bbox[2]:bbox[3]]", "range (batch_size): random_x = np.random.randint(0, mask_.shape[1] - patch_size) random_y =", "transform the image from channels-first (rasterio format) to channels-last (default", "random_y + patch_size, random_x : random_x + patch_size] / mask_max", "patches, image is turned to 'channels last' as required by", "+ patch_size > bbox[1] or bbox[2] + patch_size > bbox[3]", "bbox or patch size\") img_ = image[:, bbox[0] : bbox[1],", "np.ndim(mask) != 2 or np.ndim(image) != 3: raise ValueError('image must", "float(np.max(image)) mask_max = 1.0 #select subimage if bbox is not", "augmentation. The augmentation function is random_augmentation() above returns batch of", "format) img_patch = np.moveaxis(img_patch, 0, 2) mask_patch = mask_[random_y :", "mask_ = mask while 1: x = [] y =", "= mask[bbox[0] : bbox[1], bbox[2]:bbox[3]] else: img_ = image mask_", "2 dims') if mask.shape != image.shape[1:]: raise ValueError('image and mask", "= [] for i in range (batch_size): random_x = np.random.randint(0,", "mask is cropped as it may be useful for some", "pixels should be cropped off the mask bbox: None or", "if augmentation: img_patch, mask_patch = random_augmentation(img_patch, mask_patch) # mask is", "much pixels should be cropped off the mask bbox: None", "in a batch patch_size: int, size of the image returned,", "batch of image and mask patches, image is turned to", "dimensions, same size as image batch_size: int, number of images", "= mask_[random_y : random_y + patch_size, random_x : random_x +", "0, 2) mask_patch = mask_[random_y : random_y + patch_size, random_x", "a batch patch_size: int, size of the image returned, patch", "returned, patch is square crop_size: int, how much pixels should", "patch_size: int, size of the image returned, patch is square", "mask.shape != image.shape[1:]: raise ValueError('image and mask shape is different')", "mask 2 dims') if mask.shape != image.shape[1:]: raise ValueError('image and", "patch_size] / im_max # transform the image from channels-first (rasterio", "img_patch = np.moveaxis(img_patch, 0, 2) mask_patch = mask_[random_y : random_y", "ValueError('image and mask shape is different') im_max = float(np.max(image)) mask_max", "is not None: # check bbox if bbox[0] < 0", "size\") img_ = image[:, bbox[0] : bbox[1], bbox[2]:bbox[3]] mask_ =", "i in range (batch_size): random_x = np.random.randint(0, mask_.shape[1] - patch_size)", "img_patch, mask_patch = random_augmentation(img_patch, mask_patch) # mask is cropped as", "and mask shape is different') im_max = float(np.max(image)) mask_max =", "< 0 \\ or bbox[1] > mask.shape[0] or bbox[3] >", "= np.random.randint(0, mask_.shape[1] - patch_size) random_y = np.random.randint(0, mask_.shape[0] -", "unet ''' if np.ndim(mask) != 2 or np.ndim(image) != 3:", "be cropped off the mask bbox: None or tuple of", "that have output size less than input if crop_size >", "than input if crop_size > 0: mask_patch = mask_patch[crop_size :", ": bbox[1], bbox[2]:bbox[3]] else: img_ = image mask_ = mask", "None or tuple of 4 ints, (min_y, max_y, min_x, max_x),", "bbox[2]:bbox[3]] else: img_ = image mask_ = mask while 1:", "or bbox [2] < 0 \\ or bbox[1] > mask.shape[0]", "crop_size=0, patch_size=256, bbox= None, augmentation=False): ''' image: nparray, must have", "mask_[random_y : random_y + patch_size, random_x : random_x + patch_size]", "- patch_size) img_patch = img_[:, random_y : random_y + patch_size,", "crop_size: int, how much pixels should be cropped off the", "return img, mask def batch_generator(image, mask, batch_size=1, crop_size=0, patch_size=256, bbox=", "''' if np.ndim(mask) != 2 or np.ndim(image) != 3: raise", "random_augmentation(img_patch, mask_patch) # mask is cropped as it may be", ": random_y + patch_size, random_x : random_x + patch_size] /", "as np def random_augmentation(img, mask): #you can add any augmentations", "mask.shape[0] \\ or bbox[0] + patch_size > bbox[1] or bbox[2]", "any augmentations you need return img, mask def batch_generator(image, mask,", "<= 0: raise ValueError(\"Incorrect bbox or patch size\") img_ =", "image and mask patches, image is turned to 'channels last'", "im_max # transform the image from channels-first (rasterio format) to", "of image and mask patches, image is turned to 'channels", "mask_max = 1.0 #select subimage if bbox is not None:", "random_x + patch_size] / mask_max if augmentation: img_patch, mask_patch =", "have 3 dims and mask 2 dims') if mask.shape !=", "random_y : random_y + patch_size, random_x : random_x + patch_size]", "+ patch_size, random_x : random_x + patch_size] / mask_max if", "int, how much pixels should be cropped off the mask", "numpy as np def random_augmentation(img, mask): #you can add any", "batch_generator(image, mask, batch_size=1, crop_size=0, patch_size=256, bbox= None, augmentation=False): ''' image:", "None, augmentation=False): ''' image: nparray, must have 3 dimension mask:", "-crop_size, crop_size : -crop_size] mask_patch = np.expand_dims(mask_patch, 2) x.append(img_patch) y.append(mask_patch)", "mask_max if augmentation: img_patch, mask_patch = random_augmentation(img_patch, mask_patch) # mask", "#select subimage if bbox is not None: # check bbox", "patch_size, random_x : random_x + patch_size] / mask_max if augmentation:", "image.shape[1:]: raise ValueError('image and mask shape is different') im_max =", "crop_size > 0: mask_patch = mask_patch[crop_size : -crop_size, crop_size :", "def batch_generator(image, mask, batch_size=1, crop_size=0, patch_size=256, bbox= None, augmentation=False): '''", "raise ValueError(\"Incorrect bbox or patch size\") img_ = image[:, bbox[0]", "bbox[1] > mask.shape[0] or bbox[3] > mask.shape[0] \\ or bbox[0]", "patch_size=256, bbox= None, augmentation=False): ''' image: nparray, must have 3", "> mask.shape[0] \\ or bbox[0] + patch_size > bbox[1] or", "> mask.shape[0] or bbox[3] > mask.shape[0] \\ or bbox[0] +", "should be cropped off the mask bbox: None or tuple", "within the bbox augmentation: turn on/off data augmentation. The augmentation", "the image from channels-first (rasterio format) to channels-last (default tensorflow", "output size less than input if crop_size > 0: mask_patch", "mask[bbox[0] : bbox[1], bbox[2]:bbox[3]] else: img_ = image mask_ =", "function is random_augmentation() above returns batch of image and mask", "image mask_ = mask while 1: x = [] y", "it may be useful for some convnets that have output", "dimension mask: nparray, 2 dimensions, same size as image batch_size:", "= float(np.max(image)) mask_max = 1.0 #select subimage if bbox is", "patch_size > bbox[1] or bbox[2] + patch_size > bbox[3] \\", "of images in a batch patch_size: int, size of the", "nparray, must have 3 dimension mask: nparray, 2 dimensions, same", "y = [] for i in range (batch_size): random_x =", "dims and mask 2 dims') if mask.shape != image.shape[1:]: raise", "mask_.shape[1] - patch_size) random_y = np.random.randint(0, mask_.shape[0] - patch_size) img_patch", "patch_size] / mask_max if augmentation: img_patch, mask_patch = random_augmentation(img_patch, mask_patch)", "np.random.randint(0, mask_.shape[1] - patch_size) random_y = np.random.randint(0, mask_.shape[0] - patch_size)", "you need return img, mask def batch_generator(image, mask, batch_size=1, crop_size=0,", "patch_size) random_y = np.random.randint(0, mask_.shape[0] - patch_size) img_patch = img_[:,", "bbox augmentation: turn on/off data augmentation. The augmentation function is", "of 4 ints, (min_y, max_y, min_x, max_x), the data is", "crop_size : -crop_size] mask_patch = np.expand_dims(mask_patch, 2) x.append(img_patch) y.append(mask_patch) yield", "int, number of images in a batch patch_size: int, size", "random_x + patch_size] / im_max # transform the image from", "random_augmentation() above returns batch of image and mask patches, image", "and mask 2 dims') if mask.shape != image.shape[1:]: raise ValueError('image", "mask patches, image is turned to 'channels last' as required", "The augmentation function is random_augmentation() above returns batch of image", "or np.ndim(image) != 3: raise ValueError('image must have 3 dims", "in range (batch_size): random_x = np.random.randint(0, mask_.shape[1] - patch_size) random_y", "mask, batch_size=1, crop_size=0, patch_size=256, bbox= None, augmentation=False): ''' image: nparray,", "\\ or bbox[0] + patch_size > bbox[1] or bbox[2] +", "= [] y = [] for i in range (batch_size):", "ValueError(\"Incorrect bbox or patch size\") img_ = image[:, bbox[0] :", "\\ or bbox[1] > mask.shape[0] or bbox[3] > mask.shape[0] \\", "patch is square crop_size: int, how much pixels should be", "- patch_size) random_y = np.random.randint(0, mask_.shape[0] - patch_size) img_patch =", "subimage if bbox is not None: # check bbox if", "patch_size, random_x : random_x + patch_size] / im_max # transform", "the data is selected from within the bbox augmentation: turn", "off the mask bbox: None or tuple of 4 ints,", "[] for i in range (batch_size): random_x = np.random.randint(0, mask_.shape[1]", "as it may be useful for some convnets that have", "(min_y, max_y, min_x, max_x), the data is selected from within", "= random_augmentation(img_patch, mask_patch) # mask is cropped as it may", ": -crop_size] mask_patch = np.expand_dims(mask_patch, 2) x.append(img_patch) y.append(mask_patch) yield (np.array(x),", "or tuple of 4 ints, (min_y, max_y, min_x, max_x), the", "> 0: mask_patch = mask_patch[crop_size : -crop_size, crop_size : -crop_size]", "returns batch of image and mask patches, image is turned", "must have 3 dims and mask 2 dims') if mask.shape", "channels-last (default tensorflow format) img_patch = np.moveaxis(img_patch, 0, 2) mask_patch", "required by unet ''' if np.ndim(mask) != 2 or np.ndim(image)", "[2] < 0 \\ or bbox[1] > mask.shape[0] or bbox[3]", "np def random_augmentation(img, mask): #you can add any augmentations you", "# mask is cropped as it may be useful for", "size as image batch_size: int, number of images in a", "mask shape is different') im_max = float(np.max(image)) mask_max = 1.0", "mask): #you can add any augmentations you need return img,", "image is turned to 'channels last' as required by unet", "data augmentation. The augmentation function is random_augmentation() above returns batch", "max_x), the data is selected from within the bbox augmentation:", "!= 2 or np.ndim(image) != 3: raise ValueError('image must have", ": random_x + patch_size] / im_max # transform the image", "0: mask_patch = mask_patch[crop_size : -crop_size, crop_size : -crop_size] mask_patch", "im_max = float(np.max(image)) mask_max = 1.0 #select subimage if bbox", "channels-first (rasterio format) to channels-last (default tensorflow format) img_patch =", "3: raise ValueError('image must have 3 dims and mask 2", "#you can add any augmentations you need return img, mask", "if bbox[0] < 0 or bbox [2] < 0 \\", "by unet ''' if np.ndim(mask) != 2 or np.ndim(image) !=", "!= 3: raise ValueError('image must have 3 dims and mask", "the mask bbox: None or tuple of 4 ints, (min_y,", "less than input if crop_size > 0: mask_patch = mask_patch[crop_size", "# transform the image from channels-first (rasterio format) to channels-last", "size less than input if crop_size > 0: mask_patch =", "if mask.shape != image.shape[1:]: raise ValueError('image and mask shape is", "or bbox[2] + patch_size > bbox[3] \\ or patch_size <=", "image returned, patch is square crop_size: int, how much pixels", "mask_ = mask[bbox[0] : bbox[1], bbox[2]:bbox[3]] else: img_ = image", "mask_.shape[0] - patch_size) img_patch = img_[:, random_y : random_y +", "image batch_size: int, number of images in a batch patch_size:", "augmentation: turn on/off data augmentation. The augmentation function is random_augmentation()", "-crop_size] mask_patch = np.expand_dims(mask_patch, 2) x.append(img_patch) y.append(mask_patch) yield (np.array(x), np.array(y))", "1.0 #select subimage if bbox is not None: # check", "can add any augmentations you need return img, mask def", "tuple of 4 ints, (min_y, max_y, min_x, max_x), the data", "while 1: x = [] y = [] for i", "= np.random.randint(0, mask_.shape[0] - patch_size) img_patch = img_[:, random_y :", "the bbox augmentation: turn on/off data augmentation. The augmentation function", "2 or np.ndim(image) != 3: raise ValueError('image must have 3", "np.ndim(image) != 3: raise ValueError('image must have 3 dims and", "None: # check bbox if bbox[0] < 0 or bbox", "bbox[0] + patch_size > bbox[1] or bbox[2] + patch_size >", "must have 3 dimension mask: nparray, 2 dimensions, same size", "mask def batch_generator(image, mask, batch_size=1, crop_size=0, patch_size=256, bbox= None, augmentation=False):", "random_x = np.random.randint(0, mask_.shape[1] - patch_size) random_y = np.random.randint(0, mask_.shape[0]", "min_x, max_x), the data is selected from within the bbox", "image[:, bbox[0] : bbox[1], bbox[2]:bbox[3]] mask_ = mask[bbox[0] : bbox[1],", "as required by unet ''' if np.ndim(mask) != 2 or", "format) to channels-last (default tensorflow format) img_patch = np.moveaxis(img_patch, 0,", "is selected from within the bbox augmentation: turn on/off data", "convnets that have output size less than input if crop_size", "4 ints, (min_y, max_y, min_x, max_x), the data is selected", "from channels-first (rasterio format) to channels-last (default tensorflow format) img_patch", "images in a batch patch_size: int, size of the image", "augmentation=False): ''' image: nparray, must have 3 dimension mask: nparray,", "mask_patch = mask_[random_y : random_y + patch_size, random_x : random_x", "!= image.shape[1:]: raise ValueError('image and mask shape is different') im_max", "bbox [2] < 0 \\ or bbox[1] > mask.shape[0] or", "mask_patch = random_augmentation(img_patch, mask_patch) # mask is cropped as it", "+ patch_size] / im_max # transform the image from channels-first", "\\ or patch_size <= 0: raise ValueError(\"Incorrect bbox or patch", "0 \\ or bbox[1] > mask.shape[0] or bbox[3] > mask.shape[0]", "raise ValueError('image and mask shape is different') im_max = float(np.max(image))", "bbox[2] + patch_size > bbox[3] \\ or patch_size <= 0:", "3 dimension mask: nparray, 2 dimensions, same size as image", "/ im_max # transform the image from channels-first (rasterio format)", "last' as required by unet ''' if np.ndim(mask) != 2", "bbox[2]:bbox[3]] mask_ = mask[bbox[0] : bbox[1], bbox[2]:bbox[3]] else: img_ =", "tensorflow format) img_patch = np.moveaxis(img_patch, 0, 2) mask_patch = mask_[random_y", "= mask_patch[crop_size : -crop_size, crop_size : -crop_size] mask_patch = np.expand_dims(mask_patch,", "import numpy as np def random_augmentation(img, mask): #you can add", "or patch_size <= 0: raise ValueError(\"Incorrect bbox or patch size\")", "need return img, mask def batch_generator(image, mask, batch_size=1, crop_size=0, patch_size=256,", ": random_x + patch_size] / mask_max if augmentation: img_patch, mask_patch", "or bbox[1] > mask.shape[0] or bbox[3] > mask.shape[0] \\ or", "bbox[1] or bbox[2] + patch_size > bbox[3] \\ or patch_size", "augmentation function is random_augmentation() above returns batch of image and", "how much pixels should be cropped off the mask bbox:", "is different') im_max = float(np.max(image)) mask_max = 1.0 #select subimage", "(default tensorflow format) img_patch = np.moveaxis(img_patch, 0, 2) mask_patch =", "np.moveaxis(img_patch, 0, 2) mask_patch = mask_[random_y : random_y + patch_size,", "be useful for some convnets that have output size less", "input if crop_size > 0: mask_patch = mask_patch[crop_size : -crop_size,", "img, mask def batch_generator(image, mask, batch_size=1, crop_size=0, patch_size=256, bbox= None,", "def random_augmentation(img, mask): #you can add any augmentations you need", "have output size less than input if crop_size > 0:", "check bbox if bbox[0] < 0 or bbox [2] <", "data is selected from within the bbox augmentation: turn on/off", "= 1.0 #select subimage if bbox is not None: #", "different') im_max = float(np.max(image)) mask_max = 1.0 #select subimage if" ]
[ "the required properties # are conditional on the type selected.", "isinstance(model_field, JSONField) or isinstance(field, DRFJSONField) or isinstance(getattr(field, 'model_field', None), JSONField)", "type selected. try: view_model = field.context['view'].model except (AttributeError, KeyError): view_model", "= [] model = getattr(view, 'model', None) if model: for", "'Meta') and hasattr(serializer.Meta, 'model'): # Update help text for common", "of related resources.'), 'summary_fields': _('Data structure with name/description for related", "serializer and hasattr(serializer, 'Meta') and hasattr(serializer.Meta, 'model'): try: model_field =", "== 'https://towerhost': default = '{}://{}'.format(self.request.scheme, self.request.get_host()) field_info['default'] = default except", "generics.ListAPIView) and hasattr(view, 'paginator'): metadata['max_page_size'] = view.paginator.max_page_size return metadata class", "'datetime' elif ( RelatedField in field.__class__.__bases__ or isinstance(model_field, ForeignKey) ):", "= smart_text(opts.verbose_name) field_info['help_text'] = field_help_text[field.field_name].format(verbose_name) if field.field_name == 'type': field_info['filterable']", "True # Special handling of inventory source_region choices that vary", "clone_request(request, method) obj = None try: # Test global permissions", "field == 'id' and hasattr(view, 'attach'): continue actions[method].pop(field) return actions", "False) text_attrs = [ 'read_only', 'label', 'help_text', 'min_length', 'max_length', 'min_value',", "actions: for field in list(actions[method].keys()): if field == 'id': continue", "write-only. if getattr(field, 'write_only', False): field_info['write_only'] = True # Special", "field.field_name in ('url', 'custom_virtualenv', 'token'): field_info['type'] = 'string' elif field.field_name", "names in metadata roles = [] model = getattr(view, 'model',", "= field_help_text[field.field_name].format(verbose_name) if field.field_name == 'type': field_info['filterable'] = True else:", "when we can't POST/PUT). actions = {} for method in", "'summary_fields': _('Data structure with name/description for related resources.'), 'created': _('Timestamp", "serializer, method=None): filterer = getattr(serializer, 'filter_field_metadata', lambda fields, method: fields)", "aren't relevant # when reading a field and remove write-only", "= 'json' elif ( isinstance(field, ManyRelatedField) and field.field_name == 'credentials'", "this {}.'), 'related': _('Data structure with URLs of related resources.'),", "else: # If user has appropriate permissions for the view,", "request, view): metadata = super(RoleMetadata, self).determine_metadata(request, view) if 'actions' in", "or field.field_name == 'credential_passwords' ): field_info['type'] = 'json' elif (", "if getattr(model_field, '__accepts_json__', None): field_info['type'] = 'json' field_info['filterable'] = True", "global permissions if hasattr(view, 'check_permissions'): view.check_permissions(view.request) # Test object permissions", "properties # are conditional on the type selected. try: view_model", "awx.main.fields import JSONField, ImplicitRoleField from awx.main.models import InventorySource, NotificationTemplate from", "elif ( isinstance(field, JSONField) or isinstance(model_field, JSONField) or isinstance(field, DRFJSONField)", "information for GET requests (so field names/labels are # available", "hasattr(view, 'get_serializer'): serializer = view.get_serializer() if hasattr(serializer, 'get_types'): metadata['types'] =", "rest_framework import exceptions from rest_framework import metadata from rest_framework import", "are conditional on the type selected. if field.field_name == 'notification_configuration':", "'integer' elif field.field_name in ('created', 'modified'): field_info['type'] = 'datetime' elif", "field names/labels are # available even when we can't POST/PUT).", "# are conditional on the type selected. try: view_model =", "For GET method, remove meta attributes that aren't relevant #", "determine_metadata(self, request, view): metadata = super(RoleMetadata, self).determine_metadata(request, view) if 'actions'", "rest_framework import serializers from rest_framework.relations import RelatedField, ManyRelatedField from rest_framework.fields", "False): field_info['write_only'] = True # Special handling of inventory source_region", "attr, None) if value is not None and value !=", "= True else: for model_field in serializer.Meta.model._meta.fields: if field.field_name ==", "# store request on self so we can use it", "type(field) is ImplicitRoleField: roles.append(field.name) if len(roles) > 0: metadata['object_roles'] =", "awx.main.models import InventorySource, NotificationTemplate from awx.main.scheduler.kubernetes import PodManager class Metadata(metadata.SimpleMetadata):", "field.choices.items()] # Indicate if a field is write-only. if getattr(field,", "== model_field.name: if getattr(model_field, '__accepts_json__', None): field_info['type'] = 'json' field_info['filterable']", "== 'credential_passwords' ): field_info['type'] = 'json' elif ( isinstance(field, ManyRelatedField)", "'related_search_fields', None): metadata['related_search_fields'] = view.related_search_fields # include role names in", "default = '{}://{}'.format(self.request.scheme, self.request.get_host()) field_info['default'] = default except serializers.SkipField: pass", "that aren't relevant # when reading a field and remove", "Rights Reserved. from collections import OrderedDict # Django from django.core.exceptions", "): field_info['type'] = 'json' elif ( isinstance(field, ManyRelatedField) and field.field_name", "method=None): filterer = getattr(serializer, 'filter_field_metadata', lambda fields, method: fields) return", "# Special handling of notification configuration where the required properties", "rest_framework.fields import JSONField as DRFJSONField from rest_framework.request import clone_request #", "'category', 'category_slug', 'defined_in_file' ] for attr in text_attrs: value =", "field has a default value. # FIXME: Still isn't showing", "'type' and hasattr(serializer, 'get_type_choices'): meta['choices'] = serializer.get_type_choices() # For GET", "BooleanField): field_info['type'] = 'boolean' return field_info def get_serializer_info(self, serializer, method=None):", "that should be supplied. serializer = view.get_serializer(instance=obj) actions[method] = self.get_serializer_info(serializer,", "= PodManager().pod_definition # Add type choices if available from the", "self.get_serializer_info(field) if not isinstance(field, (RelatedField, ManyRelatedField)) and hasattr(field, 'choices'): field_info['choices']", "field.field_name == 'credential_passwords' ): field_info['type'] = 'json' elif ( isinstance(field,", "# when reading a field and remove write-only fields. if", "model_field in serializer.Meta.model._meta.fields: if field.field_name == model_field.name: if getattr(model_field, '__accepts_json__',", "return filterer( super(Metadata, self).get_serializer_info(serializer), method ) def determine_actions(self, request, view):", "as TOWER_URL_BASE) self.request = request try: setattr(view, '_request', request) metadata", "= 'POST' if method in actions: for field in list(actions[method].keys()):", "# appropriate metadata about the fields that should be supplied.", "can't POST/PUT). actions = {} for method in {'GET', 'PUT',", "= force_text(value, strings_only=True) placeholder = getattr(field, 'placeholder', serializers.empty) if placeholder", "if field.field_name == 'source_regions': for cp in ('azure_rm', 'ec2', 'gce'):", "in ('azure_rm', 'ec2', 'gce'): get_regions = getattr(InventorySource, 'get_%s_region_choices' % cp)", "# are conditional on the type selected. if field.field_name ==", "in ('created', 'modified'): field_info['type'] = 'datetime' elif ( RelatedField in", "in list(actions[method].keys()): if field == 'id': continue actions[method].pop(field) return actions", "== NotificationTemplate and field.field_name == 'messages': for (notification_type_name, notification_tr_name, notification_type_class)", "False) if meta.pop('read_only', False): if field == 'id' and hasattr(view,", "= OrderedDict() field_info['type'] = self.label_lookup[field] field_info['required'] = getattr(field, 'required', False)", "model = getattr(view, 'model', None) if model: for field in", "if method == 'PUT' and hasattr(view, 'get_object'): obj = view.get_object()", "ImplicitRoleField: roles.append(field.name) if len(roles) > 0: metadata['object_roles'] = roles from", "= 'list_of_ids' elif isinstance(model_field, BooleanField): field_info['type'] = 'boolean' return field_info", "== 'TOWER_URL_BASE' and default == 'https://towerhost': default = '{}://{}'.format(self.request.scheme, self.request.get_host())", "= True # Special handling of inventory source_region choices that", "from rest_framework import generics if isinstance(view, generics.ListAPIView) and hasattr(view, 'paginator'):", "'modified'): field_info['type'] = 'datetime' elif ( RelatedField in field.__class__.__bases__ or", "# All Rights Reserved. from collections import OrderedDict # Django", "False # Indicate if a field has a default value.", "notification_type_class.init_parameters # Special handling of notification messages where the required", "super(Metadata, self).get_serializer_info(serializer), method ) def determine_actions(self, request, view): # Add", "last modified.'), } if field.field_name in field_help_text: opts = serializer.Meta.model._meta.concrete_model._meta", "import PodManager class Metadata(metadata.SimpleMetadata): def get_field_info(self, field): field_info = OrderedDict()", "fields. if method in ('PUT', 'POST'): # This value should", "(c) 2016 Ansible, Inc. # All Rights Reserved. from collections", "about the fields that should be supplied. serializer = view.get_serializer(instance=obj)", "field_info['type'] = 'integer' elif field.field_name in ('created', 'modified'): field_info['type'] =", "\"help_text\": \"Database ID for this role.\"}, \"disassociate\": {\"type\": \"integer\", \"label\":", "request, view): # Add field information for GET requests (so", "if serializer and hasattr(serializer, 'Meta') and hasattr(serializer.Meta, 'model'): try: model_field", "JSONField, ImplicitRoleField from awx.main.models import InventorySource, NotificationTemplate from awx.main.scheduler.kubernetes import", "for PUT/POST, so don't # show it (file-based read-only settings", "placeholder = getattr(field, 'placeholder', serializers.empty) if placeholder is not serializers.empty:", "modified.'), } if field.field_name in field_help_text: opts = serializer.Meta.model._meta.concrete_model._meta verbose_name", "meta attributes that aren't relevant # when reading a field", "field_info['choices'] = [(choice_value, choice_name) for choice_value, choice_name in field.choices.items()] #", "metadata roles = [] model = getattr(view, 'model', None) if", "import force_text, smart_text from django.utils.translation import ugettext_lazy as _ #", "metadata from rest_framework import serializers from rest_framework.relations import RelatedField, ManyRelatedField", "if placeholder is not serializers.empty: field_info['placeholder'] = placeholder serializer =", "actions = super(SublistAttachDetatchMetadata, self).determine_actions(request, view) method = 'POST' if method", "available from the view. if getattr(view, 'related_search_fields', None): metadata['related_search_fields'] =", "'messages': for (notification_type_name, notification_tr_name, notification_type_class) in NotificationTemplate.NOTIFICATION_TYPES: field_info[notification_type_name] = notification_type_class.default_messages", "isinstance(model_field, BooleanField): field_info['type'] = 'boolean' return field_info def get_serializer_info(self, serializer,", "so we can use it to generate field defaults #", "in actions: for field in list(actions[method].keys()): if field == 'id':", "'id': _('Database ID for this {}.'), 'name': _('Name of this", "of this {}.'), 'type': _('Data type for this {}.'), 'url':", "vary based on # selected inventory source. if field.field_name ==", "if field.field_name == 'type': field_info['type'] = 'choice' elif field.field_name in", "None), JSONField) or field.field_name == 'credential_passwords' ): field_info['type'] = 'json'", "finally: view.request = request for field, meta in list(actions[method].items()): if", "even when we can't POST/PUT). actions = {} for method", "RelatedField, ManyRelatedField from rest_framework.fields import JSONField as DRFJSONField from rest_framework.request", "field.field_name == 'TOWER_URL_BASE' and default == 'https://towerhost': default = '{}://{}'.format(self.request.scheme,", "if not isinstance(meta, dict): continue if field == \"pod_spec_override\": meta['default']", "a field is write-only. if getattr(field, 'write_only', False): field_info['write_only'] =", "method == 'GET': attrs_to_remove = ('required', 'read_only', 'default', 'min_length', 'max_length',", "model: for field in model._meta.get_fields(): if type(field) is ImplicitRoleField: roles.append(field.name)", "'check_permissions'): view.check_permissions(view.request) # Test object permissions if method == 'PUT'", "this view/serializer. if hasattr(view, 'get_serializer'): serializer = view.get_serializer() if hasattr(serializer,", "if 'actions' in metadata: metadata['actions'].pop('POST') metadata['actions']['POST'] = { \"id\": {\"type\":", "\"disassociate\": {\"type\": \"integer\", \"label\": \"Disassociate\", \"help_text\": \"Provide to remove this", "{\"type\": \"integer\", \"label\": \"Disassociate\", \"help_text\": \"Provide to remove this role.\"},", "view.get_object() except (exceptions.APIException, PermissionDenied, Http404): continue else: # If user", "= [ 'read_only', 'label', 'help_text', 'min_length', 'max_length', 'min_value', 'max_value', 'category',", "{}.'), 'related': _('Data structure with URLs of related resources.'), 'summary_fields':", "and default == 'https://towerhost': default = '{}://{}'.format(self.request.scheme, self.request.get_host()) field_info['default'] =", "getattr(model_field, '__accepts_json__', None): field_info['type'] = 'json' field_info['filterable'] = True break", "'label', 'help_text', 'min_length', 'max_length', 'min_value', 'max_value', 'category', 'category_slug', 'defined_in_file' ]", "\"Provide to remove this role.\"}, } return metadata class SublistAttachDetatchMetadata(Metadata):", "django.db.models.fields import PositiveIntegerField, BooleanField from django.db.models.fields.related import ForeignKey from django.http", "default except serializers.SkipField: pass if getattr(field, 'child', None): field_info['child'] =", "and remove write-only fields. if method == 'GET': attrs_to_remove =", "(AttributeError, KeyError): view_model = None if view_model == NotificationTemplate and", "if type(field) is ImplicitRoleField: roles.append(field.name) if len(roles) > 0: metadata['object_roles']", "field): field_info = OrderedDict() field_info['type'] = self.label_lookup[field] field_info['required'] = getattr(field,", "the type selected. if field.field_name == 'notification_configuration': for (notification_type_name, notification_tr_name,", "the serializer. if field == 'type' and hasattr(serializer, 'get_type_choices'): meta['choices']", "of fields returned... model_field = None if serializer and hasattr(serializer,", "\"label\": \"Disassociate\", \"help_text\": \"Provide to remove this role.\"}, } return", "model_field = serializer.Meta.model._meta.get_field(field.field_name) except Exception: pass if field.field_name == 'type':", "{}.'), 'name': _('Name of this {}.'), 'description': _('Optional description of", "'TOWER_URL_BASE' and default == 'https://towerhost': default = '{}://{}'.format(self.request.scheme, self.request.get_host()) field_info['default']", "get_serializer_info(self, serializer, method=None): filterer = getattr(serializer, 'filter_field_metadata', lambda fields, method:", "{}.'), 'url': _('URL for this {}.'), 'related': _('Data structure with", "actions = {} for method in {'GET', 'PUT', 'POST'} &", "django.http import Http404 from django.utils.encoding import force_text, smart_text from django.utils.translation", "'read_only', 'default', 'min_length', 'max_length', 'placeholder') for attr in attrs_to_remove: meta.pop(attr,", "PermissionDenied, Http404): continue else: # If user has appropriate permissions", "metadata['actions'].pop('POST') metadata['actions']['POST'] = { \"id\": {\"type\": \"integer\", \"label\": \"ID\", \"help_text\":", "# Add search fields if available from the view. if", "= field.context['view'].model except (AttributeError, KeyError): view_model = None if view_model", "type selected. if field.field_name == 'notification_configuration': for (notification_type_name, notification_tr_name, notification_type_class)", "get_regions() # Special handling of group_by choices for EC2. if", "hasattr(field, 'choices'): field_info['choices'] = [(choice_value, choice_name) for choice_value, choice_name in", "launch-time credentials ): field_info['type'] = 'list_of_ids' elif isinstance(model_field, BooleanField): field_info['type']", "for this role.\"}, \"disassociate\": {\"type\": \"integer\", \"label\": \"Disassociate\", \"help_text\": \"Provide", "except (AttributeError, KeyError): view_model = None if view_model == NotificationTemplate", "('related', 'summary_fields'): field_info['type'] = 'object' elif isinstance(field, PositiveIntegerField): field_info['type'] =", "if meta.pop('read_only', False): if field == 'id' and hasattr(view, 'attach'):", "'get_object'): obj = view.get_object() except (exceptions.APIException, PermissionDenied, Http404): continue else:", "field_info['filterable'] = True break else: field_info['filterable'] = False # Indicate", "getattr(field, 'parent', None) if serializer and hasattr(serializer, 'Meta') and hasattr(serializer.Meta,", "requests (so field names/labels are # available even when we", "{} was last modified.'), } if field.field_name in field_help_text: opts", "and field.field_name == 'credentials' # launch-time credentials ): field_info['type'] =", "JSONField) or isinstance(model_field, JSONField) or isinstance(field, DRFJSONField) or isinstance(getattr(field, 'model_field',", "elif ( RelatedField in field.__class__.__bases__ or isinstance(model_field, ForeignKey) ): field_info['type']", "if value is not None and value != '': field_info[attr]", "= notification_type_class.default_messages # Update type of fields returned... model_field =", "type choices if available from the serializer. if field ==", "except (exceptions.APIException, PermissionDenied, Http404): continue else: # If user has", "read-only settings can't be updated) meta.pop('defined_in_file', False) if meta.pop('read_only', False):", "# Test object permissions if method == 'PUT' and hasattr(view,", "isinstance(view, generics.ListAPIView) and hasattr(view, 'paginator'): metadata['max_page_size'] = view.paginator.max_page_size return metadata", "'': field_info[attr] = force_text(value, strings_only=True) placeholder = getattr(field, 'placeholder', serializers.empty)", "'Meta') and hasattr(serializer.Meta, 'model'): try: model_field = serializer.Meta.model._meta.get_field(field.field_name) except Exception:", "method in {'GET', 'PUT', 'POST'} & set(view.allowed_methods): view.request = clone_request(request,", "'get_types'): metadata['types'] = serializer.get_types() # Add search fields if available", "PodManager class Metadata(metadata.SimpleMetadata): def get_field_info(self, field): field_info = OrderedDict() field_info['type']", "{\"type\": \"integer\", \"label\": \"ID\", \"help_text\": \"Database ID for this role.\"},", "determine_actions(self, request, view): # Add field information for GET requests", "'max_length', 'min_value', 'max_value', 'category', 'category_slug', 'defined_in_file' ] for attr in", "{ \"id\": {\"type\": \"integer\", \"label\": \"ID\", \"help_text\": \"Database ID for", "None): metadata['related_search_fields'] = view.related_search_fields # include role names in metadata", "view): # Add field information for GET requests (so field", "PermissionDenied from django.db.models.fields import PositiveIntegerField, BooleanField from django.db.models.fields.related import ForeignKey", "== 'id' and hasattr(view, 'attach'): continue actions[method].pop(field) return actions def", "get_regions = getattr(InventorySource, 'get_%s_region_choices' % cp) field_info['%s_region_choices' % cp] =", "# FIXME: Still isn't showing all default values? try: default", "cp in ('ec2',): get_group_by_choices = getattr(InventorySource, 'get_%s_group_by_choices' % cp) field_info['%s_group_by_choices'", "field.field_name in ('related', 'summary_fields'): field_info['type'] = 'object' elif isinstance(field, PositiveIntegerField):", "with name/description for related resources.'), 'created': _('Timestamp when this {}", "so don't # show it (file-based read-only settings can't be", "don't # show it (file-based read-only settings can't be updated)", "None) meta.get('child', {}).pop(attr, None) if meta.pop('write_only', False): actions['GET'].pop(field) # For", "): field_info['type'] = 'id' elif ( isinstance(field, JSONField) or isinstance(model_field,", "from the view. if getattr(view, 'search_fields', None): metadata['search_fields'] = view.search_fields", "view.paginator.max_page_size return metadata class RoleMetadata(Metadata): def determine_metadata(self, request, view): metadata", "smart_text from django.utils.translation import ugettext_lazy as _ # Django REST", "_('Database ID for this {}.'), 'name': _('Name of this {}.'),", "'gce'): get_regions = getattr(InventorySource, 'get_%s_region_choices' % cp) field_info['%s_region_choices' % cp]", "{}.'), 'description': _('Optional description of this {}.'), 'type': _('Data type", "notification_tr_name, notification_type_class) in NotificationTemplate.NOTIFICATION_TYPES: field_info[notification_type_name] = notification_type_class.default_messages # Update type", "reading a field and remove write-only fields. if method ==", "len(roles) > 0: metadata['object_roles'] = roles from rest_framework import generics", "PUT/POST, so don't # show it (file-based read-only settings can't", "opts = serializer.Meta.model._meta.concrete_model._meta verbose_name = smart_text(opts.verbose_name) field_info['help_text'] = field_help_text[field.field_name].format(verbose_name) if", "in NotificationTemplate.NOTIFICATION_TYPES: field_info[notification_type_name] = notification_type_class.default_messages # Update type of fields", "in attrs_to_remove: meta.pop(attr, None) meta.get('child', {}).pop(attr, None) if meta.pop('write_only', False):", "'read_only', 'label', 'help_text', 'min_length', 'max_length', 'min_value', 'max_value', 'category', 'category_slug', 'defined_in_file'", "field_info[attr] = force_text(value, strings_only=True) placeholder = getattr(field, 'placeholder', serializers.empty) if", "are conditional on the type selected. try: view_model = field.context['view'].model", "= 'choice' elif field.field_name in ('url', 'custom_virtualenv', 'token'): field_info['type'] =", "'object' elif isinstance(field, PositiveIntegerField): field_info['type'] = 'integer' elif field.field_name in", "field_info[notification_type_name] = notification_type_class.default_messages # Update type of fields returned... model_field", "a field has a default value. # FIXME: Still isn't", "'choice' elif field.field_name in ('url', 'custom_virtualenv', 'token'): field_info['type'] = 'string'", "isinstance(meta, dict): continue if field == \"pod_spec_override\": meta['default'] = PodManager().pod_definition", "in field.__class__.__bases__ or isinstance(model_field, ForeignKey) ): field_info['type'] = 'id' elif", "fields that should be supplied. serializer = view.get_serializer(instance=obj) actions[method] =", "getattr(field, attr, None) if value is not None and value", "returned... model_field = None if serializer and hasattr(serializer, 'Meta') and", "include # appropriate metadata about the fields that should be", "was last modified.'), } if field.field_name in field_help_text: opts =", "self so we can use it to generate field defaults", "and hasattr(view, 'attach'): continue actions[method].pop(field) return actions def determine_metadata(self, request,", "= getattr(InventorySource, 'get_%s_group_by_choices' % cp) field_info['%s_group_by_choices' % cp] = get_group_by_choices()", "if field == 'type' and hasattr(serializer, 'get_type_choices'): meta['choices'] = serializer.get_type_choices()", "getattr(view, 'related_search_fields', None): metadata['related_search_fields'] = view.related_search_fields # include role names", "in ('PUT', 'POST'): # This value should always be False", "if field.field_name == 'notification_configuration': for (notification_type_name, notification_tr_name, notification_type_class) in NotificationTemplate.NOTIFICATION_TYPES:", "metadata['search_fields'] = view.search_fields # Add related search fields if available", "If user has appropriate permissions for the view, include #", "[] model = getattr(view, 'model', None) if model: for field", "= {} for method in {'GET', 'PUT', 'POST'} & set(view.allowed_methods):", "elif ( isinstance(field, ManyRelatedField) and field.field_name == 'credentials' # launch-time", "a default value. # FIXME: Still isn't showing all default", "(file-based read-only settings can't be updated) meta.pop('defined_in_file', False) if meta.pop('read_only',", "# AWX from awx.main.fields import JSONField, ImplicitRoleField from awx.main.models import", "OrderedDict() field_info['type'] = self.label_lookup[field] field_info['required'] = getattr(field, 'required', False) text_attrs", "roles = [] model = getattr(view, 'model', None) if model:", "available from the serializer. if field == 'type' and hasattr(serializer,", "'ec2', 'gce'): get_regions = getattr(InventorySource, 'get_%s_region_choices' % cp) field_info['%s_region_choices' %", "PositiveIntegerField, BooleanField from django.db.models.fields.related import ForeignKey from django.http import Http404", "= default except serializers.SkipField: pass if getattr(field, 'child', None): field_info['child']", "set(view.allowed_methods): view.request = clone_request(request, method) obj = None try: #", "Copyright (c) 2016 Ansible, Inc. # All Rights Reserved. from", "== \"pod_spec_override\": meta['default'] = PodManager().pod_definition # Add type choices if", "= view.get_object() except (exceptions.APIException, PermissionDenied, Http404): continue else: # If", "verbose_name = smart_text(opts.verbose_name) field_info['help_text'] = field_help_text[field.field_name].format(verbose_name) if field.field_name == 'type':", "notification_tr_name, notification_type_class) in NotificationTemplate.NOTIFICATION_TYPES: field_info[notification_type_name] = notification_type_class.init_parameters # Special handling", "fields returned... model_field = None if serializer and hasattr(serializer, 'Meta')", "(notification_type_name, notification_tr_name, notification_type_class) in NotificationTemplate.NOTIFICATION_TYPES: field_info[notification_type_name] = notification_type_class.default_messages # Update", "True else: for model_field in serializer.Meta.model._meta.fields: if field.field_name == model_field.name:", "view, include # appropriate metadata about the fields that should", "self).determine_actions(request, view) method = 'POST' if method in actions: for", "_('Timestamp when this {} was created.'), 'modified': _('Timestamp when this", "Update type of fields returned... model_field = None if serializer", "import InventorySource, NotificationTemplate from awx.main.scheduler.kubernetes import PodManager class Metadata(metadata.SimpleMetadata): def", "Special handling of inventory source_region choices that vary based on", "(notification_type_name, notification_tr_name, notification_type_class) in NotificationTemplate.NOTIFICATION_TYPES: field_info[notification_type_name] = notification_type_class.init_parameters # Special", "view_model = field.context['view'].model except (AttributeError, KeyError): view_model = None if", "view. if getattr(view, 'related_search_fields', None): metadata['related_search_fields'] = view.related_search_fields # include", "if isinstance(view, generics.ListAPIView) and hasattr(view, 'paginator'): metadata['max_page_size'] = view.paginator.max_page_size return", "structure with URLs of related resources.'), 'summary_fields': _('Data structure with", "serializer and hasattr(serializer, 'Meta') and hasattr(serializer.Meta, 'model'): # Update help", "Special handling of group_by choices for EC2. if field.field_name ==", "{} was created.'), 'modified': _('Timestamp when this {} was last", "field_info['child'] = self.get_field_info(field.child) elif getattr(field, 'fields', None): field_info['children'] = self.get_serializer_info(field)", "isinstance(field, PositiveIntegerField): field_info['type'] = 'integer' elif field.field_name in ('created', 'modified'):", "on self so we can use it to generate field", "request) metadata = super(Metadata, self).determine_metadata(request, view) finally: delattr(view, '_request') #", "\"id\": {\"type\": \"integer\", \"label\": \"ID\", \"help_text\": \"Database ID for this", "handling of inventory source_region choices that vary based on #", "if getattr(field, 'write_only', False): field_info['write_only'] = True # Special handling", "credentials ): field_info['type'] = 'list_of_ids' elif isinstance(model_field, BooleanField): field_info['type'] =", "field.field_name == model_field.name: if getattr(model_field, '__accepts_json__', None): field_info['type'] = 'json'", "NotificationTemplate.NOTIFICATION_TYPES: field_info[notification_type_name] = notification_type_class.default_messages # Update type of fields returned...", "BooleanField from django.db.models.fields.related import ForeignKey from django.http import Http404 from", "field_info['%s_group_by_choices' % cp] = get_group_by_choices() # Special handling of notification", "django.db.models.fields.related import ForeignKey from django.http import Http404 from django.utils.encoding import", "if field.field_name in field_help_text: opts = serializer.Meta.model._meta.concrete_model._meta verbose_name = smart_text(opts.verbose_name)", "conditional on the type selected. if field.field_name == 'notification_configuration': for", "PositiveIntegerField): field_info['type'] = 'integer' elif field.field_name in ('created', 'modified'): field_info['type']", "= super(Metadata, self).determine_metadata(request, view) finally: delattr(view, '_request') # Add type(s)", "type of fields returned... model_field = None if serializer and", "is not None and value != '': field_info[attr] = force_text(value,", "this {}.'), 'url': _('URL for this {}.'), 'related': _('Data structure", "value. # FIXME: Still isn't showing all default values? try:", "'type': field_info['type'] = 'choice' elif field.field_name in ('url', 'custom_virtualenv', 'token'):", "field information for GET requests (so field names/labels are #", "Special handling of notification configuration where the required properties #", "isinstance(field, ManyRelatedField) and field.field_name == 'credentials' # launch-time credentials ):", "text for common fields. field_help_text = { 'id': _('Database ID", "def get_serializer_info(self, serializer, method=None): filterer = getattr(serializer, 'filter_field_metadata', lambda fields,", "remove meta attributes that aren't relevant # when reading a", "field in model._meta.get_fields(): if type(field) is ImplicitRoleField: roles.append(field.name) if len(roles)", "model._meta.get_fields(): if type(field) is ImplicitRoleField: roles.append(field.name) if len(roles) > 0:", "type for this {}.'), 'url': _('URL for this {}.'), 'related':", "= view.get_serializer() if hasattr(serializer, 'get_types'): metadata['types'] = serializer.get_types() # Add", "resources.'), 'summary_fields': _('Data structure with name/description for related resources.'), 'created':", "import PermissionDenied from django.db.models.fields import PositiveIntegerField, BooleanField from django.db.models.fields.related import", "in ('url', 'custom_virtualenv', 'token'): field_info['type'] = 'string' elif field.field_name in", "method in ('PUT', 'POST'): # This value should always be", "'id' and hasattr(view, 'attach'): continue actions[method].pop(field) return actions def determine_metadata(self,", "break else: field_info['filterable'] = False # Indicate if a field", "= None try: # Test global permissions if hasattr(view, 'check_permissions'):", "rest_framework import metadata from rest_framework import serializers from rest_framework.relations import", "serializer. if field == 'type' and hasattr(serializer, 'get_type_choices'): meta['choices'] =", "else: field_info['filterable'] = False # Indicate if a field has", "handling of group_by choices for EC2. if field.field_name == 'group_by':", "'boolean' return field_info def get_serializer_info(self, serializer, method=None): filterer = getattr(serializer,", "meta.pop(attr, None) meta.get('child', {}).pop(attr, None) if meta.pop('write_only', False): actions['GET'].pop(field) #", "field_info['type'] = 'json' elif ( isinstance(field, ManyRelatedField) and field.field_name ==", "obj = view.get_object() except (exceptions.APIException, PermissionDenied, Http404): continue else: #", "not isinstance(meta, dict): continue if field == \"pod_spec_override\": meta['default'] =", "import OrderedDict # Django from django.core.exceptions import PermissionDenied from django.db.models.fields", "'attach'): continue actions[method].pop(field) return actions def determine_metadata(self, request, view): #", "\"integer\", \"label\": \"Disassociate\", \"help_text\": \"Provide to remove this role.\"}, }", "\"help_text\": \"Provide to remove this role.\"}, } return metadata class", "django.core.exceptions import PermissionDenied from django.db.models.fields import PositiveIntegerField, BooleanField from django.db.models.fields.related", "isinstance(getattr(field, 'model_field', None), JSONField) or field.field_name == 'credential_passwords' ): field_info['type']", "InventorySource, NotificationTemplate from awx.main.scheduler.kubernetes import PodManager class Metadata(metadata.SimpleMetadata): def get_field_info(self,", "# (such as TOWER_URL_BASE) self.request = request try: setattr(view, '_request',", "if available from the view. if getattr(view, 'search_fields', None): metadata['search_fields']", "'credential_passwords' ): field_info['type'] = 'json' elif ( isinstance(field, ManyRelatedField) and", "in field.choices.items()] # Indicate if a field is write-only. if", "hasattr(serializer, 'get_types'): metadata['types'] = serializer.get_types() # Add search fields if", "if method in ('PUT', 'POST'): # This value should always", "_ # Django REST Framework from rest_framework import exceptions from", "from django.core.exceptions import PermissionDenied from django.db.models.fields import PositiveIntegerField, BooleanField from", "if model: for field in model._meta.get_fields(): if type(field) is ImplicitRoleField:", "view_model == NotificationTemplate and field.field_name == 'messages': for (notification_type_name, notification_tr_name,", "has appropriate permissions for the view, include # appropriate metadata", "serializer = view.get_serializer(instance=obj) actions[method] = self.get_serializer_info(serializer, method=method) finally: view.request =", "DRFJSONField) or isinstance(getattr(field, 'model_field', None), JSONField) or field.field_name == 'credential_passwords'", "False): actions['GET'].pop(field) # For PUT/POST methods, remove read-only fields. if", "not isinstance(field, (RelatedField, ManyRelatedField)) and hasattr(field, 'choices'): field_info['choices'] = [(choice_value,", "and hasattr(serializer, 'get_type_choices'): meta['choices'] = serializer.get_type_choices() # For GET method,", "# Indicate if a field is write-only. if getattr(field, 'write_only',", "{}.'), 'type': _('Data type for this {}.'), 'url': _('URL for", "if a field is write-only. if getattr(field, 'write_only', False): field_info['write_only']", "getattr(field, 'write_only', False): field_info['write_only'] = True # Special handling of", "finally: delattr(view, '_request') # Add type(s) handled by this view/serializer.", "for (notification_type_name, notification_tr_name, notification_type_class) in NotificationTemplate.NOTIFICATION_TYPES: field_info[notification_type_name] = notification_type_class.init_parameters #", "for field, meta in list(actions[method].items()): if not isinstance(meta, dict): continue", "as DRFJSONField from rest_framework.request import clone_request # AWX from awx.main.fields", "strings_only=True) placeholder = getattr(field, 'placeholder', serializers.empty) if placeholder is not", "} if field.field_name in field_help_text: opts = serializer.Meta.model._meta.concrete_model._meta verbose_name =", "object permissions if method == 'PUT' and hasattr(view, 'get_object'): obj", "clone_request # AWX from awx.main.fields import JSONField, ImplicitRoleField from awx.main.models", "in serializer.Meta.model._meta.fields: if field.field_name == model_field.name: if getattr(model_field, '__accepts_json__', None):", "names/labels are # available even when we can't POST/PUT). actions", "= getattr(InventorySource, 'get_%s_region_choices' % cp) field_info['%s_region_choices' % cp] = get_regions()", "'notification_configuration': for (notification_type_name, notification_tr_name, notification_type_class) in NotificationTemplate.NOTIFICATION_TYPES: field_info[notification_type_name] = notification_type_class.init_parameters", "import serializers from rest_framework.relations import RelatedField, ManyRelatedField from rest_framework.fields import", "in ('ec2',): get_group_by_choices = getattr(InventorySource, 'get_%s_group_by_choices' % cp) field_info['%s_group_by_choices' %", "= 'boolean' return field_info def get_serializer_info(self, serializer, method=None): filterer =", "self.request = request try: setattr(view, '_request', request) metadata = super(Metadata,", "'help_text', 'min_length', 'max_length', 'min_value', 'max_value', 'category', 'category_slug', 'defined_in_file' ] for", "include role names in metadata roles = [] model =", "for method in {'GET', 'PUT', 'POST'} & set(view.allowed_methods): view.request =", "('ec2',): get_group_by_choices = getattr(InventorySource, 'get_%s_group_by_choices' % cp) field_info['%s_group_by_choices' % cp]", "= ('required', 'read_only', 'default', 'min_length', 'max_length', 'placeholder') for attr in", "updated) meta.pop('defined_in_file', False) if meta.pop('read_only', False): if field == 'id'", "import RelatedField, ManyRelatedField from rest_framework.fields import JSONField as DRFJSONField from", "'filter_field_metadata', lambda fields, method: fields) return filterer( super(Metadata, self).get_serializer_info(serializer), method", "# Add type(s) handled by this view/serializer. if hasattr(view, 'get_serializer'):", "on the type selected. try: view_model = field.context['view'].model except (AttributeError,", "field.field_name == 'notification_configuration': for (notification_type_name, notification_tr_name, notification_type_class) in NotificationTemplate.NOTIFICATION_TYPES: field_info[notification_type_name]", "== 'credentials' # launch-time credentials ): field_info['type'] = 'list_of_ids' elif", "smart_text(opts.verbose_name) field_info['help_text'] = field_help_text[field.field_name].format(verbose_name) if field.field_name == 'type': field_info['filterable'] =", "and hasattr(serializer.Meta, 'model'): try: model_field = serializer.Meta.model._meta.get_field(field.field_name) except Exception: pass", "view.check_permissions(view.request) # Test object permissions if method == 'PUT' and", "delattr(view, '_request') # Add type(s) handled by this view/serializer. if", "default = field.get_default() if field.field_name == 'TOWER_URL_BASE' and default ==", "from rest_framework import exceptions from rest_framework import metadata from rest_framework", "Http404): continue else: # If user has appropriate permissions for", "'min_length', 'max_length', 'min_value', 'max_value', 'category', 'category_slug', 'defined_in_file' ] for attr", "if hasattr(view, 'check_permissions'): view.check_permissions(view.request) # Test object permissions if method", "'write_only', False): field_info['write_only'] = True # Special handling of inventory", "'list_of_ids' elif isinstance(model_field, BooleanField): field_info['type'] = 'boolean' return field_info def", "else: for model_field in serializer.Meta.model._meta.fields: if field.field_name == model_field.name: if", "except serializers.SkipField: pass if getattr(field, 'child', None): field_info['child'] = self.get_field_info(field.child)", "field.field_name == 'type': field_info['type'] = 'choice' elif field.field_name in ('url',", "all default values? try: default = field.get_default() if field.field_name ==", "or isinstance(model_field, JSONField) or isinstance(field, DRFJSONField) or isinstance(getattr(field, 'model_field', None),", "we can't POST/PUT). actions = {} for method in {'GET',", "# Django from django.core.exceptions import PermissionDenied from django.db.models.fields import PositiveIntegerField,", "== 'messages': for (notification_type_name, notification_tr_name, notification_type_class) in NotificationTemplate.NOTIFICATION_TYPES: field_info[notification_type_name] =", "(exceptions.APIException, PermissionDenied, Http404): continue else: # If user has appropriate", "inventory source_region choices that vary based on # selected inventory", "'source_regions': for cp in ('azure_rm', 'ec2', 'gce'): get_regions = getattr(InventorySource,", "pass if field.field_name == 'type': field_info['type'] = 'choice' elif field.field_name", "None if serializer and hasattr(serializer, 'Meta') and hasattr(serializer.Meta, 'model'): try:", "field_info['filterable'] = False # Indicate if a field has a", "field is write-only. if getattr(field, 'write_only', False): field_info['write_only'] = True", "'get_%s_region_choices' % cp) field_info['%s_region_choices' % cp] = get_regions() # Special", "of notification messages where the required properties # are conditional", "role names in metadata roles = [] model = getattr(view,", "the type selected. try: view_model = field.context['view'].model except (AttributeError, KeyError):", "For PUT/POST methods, remove read-only fields. if method in ('PUT',", "\"Database ID for this role.\"}, \"disassociate\": {\"type\": \"integer\", \"label\": \"Disassociate\",", "from awx.main.fields import JSONField, ImplicitRoleField from awx.main.models import InventorySource, NotificationTemplate", "metadata['max_page_size'] = view.paginator.max_page_size return metadata class RoleMetadata(Metadata): def determine_metadata(self, request,", "field_help_text[field.field_name].format(verbose_name) if field.field_name == 'type': field_info['filterable'] = True else: for", "permissions if method == 'PUT' and hasattr(view, 'get_object'): obj =", "Ansible, Inc. # All Rights Reserved. from collections import OrderedDict", "& set(view.allowed_methods): view.request = clone_request(request, method) obj = None try:", "if hasattr(serializer, 'get_types'): metadata['types'] = serializer.get_types() # Add search fields", "{} for method in {'GET', 'PUT', 'POST'} & set(view.allowed_methods): view.request", "for the view, include # appropriate metadata about the fields", "# If user has appropriate permissions for the view, include", "and hasattr(serializer.Meta, 'model'): # Update help text for common fields.", "cp) field_info['%s_region_choices' % cp] = get_regions() # Special handling of", "hasattr(serializer.Meta, 'model'): try: model_field = serializer.Meta.model._meta.get_field(field.field_name) except Exception: pass if", "rest_framework.request import clone_request # AWX from awx.main.fields import JSONField, ImplicitRoleField", "= self.get_serializer_info(serializer, method=method) finally: view.request = request for field, meta", "field.get_default() if field.field_name == 'TOWER_URL_BASE' and default == 'https://towerhost': default", "handling of notification messages where the required properties # are", "= getattr(view, 'model', None) if model: for field in model._meta.get_fields():", "NotificationTemplate from awx.main.scheduler.kubernetes import PodManager class Metadata(metadata.SimpleMetadata): def get_field_info(self, field):", "field in list(actions[method].keys()): if field == 'id': continue actions[method].pop(field) return", "is write-only. if getattr(field, 'write_only', False): field_info['write_only'] = True #", "placeholder is not serializers.empty: field_info['placeholder'] = placeholder serializer = getattr(field,", "def determine_actions(self, request, view): actions = super(SublistAttachDetatchMetadata, self).determine_actions(request, view) method", "be updated) meta.pop('defined_in_file', False) if meta.pop('read_only', False): if field ==", "name/description for related resources.'), 'created': _('Timestamp when this {} was", "pass if getattr(field, 'child', None): field_info['child'] = self.get_field_info(field.child) elif getattr(field,", "'json' elif ( isinstance(field, ManyRelatedField) and field.field_name == 'credentials' #", "attrs_to_remove = ('required', 'read_only', 'default', 'min_length', 'max_length', 'placeholder') for attr", "request, view): # store request on self so we can", "# selected inventory source. if field.field_name == 'source_regions': for cp", "_('Data structure with URLs of related resources.'), 'summary_fields': _('Data structure", "choice_value, choice_name in field.choices.items()] # Indicate if a field is", "resources.'), 'created': _('Timestamp when this {} was created.'), 'modified': _('Timestamp", "this {}.'), 'description': _('Optional description of this {}.'), 'type': _('Data", "for related resources.'), 'created': _('Timestamp when this {} was created.'),", "from django.db.models.fields.related import ForeignKey from django.http import Http404 from django.utils.encoding", "isinstance(field, (RelatedField, ManyRelatedField)) and hasattr(field, 'choices'): field_info['choices'] = [(choice_value, choice_name)", "force_text(value, strings_only=True) placeholder = getattr(field, 'placeholder', serializers.empty) if placeholder is", "'PUT' and hasattr(view, 'get_object'): obj = view.get_object() except (exceptions.APIException, PermissionDenied,", "notification configuration where the required properties # are conditional on", "meta.get('child', {}).pop(attr, None) if meta.pop('write_only', False): actions['GET'].pop(field) # For PUT/POST", "# For PUT/POST methods, remove read-only fields. if method in", "serializer.Meta.model._meta.concrete_model._meta verbose_name = smart_text(opts.verbose_name) field_info['help_text'] = field_help_text[field.field_name].format(verbose_name) if field.field_name ==", "metadata['object_roles'] = roles from rest_framework import generics if isinstance(view, generics.ListAPIView)", "Exception: pass if field.field_name == 'type': field_info['type'] = 'choice' elif", "in metadata roles = [] model = getattr(view, 'model', None)", "= notification_type_class.init_parameters # Special handling of notification messages where the", "method: fields) return filterer( super(Metadata, self).get_serializer_info(serializer), method ) def determine_actions(self,", "'_request', request) metadata = super(Metadata, self).determine_metadata(request, view) finally: delattr(view, '_request')", "Add type choices if available from the serializer. if field", "from django.http import Http404 from django.utils.encoding import force_text, smart_text from", "= 'datetime' elif ( RelatedField in field.__class__.__bases__ or isinstance(model_field, ForeignKey)", "= 'object' elif isinstance(field, PositiveIntegerField): field_info['type'] = 'integer' elif field.field_name", "getattr(field, 'placeholder', serializers.empty) if placeholder is not serializers.empty: field_info['placeholder'] =", "this {} was created.'), 'modified': _('Timestamp when this {} was", "'max_value', 'category', 'category_slug', 'defined_in_file' ] for attr in text_attrs: value", "elif field.field_name in ('related', 'summary_fields'): field_info['type'] = 'object' elif isinstance(field,", "# Django REST Framework from rest_framework import exceptions from rest_framework", "from django.db.models.fields import PositiveIntegerField, BooleanField from django.db.models.fields.related import ForeignKey from", "lambda fields, method: fields) return filterer( super(Metadata, self).get_serializer_info(serializer), method )", "selected. try: view_model = field.context['view'].model except (AttributeError, KeyError): view_model =", "Django REST Framework from rest_framework import exceptions from rest_framework import", "JSONField as DRFJSONField from rest_framework.request import clone_request # AWX from", "and field.field_name == 'messages': for (notification_type_name, notification_tr_name, notification_type_class) in NotificationTemplate.NOTIFICATION_TYPES:", "permissions for the view, include # appropriate metadata about the", "view) method = 'POST' if method in actions: for field", "cp] = get_group_by_choices() # Special handling of notification configuration where", "value is not None and value != '': field_info[attr] =", "values? try: default = field.get_default() if field.field_name == 'TOWER_URL_BASE' and", "None): field_info['type'] = 'json' field_info['filterable'] = True break else: field_info['filterable']", "not None and value != '': field_info[attr] = force_text(value, strings_only=True)", "_('Data structure with name/description for related resources.'), 'created': _('Timestamp when", "isn't showing all default values? try: default = field.get_default() if", "# Special handling of inventory source_region choices that vary based", "( RelatedField in field.__class__.__bases__ or isinstance(model_field, ForeignKey) ): field_info['type'] =", "\"label\": \"ID\", \"help_text\": \"Database ID for this role.\"}, \"disassociate\": {\"type\":", "when this {} was created.'), 'modified': _('Timestamp when this {}", "for this {}.'), 'name': _('Name of this {}.'), 'description': _('Optional", "): field_info['type'] = 'list_of_ids' elif isinstance(model_field, BooleanField): field_info['type'] = 'boolean'", "attr in attrs_to_remove: meta.pop(attr, None) meta.get('child', {}).pop(attr, None) if meta.pop('write_only',", "None) if meta.pop('write_only', False): actions['GET'].pop(field) # For PUT/POST methods, remove", "notification_type_class) in NotificationTemplate.NOTIFICATION_TYPES: field_info[notification_type_name] = notification_type_class.default_messages # Update type of", "of notification configuration where the required properties # are conditional", "_('URL for this {}.'), 'related': _('Data structure with URLs of", "'custom_virtualenv', 'token'): field_info['type'] = 'string' elif field.field_name in ('related', 'summary_fields'):", "'_request') # Add type(s) handled by this view/serializer. if hasattr(view,", "Metadata(metadata.SimpleMetadata): def get_field_info(self, field): field_info = OrderedDict() field_info['type'] = self.label_lookup[field]", "RelatedField in field.__class__.__bases__ or isinstance(model_field, ForeignKey) ): field_info['type'] = 'id'", "selected inventory source. if field.field_name == 'source_regions': for cp in", "POST/PUT). actions = {} for method in {'GET', 'PUT', 'POST'}", "list(actions[method].items()): if not isinstance(meta, dict): continue if field == \"pod_spec_override\":", "metadata['related_search_fields'] = view.related_search_fields # include role names in metadata roles", "= self.get_serializer_info(field) if not isinstance(field, (RelatedField, ManyRelatedField)) and hasattr(field, 'choices'):", "field_info['required'] = getattr(field, 'required', False) text_attrs = [ 'read_only', 'label',", "choices that vary based on # selected inventory source. if", "import JSONField, ImplicitRoleField from awx.main.models import InventorySource, NotificationTemplate from awx.main.scheduler.kubernetes", "metadata['types'] = serializer.get_types() # Add search fields if available from", "for common fields. field_help_text = { 'id': _('Database ID for", "with URLs of related resources.'), 'summary_fields': _('Data structure with name/description", "fields) return filterer( super(Metadata, self).get_serializer_info(serializer), method ) def determine_actions(self, request,", "view.related_search_fields # include role names in metadata roles = []", "Add related search fields if available from the view. if", "'type': field_info['filterable'] = True else: for model_field in serializer.Meta.model._meta.fields: if", "rest_framework.relations import RelatedField, ManyRelatedField from rest_framework.fields import JSONField as DRFJSONField", "[(choice_value, choice_name) for choice_value, choice_name in field.choices.items()] # Indicate if", "of group_by choices for EC2. if field.field_name == 'group_by': for", "view_model = None if view_model == NotificationTemplate and field.field_name ==", "RoleMetadata(Metadata): def determine_metadata(self, request, view): metadata = super(RoleMetadata, self).determine_metadata(request, view)", "attr in text_attrs: value = getattr(field, attr, None) if value", "if field == 'id' and hasattr(view, 'attach'): continue actions[method].pop(field) return", "hasattr(view, 'get_object'): obj = view.get_object() except (exceptions.APIException, PermissionDenied, Http404): continue", "for cp in ('ec2',): get_group_by_choices = getattr(InventorySource, 'get_%s_group_by_choices' % cp)", "request try: setattr(view, '_request', request) metadata = super(Metadata, self).determine_metadata(request, view)", "self).determine_metadata(request, view) if 'actions' in metadata: metadata['actions'].pop('POST') metadata['actions']['POST'] = {", "method ) def determine_actions(self, request, view): # Add field information", "field_info['children'] = self.get_serializer_info(field) if not isinstance(field, (RelatedField, ManyRelatedField)) and hasattr(field,", "request, view): actions = super(SublistAttachDetatchMetadata, self).determine_actions(request, view) method = 'POST'", "when reading a field and remove write-only fields. if method", "} return metadata class SublistAttachDetatchMetadata(Metadata): def determine_actions(self, request, view): actions", "field_info['type'] = 'list_of_ids' elif isinstance(model_field, BooleanField): field_info['type'] = 'boolean' return", "in {'GET', 'PUT', 'POST'} & set(view.allowed_methods): view.request = clone_request(request, method)", "appropriate permissions for the view, include # appropriate metadata about", "selected. if field.field_name == 'notification_configuration': for (notification_type_name, notification_tr_name, notification_type_class) in", "a field and remove write-only fields. if method == 'GET':", "All Rights Reserved. from collections import OrderedDict # Django from", "field.field_name == 'type': field_info['filterable'] = True else: for model_field in", "as _ # Django REST Framework from rest_framework import exceptions", "and hasattr(view, 'get_object'): obj = view.get_object() except (exceptions.APIException, PermissionDenied, Http404):", "user has appropriate permissions for the view, include # appropriate", "PodManager().pod_definition # Add type choices if available from the serializer.", "= view.get_serializer(instance=obj) actions[method] = self.get_serializer_info(serializer, method=method) finally: view.request = request", "continue actions[method].pop(field) return actions def determine_metadata(self, request, view): # store", "field_help_text = { 'id': _('Database ID for this {}.'), 'name':", "(RelatedField, ManyRelatedField)) and hasattr(field, 'choices'): field_info['choices'] = [(choice_value, choice_name) for", "field_info['type'] = 'choice' elif field.field_name in ('url', 'custom_virtualenv', 'token'): field_info['type']", "None) if value is not None and value != '':", "value != '': field_info[attr] = force_text(value, strings_only=True) placeholder = getattr(field,", "created.'), 'modified': _('Timestamp when this {} was last modified.'), }", "field_info['help_text'] = field_help_text[field.field_name].format(verbose_name) if field.field_name == 'type': field_info['filterable'] = True", "for this {}.'), 'url': _('URL for this {}.'), 'related': _('Data", "import JSONField as DRFJSONField from rest_framework.request import clone_request # AWX", "self.get_field_info(field.child) elif getattr(field, 'fields', None): field_info['children'] = self.get_serializer_info(field) if not", "ManyRelatedField) and field.field_name == 'credentials' # launch-time credentials ): field_info['type']", "view.request = clone_request(request, method) obj = None try: # Test", "{ 'id': _('Database ID for this {}.'), 'name': _('Name of", "'group_by': for cp in ('ec2',): get_group_by_choices = getattr(InventorySource, 'get_%s_group_by_choices' %", "field, meta in list(actions[method].items()): if not isinstance(meta, dict): continue if", "if field.field_name == 'type': field_info['filterable'] = True else: for model_field", "based on # selected inventory source. if field.field_name == 'source_regions':", "= getattr(serializer, 'filter_field_metadata', lambda fields, method: fields) return filterer( super(Metadata,", "hasattr(view, 'paginator'): metadata['max_page_size'] = view.paginator.max_page_size return metadata class RoleMetadata(Metadata): def", "conditional on the type selected. try: view_model = field.context['view'].model except", "model_field = None if serializer and hasattr(serializer, 'Meta') and hasattr(serializer.Meta,", "Update help text for common fields. field_help_text = { 'id':", "= view.search_fields # Add related search fields if available from", "cp] = get_regions() # Special handling of group_by choices for", "or isinstance(field, DRFJSONField) or isinstance(getattr(field, 'model_field', None), JSONField) or field.field_name", "are # available even when we can't POST/PUT). actions =", "source_region choices that vary based on # selected inventory source.", "field_info def get_serializer_info(self, serializer, method=None): filterer = getattr(serializer, 'filter_field_metadata', lambda", "= self.get_field_info(field.child) elif getattr(field, 'fields', None): field_info['children'] = self.get_serializer_info(field) if", "= False # Indicate if a field has a default", "method=method) finally: view.request = request for field, meta in list(actions[method].items()):", "not serializers.empty: field_info['placeholder'] = placeholder serializer = getattr(field, 'parent', None)", "if field == \"pod_spec_override\": meta['default'] = PodManager().pod_definition # Add type", "fields. field_help_text = { 'id': _('Database ID for this {}.'),", "common fields. field_help_text = { 'id': _('Database ID for this", "# Indicate if a field has a default value. #", "rest_framework import generics if isinstance(view, generics.ListAPIView) and hasattr(view, 'paginator'): metadata['max_page_size']", "'category_slug', 'defined_in_file' ] for attr in text_attrs: value = getattr(field,", "if serializer and hasattr(serializer, 'Meta') and hasattr(serializer.Meta, 'model'): # Update", "self.label_lookup[field] field_info['required'] = getattr(field, 'required', False) text_attrs = [ 'read_only',", "value = getattr(field, attr, None) if value is not None", "] for attr in text_attrs: value = getattr(field, attr, None)", "None): field_info['children'] = self.get_serializer_info(field) if not isinstance(field, (RelatedField, ManyRelatedField)) and", "'PUT', 'POST'} & set(view.allowed_methods): view.request = clone_request(request, method) obj =", "getattr(InventorySource, 'get_%s_group_by_choices' % cp) field_info['%s_group_by_choices' % cp] = get_group_by_choices() #", "serializers.empty) if placeholder is not serializers.empty: field_info['placeholder'] = placeholder serializer", "Http404 from django.utils.encoding import force_text, smart_text from django.utils.translation import ugettext_lazy", "value should always be False for PUT/POST, so don't #", "method) obj = None try: # Test global permissions if", "serializer = getattr(field, 'parent', None) if serializer and hasattr(serializer, 'Meta')", "this {}.'), 'type': _('Data type for this {}.'), 'url': _('URL", "\"integer\", \"label\": \"ID\", \"help_text\": \"Database ID for this role.\"}, \"disassociate\":", "'model_field', None), JSONField) or field.field_name == 'credential_passwords' ): field_info['type'] =", "hasattr(view, 'check_permissions'): view.check_permissions(view.request) # Test object permissions if method ==", "def determine_metadata(self, request, view): metadata = super(RoleMetadata, self).determine_metadata(request, view) if", "'max_length', 'placeholder') for attr in attrs_to_remove: meta.pop(attr, None) meta.get('child', {}).pop(attr,", "for EC2. if field.field_name == 'group_by': for cp in ('ec2',):", "if getattr(field, 'child', None): field_info['child'] = self.get_field_info(field.child) elif getattr(field, 'fields',", "'child', None): field_info['child'] = self.get_field_info(field.child) elif getattr(field, 'fields', None): field_info['children']", "getattr(field, 'required', False) text_attrs = [ 'read_only', 'label', 'help_text', 'min_length',", "from rest_framework.relations import RelatedField, ManyRelatedField from rest_framework.fields import JSONField as", "was created.'), 'modified': _('Timestamp when this {} was last modified.'),", "or isinstance(model_field, ForeignKey) ): field_info['type'] = 'id' elif ( isinstance(field,", "# launch-time credentials ): field_info['type'] = 'list_of_ids' elif isinstance(model_field, BooleanField):", "be False for PUT/POST, so don't # show it (file-based", "hasattr(serializer, 'get_type_choices'): meta['choices'] = serializer.get_type_choices() # For GET method, remove", "for field in list(actions[method].keys()): if field == 'id': continue actions[method].pop(field)", "URLs of related resources.'), 'summary_fields': _('Data structure with name/description for", "# Update type of fields returned... model_field = None if", "notification_type_class) in NotificationTemplate.NOTIFICATION_TYPES: field_info[notification_type_name] = notification_type_class.init_parameters # Special handling of", "JSONField) or field.field_name == 'credential_passwords' ): field_info['type'] = 'json' elif", "field == \"pod_spec_override\": meta['default'] = PodManager().pod_definition # Add type choices", "dict): continue if field == \"pod_spec_override\": meta['default'] = PodManager().pod_definition #", "= serializer.get_type_choices() # For GET method, remove meta attributes that", "if not isinstance(field, (RelatedField, ManyRelatedField)) and hasattr(field, 'choices'): field_info['choices'] =", "choices if available from the serializer. if field == 'type'", "metadata = super(Metadata, self).determine_metadata(request, view) finally: delattr(view, '_request') # Add", "def get_field_info(self, field): field_info = OrderedDict() field_info['type'] = self.label_lookup[field] field_info['required']", "ManyRelatedField)) and hasattr(field, 'choices'): field_info['choices'] = [(choice_value, choice_name) for choice_value,", "return field_info def get_serializer_info(self, serializer, method=None): filterer = getattr(serializer, 'filter_field_metadata',", "the view, include # appropriate metadata about the fields that", "search fields if available from the view. if getattr(view, 'related_search_fields',", "% cp) field_info['%s_region_choices' % cp] = get_regions() # Special handling", "role.\"}, } return metadata class SublistAttachDetatchMetadata(Metadata): def determine_actions(self, request, view):", "if method in actions: for field in list(actions[method].keys()): if field", "'description': _('Optional description of this {}.'), 'type': _('Data type for", "'search_fields', None): metadata['search_fields'] = view.search_fields # Add related search fields", "2016 Ansible, Inc. # All Rights Reserved. from collections import", "_('Timestamp when this {} was last modified.'), } if field.field_name", "field and remove write-only fields. if method == 'GET': attrs_to_remove", "super(SublistAttachDetatchMetadata, self).determine_actions(request, view) method = 'POST' if method in actions:", "= clone_request(request, method) obj = None try: # Test global", "('required', 'read_only', 'default', 'min_length', 'max_length', 'placeholder') for attr in attrs_to_remove:", "ImplicitRoleField from awx.main.models import InventorySource, NotificationTemplate from awx.main.scheduler.kubernetes import PodManager", "django.utils.encoding import force_text, smart_text from django.utils.translation import ugettext_lazy as _", "= 'json' field_info['filterable'] = True break else: field_info['filterable'] = False", "Special handling of notification messages where the required properties #", "this {}.'), 'name': _('Name of this {}.'), 'description': _('Optional description", "% cp] = get_group_by_choices() # Special handling of notification configuration", "'placeholder', serializers.empty) if placeholder is not serializers.empty: field_info['placeholder'] = placeholder", "= serializer.Meta.model._meta.concrete_model._meta verbose_name = smart_text(opts.verbose_name) field_info['help_text'] = field_help_text[field.field_name].format(verbose_name) if field.field_name", "by this view/serializer. if hasattr(view, 'get_serializer'): serializer = view.get_serializer() if", "method in actions: for field in list(actions[method].keys()): if field ==", "'id' elif ( isinstance(field, JSONField) or isinstance(model_field, JSONField) or isinstance(field,", "FIXME: Still isn't showing all default values? try: default =", "% cp] = get_regions() # Special handling of group_by choices", "Reserved. from collections import OrderedDict # Django from django.core.exceptions import", "'model', None) if model: for field in model._meta.get_fields(): if type(field)", "metadata['actions']['POST'] = { \"id\": {\"type\": \"integer\", \"label\": \"ID\", \"help_text\": \"Database", "'token'): field_info['type'] = 'string' elif field.field_name in ('related', 'summary_fields'): field_info['type']", "Still isn't showing all default values? try: default = field.get_default()", "handling of notification configuration where the required properties # are", "= None if view_model == NotificationTemplate and field.field_name == 'messages':", "= get_regions() # Special handling of group_by choices for EC2.", "'get_%s_group_by_choices' % cp) field_info['%s_group_by_choices' % cp] = get_group_by_choices() # Special", "Add field information for GET requests (so field names/labels are", "None and value != '': field_info[attr] = force_text(value, strings_only=True) placeholder", "# include role names in metadata roles = [] model", "be supplied. serializer = view.get_serializer(instance=obj) actions[method] = self.get_serializer_info(serializer, method=method) finally:", "source. if field.field_name == 'source_regions': for cp in ('azure_rm', 'ec2',", "_('Optional description of this {}.'), 'type': _('Data type for this", "field_info = OrderedDict() field_info['type'] = self.label_lookup[field] field_info['required'] = getattr(field, 'required',", "should be supplied. serializer = view.get_serializer(instance=obj) actions[method] = self.get_serializer_info(serializer, method=method)", "ID for this role.\"}, \"disassociate\": {\"type\": \"integer\", \"label\": \"Disassociate\", \"help_text\":", "related search fields if available from the view. if getattr(view,", "= self.label_lookup[field] field_info['required'] = getattr(field, 'required', False) text_attrs = [", "serializer.Meta.model._meta.fields: if field.field_name == model_field.name: if getattr(model_field, '__accepts_json__', None): field_info['type']", "# Special handling of group_by choices for EC2. if field.field_name", "Indicate if a field is write-only. if getattr(field, 'write_only', False):", "False): if field == 'id' and hasattr(view, 'attach'): continue actions[method].pop(field)", "if field.field_name == model_field.name: if getattr(model_field, '__accepts_json__', None): field_info['type'] =", "'min_value', 'max_value', 'category', 'category_slug', 'defined_in_file' ] for attr in text_attrs:", "getattr(serializer, 'filter_field_metadata', lambda fields, method: fields) return filterer( super(Metadata, self).get_serializer_info(serializer),", "= { \"id\": {\"type\": \"integer\", \"label\": \"ID\", \"help_text\": \"Database ID", "appropriate metadata about the fields that should be supplied. serializer", "view.search_fields # Add related search fields if available from the", "attrs_to_remove: meta.pop(attr, None) meta.get('child', {}).pop(attr, None) if meta.pop('write_only', False): actions['GET'].pop(field)", "properties # are conditional on the type selected. if field.field_name", "default value. # FIXME: Still isn't showing all default values?", "metadata class SublistAttachDetatchMetadata(Metadata): def determine_actions(self, request, view): actions = super(SublistAttachDetatchMetadata,", "field_info['type'] = 'string' elif field.field_name in ('related', 'summary_fields'): field_info['type'] =", "False for PUT/POST, so don't # show it (file-based read-only", "exceptions from rest_framework import metadata from rest_framework import serializers from", "class SublistAttachDetatchMetadata(Metadata): def determine_actions(self, request, view): actions = super(SublistAttachDetatchMetadata, self).determine_actions(request,", "serializer.get_types() # Add search fields if available from the view.", "{'GET', 'PUT', 'POST'} & set(view.allowed_methods): view.request = clone_request(request, method) obj", "for GET requests (so field names/labels are # available even", "self.request.get_host()) field_info['default'] = default except serializers.SkipField: pass if getattr(field, 'child',", "field_info['type'] = 'object' elif isinstance(field, PositiveIntegerField): field_info['type'] = 'integer' elif", "Add type(s) handled by this view/serializer. if hasattr(view, 'get_serializer'): serializer", "( isinstance(field, JSONField) or isinstance(model_field, JSONField) or isinstance(field, DRFJSONField) or", "in model._meta.get_fields(): if type(field) is ImplicitRoleField: roles.append(field.name) if len(roles) >", "related resources.'), 'summary_fields': _('Data structure with name/description for related resources.'),", "try: setattr(view, '_request', request) metadata = super(Metadata, self).determine_metadata(request, view) finally:", "== 'GET': attrs_to_remove = ('required', 'read_only', 'default', 'min_length', 'max_length', 'placeholder')", "'parent', None) if serializer and hasattr(serializer, 'Meta') and hasattr(serializer.Meta, 'model'):", "from awx.main.models import InventorySource, NotificationTemplate from awx.main.scheduler.kubernetes import PodManager class", "of this {}.'), 'description': _('Optional description of this {}.'), 'type':", "field.context['view'].model except (AttributeError, KeyError): view_model = None if view_model ==", "= serializer.Meta.model._meta.get_field(field.field_name) except Exception: pass if field.field_name == 'type': field_info['type']", "metadata about the fields that should be supplied. serializer =", "metadata class RoleMetadata(Metadata): def determine_metadata(self, request, view): metadata = super(RoleMetadata,", "field_info['type'] = 'datetime' elif ( RelatedField in field.__class__.__bases__ or isinstance(model_field,", "'choices'): field_info['choices'] = [(choice_value, choice_name) for choice_value, choice_name in field.choices.items()]", "AWX from awx.main.fields import JSONField, ImplicitRoleField from awx.main.models import InventorySource,", "Indicate if a field has a default value. # FIXME:", "= getattr(field, 'required', False) text_attrs = [ 'read_only', 'label', 'help_text',", "filterer( super(Metadata, self).get_serializer_info(serializer), method ) def determine_actions(self, request, view): #", "(so field names/labels are # available even when we can't", "generate field defaults # (such as TOWER_URL_BASE) self.request = request", "= { 'id': _('Database ID for this {}.'), 'name': _('Name", "return metadata class RoleMetadata(Metadata): def determine_metadata(self, request, view): metadata =", "# Special handling of notification messages where the required properties", "if available from the view. if getattr(view, 'related_search_fields', None): metadata['related_search_fields']", "metadata = super(RoleMetadata, self).determine_metadata(request, view) if 'actions' in metadata: metadata['actions'].pop('POST')", "elif isinstance(field, PositiveIntegerField): field_info['type'] = 'integer' elif field.field_name in ('created',", "> 0: metadata['object_roles'] = roles from rest_framework import generics if", "'actions' in metadata: metadata['actions'].pop('POST') metadata['actions']['POST'] = { \"id\": {\"type\": \"integer\",", "view.get_serializer(instance=obj) actions[method] = self.get_serializer_info(serializer, method=method) finally: view.request = request for", "\"Disassociate\", \"help_text\": \"Provide to remove this role.\"}, } return metadata", "search fields if available from the view. if getattr(view, 'search_fields',", "if view_model == NotificationTemplate and field.field_name == 'messages': for (notification_type_name,", "{}).pop(attr, None) if meta.pop('write_only', False): actions['GET'].pop(field) # For PUT/POST methods,", "if meta.pop('write_only', False): actions['GET'].pop(field) # For PUT/POST methods, remove read-only", "Framework from rest_framework import exceptions from rest_framework import metadata from", "can use it to generate field defaults # (such as", "'defined_in_file' ] for attr in text_attrs: value = getattr(field, attr,", "from rest_framework import metadata from rest_framework import serializers from rest_framework.relations", "'type': _('Data type for this {}.'), 'url': _('URL for this", "hasattr(view, 'attach'): continue actions[method].pop(field) return actions def determine_metadata(self, request, view):", "in text_attrs: value = getattr(field, attr, None) if value is", "SublistAttachDetatchMetadata(Metadata): def determine_actions(self, request, view): actions = super(SublistAttachDetatchMetadata, self).determine_actions(request, view)", "'json' field_info['filterable'] = True break else: field_info['filterable'] = False #", "(such as TOWER_URL_BASE) self.request = request try: setattr(view, '_request', request)", "for this {}.'), 'related': _('Data structure with URLs of related", "== 'notification_configuration': for (notification_type_name, notification_tr_name, notification_type_class) in NotificationTemplate.NOTIFICATION_TYPES: field_info[notification_type_name] =", "'model'): # Update help text for common fields. field_help_text =", "field_help_text: opts = serializer.Meta.model._meta.concrete_model._meta verbose_name = smart_text(opts.verbose_name) field_info['help_text'] = field_help_text[field.field_name].format(verbose_name)", "== 'source_regions': for cp in ('azure_rm', 'ec2', 'gce'): get_regions =", "available from the view. if getattr(view, 'search_fields', None): metadata['search_fields'] =", "'created': _('Timestamp when this {} was created.'), 'modified': _('Timestamp when", "to remove this role.\"}, } return metadata class SublistAttachDetatchMetadata(Metadata): def", "methods, remove read-only fields. if method in ('PUT', 'POST'): #", "generics if isinstance(view, generics.ListAPIView) and hasattr(view, 'paginator'): metadata['max_page_size'] = view.paginator.max_page_size", "supplied. serializer = view.get_serializer(instance=obj) actions[method] = self.get_serializer_info(serializer, method=method) finally: view.request", "field_info['filterable'] = True else: for model_field in serializer.Meta.model._meta.fields: if field.field_name", "for choice_value, choice_name in field.choices.items()] # Indicate if a field", "get_group_by_choices() # Special handling of notification configuration where the required", "= None if serializer and hasattr(serializer, 'Meta') and hasattr(serializer.Meta, 'model'):", ") def determine_actions(self, request, view): # Add field information for", "import clone_request # AWX from awx.main.fields import JSONField, ImplicitRoleField from", "serializer = view.get_serializer() if hasattr(serializer, 'get_types'): metadata['types'] = serializer.get_types() #", "view): actions = super(SublistAttachDetatchMetadata, self).determine_actions(request, view) method = 'POST' if", "in NotificationTemplate.NOTIFICATION_TYPES: field_info[notification_type_name] = notification_type_class.init_parameters # Special handling of notification", "('azure_rm', 'ec2', 'gce'): get_regions = getattr(InventorySource, 'get_%s_region_choices' % cp) field_info['%s_region_choices'", "self).get_serializer_info(serializer), method ) def determine_actions(self, request, view): # Add field", "for attr in attrs_to_remove: meta.pop(attr, None) meta.get('child', {}).pop(attr, None) if", "== 'group_by': for cp in ('ec2',): get_group_by_choices = getattr(InventorySource, 'get_%s_group_by_choices'", "and hasattr(field, 'choices'): field_info['choices'] = [(choice_value, choice_name) for choice_value, choice_name", "field_info['type'] = 'boolean' return field_info def get_serializer_info(self, serializer, method=None): filterer", "configuration where the required properties # are conditional on the", "default == 'https://towerhost': default = '{}://{}'.format(self.request.scheme, self.request.get_host()) field_info['default'] = default", "and hasattr(serializer, 'Meta') and hasattr(serializer.Meta, 'model'): try: model_field = serializer.Meta.model._meta.get_field(field.field_name)", "'credentials' # launch-time credentials ): field_info['type'] = 'list_of_ids' elif isinstance(model_field,", "inventory source. if field.field_name == 'source_regions': for cp in ('azure_rm',", "KeyError): view_model = None if view_model == NotificationTemplate and field.field_name", "= getattr(field, 'parent', None) if serializer and hasattr(serializer, 'Meta') and", "from django.utils.translation import ugettext_lazy as _ # Django REST Framework", "if hasattr(view, 'get_serializer'): serializer = view.get_serializer() if hasattr(serializer, 'get_types'): metadata['types']", "roles.append(field.name) if len(roles) > 0: metadata['object_roles'] = roles from rest_framework", "for field in model._meta.get_fields(): if type(field) is ImplicitRoleField: roles.append(field.name) if", "store request on self so we can use it to", "Test object permissions if method == 'PUT' and hasattr(view, 'get_object'):", "showing all default values? try: default = field.get_default() if field.field_name", "isinstance(field, JSONField) or isinstance(model_field, JSONField) or isinstance(field, DRFJSONField) or isinstance(getattr(field,", "serializer.get_type_choices() # For GET method, remove meta attributes that aren't", "fields. if method == 'GET': attrs_to_remove = ('required', 'read_only', 'default',", "text_attrs = [ 'read_only', 'label', 'help_text', 'min_length', 'max_length', 'min_value', 'max_value',", "get_field_info(self, field): field_info = OrderedDict() field_info['type'] = self.label_lookup[field] field_info['required'] =", "'model'): try: model_field = serializer.Meta.model._meta.get_field(field.field_name) except Exception: pass if field.field_name", "on # selected inventory source. if field.field_name == 'source_regions': for", "0: metadata['object_roles'] = roles from rest_framework import generics if isinstance(view,", "super(RoleMetadata, self).determine_metadata(request, view) if 'actions' in metadata: metadata['actions'].pop('POST') metadata['actions']['POST'] =", "is not serializers.empty: field_info['placeholder'] = placeholder serializer = getattr(field, 'parent',", "# This value should always be False for PUT/POST, so", "fields if available from the view. if getattr(view, 'search_fields', None):", "Inc. # All Rights Reserved. from collections import OrderedDict #", "NotificationTemplate and field.field_name == 'messages': for (notification_type_name, notification_tr_name, notification_type_class) in", "elif field.field_name in ('created', 'modified'): field_info['type'] = 'datetime' elif (", "# Test global permissions if hasattr(view, 'check_permissions'): view.check_permissions(view.request) # Test", "'default', 'min_length', 'max_length', 'placeholder') for attr in attrs_to_remove: meta.pop(attr, None)", "from rest_framework.fields import JSONField as DRFJSONField from rest_framework.request import clone_request", "default values? try: default = field.get_default() if field.field_name == 'TOWER_URL_BASE'", "None): field_info['child'] = self.get_field_info(field.child) elif getattr(field, 'fields', None): field_info['children'] =", "field.field_name in ('created', 'modified'): field_info['type'] = 'datetime' elif ( RelatedField", "when this {} was last modified.'), } if field.field_name in", "isinstance(field, DRFJSONField) or isinstance(getattr(field, 'model_field', None), JSONField) or field.field_name ==", "settings can't be updated) meta.pop('defined_in_file', False) if meta.pop('read_only', False): if", "to generate field defaults # (such as TOWER_URL_BASE) self.request =", "= [(choice_value, choice_name) for choice_value, choice_name in field.choices.items()] # Indicate", "field.__class__.__bases__ or isinstance(model_field, ForeignKey) ): field_info['type'] = 'id' elif (", "\"pod_spec_override\": meta['default'] = PodManager().pod_definition # Add type choices if available", "if method == 'GET': attrs_to_remove = ('required', 'read_only', 'default', 'min_length',", "type(s) handled by this view/serializer. if hasattr(view, 'get_serializer'): serializer =", "None): metadata['search_fields'] = view.search_fields # Add related search fields if", "'fields', None): field_info['children'] = self.get_serializer_info(field) if not isinstance(field, (RelatedField, ManyRelatedField))", "choice_name in field.choices.items()] # Indicate if a field is write-only.", "PUT/POST methods, remove read-only fields. if method in ('PUT', 'POST'):", "== 'type' and hasattr(serializer, 'get_type_choices'): meta['choices'] = serializer.get_type_choices() # For", "field_info['default'] = default except serializers.SkipField: pass if getattr(field, 'child', None):", "from the view. if getattr(view, 'related_search_fields', None): metadata['related_search_fields'] = view.related_search_fields", "elif field.field_name in ('url', 'custom_virtualenv', 'token'): field_info['type'] = 'string' elif", "the view. if getattr(view, 'related_search_fields', None): metadata['related_search_fields'] = view.related_search_fields #", "'modified': _('Timestamp when this {} was last modified.'), } if", "This value should always be False for PUT/POST, so don't", "this {} was last modified.'), } if field.field_name in field_help_text:", "'get_serializer'): serializer = view.get_serializer() if hasattr(serializer, 'get_types'): metadata['types'] = serializer.get_types()", "== 'type': field_info['filterable'] = True else: for model_field in serializer.Meta.model._meta.fields:", "cp) field_info['%s_group_by_choices' % cp] = get_group_by_choices() # Special handling of", "for model_field in serializer.Meta.model._meta.fields: if field.field_name == model_field.name: if getattr(model_field,", "it (file-based read-only settings can't be updated) meta.pop('defined_in_file', False) if", "DRFJSONField from rest_framework.request import clone_request # AWX from awx.main.fields import", "ManyRelatedField from rest_framework.fields import JSONField as DRFJSONField from rest_framework.request import", "remove write-only fields. if method == 'GET': attrs_to_remove = ('required',", "True break else: field_info['filterable'] = False # Indicate if a", "awx.main.scheduler.kubernetes import PodManager class Metadata(metadata.SimpleMetadata): def get_field_info(self, field): field_info =", "None) if serializer and hasattr(serializer, 'Meta') and hasattr(serializer.Meta, 'model'): #", "remove read-only fields. if method in ('PUT', 'POST'): # This", "( isinstance(field, ManyRelatedField) and field.field_name == 'credentials' # launch-time credentials", "choice_name) for choice_value, choice_name in field.choices.items()] # Indicate if a", "= serializer.get_types() # Add search fields if available from the", "determine_metadata(self, request, view): # store request on self so we", "hasattr(serializer, 'Meta') and hasattr(serializer.Meta, 'model'): try: model_field = serializer.Meta.model._meta.get_field(field.field_name) except", "field_info['type'] = 'id' elif ( isinstance(field, JSONField) or isinstance(model_field, JSONField)", "try: model_field = serializer.Meta.model._meta.get_field(field.field_name) except Exception: pass if field.field_name ==", "determine_actions(self, request, view): actions = super(SublistAttachDetatchMetadata, self).determine_actions(request, view) method =", "metadata: metadata['actions'].pop('POST') metadata['actions']['POST'] = { \"id\": {\"type\": \"integer\", \"label\": \"ID\",", "on the type selected. if field.field_name == 'notification_configuration': for (notification_type_name,", "field_info['type'] = 'json' field_info['filterable'] = True break else: field_info['filterable'] =", "class Metadata(metadata.SimpleMetadata): def get_field_info(self, field): field_info = OrderedDict() field_info['type'] =", "= request try: setattr(view, '_request', request) metadata = super(Metadata, self).determine_metadata(request,", "we can use it to generate field defaults # (such", "it to generate field defaults # (such as TOWER_URL_BASE) self.request", "OrderedDict # Django from django.core.exceptions import PermissionDenied from django.db.models.fields import", "def determine_actions(self, request, view): # Add field information for GET", "field.field_name == 'messages': for (notification_type_name, notification_tr_name, notification_type_class) in NotificationTemplate.NOTIFICATION_TYPES: field_info[notification_type_name]", "field_info['placeholder'] = placeholder serializer = getattr(field, 'parent', None) if serializer", "serializers.empty: field_info['placeholder'] = placeholder serializer = getattr(field, 'parent', None) if", "elif isinstance(model_field, BooleanField): field_info['type'] = 'boolean' return field_info def get_serializer_info(self,", "available even when we can't POST/PUT). actions = {} for", "actions[method].pop(field) return actions def determine_metadata(self, request, view): # store request", "for attr in text_attrs: value = getattr(field, attr, None) if", "hasattr(serializer, 'Meta') and hasattr(serializer.Meta, 'model'): # Update help text for", "where the required properties # are conditional on the type", "('PUT', 'POST'): # This value should always be False for", "in metadata: metadata['actions'].pop('POST') metadata['actions']['POST'] = { \"id\": {\"type\": \"integer\", \"label\":", "= field.get_default() if field.field_name == 'TOWER_URL_BASE' and default == 'https://towerhost':", "import ugettext_lazy as _ # Django REST Framework from rest_framework", "JSONField) or isinstance(field, DRFJSONField) or isinstance(getattr(field, 'model_field', None), JSONField) or", "field.field_name in field_help_text: opts = serializer.Meta.model._meta.concrete_model._meta verbose_name = smart_text(opts.verbose_name) field_info['help_text']", "getattr(field, 'fields', None): field_info['children'] = self.get_serializer_info(field) if not isinstance(field, (RelatedField,", "serializers.SkipField: pass if getattr(field, 'child', None): field_info['child'] = self.get_field_info(field.child) elif", "always be False for PUT/POST, so don't # show it", "'min_length', 'max_length', 'placeholder') for attr in attrs_to_remove: meta.pop(attr, None) meta.get('child',", "request on self so we can use it to generate", "if len(roles) > 0: metadata['object_roles'] = roles from rest_framework import", "or isinstance(getattr(field, 'model_field', None), JSONField) or field.field_name == 'credential_passwords' ):", "this role.\"}, } return metadata class SublistAttachDetatchMetadata(Metadata): def determine_actions(self, request,", "force_text, smart_text from django.utils.translation import ugettext_lazy as _ # Django", "super(Metadata, self).determine_metadata(request, view) finally: delattr(view, '_request') # Add type(s) handled", "GET requests (so field names/labels are # available even when", "collections import OrderedDict # Django from django.core.exceptions import PermissionDenied from", "serializers from rest_framework.relations import RelatedField, ManyRelatedField from rest_framework.fields import JSONField", "Django from django.core.exceptions import PermissionDenied from django.db.models.fields import PositiveIntegerField, BooleanField", "and hasattr(serializer, 'Meta') and hasattr(serializer.Meta, 'model'): # Update help text", "ID for this {}.'), 'name': _('Name of this {}.'), 'description':", "= get_group_by_choices() # Special handling of notification configuration where the", "permissions if hasattr(view, 'check_permissions'): view.check_permissions(view.request) # Test object permissions if", "from collections import OrderedDict # Django from django.core.exceptions import PermissionDenied", "= True break else: field_info['filterable'] = False # Indicate if", "== 'type': field_info['type'] = 'choice' elif field.field_name in ('url', 'custom_virtualenv',", "cp in ('azure_rm', 'ec2', 'gce'): get_regions = getattr(InventorySource, 'get_%s_region_choices' %", "handled by this view/serializer. if hasattr(view, 'get_serializer'): serializer = view.get_serializer()", "continue if field == \"pod_spec_override\": meta['default'] = PodManager().pod_definition # Add", "getattr(view, 'search_fields', None): metadata['search_fields'] = view.search_fields # Add related search", "= super(SublistAttachDetatchMetadata, self).determine_actions(request, view) method = 'POST' if method in", "import exceptions from rest_framework import metadata from rest_framework import serializers", "import ForeignKey from django.http import Http404 from django.utils.encoding import force_text,", "import generics if isinstance(view, generics.ListAPIView) and hasattr(view, 'paginator'): metadata['max_page_size'] =", "class RoleMetadata(Metadata): def determine_metadata(self, request, view): metadata = super(RoleMetadata, self).determine_metadata(request,", "if getattr(view, 'related_search_fields', None): metadata['related_search_fields'] = view.related_search_fields # include role", "placeholder serializer = getattr(field, 'parent', None) if serializer and hasattr(serializer,", "remove this role.\"}, } return metadata class SublistAttachDetatchMetadata(Metadata): def determine_actions(self,", "from rest_framework import serializers from rest_framework.relations import RelatedField, ManyRelatedField from", "'summary_fields'): field_info['type'] = 'object' elif isinstance(field, PositiveIntegerField): field_info['type'] = 'integer'", "meta in list(actions[method].items()): if not isinstance(meta, dict): continue if field", "field == 'type' and hasattr(serializer, 'get_type_choices'): meta['choices'] = serializer.get_type_choices() #", "try: view_model = field.context['view'].model except (AttributeError, KeyError): view_model = None", "= 'string' elif field.field_name in ('related', 'summary_fields'): field_info['type'] = 'object'", "use it to generate field defaults # (such as TOWER_URL_BASE)", "from awx.main.scheduler.kubernetes import PodManager class Metadata(metadata.SimpleMetadata): def get_field_info(self, field): field_info", "if field.field_name == 'TOWER_URL_BASE' and default == 'https://towerhost': default =", "TOWER_URL_BASE) self.request = request try: setattr(view, '_request', request) metadata =", "view/serializer. if hasattr(view, 'get_serializer'): serializer = view.get_serializer() if hasattr(serializer, 'get_types'):", "obj = None try: # Test global permissions if hasattr(view,", "'placeholder') for attr in attrs_to_remove: meta.pop(attr, None) meta.get('child', {}).pop(attr, None)", "view): metadata = super(RoleMetadata, self).determine_metadata(request, view) if 'actions' in metadata:", "= request for field, meta in list(actions[method].items()): if not isinstance(meta,", "if a field has a default value. # FIXME: Still", "view) if 'actions' in metadata: metadata['actions'].pop('POST') metadata['actions']['POST'] = { \"id\":", "'required', False) text_attrs = [ 'read_only', 'label', 'help_text', 'min_length', 'max_length',", "notification messages where the required properties # are conditional on", "request for field, meta in list(actions[method].items()): if not isinstance(meta, dict):", "role.\"}, \"disassociate\": {\"type\": \"integer\", \"label\": \"Disassociate\", \"help_text\": \"Provide to remove", "!= '': field_info[attr] = force_text(value, strings_only=True) placeholder = getattr(field, 'placeholder',", "'{}://{}'.format(self.request.scheme, self.request.get_host()) field_info['default'] = default except serializers.SkipField: pass if getattr(field,", "serializer.Meta.model._meta.get_field(field.field_name) except Exception: pass if field.field_name == 'type': field_info['type'] =", "= view.paginator.max_page_size return metadata class RoleMetadata(Metadata): def determine_metadata(self, request, view):", "field.field_name == 'group_by': for cp in ('ec2',): get_group_by_choices = getattr(InventorySource,", "'name': _('Name of this {}.'), 'description': _('Optional description of this", "= super(RoleMetadata, self).determine_metadata(request, view) if 'actions' in metadata: metadata['actions'].pop('POST') metadata['actions']['POST']", "show it (file-based read-only settings can't be updated) meta.pop('defined_in_file', False)", "'string' elif field.field_name in ('related', 'summary_fields'): field_info['type'] = 'object' elif", "field defaults # (such as TOWER_URL_BASE) self.request = request try:", "meta.pop('read_only', False): if field == 'id' and hasattr(view, 'attach'): continue", "None try: # Test global permissions if hasattr(view, 'check_permissions'): view.check_permissions(view.request)", "from django.utils.encoding import force_text, smart_text from django.utils.translation import ugettext_lazy as", "return actions def determine_metadata(self, request, view): # store request on", "'url': _('URL for this {}.'), 'related': _('Data structure with URLs", "required properties # are conditional on the type selected. if", "'paginator'): metadata['max_page_size'] = view.paginator.max_page_size return metadata class RoleMetadata(Metadata): def determine_metadata(self,", "model_field.name: if getattr(model_field, '__accepts_json__', None): field_info['type'] = 'json' field_info['filterable'] =", "if field.field_name == 'group_by': for cp in ('ec2',): get_group_by_choices =", "ugettext_lazy as _ # Django REST Framework from rest_framework import", "import metadata from rest_framework import serializers from rest_framework.relations import RelatedField,", "= 'integer' elif field.field_name in ('created', 'modified'): field_info['type'] = 'datetime'", "view.request = request for field, meta in list(actions[method].items()): if not", "actions['GET'].pop(field) # For PUT/POST methods, remove read-only fields. if method", "meta['choices'] = serializer.get_type_choices() # For GET method, remove meta attributes", "fields, method: fields) return filterer( super(Metadata, self).get_serializer_info(serializer), method ) def", "from rest_framework.request import clone_request # AWX from awx.main.fields import JSONField,", "'POST' if method in actions: for field in list(actions[method].keys()): if", "view) finally: delattr(view, '_request') # Add type(s) handled by this", "field_info['write_only'] = True # Special handling of inventory source_region choices", "view. if getattr(view, 'search_fields', None): metadata['search_fields'] = view.search_fields # Add", "# Copyright (c) 2016 Ansible, Inc. # All Rights Reserved.", "Add search fields if available from the view. if getattr(view,", "EC2. if field.field_name == 'group_by': for cp in ('ec2',): get_group_by_choices", "elif getattr(field, 'fields', None): field_info['children'] = self.get_serializer_info(field) if not isinstance(field,", "= roles from rest_framework import generics if isinstance(view, generics.ListAPIView) and", "in field_help_text: opts = serializer.Meta.model._meta.concrete_model._meta verbose_name = smart_text(opts.verbose_name) field_info['help_text'] =", "'get_type_choices'): meta['choices'] = serializer.get_type_choices() # For GET method, remove meta", "'__accepts_json__', None): field_info['type'] = 'json' field_info['filterable'] = True break else:", "import Http404 from django.utils.encoding import force_text, smart_text from django.utils.translation import", "= 'id' elif ( isinstance(field, JSONField) or isinstance(model_field, JSONField) or", "for (notification_type_name, notification_tr_name, notification_type_class) in NotificationTemplate.NOTIFICATION_TYPES: field_info[notification_type_name] = notification_type_class.default_messages #", "field_info[notification_type_name] = notification_type_class.init_parameters # Special handling of notification messages where", "field_info['%s_region_choices' % cp] = get_regions() # Special handling of group_by", "== 'PUT' and hasattr(view, 'get_object'): obj = view.get_object() except (exceptions.APIException,", "% cp) field_info['%s_group_by_choices' % cp] = get_group_by_choices() # Special handling", "method, remove meta attributes that aren't relevant # when reading", "'https://towerhost': default = '{}://{}'.format(self.request.scheme, self.request.get_host()) field_info['default'] = default except serializers.SkipField:", "structure with name/description for related resources.'), 'created': _('Timestamp when this", "notification_type_class.default_messages # Update type of fields returned... model_field = None", "return metadata class SublistAttachDetatchMetadata(Metadata): def determine_actions(self, request, view): actions =", "= '{}://{}'.format(self.request.scheme, self.request.get_host()) field_info['default'] = default except serializers.SkipField: pass if", "NotificationTemplate.NOTIFICATION_TYPES: field_info[notification_type_name] = notification_type_class.init_parameters # Special handling of notification messages", "# available even when we can't POST/PUT). actions = {}", "method == 'PUT' and hasattr(view, 'get_object'): obj = view.get_object() except", "except Exception: pass if field.field_name == 'type': field_info['type'] = 'choice'", "getattr(InventorySource, 'get_%s_region_choices' % cp) field_info['%s_region_choices' % cp] = get_regions() #", "continue else: # If user has appropriate permissions for the", "get_group_by_choices = getattr(InventorySource, 'get_%s_group_by_choices' % cp) field_info['%s_group_by_choices' % cp] =", "# Add type choices if available from the serializer. if", "_('Name of this {}.'), 'description': _('Optional description of this {}.'),", "meta.pop('write_only', False): actions['GET'].pop(field) # For PUT/POST methods, remove read-only fields.", "group_by choices for EC2. if field.field_name == 'group_by': for cp", "if getattr(view, 'search_fields', None): metadata['search_fields'] = view.search_fields # Add related", "= placeholder serializer = getattr(field, 'parent', None) if serializer and", "attributes that aren't relevant # when reading a field and", "and hasattr(view, 'paginator'): metadata['max_page_size'] = view.paginator.max_page_size return metadata class RoleMetadata(Metadata):", "_('Data type for this {}.'), 'url': _('URL for this {}.'),", "for cp in ('azure_rm', 'ec2', 'gce'): get_regions = getattr(InventorySource, 'get_%s_region_choices'", "self).determine_metadata(request, view) finally: delattr(view, '_request') # Add type(s) handled by", "setattr(view, '_request', request) metadata = super(Metadata, self).determine_metadata(request, view) finally: delattr(view,", "django.utils.translation import ugettext_lazy as _ # Django REST Framework from", "fields if available from the view. if getattr(view, 'related_search_fields', None):", "try: default = field.get_default() if field.field_name == 'TOWER_URL_BASE' and default", "actions def determine_metadata(self, request, view): # store request on self", "view.get_serializer() if hasattr(serializer, 'get_types'): metadata['types'] = serializer.get_types() # Add search", "field.field_name == 'source_regions': for cp in ('azure_rm', 'ec2', 'gce'): get_regions", "'related': _('Data structure with URLs of related resources.'), 'summary_fields': _('Data", "# Update help text for common fields. field_help_text = {", "the view. if getattr(view, 'search_fields', None): metadata['search_fields'] = view.search_fields #", "that vary based on # selected inventory source. if field.field_name", "view): # store request on self so we can use", "('url', 'custom_virtualenv', 'token'): field_info['type'] = 'string' elif field.field_name in ('related',", "try: # Test global permissions if hasattr(view, 'check_permissions'): view.check_permissions(view.request) #", "meta.pop('defined_in_file', False) if meta.pop('read_only', False): if field == 'id' and", "ForeignKey) ): field_info['type'] = 'id' elif ( isinstance(field, JSONField) or", "import PositiveIntegerField, BooleanField from django.db.models.fields.related import ForeignKey from django.http import", "has a default value. # FIXME: Still isn't showing all", "'POST'): # This value should always be False for PUT/POST,", "can't be updated) meta.pop('defined_in_file', False) if meta.pop('read_only', False): if field", "actions[method] = self.get_serializer_info(serializer, method=method) finally: view.request = request for field,", "roles from rest_framework import generics if isinstance(view, generics.ListAPIView) and hasattr(view,", "self.get_serializer_info(serializer, method=method) finally: view.request = request for field, meta in", "defaults # (such as TOWER_URL_BASE) self.request = request try: setattr(view,", "= view.related_search_fields # include role names in metadata roles =", "getattr(view, 'model', None) if model: for field in model._meta.get_fields(): if", "relevant # when reading a field and remove write-only fields.", "read-only fields. if method in ('PUT', 'POST'): # This value", "text_attrs: value = getattr(field, attr, None) if value is not", "from the serializer. if field == 'type' and hasattr(serializer, 'get_type_choices'):", "filterer = getattr(serializer, 'filter_field_metadata', lambda fields, method: fields) return filterer(", "field_info['type'] = self.label_lookup[field] field_info['required'] = getattr(field, 'required', False) text_attrs =", "the fields that should be supplied. serializer = view.get_serializer(instance=obj) actions[method]", "def determine_metadata(self, request, view): # store request on self so", "this role.\"}, \"disassociate\": {\"type\": \"integer\", \"label\": \"Disassociate\", \"help_text\": \"Provide to", "required properties # are conditional on the type selected. try:", "= getattr(field, 'placeholder', serializers.empty) if placeholder is not serializers.empty: field_info['placeholder']", "of inventory source_region choices that vary based on # selected", "None if view_model == NotificationTemplate and field.field_name == 'messages': for", "= getattr(field, attr, None) if value is not None and", "getattr(field, 'child', None): field_info['child'] = self.get_field_info(field.child) elif getattr(field, 'fields', None):", "isinstance(model_field, ForeignKey) ): field_info['type'] = 'id' elif ( isinstance(field, JSONField)", "# For GET method, remove meta attributes that aren't relevant", "should always be False for PUT/POST, so don't # show", "is ImplicitRoleField: roles.append(field.name) if len(roles) > 0: metadata['object_roles'] = roles", "method = 'POST' if method in actions: for field in", "('created', 'modified'): field_info['type'] = 'datetime' elif ( RelatedField in field.__class__.__bases__", "field.field_name == 'credentials' # launch-time credentials ): field_info['type'] = 'list_of_ids'", "and value != '': field_info[attr] = force_text(value, strings_only=True) placeholder =", "GET method, remove meta attributes that aren't relevant # when", "\"ID\", \"help_text\": \"Database ID for this role.\"}, \"disassociate\": {\"type\": \"integer\",", "REST Framework from rest_framework import exceptions from rest_framework import metadata", "write-only fields. if method == 'GET': attrs_to_remove = ('required', 'read_only',", "Test global permissions if hasattr(view, 'check_permissions'): view.check_permissions(view.request) # Test object", "None) if model: for field in model._meta.get_fields(): if type(field) is", "help text for common fields. field_help_text = { 'id': _('Database", "choices for EC2. if field.field_name == 'group_by': for cp in", "# show it (file-based read-only settings can't be updated) meta.pop('defined_in_file',", "description of this {}.'), 'type': _('Data type for this {}.'),", "in ('related', 'summary_fields'): field_info['type'] = 'object' elif isinstance(field, PositiveIntegerField): field_info['type']", "[ 'read_only', 'label', 'help_text', 'min_length', 'max_length', 'min_value', 'max_value', 'category', 'category_slug',", "'GET': attrs_to_remove = ('required', 'read_only', 'default', 'min_length', 'max_length', 'placeholder') for", "'POST'} & set(view.allowed_methods): view.request = clone_request(request, method) obj = None", "# Add field information for GET requests (so field names/labels", "meta['default'] = PodManager().pod_definition # Add type choices if available from", "ForeignKey from django.http import Http404 from django.utils.encoding import force_text, smart_text", "if available from the serializer. if field == 'type' and", "related resources.'), 'created': _('Timestamp when this {} was created.'), 'modified':", "# Add related search fields if available from the view.", "messages where the required properties # are conditional on the", "hasattr(serializer.Meta, 'model'): # Update help text for common fields. field_help_text", "in list(actions[method].items()): if not isinstance(meta, dict): continue if field ==" ]
[ "from washer.worker.commands import washertask def pipenv_graph2deps(rawgraph): graph = json.loads(rawgraph) def", "with c.cd(path): res = c.run(\"pipenv install -r %s\" % requirement)", "from washer.worker.actions import SetProperty from washer.worker.commands import washertask def pipenv_graph2deps(rawgraph):", "SetProperty(\"dependencies\", list(pipenv_graph2deps(deps.stdout))) return True @washertask def requirement_file(repopath, requirement=\"requirements.txt\", path=\".\", **kwargs):", "c.cd(repopath): with c.cd(path): res = c.run(\"pipenv install .\") deps =", "else: yield build_entry(entry) yield from extract_dependencies(graph) @washertask def pip_install(repopath, path=\".\",", "washer.worker.actions import AppendStdout, AppendStderr from washer.worker.actions import CreateNamedLog, AppendToLog from", "path=\".\", **kwargs): import invoke c = invoke.Context() with c.cd(repopath): with", "AppendStdout(res.stdout) yield AppendStderr(res.stderr) yield SetProperty(\"dependencies\", list(pipenv_graph2deps(deps.stdout))) return True @washertask def", "pipenv_graph2deps(rawgraph): graph = json.loads(rawgraph) def build_entry(data): if 'required_version' in data:", "--json\") yield AppendStdout(res.stdout) yield AppendStderr(res.stderr) yield SetProperty(\"dependencies\", list(pipenv_graph2deps(deps.stdout))) return True", "yield build_entry(entry) yield from extract_dependencies(graph) @washertask def pip_install(repopath, path=\".\", **kwargs):", "json from washer.worker.actions import AppendStdout, AppendStderr from washer.worker.actions import CreateNamedLog,", "yield AppendStderr(res.stderr) yield SetProperty(\"dependencies\", list(pipenv_graph2deps(deps.stdout))) return True @washertask def requirement_file(repopath,", "build_entry(package) yield from extract_dependencies(dependencies) else: yield build_entry(entry) yield from extract_dependencies(graph)", "= invoke.Context() with c.cd(repopath): with c.cd(path): res = c.run(\"pipenv install", "'pipenv', 'spec': spec, 'source': 'pypi', 'name': data['package_name'], 'version': data['installed_version']} def", "entries: if 'package' in entry: package = entry['package'] dependencies =", "@washertask def pip_install(repopath, path=\".\", **kwargs): import invoke c = invoke.Context()", "def requirement_file(repopath, requirement=\"requirements.txt\", path=\".\", **kwargs): import invoke c = invoke.Context()", "@washertask def requirement_file(repopath, requirement=\"requirements.txt\", path=\".\", **kwargs): import invoke c =", "= data['key'] + data['required_version'] else: spec = data['key'] return {'installer':", "deps = c.run(\"pipenv graph --json\") yield AppendStdout(res.stdout) yield AppendStderr(res.stderr) yield", "% requirement) deps = c.run(\"pipenv graph --json\") yield AppendStdout(res.stdout) yield", "-r %s\" % requirement) deps = c.run(\"pipenv graph --json\") yield", "graph = json.loads(rawgraph) def build_entry(data): if 'required_version' in data: spec", "yield AppendStdout(res.stdout) yield AppendStderr(res.stderr) yield SetProperty(\"dependencies\", list(pipenv_graph2deps(deps.stdout))) return True @washertask", "spec, 'source': 'pypi', 'name': data['package_name'], 'version': data['installed_version']} def extract_dependencies(entries): for", "yield build_entry(package) yield from extract_dependencies(dependencies) else: yield build_entry(entry) yield from", "'name': data['package_name'], 'version': data['installed_version']} def extract_dependencies(entries): for entry in entries:", "c.cd(repopath): with c.cd(path): res = c.run(\"pipenv install -r %s\" %", "for entry in entries: if 'package' in entry: package =", "c.run(\"pipenv install -r %s\" % requirement) deps = c.run(\"pipenv graph", "c.run(\"pipenv install .\") deps = c.run(\"pipenv graph --json\") yield AppendStdout(res.stdout)", "'version': data['installed_version']} def extract_dependencies(entries): for entry in entries: if 'package'", "extract_dependencies(entries): for entry in entries: if 'package' in entry: package", "c = invoke.Context() with c.cd(repopath): with c.cd(path): res = c.run(\"pipenv", "install .\") deps = c.run(\"pipenv graph --json\") yield AppendStdout(res.stdout) yield", "build_entry(data): if 'required_version' in data: spec = data['key'] + data['required_version']", "True @washertask def requirement_file(repopath, requirement=\"requirements.txt\", path=\".\", **kwargs): import invoke c", "from washer.worker.actions import CreateNamedLog, AppendToLog from washer.worker.actions import SetProperty from", "import AppendStdout, AppendStderr from washer.worker.actions import CreateNamedLog, AppendToLog from washer.worker.actions", "c.cd(path): res = c.run(\"pipenv install .\") deps = c.run(\"pipenv graph", "washer.worker.commands import washertask def pipenv_graph2deps(rawgraph): graph = json.loads(rawgraph) def build_entry(data):", "def pip_install(repopath, path=\".\", **kwargs): import invoke c = invoke.Context() with", "washertask def pipenv_graph2deps(rawgraph): graph = json.loads(rawgraph) def build_entry(data): if 'required_version'", "'spec': spec, 'source': 'pypi', 'name': data['package_name'], 'version': data['installed_version']} def extract_dependencies(entries):", "'required_version' in data: spec = data['key'] + data['required_version'] else: spec", "extract_dependencies(dependencies) else: yield build_entry(entry) yield from extract_dependencies(graph) @washertask def pip_install(repopath,", "data['key'] return {'installer': 'pipenv', 'spec': spec, 'source': 'pypi', 'name': data['package_name'],", "if 'required_version' in data: spec = data['key'] + data['required_version'] else:", "'source': 'pypi', 'name': data['package_name'], 'version': data['installed_version']} def extract_dependencies(entries): for entry", "**kwargs): import invoke c = invoke.Context() with c.cd(repopath): with c.cd(path):", "if 'package' in entry: package = entry['package'] dependencies = entry.get('dependencies',", "= data['key'] return {'installer': 'pipenv', 'spec': spec, 'source': 'pypi', 'name':", "dependencies = entry.get('dependencies', []) yield build_entry(package) yield from extract_dependencies(dependencies) else:", "c.run(\"pipenv graph --json\") yield AppendStdout(res.stdout) yield AppendStderr(res.stderr) yield SetProperty(\"dependencies\", list(pipenv_graph2deps(deps.stdout)))", "from extract_dependencies(dependencies) else: yield build_entry(entry) yield from extract_dependencies(graph) @washertask def", "list(pipenv_graph2deps(deps.stdout))) return True @washertask def requirement_file(repopath, requirement=\"requirements.txt\", path=\".\", **kwargs): import", "with c.cd(repopath): with c.cd(path): res = c.run(\"pipenv install -r %s\"", "pip_install(repopath, path=\".\", **kwargs): import invoke c = invoke.Context() with c.cd(repopath):", ".\") deps = c.run(\"pipenv graph --json\") yield AppendStdout(res.stdout) yield AppendStderr(res.stderr)", "from washer.worker.actions import AppendStdout, AppendStderr from washer.worker.actions import CreateNamedLog, AppendToLog", "= json.loads(rawgraph) def build_entry(data): if 'required_version' in data: spec =", "entry.get('dependencies', []) yield build_entry(package) yield from extract_dependencies(dependencies) else: yield build_entry(entry)", "in entry: package = entry['package'] dependencies = entry.get('dependencies', []) yield", "= c.run(\"pipenv install .\") deps = c.run(\"pipenv graph --json\") yield", "def pipenv_graph2deps(rawgraph): graph = json.loads(rawgraph) def build_entry(data): if 'required_version' in", "install -r %s\" % requirement) deps = c.run(\"pipenv graph --json\")", "%s\" % requirement) deps = c.run(\"pipenv graph --json\") yield AppendStdout(res.stdout)", "import SetProperty from washer.worker.commands import washertask def pipenv_graph2deps(rawgraph): graph =", "import washertask def pipenv_graph2deps(rawgraph): graph = json.loads(rawgraph) def build_entry(data): if", "return {'installer': 'pipenv', 'spec': spec, 'source': 'pypi', 'name': data['package_name'], 'version':", "SetProperty from washer.worker.commands import washertask def pipenv_graph2deps(rawgraph): graph = json.loads(rawgraph)", "invoke.Context() with c.cd(repopath): with c.cd(path): res = c.run(\"pipenv install .\")", "json.loads(rawgraph) def build_entry(data): if 'required_version' in data: spec = data['key']", "'pypi', 'name': data['package_name'], 'version': data['installed_version']} def extract_dependencies(entries): for entry in", "entry['package'] dependencies = entry.get('dependencies', []) yield build_entry(package) yield from extract_dependencies(dependencies)", "extract_dependencies(graph) @washertask def pip_install(repopath, path=\".\", **kwargs): import invoke c =", "invoke c = invoke.Context() with c.cd(repopath): with c.cd(path): res =", "= c.run(\"pipenv graph --json\") yield AppendStdout(res.stdout) yield AppendStderr(res.stderr) yield SetProperty(\"dependencies\",", "yield SetProperty(\"dependencies\", list(pipenv_graph2deps(deps.stdout))) return True @washertask def requirement_file(repopath, requirement=\"requirements.txt\", path=\".\",", "spec = data['key'] + data['required_version'] else: spec = data['key'] return", "build_entry(entry) yield from extract_dependencies(graph) @washertask def pip_install(repopath, path=\".\", **kwargs): import", "data['key'] + data['required_version'] else: spec = data['key'] return {'installer': 'pipenv',", "in entries: if 'package' in entry: package = entry['package'] dependencies", "{'installer': 'pipenv', 'spec': spec, 'source': 'pypi', 'name': data['package_name'], 'version': data['installed_version']}", "res = c.run(\"pipenv install -r %s\" % requirement) deps =", "data['package_name'], 'version': data['installed_version']} def extract_dependencies(entries): for entry in entries: if", "requirement=\"requirements.txt\", path=\".\", **kwargs): import invoke c = invoke.Context() with c.cd(repopath):", "c.cd(path): res = c.run(\"pipenv install -r %s\" % requirement) deps", "data['installed_version']} def extract_dependencies(entries): for entry in entries: if 'package' in", "spec = data['key'] return {'installer': 'pipenv', 'spec': spec, 'source': 'pypi',", "[]) yield build_entry(package) yield from extract_dependencies(dependencies) else: yield build_entry(entry) yield", "return True @washertask def requirement_file(repopath, requirement=\"requirements.txt\", path=\".\", **kwargs): import invoke", "yield from extract_dependencies(graph) @washertask def pip_install(repopath, path=\".\", **kwargs): import invoke", "invoke.Context() with c.cd(repopath): with c.cd(path): res = c.run(\"pipenv install -r", "washer.worker.actions import SetProperty from washer.worker.commands import washertask def pipenv_graph2deps(rawgraph): graph", "+ data['required_version'] else: spec = data['key'] return {'installer': 'pipenv', 'spec':", "import invoke c = invoke.Context() with c.cd(repopath): with c.cd(path): res", "res = c.run(\"pipenv install .\") deps = c.run(\"pipenv graph --json\")", "import json from washer.worker.actions import AppendStdout, AppendStderr from washer.worker.actions import", "data: spec = data['key'] + data['required_version'] else: spec = data['key']", "washer.worker.actions import CreateNamedLog, AppendToLog from washer.worker.actions import SetProperty from washer.worker.commands", "AppendStderr from washer.worker.actions import CreateNamedLog, AppendToLog from washer.worker.actions import SetProperty", "AppendToLog from washer.worker.actions import SetProperty from washer.worker.commands import washertask def", "import CreateNamedLog, AppendToLog from washer.worker.actions import SetProperty from washer.worker.commands import", "package = entry['package'] dependencies = entry.get('dependencies', []) yield build_entry(package) yield", "else: spec = data['key'] return {'installer': 'pipenv', 'spec': spec, 'source':", "entry: package = entry['package'] dependencies = entry.get('dependencies', []) yield build_entry(package)", "from extract_dependencies(graph) @washertask def pip_install(repopath, path=\".\", **kwargs): import invoke c", "AppendStderr(res.stderr) yield SetProperty(\"dependencies\", list(pipenv_graph2deps(deps.stdout))) return True @washertask def requirement_file(repopath, requirement=\"requirements.txt\",", "= c.run(\"pipenv install -r %s\" % requirement) deps = c.run(\"pipenv", "= entry.get('dependencies', []) yield build_entry(package) yield from extract_dependencies(dependencies) else: yield", "data['required_version'] else: spec = data['key'] return {'installer': 'pipenv', 'spec': spec,", "requirement) deps = c.run(\"pipenv graph --json\") yield AppendStdout(res.stdout) yield AppendStderr(res.stderr)", "def extract_dependencies(entries): for entry in entries: if 'package' in entry:", "AppendStdout, AppendStderr from washer.worker.actions import CreateNamedLog, AppendToLog from washer.worker.actions import", "graph --json\") yield AppendStdout(res.stdout) yield AppendStderr(res.stderr) yield SetProperty(\"dependencies\", list(pipenv_graph2deps(deps.stdout))) return", "requirement_file(repopath, requirement=\"requirements.txt\", path=\".\", **kwargs): import invoke c = invoke.Context() with", "def build_entry(data): if 'required_version' in data: spec = data['key'] +", "in data: spec = data['key'] + data['required_version'] else: spec =", "with c.cd(path): res = c.run(\"pipenv install .\") deps = c.run(\"pipenv", "'package' in entry: package = entry['package'] dependencies = entry.get('dependencies', [])", "CreateNamedLog, AppendToLog from washer.worker.actions import SetProperty from washer.worker.commands import washertask", "yield from extract_dependencies(dependencies) else: yield build_entry(entry) yield from extract_dependencies(graph) @washertask", "= entry['package'] dependencies = entry.get('dependencies', []) yield build_entry(package) yield from", "entry in entries: if 'package' in entry: package = entry['package']", "with c.cd(repopath): with c.cd(path): res = c.run(\"pipenv install .\") deps" ]
[ "json_data = json.load(json_file) return json_data # get all site profile", "site profile def getAllSiteProfiles(site_folder): allSiteProfiles = {} allSiteFiles = os.listdir(site_folder)", "[] for device in sp[\"devicesAvailable\"]: for i in range(device[\"deviceCounter\"]): allSiteProfiles[sp[\"siteName\"]].append(device[\"deviceName\"])", "for sf in allSiteFiles: sp = getSiteProfile(site_folder + \"/\" +", "= os.listdir(site_folder) for sf in allSiteFiles: sp = getSiteProfile(site_folder +", "getSiteProfile(site_folder + \"/\" + sf) allSiteProfiles[sp[\"siteName\"]] = [] for device", "json.load(json_file) return json_data # get all site profile def getAllSiteProfiles(site_folder):", "# get all site profile def getAllSiteProfiles(site_folder): allSiteProfiles = {}", "in allSiteFiles: sp = getSiteProfile(site_folder + \"/\" + sf) allSiteProfiles[sp[\"siteName\"]]", "open(site_file) as json_file: json_data = json.load(json_file) return json_data # get", "= json.load(json_file) return json_data # get all site profile def", "sf) allSiteProfiles[sp[\"siteName\"]] = [] for device in sp[\"devicesAvailable\"]: for i", "{} allSiteFiles = os.listdir(site_folder) for sf in allSiteFiles: sp =", "allSiteProfiles[sp[\"siteName\"]] = [] for device in sp[\"devicesAvailable\"]: for i in", "# get site profile def getSiteProfile(site_file): with open(site_file) as json_file:", "sp[\"devicesAvailable\"]: for i in range(device[\"deviceCounter\"]): allSiteProfiles[sp[\"siteName\"]].append(device[\"deviceName\"]) return allSiteProfiles #sites_folder =", "def getSiteProfile(site_file): with open(site_file) as json_file: json_data = json.load(json_file) return", "in range(device[\"deviceCounter\"]): allSiteProfiles[sp[\"siteName\"]].append(device[\"deviceName\"]) return allSiteProfiles #sites_folder = \"sites\" #print getAllSiteProfiles(sites_folder)", "sp = getSiteProfile(site_folder + \"/\" + sf) allSiteProfiles[sp[\"siteName\"]] = []", "device in sp[\"devicesAvailable\"]: for i in range(device[\"deviceCounter\"]): allSiteProfiles[sp[\"siteName\"]].append(device[\"deviceName\"]) return allSiteProfiles", "allSiteFiles = os.listdir(site_folder) for sf in allSiteFiles: sp = getSiteProfile(site_folder", "site profile def getSiteProfile(site_file): with open(site_file) as json_file: json_data =", "for i in range(device[\"deviceCounter\"]): allSiteProfiles[sp[\"siteName\"]].append(device[\"deviceName\"]) return allSiteProfiles #sites_folder = \"sites\"", "profile def getSiteProfile(site_file): with open(site_file) as json_file: json_data = json.load(json_file)", "as json_file: json_data = json.load(json_file) return json_data # get all", "get all site profile def getAllSiteProfiles(site_folder): allSiteProfiles = {} allSiteFiles", "sf in allSiteFiles: sp = getSiteProfile(site_folder + \"/\" + sf)", "\"/\" + sf) allSiteProfiles[sp[\"siteName\"]] = [] for device in sp[\"devicesAvailable\"]:", "= getSiteProfile(site_folder + \"/\" + sf) allSiteProfiles[sp[\"siteName\"]] = [] for", "= [] for device in sp[\"devicesAvailable\"]: for i in range(device[\"deviceCounter\"]):", "def getAllSiteProfiles(site_folder): allSiteProfiles = {} allSiteFiles = os.listdir(site_folder) for sf", "+ sf) allSiteProfiles[sp[\"siteName\"]] = [] for device in sp[\"devicesAvailable\"]: for", "return json_data # get all site profile def getAllSiteProfiles(site_folder): allSiteProfiles", "import json import os # get site profile def getSiteProfile(site_file):", "json_file: json_data = json.load(json_file) return json_data # get all site", "get site profile def getSiteProfile(site_file): with open(site_file) as json_file: json_data", "getSiteProfile(site_file): with open(site_file) as json_file: json_data = json.load(json_file) return json_data", "all site profile def getAllSiteProfiles(site_folder): allSiteProfiles = {} allSiteFiles =", "profile def getAllSiteProfiles(site_folder): allSiteProfiles = {} allSiteFiles = os.listdir(site_folder) for", "+ \"/\" + sf) allSiteProfiles[sp[\"siteName\"]] = [] for device in", "os.listdir(site_folder) for sf in allSiteFiles: sp = getSiteProfile(site_folder + \"/\"", "in sp[\"devicesAvailable\"]: for i in range(device[\"deviceCounter\"]): allSiteProfiles[sp[\"siteName\"]].append(device[\"deviceName\"]) return allSiteProfiles #sites_folder", "getAllSiteProfiles(site_folder): allSiteProfiles = {} allSiteFiles = os.listdir(site_folder) for sf in", "i in range(device[\"deviceCounter\"]): allSiteProfiles[sp[\"siteName\"]].append(device[\"deviceName\"]) return allSiteProfiles #sites_folder = \"sites\" #print", "json_data # get all site profile def getAllSiteProfiles(site_folder): allSiteProfiles =", "allSiteFiles: sp = getSiteProfile(site_folder + \"/\" + sf) allSiteProfiles[sp[\"siteName\"]] =", "os # get site profile def getSiteProfile(site_file): with open(site_file) as", "for device in sp[\"devicesAvailable\"]: for i in range(device[\"deviceCounter\"]): allSiteProfiles[sp[\"siteName\"]].append(device[\"deviceName\"]) return", "import os # get site profile def getSiteProfile(site_file): with open(site_file)", "with open(site_file) as json_file: json_data = json.load(json_file) return json_data #", "= {} allSiteFiles = os.listdir(site_folder) for sf in allSiteFiles: sp", "<filename>senity/utils/getSiteProfile.py import json import os # get site profile def", "json import os # get site profile def getSiteProfile(site_file): with", "allSiteProfiles = {} allSiteFiles = os.listdir(site_folder) for sf in allSiteFiles:" ]
[ "crash_rate_list.append(crash_rate) level_1_danger_list.append(level_1_danger_rate) level_2_danger_list.append(level_2_danger_rate) coll_rate_list.append(coll_rate) succ_rate_list.append(success_rate) succ_len_list.append(success_len) print('reward: ', reward_list) print('danger", "coll_rate = collision_num / num_eps success_rate = success_num / float(num_eps)", "[] coll_rate_list = [] succ_rate_list = [] succ_len_list = []", "cur_ep_acs.append(ac) if new: return {\"ep_obs\": cur_ep_obs, \"ep_acs\": cur_ep_acs, \"ep_ret\": cur_ep_ret,", "1, 2, 3] # ttcs = [2] gap = 0", "= crash_num / num_eps level_1_danger_rate = np.mean(level_1_danger) level_2_danger_rate = np.mean(level_2_danger)", "0 # abort ac = ac_lat * 3 + 1", "', level_2_danger_list) print('collison rate: ', coll_rate_list) print('success rate: ', succ_rate_list)", "env, is_gui, ttc, gap, sumoseed, randomseed): egoid = 'lane1.' +", "change lane else: ac_lat = 0 # abort ac =", "'\\nlevel-1-danger_rate: ', level_1_danger_rate, '\\nlevel-2-danger_rate: ', level_2_danger_rate, '\\ncollision_rate: ', coll_rate, '\\nsuccess_rate:", "traci def episode_generator(pi, env, is_gui, ttc, gap, sumoseed, randomseed): egoid", "success_len = evaluate_baseline(NUM_EPS, ttc, gap, IS_GUI) reward_list.append(ret_eval) danger_rate_list.append(danger_rate) crash_rate_list.append(crash_rate) level_1_danger_list.append(level_1_danger_rate)", "0.5, 1.24, 2.09, 2.09] # level-1-danger_rate: [0.23, 0.09, 0.05, 0.14,", "[] succ_rate_list = [] succ_len_list = [] for ttc in", "+= np.array(list(info['reward_dict'].values())) cur_ep_len += 1 cur_ep_obs.append(ob) cur_ep_acs.append(ac) if new: return", "1 # change lane else: ac_lat = 0 # abort", "* 4 + 0 + 1])*239.8 TTC = (leader_dis -", "cur_ep_ret_detail += np.array(list(info['reward_dict'].values())) cur_ep_len += 1 cur_ep_obs.append(ob) cur_ep_acs.append(ac) if new:", "collision_num += ep_eval['ep_is_collision'] success_num += int(ep_eval['ep_is_success']) if ep_eval['ep_is_success']: ep_len_list.append(ep_eval['ep_len']) sumoseed", "float(num_eps) ret_det_eval /= float(num_eps) danger_rate = danger_num / num_eps crash_rate", "'\\ndanger_rate: ', danger_rate, '\\ncrash_rate: ', crash_rate, '\\nlevel-1-danger_rate: ', level_1_danger_rate, '\\nlevel-2-danger_rate:", "is_gui=is_gui, sumoseed=sumoseed, randomseed=randomseed) traci.vehicle.setColor(egoid, (255, 69, 0)) cur_ep_ret = 0", "randomseed = 0 pi = pi_baseline env = LaneChangeEnv(is_train=False) ret_eval", "= success_num / float(num_eps) success_len = np.mean(ep_len_list) print('reward_detail: ', ret_det_eval)", "os.path.join(os.environ['SUMO_HOME'], 'tools') sys.path.append(tools) print('success') else: sys.exit(\"please declare environment variable 'SUMO_HOME'\")", "follower_speed = env.ego.trgt_follower.speed else: follower_speed = env.ego.speed leader_dis = abs(ob[3", "= [] coll_rate_list = [] succ_rate_list = [] succ_len_list =", "pi_baseline env = LaneChangeEnv(is_train=False) ret_eval = 0 ret_det_eval = 0", "0 + 1])*239.8 TTC = (leader_dis - 5) / max(env.ego.speed,", "success_rate, success_len NUM_EPS = 100 IS_GUI = False # f", "[] while True: ac = pi(ob=ob, env=env, ttc=ttc, gap=gap) ob,", "ep_eval['ep_rets_detail'] danger_num += ep_eval['ep_num_danger'] crash_num += ep_eval['ep_num_crash'] level_1_danger.append(1 if ep_eval['ep_num_danger']", "return ac def evaluate_baseline(num_eps, ttc, gap, is_gui): sumoseed = 0", "level_1_danger_list = [] level_2_danger_list = [] coll_rate_list = [] succ_rate_list", "= 0 level_1_danger = [] level_2_danger = [] collision_num =", "# abort ac = ac_lat * 3 + 1 return", "variable 'SUMO_HOME'\") import traci def episode_generator(pi, env, is_gui, ttc, gap,", "= abs(ob[4 * 4 + 0 + 1])*239.8 TTC =", "sumoseed=sumoseed, randomseed=randomseed) ret_eval += ep_eval['ep_ret'] ret_det_eval += ep_eval['ep_rets_detail'] danger_num +=", "10.0, 20.0] ttcs = [0.1, 0.3, 0.5, 1, 2, 3]", "danger_num / num_eps crash_rate = crash_num / num_eps level_1_danger_rate =", "leader_speed = env.ego.speed if env.ego.trgt_follower: follower_speed = env.ego.trgt_follower.speed else: follower_speed", "danger_rate, crash_rate, level_1_danger_rate, level_2_danger_rate, coll_rate, success_rate, success_len NUM_EPS = 100", "= pi_baseline env = LaneChangeEnv(is_train=False) ret_eval = 0 ret_det_eval =", "ttc, gap, IS_GUI) reward_list.append(ret_eval) danger_rate_list.append(danger_rate) crash_rate_list.append(crash_rate) level_1_danger_list.append(level_1_danger_rate) level_2_danger_list.append(level_2_danger_rate) coll_rate_list.append(coll_rate) succ_rate_list.append(success_rate)", "= [] succ_len_list = [] for ttc in ttcs: ret_eval,", "= [] cur_ep_acs = [] while True: ac = pi(ob=ob,", "rate: [0.58, 0.33, 0.5, 1.24, 2.09, 2.09] # level-1-danger_rate: [0.23,", "rew, new, info = env.step(ac) cur_ep_ret += rew cur_ep_ret_detail +=", "2, 3] # ttcs = [2] gap = 0 reward_list", "if new: return {\"ep_obs\": cur_ep_obs, \"ep_acs\": cur_ep_acs, \"ep_ret\": cur_ep_ret, 'ep_rets_detail':", "ret_det_eval += ep_eval['ep_rets_detail'] danger_num += ep_eval['ep_num_danger'] crash_num += ep_eval['ep_num_crash'] level_1_danger.append(1", "open('../data/baseline_evaluation/testseed2.csv', 'w+') # safety_gap = 2 constraints_list = [3.0] #", "randomseed += 1 ret_eval /= float(num_eps) ret_det_eval /= float(num_eps) danger_rate", "reward_list) print('danger rate: ', danger_rate_list) print('crash rate: ', crash_rate_list) print('level-1-danger_rate:", "\"ep_ret\": cur_ep_ret, 'ep_rets_detail': cur_ep_ret_detail, \"ep_len\": cur_ep_len, 'ep_num_danger': info['num_danger'], 'ep_is_success': info['is_success'],", "+ str(random.randint(1, 6)) ob = env.reset(egoid=egoid, tlane=0, tfc=2, is_gui=is_gui, sumoseed=sumoseed,", "[] level_2_danger_list = [] coll_rate_list = [] succ_rate_list = []", "in ttcs: ret_eval, danger_rate, crash_rate, level_1_danger_rate, level_2_danger_rate, coll_rate, success_rate, success_len", "gap): # safety gap set to seconds to collision if", "cur_ep_ret_detail, \"ep_len\": cur_ep_len, 'ep_num_danger': info['num_danger'], 'ep_is_success': info['is_success'], 'ep_num_crash': info['num_crash'], 'ep_is_collision':", "IS_GUI = False # f = open('../data/baseline_evaluation/testseed2.csv', 'w+') # safety_gap", "+= int(ep_eval['ep_is_success']) if ep_eval['ep_is_success']: ep_len_list.append(ep_eval['ep_len']) sumoseed += 1 randomseed +=", "level_2_danger_rate, '\\ncollision_rate: ', coll_rate, '\\nsuccess_rate: ', success_rate, '\\nsucess_len: ', success_len)", "current episode cur_ep_ret_detail = 0 cur_ep_len = 0 # len", "'tools') sys.path.append(tools) print('success') else: sys.exit(\"please declare environment variable 'SUMO_HOME'\") import", "/ num_eps crash_rate = crash_num / num_eps level_1_danger_rate = np.mean(level_1_danger)", "coll_rate, success_rate, success_len = evaluate_baseline(NUM_EPS, ttc, gap, IS_GUI) reward_list.append(ret_eval) danger_rate_list.append(danger_rate)", "[2] gap = 0 reward_list = [] danger_rate_list = []", "# safety_gap = 2 constraints_list = [3.0] # [1.0, 2.0,", "-69.84537459892903, -73.81562785829651, -148.23580687485645, -227.71842861064192, -229.9101089174337] # danger rate: [2.13, 0.88,", "gap and follower_dis > gap: ac_lat = 1 # change", "5) / max(env.ego.speed, 0.001) TTC2 = (follower_dis - 5) /", "* 4 + 0 + 1])*239.8 follower_dis = abs(ob[4 *", "env = LaneChangeEnv(is_train=False) ret_eval = 0 ret_det_eval = 0 #", "[0.0, 0.0, 0.02, 0.09, 0.14, 0.14] # success rate: [0.99,", "and TTC2 > ttc and leader_dis > gap and follower_dis", "= [] level_1_danger_list = [] level_2_danger_list = [] coll_rate_list =", "1])*239.8 TTC = (leader_dis - 5) / max(env.ego.speed, 0.001) TTC2", "gap=gap, sumoseed=sumoseed, randomseed=randomseed) ret_eval += ep_eval['ep_ret'] ret_det_eval += ep_eval['ep_rets_detail'] danger_num", "20.0] ttcs = [0.1, 0.3, 0.5, 1, 2, 3] #", "\"ep_len\": cur_ep_len, 'ep_num_danger': info['num_danger'], 'ep_is_success': info['is_success'], 'ep_num_crash': info['num_crash'], 'ep_is_collision': info[\"is_collision\"]}", "success_rate, success_len = evaluate_baseline(NUM_EPS, ttc, gap, IS_GUI) reward_list.append(ret_eval) danger_rate_list.append(danger_rate) crash_rate_list.append(crash_rate)", "level_1_danger_list) print('level-2-danger_rate: ', level_2_danger_list) print('collison rate: ', coll_rate_list) print('success rate:", "collision if env.ego.trgt_leader: leader_speed = env.ego.trgt_leader.speed else: leader_speed = env.ego.speed", "ep_eval['ep_num_crash'] level_1_danger.append(1 if ep_eval['ep_num_danger'] > 0 else 0) level_2_danger.append((1 if", "6)) ob = env.reset(egoid=egoid, tlane=0, tfc=2, is_gui=is_gui, sumoseed=sumoseed, randomseed=randomseed) traci.vehicle.setColor(egoid,", "[] cur_ep_acs = [] while True: ac = pi(ob=ob, env=env,", "gap = 0 reward_list = [] danger_rate_list = [] crash_rate_list", "+= ep_eval['ep_is_collision'] success_num += int(ep_eval['ep_is_success']) if ep_eval['ep_is_success']: ep_len_list.append(ep_eval['ep_len']) sumoseed +=", "# return in current episode cur_ep_ret_detail = 0 cur_ep_len =", "ttc in ttcs: ret_eval, danger_rate, crash_rate, level_1_danger_rate, level_2_danger_rate, coll_rate, success_rate,", "gap, IS_GUI) reward_list.append(ret_eval) danger_rate_list.append(danger_rate) crash_rate_list.append(crash_rate) level_1_danger_list.append(level_1_danger_rate) level_2_danger_list.append(level_2_danger_rate) coll_rate_list.append(coll_rate) succ_rate_list.append(success_rate) succ_len_list.append(success_len)", "import traci def episode_generator(pi, env, is_gui, ttc, gap, sumoseed, randomseed):", "= env.ego.speed if env.ego.trgt_follower: follower_speed = env.ego.trgt_follower.speed else: follower_speed =", "tools = os.path.join(os.environ['SUMO_HOME'], 'tools') sys.path.append(tools) print('success') else: sys.exit(\"please declare environment", "0 cur_ep_len = 0 # len of current episode cur_ep_obs", "/ max(env.ego.speed, 0.001) TTC2 = (follower_dis - 5) / max(follower_speed,", "= 0 pi = pi_baseline env = LaneChangeEnv(is_train=False) ret_eval =", "# len of current episode cur_ep_obs = [] cur_ep_acs =", "pi = pi_baseline env = LaneChangeEnv(is_train=False) ret_eval = 0 ret_det_eval", "NUM_EPS = 100 IS_GUI = False # f = open('../data/baseline_evaluation/testseed2.csv',", "', level_1_danger_list) print('level-2-danger_rate: ', level_2_danger_list) print('collison rate: ', coll_rate_list) print('success", "0 # not a integer, will be broadcasted danger_num =", "level_2_danger_rate = np.mean(level_2_danger) coll_rate = collision_num / num_eps success_rate =", "'ep_rets_detail': cur_ep_ret_detail, \"ep_len\": cur_ep_len, 'ep_num_danger': info['num_danger'], 'ep_is_success': info['is_success'], 'ep_num_crash': info['num_crash'],", "[] level_1_danger_list = [] level_2_danger_list = [] coll_rate_list = []", "0.05, 0.14, 0.25, 0.25] # level-2-danger_rate: [0.05, 0.03, 0.05, 0.12,", "LaneChangeEnv(is_train=False) ret_eval = 0 ret_det_eval = 0 # not a", "abs(ob[4 * 4 + 0 + 1])*239.8 TTC = (leader_dis", "True: ac = pi(ob=ob, env=env, ttc=ttc, gap=gap) ob, rew, new,", "succ_rate_list.append(success_rate) succ_len_list.append(success_len) print('reward: ', reward_list) print('danger rate: ', danger_rate_list) print('crash", "ret_eval /= float(num_eps) ret_det_eval /= float(num_eps) danger_rate = danger_num /", "= 0 # len of current episode cur_ep_obs = []", "sys from env.LaneChangeEnv import LaneChangeEnv import random import numpy as", "= env.ego.trgt_follower.speed else: follower_speed = env.ego.speed leader_dis = abs(ob[3 *", "danger_rate_list.append(danger_rate) crash_rate_list.append(crash_rate) level_1_danger_list.append(level_1_danger_rate) level_2_danger_list.append(level_2_danger_rate) coll_rate_list.append(coll_rate) succ_rate_list.append(success_rate) succ_len_list.append(success_len) print('reward: ', reward_list)", "0 reward_list = [] danger_rate_list = [] crash_rate_list = []", "leader_speed = env.ego.trgt_leader.speed else: leader_speed = env.ego.speed if env.ego.trgt_follower: follower_speed", "4 + 0 + 1])*239.8 follower_dis = abs(ob[4 * 4", "ac_lat = 1 # change lane else: ac_lat = 0", "episode_generator(pi, env, is_gui=is_gui, ttc=ttc, gap=gap, sumoseed=sumoseed, randomseed=randomseed) ret_eval += ep_eval['ep_ret']", "print('collison rate: ', coll_rate_list) print('success rate: ', succ_rate_list) print('sucess len:", "def evaluate_baseline(num_eps, ttc, gap, is_gui): sumoseed = 0 randomseed =", "level-1-danger_rate: [0.23, 0.09, 0.05, 0.14, 0.25, 0.25] # level-2-danger_rate: [0.05,", "ret_det_eval = 0 # not a integer, will be broadcasted", "= 0 cur_ep_len = 0 # len of current episode", "def episode_generator(pi, env, is_gui, ttc, gap, sumoseed, randomseed): egoid =", "cur_ep_obs = [] cur_ep_acs = [] while True: ac =", "0.14, 0.14] # success rate: [0.99, 0.99, 0.9, 0.6, 0.08,", "env, is_gui=is_gui, ttc=ttc, gap=gap, sumoseed=sumoseed, randomseed=randomseed) ret_eval += ep_eval['ep_ret'] ret_det_eval", "info['is_success'], 'ep_num_crash': info['num_crash'], 'ep_is_collision': info[\"is_collision\"]} def pi_baseline(ob, env, ttc, gap):", "else: leader_speed = env.ego.speed if env.ego.trgt_follower: follower_speed = env.ego.trgt_follower.speed else:", "= env.ego.speed leader_dis = abs(ob[3 * 4 + 0 +", "collison rate: [0.0, 0.0, 0.02, 0.09, 0.14, 0.14] # success", "= os.path.join(os.environ['SUMO_HOME'], 'tools') sys.path.append(tools) print('success') else: sys.exit(\"please declare environment variable", "[] level_2_danger = [] collision_num = 0 ep_len_list = []", "', succ_rate_list) print('sucess len: ', succ_len_list) # reward: [-89.12552753359037, -69.84537459892903,", "to collision if env.ego.trgt_leader: leader_speed = env.ego.trgt_leader.speed else: leader_speed =", "ob, rew, new, info = env.step(ac) cur_ep_ret += rew cur_ep_ret_detail", "= 0 crash_num = 0 level_1_danger = [] level_2_danger =", "0 # return in current episode cur_ep_ret_detail = 0 cur_ep_len", "as np if 'SUMO_HOME' in os.environ: tools = os.path.join(os.environ['SUMO_HOME'], 'tools')", "len of current episode cur_ep_obs = [] cur_ep_acs = []", "0.25] # level-2-danger_rate: [0.05, 0.03, 0.05, 0.12, 0.2, 0.2] #", "is_gui, ttc, gap, sumoseed, randomseed): egoid = 'lane1.' + str(random.randint(1,", "= env.ego.trgt_leader.speed else: leader_speed = env.ego.speed if env.ego.trgt_follower: follower_speed =", "tlane=0, tfc=2, is_gui=is_gui, sumoseed=sumoseed, randomseed=randomseed) traci.vehicle.setColor(egoid, (255, 69, 0)) cur_ep_ret", "to seconds to collision if env.ego.trgt_leader: leader_speed = env.ego.trgt_leader.speed else:", "len: ', succ_len_list) # reward: [-89.12552753359037, -69.84537459892903, -73.81562785829651, -148.23580687485645, -227.71842861064192,", "0.001) # print(TTC, TTC) if TTC > ttc and TTC2", "os.environ: tools = os.path.join(os.environ['SUMO_HOME'], 'tools') sys.path.append(tools) print('success') else: sys.exit(\"please declare", "success_num = 0 for i in range(num_eps): ep_eval = episode_generator(pi,", "is_gui=is_gui, ttc=ttc, gap=gap, sumoseed=sumoseed, randomseed=randomseed) ret_eval += ep_eval['ep_ret'] ret_det_eval +=", "level_2_danger_rate, coll_rate, success_rate, success_len = evaluate_baseline(NUM_EPS, ttc, gap, IS_GUI) reward_list.append(ret_eval)", "level_2_danger_rate, coll_rate, success_rate, success_len NUM_EPS = 100 IS_GUI = False", "+ 1 return ac def evaluate_baseline(num_eps, ttc, gap, is_gui): sumoseed", "success_rate = success_num / float(num_eps) success_len = np.mean(ep_len_list) print('reward_detail: ',", "ac = ac_lat * 3 + 1 return ac def", "else 0)) collision_num += ep_eval['ep_is_collision'] success_num += int(ep_eval['ep_is_success']) if ep_eval['ep_is_success']:", "rate: ', crash_rate_list) print('level-1-danger_rate: ', level_1_danger_list) print('level-2-danger_rate: ', level_2_danger_list) print('collison", "/ float(num_eps) success_len = np.mean(ep_len_list) print('reward_detail: ', ret_det_eval) print('reward: ',", "level_1_danger_list.append(level_1_danger_rate) level_2_danger_list.append(level_2_danger_rate) coll_rate_list.append(coll_rate) succ_rate_list.append(success_rate) succ_len_list.append(success_len) print('reward: ', reward_list) print('danger rate:", "<gh_stars>1-10 import os, sys from env.LaneChangeEnv import LaneChangeEnv import random", "+= 1 ret_eval /= float(num_eps) ret_det_eval /= float(num_eps) danger_rate =", "= abs(ob[3 * 4 + 0 + 1])*239.8 follower_dis =", "0 pi = pi_baseline env = LaneChangeEnv(is_train=False) ret_eval = 0", "crash_rate_list) print('level-1-danger_rate: ', level_1_danger_list) print('level-2-danger_rate: ', level_2_danger_list) print('collison rate: ',", "1 cur_ep_obs.append(ob) cur_ep_acs.append(ac) if new: return {\"ep_obs\": cur_ep_obs, \"ep_acs\": cur_ep_acs,", "import os, sys from env.LaneChangeEnv import LaneChangeEnv import random import", "', ret_eval, '\\ndanger_rate: ', danger_rate, '\\ncrash_rate: ', crash_rate, '\\nlevel-1-danger_rate: ',", "and leader_dis > gap and follower_dis > gap: ac_lat =", "= (leader_dis - 5) / max(env.ego.speed, 0.001) TTC2 = (follower_dis", "'SUMO_HOME' in os.environ: tools = os.path.join(os.environ['SUMO_HOME'], 'tools') sys.path.append(tools) print('success') else:", "0.001) TTC2 = (follower_dis - 5) / max(follower_speed, 0.001) #", "range(num_eps): ep_eval = episode_generator(pi, env, is_gui=is_gui, ttc=ttc, gap=gap, sumoseed=sumoseed, randomseed=randomseed)", "ep_eval['ep_num_danger'] crash_num += ep_eval['ep_num_crash'] level_1_danger.append(1 if ep_eval['ep_num_danger'] > 0 else", "0.5, 1, 2, 3] # ttcs = [2] gap =", "', reward_list) print('danger rate: ', danger_rate_list) print('crash rate: ', crash_rate_list)", "', danger_rate, '\\ncrash_rate: ', crash_rate, '\\nlevel-1-danger_rate: ', level_1_danger_rate, '\\nlevel-2-danger_rate: ',", "level_1_danger = [] level_2_danger = [] collision_num = 0 ep_len_list", "succ_rate_list = [] succ_len_list = [] for ttc in ttcs:", "ep_eval['ep_ret'] ret_det_eval += ep_eval['ep_rets_detail'] danger_num += ep_eval['ep_num_danger'] crash_num += ep_eval['ep_num_crash']", "rate: [0.0, 0.0, 0.02, 0.09, 0.14, 0.14] # success rate:", "print('reward: ', reward_list) print('danger rate: ', danger_rate_list) print('crash rate: ',", "= evaluate_baseline(NUM_EPS, ttc, gap, IS_GUI) reward_list.append(ret_eval) danger_rate_list.append(danger_rate) crash_rate_list.append(crash_rate) level_1_danger_list.append(level_1_danger_rate) level_2_danger_list.append(level_2_danger_rate)", "3] # ttcs = [2] gap = 0 reward_list =", "float(num_eps) success_len = np.mean(ep_len_list) print('reward_detail: ', ret_det_eval) print('reward: ', ret_eval,", "num_eps crash_rate = crash_num / num_eps level_1_danger_rate = np.mean(level_1_danger) level_2_danger_rate", "[] succ_len_list = [] for ttc in ttcs: ret_eval, danger_rate,", "print('success rate: ', succ_rate_list) print('sucess len: ', succ_len_list) # reward:", "sys.path.append(tools) print('success') else: sys.exit(\"please declare environment variable 'SUMO_HOME'\") import traci", "coll_rate, '\\nsuccess_rate: ', success_rate, '\\nsucess_len: ', success_len) env.close() return ret_eval,", "# f = open('../data/baseline_evaluation/testseed2.csv', 'w+') # safety_gap = 2 constraints_list", "level_2_danger_list.append(level_2_danger_rate) coll_rate_list.append(coll_rate) succ_rate_list.append(success_rate) succ_len_list.append(success_len) print('reward: ', reward_list) print('danger rate: ',", "0 # len of current episode cur_ep_obs = [] cur_ep_acs", "evaluate_baseline(num_eps, ttc, gap, is_gui): sumoseed = 0 randomseed = 0", "0.12, 0.2, 0.2] # collison rate: [0.0, 0.0, 0.02, 0.09,", "+= ep_eval['ep_rets_detail'] danger_num += ep_eval['ep_num_danger'] crash_num += ep_eval['ep_num_crash'] level_1_danger.append(1 if", "np.mean(level_1_danger) level_2_danger_rate = np.mean(level_2_danger) coll_rate = collision_num / num_eps success_rate", "broadcasted danger_num = 0 crash_num = 0 level_1_danger = []", "randomseed=randomseed) ret_eval += ep_eval['ep_ret'] ret_det_eval += ep_eval['ep_rets_detail'] danger_num += ep_eval['ep_num_danger']", "in os.environ: tools = os.path.join(os.environ['SUMO_HOME'], 'tools') sys.path.append(tools) print('success') else: sys.exit(\"please", "cur_ep_len, 'ep_num_danger': info['num_danger'], 'ep_is_success': info['is_success'], 'ep_num_crash': info['num_crash'], 'ep_is_collision': info[\"is_collision\"]} def", "tfc=2, is_gui=is_gui, sumoseed=sumoseed, randomseed=randomseed) traci.vehicle.setColor(egoid, (255, 69, 0)) cur_ep_ret =", "/ num_eps success_rate = success_num / float(num_eps) success_len = np.mean(ep_len_list)", "print('level-2-danger_rate: ', level_2_danger_list) print('collison rate: ', coll_rate_list) print('success rate: ',", "rew cur_ep_ret_detail += np.array(list(info['reward_dict'].values())) cur_ep_len += 1 cur_ep_obs.append(ob) cur_ep_acs.append(ac) if", "0 ep_len_list = [] success_num = 0 for i in", "coll_rate_list) print('success rate: ', succ_rate_list) print('sucess len: ', succ_len_list) #", "ret_det_eval /= float(num_eps) danger_rate = danger_num / num_eps crash_rate =", "ttc and leader_dis > gap and follower_dis > gap: ac_lat", "1 ret_eval /= float(num_eps) ret_det_eval /= float(num_eps) danger_rate = danger_num", "+= 1 randomseed += 1 ret_eval /= float(num_eps) ret_det_eval /=", "'ep_is_success': info['is_success'], 'ep_num_crash': info['num_crash'], 'ep_is_collision': info[\"is_collision\"]} def pi_baseline(ob, env, ttc,", "'\\nlevel-2-danger_rate: ', level_2_danger_rate, '\\ncollision_rate: ', coll_rate, '\\nsuccess_rate: ', success_rate, '\\nsucess_len:", "ttcs: ret_eval, danger_rate, crash_rate, level_1_danger_rate, level_2_danger_rate, coll_rate, success_rate, success_len =", "np if 'SUMO_HOME' in os.environ: tools = os.path.join(os.environ['SUMO_HOME'], 'tools') sys.path.append(tools)", "print('sucess len: ', succ_len_list) # reward: [-89.12552753359037, -69.84537459892903, -73.81562785829651, -148.23580687485645,", "= [] level_2_danger_list = [] coll_rate_list = [] succ_rate_list =", "danger_num += ep_eval['ep_num_danger'] crash_num += ep_eval['ep_num_crash'] level_1_danger.append(1 if ep_eval['ep_num_danger'] >", "0.14, 0.25, 0.25] # level-2-danger_rate: [0.05, 0.03, 0.05, 0.12, 0.2,", "(255, 69, 0)) cur_ep_ret = 0 # return in current", "2.09] # level-1-danger_rate: [0.23, 0.09, 0.05, 0.14, 0.25, 0.25] #", "ret_eval, danger_rate, crash_rate, level_1_danger_rate, level_2_danger_rate, coll_rate, success_rate, success_len = evaluate_baseline(NUM_EPS,", "-229.9101089174337] # danger rate: [2.13, 0.88, 0.77, 1.88, 3.82, 3.82]", "cur_ep_acs, \"ep_ret\": cur_ep_ret, 'ep_rets_detail': cur_ep_ret_detail, \"ep_len\": cur_ep_len, 'ep_num_danger': info['num_danger'], 'ep_is_success':", "= 0 for i in range(num_eps): ep_eval = episode_generator(pi, env,", "level_1_danger.append(1 if ep_eval['ep_num_danger'] > 0 else 0) level_2_danger.append((1 if ep_eval['ep_num_crash']", "cur_ep_acs = [] while True: ac = pi(ob=ob, env=env, ttc=ttc,", "will be broadcasted danger_num = 0 crash_num = 0 level_1_danger", "rate: ', coll_rate_list) print('success rate: ', succ_rate_list) print('sucess len: ',", "level_2_danger_list = [] coll_rate_list = [] succ_rate_list = [] succ_len_list", "0 ret_det_eval = 0 # not a integer, will be", "cur_ep_obs, \"ep_acs\": cur_ep_acs, \"ep_ret\": cur_ep_ret, 'ep_rets_detail': cur_ep_ret_detail, \"ep_len\": cur_ep_len, 'ep_num_danger':", "', coll_rate, '\\nsuccess_rate: ', success_rate, '\\nsucess_len: ', success_len) env.close() return", "constraints_list = [3.0] # [1.0, 2.0, 3.0, 4.0, 5.0, 10.0,", "4.0, 5.0, 10.0, 20.0] ttcs = [0.1, 0.3, 0.5, 1,", "> gap and follower_dis > gap: ac_lat = 1 #", "[] for ttc in ttcs: ret_eval, danger_rate, crash_rate, level_1_danger_rate, level_2_danger_rate,", "episode_generator(pi, env, is_gui, ttc, gap, sumoseed, randomseed): egoid = 'lane1.'", "+= 1 cur_ep_obs.append(ob) cur_ep_acs.append(ac) if new: return {\"ep_obs\": cur_ep_obs, \"ep_acs\":", "pi_baseline(ob, env, ttc, gap): # safety gap set to seconds", "'w+') # safety_gap = 2 constraints_list = [3.0] # [1.0,", "', danger_rate_list) print('crash rate: ', crash_rate_list) print('level-1-danger_rate: ', level_1_danger_list) print('level-2-danger_rate:", "ttc, gap): # safety gap set to seconds to collision", "success_num += int(ep_eval['ep_is_success']) if ep_eval['ep_is_success']: ep_len_list.append(ep_eval['ep_len']) sumoseed += 1 randomseed", "level_1_danger_rate, level_2_danger_rate, coll_rate, success_rate, success_len = evaluate_baseline(NUM_EPS, ttc, gap, IS_GUI)", "[2.13, 0.88, 0.77, 1.88, 3.82, 3.82] # crash rate: [0.58,", "sumoseed, randomseed): egoid = 'lane1.' + str(random.randint(1, 6)) ob =", "succ_rate_list) print('sucess len: ', succ_len_list) # reward: [-89.12552753359037, -69.84537459892903, -73.81562785829651,", "ep_eval['ep_is_success']: ep_len_list.append(ep_eval['ep_len']) sumoseed += 1 randomseed += 1 ret_eval /=", "= [] succ_rate_list = [] succ_len_list = [] for ttc", "0.9, 0.6, 0.08, 0.05] # sucess len: [55.656565656565654, 62.43434343434343, 67.5,", "print('reward_detail: ', ret_det_eval) print('reward: ', ret_eval, '\\ndanger_rate: ', danger_rate, '\\ncrash_rate:", "2.0, 3.0, 4.0, 5.0, 10.0, 20.0] ttcs = [0.1, 0.3,", "env.LaneChangeEnv import LaneChangeEnv import random import numpy as np if", "ac = pi(ob=ob, env=env, ttc=ttc, gap=gap) ob, rew, new, info", "[] collision_num = 0 ep_len_list = [] success_num = 0", "100 IS_GUI = False # f = open('../data/baseline_evaluation/testseed2.csv', 'w+') #", "from env.LaneChangeEnv import LaneChangeEnv import random import numpy as np", "ac def evaluate_baseline(num_eps, ttc, gap, is_gui): sumoseed = 0 randomseed", "0.2, 0.2] # collison rate: [0.0, 0.0, 0.02, 0.09, 0.14,", "level_1_danger_rate, '\\nlevel-2-danger_rate: ', level_2_danger_rate, '\\ncollision_rate: ', coll_rate, '\\nsuccess_rate: ', success_rate,", "env, ttc, gap): # safety gap set to seconds to", "evaluate_baseline(NUM_EPS, ttc, gap, IS_GUI) reward_list.append(ret_eval) danger_rate_list.append(danger_rate) crash_rate_list.append(crash_rate) level_1_danger_list.append(level_1_danger_rate) level_2_danger_list.append(level_2_danger_rate) coll_rate_list.append(coll_rate)", "5) / max(follower_speed, 0.001) # print(TTC, TTC) if TTC >", "follower_dis = abs(ob[4 * 4 + 0 + 1])*239.8 TTC", "numpy as np if 'SUMO_HOME' in os.environ: tools = os.path.join(os.environ['SUMO_HOME'],", "print(TTC, TTC) if TTC > ttc and TTC2 > ttc", "= 'lane1.' + str(random.randint(1, 6)) ob = env.reset(egoid=egoid, tlane=0, tfc=2,", "env.ego.trgt_follower: follower_speed = env.ego.trgt_follower.speed else: follower_speed = env.ego.speed leader_dis =", "sumoseed += 1 randomseed += 1 ret_eval /= float(num_eps) ret_det_eval", "level_2_danger.append((1 if ep_eval['ep_num_crash'] > 0 else 0)) collision_num += ep_eval['ep_is_collision']", "5.0, 10.0, 20.0] ttcs = [0.1, 0.3, 0.5, 1, 2,", "# ttcs = [2] gap = 0 reward_list = []", "ep_eval['ep_is_collision'] success_num += int(ep_eval['ep_is_success']) if ep_eval['ep_is_success']: ep_len_list.append(ep_eval['ep_len']) sumoseed += 1", "rate: [0.99, 0.99, 0.9, 0.6, 0.08, 0.05] # sucess len:", "0.25, 0.25] # level-2-danger_rate: [0.05, 0.03, 0.05, 0.12, 0.2, 0.2]", "TTC2 > ttc and leader_dis > gap and follower_dis >", "coll_rate, success_rate, success_len NUM_EPS = 100 IS_GUI = False #", "np.mean(level_2_danger) coll_rate = collision_num / num_eps success_rate = success_num /", "if env.ego.trgt_follower: follower_speed = env.ego.trgt_follower.speed else: follower_speed = env.ego.speed leader_dis", "if ep_eval['ep_is_success']: ep_len_list.append(ep_eval['ep_len']) sumoseed += 1 randomseed += 1 ret_eval", "2 constraints_list = [3.0] # [1.0, 2.0, 3.0, 4.0, 5.0,", "'\\nsuccess_rate: ', success_rate, '\\nsucess_len: ', success_len) env.close() return ret_eval, danger_rate,", "0.2] # collison rate: [0.0, 0.0, 0.02, 0.09, 0.14, 0.14]", "= episode_generator(pi, env, is_gui=is_gui, ttc=ttc, gap=gap, sumoseed=sumoseed, randomseed=randomseed) ret_eval +=", "level_1_danger_rate = np.mean(level_1_danger) level_2_danger_rate = np.mean(level_2_danger) coll_rate = collision_num /", "print('reward: ', ret_eval, '\\ndanger_rate: ', danger_rate, '\\ncrash_rate: ', crash_rate, '\\nlevel-1-danger_rate:", "crash_rate, level_1_danger_rate, level_2_danger_rate, coll_rate, success_rate, success_len NUM_EPS = 100 IS_GUI", "', success_rate, '\\nsucess_len: ', success_len) env.close() return ret_eval, danger_rate, crash_rate,", "env=env, ttc=ttc, gap=gap) ob, rew, new, info = env.step(ac) cur_ep_ret", "1.88, 3.82, 3.82] # crash rate: [0.58, 0.33, 0.5, 1.24,", "# success rate: [0.99, 0.99, 0.9, 0.6, 0.08, 0.05] #", "0 + 1])*239.8 follower_dis = abs(ob[4 * 4 + 0", "3 + 1 return ac def evaluate_baseline(num_eps, ttc, gap, is_gui):", "return in current episode cur_ep_ret_detail = 0 cur_ep_len = 0", "and follower_dis > gap: ac_lat = 1 # change lane", "# danger rate: [2.13, 0.88, 0.77, 1.88, 3.82, 3.82] #", "pi(ob=ob, env=env, ttc=ttc, gap=gap) ob, rew, new, info = env.step(ac)", "0)) cur_ep_ret = 0 # return in current episode cur_ep_ret_detail", "[0.99, 0.99, 0.9, 0.6, 0.08, 0.05] # sucess len: [55.656565656565654,", "declare environment variable 'SUMO_HOME'\") import traci def episode_generator(pi, env, is_gui,", "[0.05, 0.03, 0.05, 0.12, 0.2, 0.2] # collison rate: [0.0,", "danger_rate = danger_num / num_eps crash_rate = crash_num / num_eps", "# change lane else: ac_lat = 0 # abort ac", "0 level_1_danger = [] level_2_danger = [] collision_num = 0", "ttc=ttc, gap=gap) ob, rew, new, info = env.step(ac) cur_ep_ret +=", "= 0 ret_det_eval = 0 # not a integer, will", "not a integer, will be broadcasted danger_num = 0 crash_num", "sys.exit(\"please declare environment variable 'SUMO_HOME'\") import traci def episode_generator(pi, env,", "if ep_eval['ep_num_danger'] > 0 else 0) level_2_danger.append((1 if ep_eval['ep_num_crash'] >", "= 0 ep_len_list = [] success_num = 0 for i", "ttc, gap, is_gui): sumoseed = 0 randomseed = 0 pi", "danger_num = 0 crash_num = 0 level_1_danger = [] level_2_danger", "f = open('../data/baseline_evaluation/testseed2.csv', 'w+') # safety_gap = 2 constraints_list =", "= open('../data/baseline_evaluation/testseed2.csv', 'w+') # safety_gap = 2 constraints_list = [3.0]", "0 else 0)) collision_num += ep_eval['ep_is_collision'] success_num += int(ep_eval['ep_is_success']) if", "'SUMO_HOME'\") import traci def episode_generator(pi, env, is_gui, ttc, gap, sumoseed,", "is_gui): sumoseed = 0 randomseed = 0 pi = pi_baseline", "rate: ', danger_rate_list) print('crash rate: ', crash_rate_list) print('level-1-danger_rate: ', level_1_danger_list)", "# not a integer, will be broadcasted danger_num = 0", "-227.71842861064192, -229.9101089174337] # danger rate: [2.13, 0.88, 0.77, 1.88, 3.82,", "0.03, 0.05, 0.12, 0.2, 0.2] # collison rate: [0.0, 0.0,", "= env.reset(egoid=egoid, tlane=0, tfc=2, is_gui=is_gui, sumoseed=sumoseed, randomseed=randomseed) traci.vehicle.setColor(egoid, (255, 69,", "crash_rate, level_1_danger_rate, level_2_danger_rate, coll_rate, success_rate, success_len = evaluate_baseline(NUM_EPS, ttc, gap,", "= [0.1, 0.3, 0.5, 1, 2, 3] # ttcs =", "0 randomseed = 0 pi = pi_baseline env = LaneChangeEnv(is_train=False)", "current episode cur_ep_obs = [] cur_ep_acs = [] while True:", "reward: [-89.12552753359037, -69.84537459892903, -73.81562785829651, -148.23580687485645, -227.71842861064192, -229.9101089174337] # danger rate:", "+ 1])*239.8 TTC = (leader_dis - 5) / max(env.ego.speed, 0.001)", "in range(num_eps): ep_eval = episode_generator(pi, env, is_gui=is_gui, ttc=ttc, gap=gap, sumoseed=sumoseed,", "+= ep_eval['ep_num_danger'] crash_num += ep_eval['ep_num_crash'] level_1_danger.append(1 if ep_eval['ep_num_danger'] > 0", "IS_GUI) reward_list.append(ret_eval) danger_rate_list.append(danger_rate) crash_rate_list.append(crash_rate) level_1_danger_list.append(level_1_danger_rate) level_2_danger_list.append(level_2_danger_rate) coll_rate_list.append(coll_rate) succ_rate_list.append(success_rate) succ_len_list.append(success_len) print('reward:", "/= float(num_eps) danger_rate = danger_num / num_eps crash_rate = crash_num", "ttc, gap, sumoseed, randomseed): egoid = 'lane1.' + str(random.randint(1, 6))", "ret_eval, '\\ndanger_rate: ', danger_rate, '\\ncrash_rate: ', crash_rate, '\\nlevel-1-danger_rate: ', level_1_danger_rate,", "env.ego.trgt_follower.speed else: follower_speed = env.ego.speed leader_dis = abs(ob[3 * 4", "if env.ego.trgt_leader: leader_speed = env.ego.trgt_leader.speed else: leader_speed = env.ego.speed if", "(leader_dis - 5) / max(env.ego.speed, 0.001) TTC2 = (follower_dis -", "info[\"is_collision\"]} def pi_baseline(ob, env, ttc, gap): # safety gap set", "str(random.randint(1, 6)) ob = env.reset(egoid=egoid, tlane=0, tfc=2, is_gui=is_gui, sumoseed=sumoseed, randomseed=randomseed)", "[0.1, 0.3, 0.5, 1, 2, 3] # ttcs = [2]", "collision_num / num_eps success_rate = success_num / float(num_eps) success_len =", "0.88, 0.77, 1.88, 3.82, 3.82] # crash rate: [0.58, 0.33,", "follower_dis > gap: ac_lat = 1 # change lane else:", "new, info = env.step(ac) cur_ep_ret += rew cur_ep_ret_detail += np.array(list(info['reward_dict'].values()))", "import random import numpy as np if 'SUMO_HOME' in os.environ:", "print('level-1-danger_rate: ', level_1_danger_list) print('level-2-danger_rate: ', level_2_danger_list) print('collison rate: ', coll_rate_list)", "ep_eval['ep_num_crash'] > 0 else 0)) collision_num += ep_eval['ep_is_collision'] success_num +=", "integer, will be broadcasted danger_num = 0 crash_num = 0", "0.77, 1.88, 3.82, 3.82] # crash rate: [0.58, 0.33, 0.5,", "success_len NUM_EPS = 100 IS_GUI = False # f =", "def pi_baseline(ob, env, ttc, gap): # safety gap set to", "0)) collision_num += ep_eval['ep_is_collision'] success_num += int(ep_eval['ep_is_success']) if ep_eval['ep_is_success']: ep_len_list.append(ep_eval['ep_len'])", "gap, sumoseed, randomseed): egoid = 'lane1.' + str(random.randint(1, 6)) ob", "0.14] # success rate: [0.99, 0.99, 0.9, 0.6, 0.08, 0.05]", "= [] for ttc in ttcs: ret_eval, danger_rate, crash_rate, level_1_danger_rate,", "3.82] # crash rate: [0.58, 0.33, 0.5, 1.24, 2.09, 2.09]", "max(env.ego.speed, 0.001) TTC2 = (follower_dis - 5) / max(follower_speed, 0.001)", "= 1 # change lane else: ac_lat = 0 #", "> 0 else 0) level_2_danger.append((1 if ep_eval['ep_num_crash'] > 0 else", "ret_eval += ep_eval['ep_ret'] ret_det_eval += ep_eval['ep_rets_detail'] danger_num += ep_eval['ep_num_danger'] crash_num", "danger rate: [2.13, 0.88, 0.77, 1.88, 3.82, 3.82] # crash", "collision_num = 0 ep_len_list = [] success_num = 0 for", "num_eps success_rate = success_num / float(num_eps) success_len = np.mean(ep_len_list) print('reward_detail:", "a integer, will be broadcasted danger_num = 0 crash_num =", "return ret_eval, danger_rate, crash_rate, level_1_danger_rate, level_2_danger_rate, coll_rate, success_rate, success_len NUM_EPS", "> gap: ac_lat = 1 # change lane else: ac_lat", "= 0 # abort ac = ac_lat * 3 +", "+= ep_eval['ep_num_crash'] level_1_danger.append(1 if ep_eval['ep_num_danger'] > 0 else 0) level_2_danger.append((1", "/ num_eps level_1_danger_rate = np.mean(level_1_danger) level_2_danger_rate = np.mean(level_2_danger) coll_rate =", "2.09, 2.09] # level-1-danger_rate: [0.23, 0.09, 0.05, 0.14, 0.25, 0.25]", "= [2] gap = 0 reward_list = [] danger_rate_list =", "env.ego.speed leader_dis = abs(ob[3 * 4 + 0 + 1])*239.8", "success_rate, '\\nsucess_len: ', success_len) env.close() return ret_eval, danger_rate, crash_rate, level_1_danger_rate,", "crash_num / num_eps level_1_danger_rate = np.mean(level_1_danger) level_2_danger_rate = np.mean(level_2_danger) coll_rate", "for ttc in ttcs: ret_eval, danger_rate, crash_rate, level_1_danger_rate, level_2_danger_rate, coll_rate,", "# reward: [-89.12552753359037, -69.84537459892903, -73.81562785829651, -148.23580687485645, -227.71842861064192, -229.9101089174337] # danger", "set to seconds to collision if env.ego.trgt_leader: leader_speed = env.ego.trgt_leader.speed", "leader_dis > gap and follower_dis > gap: ac_lat = 1", "env.close() return ret_eval, danger_rate, crash_rate, level_1_danger_rate, level_2_danger_rate, coll_rate, success_rate, success_len", "', level_2_danger_rate, '\\ncollision_rate: ', coll_rate, '\\nsuccess_rate: ', success_rate, '\\nsucess_len: ',", "randomseed=randomseed) traci.vehicle.setColor(egoid, (255, 69, 0)) cur_ep_ret = 0 # return", "env.step(ac) cur_ep_ret += rew cur_ep_ret_detail += np.array(list(info['reward_dict'].values())) cur_ep_len += 1", "level_2_danger = [] collision_num = 0 ep_len_list = [] success_num", "abs(ob[3 * 4 + 0 + 1])*239.8 follower_dis = abs(ob[4", "coll_rate_list.append(coll_rate) succ_rate_list.append(success_rate) succ_len_list.append(success_len) print('reward: ', reward_list) print('danger rate: ', danger_rate_list)", "= [] danger_rate_list = [] crash_rate_list = [] level_1_danger_list =", "lane else: ac_lat = 0 # abort ac = ac_lat", "0.02, 0.09, 0.14, 0.14] # success rate: [0.99, 0.99, 0.9,", "[0.23, 0.09, 0.05, 0.14, 0.25, 0.25] # level-2-danger_rate: [0.05, 0.03,", "= env.step(ac) cur_ep_ret += rew cur_ep_ret_detail += np.array(list(info['reward_dict'].values())) cur_ep_len +=", "print('success') else: sys.exit(\"please declare environment variable 'SUMO_HOME'\") import traci def", "traci.vehicle.setColor(egoid, (255, 69, 0)) cur_ep_ret = 0 # return in", "', coll_rate_list) print('success rate: ', succ_rate_list) print('sucess len: ', succ_len_list)", "False # f = open('../data/baseline_evaluation/testseed2.csv', 'w+') # safety_gap = 2", "of current episode cur_ep_obs = [] cur_ep_acs = [] while", "seconds to collision if env.ego.trgt_leader: leader_speed = env.ego.trgt_leader.speed else: leader_speed", "4 + 0 + 1])*239.8 TTC = (leader_dis - 5)", "cur_ep_ret = 0 # return in current episode cur_ep_ret_detail =", "return {\"ep_obs\": cur_ep_obs, \"ep_acs\": cur_ep_acs, \"ep_ret\": cur_ep_ret, 'ep_rets_detail': cur_ep_ret_detail, \"ep_len\":", "be broadcasted danger_num = 0 crash_num = 0 level_1_danger =", "randomseed): egoid = 'lane1.' + str(random.randint(1, 6)) ob = env.reset(egoid=egoid,", "cur_ep_ret, 'ep_rets_detail': cur_ep_ret_detail, \"ep_len\": cur_ep_len, 'ep_num_danger': info['num_danger'], 'ep_is_success': info['is_success'], 'ep_num_crash':", "random import numpy as np if 'SUMO_HOME' in os.environ: tools", "= pi(ob=ob, env=env, ttc=ttc, gap=gap) ob, rew, new, info =", "gap=gap) ob, rew, new, info = env.step(ac) cur_ep_ret += rew", "import LaneChangeEnv import random import numpy as np if 'SUMO_HOME'", "egoid = 'lane1.' + str(random.randint(1, 6)) ob = env.reset(egoid=egoid, tlane=0,", "+ 1])*239.8 follower_dis = abs(ob[4 * 4 + 0 +", "crash_rate_list = [] level_1_danger_list = [] level_2_danger_list = [] coll_rate_list", "np.array(list(info['reward_dict'].values())) cur_ep_len += 1 cur_ep_obs.append(ob) cur_ep_acs.append(ac) if new: return {\"ep_obs\":", "69, 0)) cur_ep_ret = 0 # return in current episode", "# [1.0, 2.0, 3.0, 4.0, 5.0, 10.0, 20.0] ttcs =", "', crash_rate_list) print('level-1-danger_rate: ', level_1_danger_list) print('level-2-danger_rate: ', level_2_danger_list) print('collison rate:", "in current episode cur_ep_ret_detail = 0 cur_ep_len = 0 #", "safety gap set to seconds to collision if env.ego.trgt_leader: leader_speed", "= LaneChangeEnv(is_train=False) ret_eval = 0 ret_det_eval = 0 # not", "LaneChangeEnv import random import numpy as np if 'SUMO_HOME' in", "= ac_lat * 3 + 1 return ac def evaluate_baseline(num_eps,", "danger_rate_list = [] crash_rate_list = [] level_1_danger_list = [] level_2_danger_list", "ep_len_list = [] success_num = 0 for i in range(num_eps):", "success_len) env.close() return ret_eval, danger_rate, crash_rate, level_1_danger_rate, level_2_danger_rate, coll_rate, success_rate,", "if ep_eval['ep_num_crash'] > 0 else 0)) collision_num += ep_eval['ep_is_collision'] success_num", "\"ep_acs\": cur_ep_acs, \"ep_ret\": cur_ep_ret, 'ep_rets_detail': cur_ep_ret_detail, \"ep_len\": cur_ep_len, 'ep_num_danger': info['num_danger'],", "[3.0] # [1.0, 2.0, 3.0, 4.0, 5.0, 10.0, 20.0] ttcs", "'lane1.' + str(random.randint(1, 6)) ob = env.reset(egoid=egoid, tlane=0, tfc=2, is_gui=is_gui,", "# level-2-danger_rate: [0.05, 0.03, 0.05, 0.12, 0.2, 0.2] # collison", "import numpy as np if 'SUMO_HOME' in os.environ: tools =", "env.ego.trgt_leader.speed else: leader_speed = env.ego.speed if env.ego.trgt_follower: follower_speed = env.ego.trgt_follower.speed", "ttc=ttc, gap=gap, sumoseed=sumoseed, randomseed=randomseed) ret_eval += ep_eval['ep_ret'] ret_det_eval += ep_eval['ep_rets_detail']", "sumoseed = 0 randomseed = 0 pi = pi_baseline env", "danger_rate_list) print('crash rate: ', crash_rate_list) print('level-1-danger_rate: ', level_1_danger_list) print('level-2-danger_rate: ',", "[1.0, 2.0, 3.0, 4.0, 5.0, 10.0, 20.0] ttcs = [0.1,", "rate: [2.13, 0.88, 0.77, 1.88, 3.82, 3.82] # crash rate:", "ob = env.reset(egoid=egoid, tlane=0, tfc=2, is_gui=is_gui, sumoseed=sumoseed, randomseed=randomseed) traci.vehicle.setColor(egoid, (255,", "cur_ep_ret += rew cur_ep_ret_detail += np.array(list(info['reward_dict'].values())) cur_ep_len += 1 cur_ep_obs.append(ob)", "= danger_num / num_eps crash_rate = crash_num / num_eps level_1_danger_rate", "ac_lat = 0 # abort ac = ac_lat * 3", "# crash rate: [0.58, 0.33, 0.5, 1.24, 2.09, 2.09] #", "while True: ac = pi(ob=ob, env=env, ttc=ttc, gap=gap) ob, rew,", "gap, is_gui): sumoseed = 0 randomseed = 0 pi =", "', ret_det_eval) print('reward: ', ret_eval, '\\ndanger_rate: ', danger_rate, '\\ncrash_rate: ',", "new: return {\"ep_obs\": cur_ep_obs, \"ep_acs\": cur_ep_acs, \"ep_ret\": cur_ep_ret, 'ep_rets_detail': cur_ep_ret_detail,", "coll_rate_list = [] succ_rate_list = [] succ_len_list = [] for", "ac_lat * 3 + 1 return ac def evaluate_baseline(num_eps, ttc,", "succ_len_list) # reward: [-89.12552753359037, -69.84537459892903, -73.81562785829651, -148.23580687485645, -227.71842861064192, -229.9101089174337] #", "env.reset(egoid=egoid, tlane=0, tfc=2, is_gui=is_gui, sumoseed=sumoseed, randomseed=randomseed) traci.vehicle.setColor(egoid, (255, 69, 0))", "0 crash_num = 0 level_1_danger = [] level_2_danger = []", "0 else 0) level_2_danger.append((1 if ep_eval['ep_num_crash'] > 0 else 0))", "level_1_danger_rate, level_2_danger_rate, coll_rate, success_rate, success_len NUM_EPS = 100 IS_GUI =", "= 100 IS_GUI = False # f = open('../data/baseline_evaluation/testseed2.csv', 'w+')", "+ 0 + 1])*239.8 TTC = (leader_dis - 5) /", "= [] crash_rate_list = [] level_1_danger_list = [] level_2_danger_list =", "reward_list.append(ret_eval) danger_rate_list.append(danger_rate) crash_rate_list.append(crash_rate) level_1_danger_list.append(level_1_danger_rate) level_2_danger_list.append(level_2_danger_rate) coll_rate_list.append(coll_rate) succ_rate_list.append(success_rate) succ_len_list.append(success_len) print('reward: ',", "print('crash rate: ', crash_rate_list) print('level-1-danger_rate: ', level_1_danger_list) print('level-2-danger_rate: ', level_2_danger_list)", "= collision_num / num_eps success_rate = success_num / float(num_eps) success_len", "danger_rate, '\\ncrash_rate: ', crash_rate, '\\nlevel-1-danger_rate: ', level_1_danger_rate, '\\nlevel-2-danger_rate: ', level_2_danger_rate,", "ep_len_list.append(ep_eval['ep_len']) sumoseed += 1 randomseed += 1 ret_eval /= float(num_eps)", "rate: ', succ_rate_list) print('sucess len: ', succ_len_list) # reward: [-89.12552753359037,", "env.ego.trgt_leader: leader_speed = env.ego.trgt_leader.speed else: leader_speed = env.ego.speed if env.ego.trgt_follower:", "+ 0 + 1])*239.8 follower_dis = abs(ob[4 * 4 +", "float(num_eps) danger_rate = danger_num / num_eps crash_rate = crash_num /", "0.6, 0.08, 0.05] # sucess len: [55.656565656565654, 62.43434343434343, 67.5, 90.1,", "0.05] # sucess len: [55.656565656565654, 62.43434343434343, 67.5, 90.1, 66.625, 73.4]", "+= rew cur_ep_ret_detail += np.array(list(info['reward_dict'].values())) cur_ep_len += 1 cur_ep_obs.append(ob) cur_ep_acs.append(ac)", "+= ep_eval['ep_ret'] ret_det_eval += ep_eval['ep_rets_detail'] danger_num += ep_eval['ep_num_danger'] crash_num +=", "num_eps level_1_danger_rate = np.mean(level_1_danger) level_2_danger_rate = np.mean(level_2_danger) coll_rate = collision_num", "success_len = np.mean(ep_len_list) print('reward_detail: ', ret_det_eval) print('reward: ', ret_eval, '\\ndanger_rate:", "> ttc and TTC2 > ttc and leader_dis > gap", "[] crash_rate_list = [] level_1_danger_list = [] level_2_danger_list = []", "(follower_dis - 5) / max(follower_speed, 0.001) # print(TTC, TTC) if", "/= float(num_eps) ret_det_eval /= float(num_eps) danger_rate = danger_num / num_eps", "succ_len_list = [] for ttc in ttcs: ret_eval, danger_rate, crash_rate,", "0.99, 0.9, 0.6, 0.08, 0.05] # sucess len: [55.656565656565654, 62.43434343434343,", "3.82, 3.82] # crash rate: [0.58, 0.33, 0.5, 1.24, 2.09,", "danger_rate, crash_rate, level_1_danger_rate, level_2_danger_rate, coll_rate, success_rate, success_len = evaluate_baseline(NUM_EPS, ttc,", "info['num_crash'], 'ep_is_collision': info[\"is_collision\"]} def pi_baseline(ob, env, ttc, gap): # safety", "ttc and TTC2 > ttc and leader_dis > gap and", "TTC) if TTC > ttc and TTC2 > ttc and", "cur_ep_len += 1 cur_ep_obs.append(ob) cur_ep_acs.append(ac) if new: return {\"ep_obs\": cur_ep_obs,", "ret_eval = 0 ret_det_eval = 0 # not a integer,", "* 3 + 1 return ac def evaluate_baseline(num_eps, ttc, gap,", "'\\nsucess_len: ', success_len) env.close() return ret_eval, danger_rate, crash_rate, level_1_danger_rate, level_2_danger_rate,", "', crash_rate, '\\nlevel-1-danger_rate: ', level_1_danger_rate, '\\nlevel-2-danger_rate: ', level_2_danger_rate, '\\ncollision_rate: ',", "cur_ep_obs.append(ob) cur_ep_acs.append(ac) if new: return {\"ep_obs\": cur_ep_obs, \"ep_acs\": cur_ep_acs, \"ep_ret\":", "= 0 # not a integer, will be broadcasted danger_num", "[-89.12552753359037, -69.84537459892903, -73.81562785829651, -148.23580687485645, -227.71842861064192, -229.9101089174337] # danger rate: [2.13,", "np.mean(ep_len_list) print('reward_detail: ', ret_det_eval) print('reward: ', ret_eval, '\\ndanger_rate: ', danger_rate,", "'ep_num_danger': info['num_danger'], 'ep_is_success': info['is_success'], 'ep_num_crash': info['num_crash'], 'ep_is_collision': info[\"is_collision\"]} def pi_baseline(ob,", "1 randomseed += 1 ret_eval /= float(num_eps) ret_det_eval /= float(num_eps)", "leader_dis = abs(ob[3 * 4 + 0 + 1])*239.8 follower_dis", "0.33, 0.5, 1.24, 2.09, 2.09] # level-1-danger_rate: [0.23, 0.09, 0.05,", "episode cur_ep_obs = [] cur_ep_acs = [] while True: ac", "# level-1-danger_rate: [0.23, 0.09, 0.05, 0.14, 0.25, 0.25] # level-2-danger_rate:", "info = env.step(ac) cur_ep_ret += rew cur_ep_ret_detail += np.array(list(info['reward_dict'].values())) cur_ep_len", "- 5) / max(follower_speed, 0.001) # print(TTC, TTC) if TTC", "= [] while True: ac = pi(ob=ob, env=env, ttc=ttc, gap=gap)", "success_num / float(num_eps) success_len = np.mean(ep_len_list) print('reward_detail: ', ret_det_eval) print('reward:", "', level_1_danger_rate, '\\nlevel-2-danger_rate: ', level_2_danger_rate, '\\ncollision_rate: ', coll_rate, '\\nsuccess_rate: ',", "[] success_num = 0 for i in range(num_eps): ep_eval =", "', success_len) env.close() return ret_eval, danger_rate, crash_rate, level_1_danger_rate, level_2_danger_rate, coll_rate,", "TTC > ttc and TTC2 > ttc and leader_dis >", "os, sys from env.LaneChangeEnv import LaneChangeEnv import random import numpy", "level_2_danger_list) print('collison rate: ', coll_rate_list) print('success rate: ', succ_rate_list) print('sucess", "crash_num += ep_eval['ep_num_crash'] level_1_danger.append(1 if ep_eval['ep_num_danger'] > 0 else 0)", "-148.23580687485645, -227.71842861064192, -229.9101089174337] # danger rate: [2.13, 0.88, 0.77, 1.88,", "ep_eval = episode_generator(pi, env, is_gui=is_gui, ttc=ttc, gap=gap, sumoseed=sumoseed, randomseed=randomseed) ret_eval", "- 5) / max(env.ego.speed, 0.001) TTC2 = (follower_dis - 5)", "'\\ncrash_rate: ', crash_rate, '\\nlevel-1-danger_rate: ', level_1_danger_rate, '\\nlevel-2-danger_rate: ', level_2_danger_rate, '\\ncollision_rate:", "# safety gap set to seconds to collision if env.ego.trgt_leader:", "= np.mean(level_1_danger) level_2_danger_rate = np.mean(level_2_danger) coll_rate = collision_num / num_eps", "safety_gap = 2 constraints_list = [3.0] # [1.0, 2.0, 3.0,", "[0.58, 0.33, 0.5, 1.24, 2.09, 2.09] # level-1-danger_rate: [0.23, 0.09,", "1 return ac def evaluate_baseline(num_eps, ttc, gap, is_gui): sumoseed =", "info['num_danger'], 'ep_is_success': info['is_success'], 'ep_num_crash': info['num_crash'], 'ep_is_collision': info[\"is_collision\"]} def pi_baseline(ob, env,", "TTC = (leader_dis - 5) / max(env.ego.speed, 0.001) TTC2 =", "ttcs = [0.1, 0.3, 0.5, 1, 2, 3] # ttcs", "0.08, 0.05] # sucess len: [55.656565656565654, 62.43434343434343, 67.5, 90.1, 66.625,", "reward_list = [] danger_rate_list = [] crash_rate_list = [] level_1_danger_list", "crash_num = 0 level_1_danger = [] level_2_danger = [] collision_num", "gap: ac_lat = 1 # change lane else: ac_lat =", "= 2 constraints_list = [3.0] # [1.0, 2.0, 3.0, 4.0,", "level-2-danger_rate: [0.05, 0.03, 0.05, 0.12, 0.2, 0.2] # collison rate:", "else: sys.exit(\"please declare environment variable 'SUMO_HOME'\") import traci def episode_generator(pi,", "0) level_2_danger.append((1 if ep_eval['ep_num_crash'] > 0 else 0)) collision_num +=", "ret_det_eval) print('reward: ', ret_eval, '\\ndanger_rate: ', danger_rate, '\\ncrash_rate: ', crash_rate,", "# print(TTC, TTC) if TTC > ttc and TTC2 >", "if TTC > ttc and TTC2 > ttc and leader_dis", "= [] success_num = 0 for i in range(num_eps): ep_eval", "= [] collision_num = 0 ep_len_list = [] success_num =", "success rate: [0.99, 0.99, 0.9, 0.6, 0.08, 0.05] # sucess", "succ_len_list.append(success_len) print('reward: ', reward_list) print('danger rate: ', danger_rate_list) print('crash rate:", "follower_speed = env.ego.speed leader_dis = abs(ob[3 * 4 + 0", "'ep_is_collision': info[\"is_collision\"]} def pi_baseline(ob, env, ttc, gap): # safety gap", "', succ_len_list) # reward: [-89.12552753359037, -69.84537459892903, -73.81562785829651, -148.23580687485645, -227.71842861064192, -229.9101089174337]", "if 'SUMO_HOME' in os.environ: tools = os.path.join(os.environ['SUMO_HOME'], 'tools') sys.path.append(tools) print('success')", "episode cur_ep_ret_detail = 0 cur_ep_len = 0 # len of", "= np.mean(ep_len_list) print('reward_detail: ', ret_det_eval) print('reward: ', ret_eval, '\\ndanger_rate: ',", "ret_eval, danger_rate, crash_rate, level_1_danger_rate, level_2_danger_rate, coll_rate, success_rate, success_len NUM_EPS =", "i in range(num_eps): ep_eval = episode_generator(pi, env, is_gui=is_gui, ttc=ttc, gap=gap,", "-73.81562785829651, -148.23580687485645, -227.71842861064192, -229.9101089174337] # danger rate: [2.13, 0.88, 0.77,", "1.24, 2.09, 2.09] # level-1-danger_rate: [0.23, 0.09, 0.05, 0.14, 0.25,", "0.09, 0.05, 0.14, 0.25, 0.25] # level-2-danger_rate: [0.05, 0.03, 0.05,", "else 0) level_2_danger.append((1 if ep_eval['ep_num_crash'] > 0 else 0)) collision_num", "'ep_num_crash': info['num_crash'], 'ep_is_collision': info[\"is_collision\"]} def pi_baseline(ob, env, ttc, gap): #", "int(ep_eval['ep_is_success']) if ep_eval['ep_is_success']: ep_len_list.append(ep_eval['ep_len']) sumoseed += 1 randomseed += 1", "# collison rate: [0.0, 0.0, 0.02, 0.09, 0.14, 0.14] #", "{\"ep_obs\": cur_ep_obs, \"ep_acs\": cur_ep_acs, \"ep_ret\": cur_ep_ret, 'ep_rets_detail': cur_ep_ret_detail, \"ep_len\": cur_ep_len,", "= False # f = open('../data/baseline_evaluation/testseed2.csv', 'w+') # safety_gap =", "= [] level_2_danger = [] collision_num = 0 ep_len_list =", "= 0 reward_list = [] danger_rate_list = [] crash_rate_list =", "cur_ep_len = 0 # len of current episode cur_ep_obs =", "TTC2 = (follower_dis - 5) / max(follower_speed, 0.001) # print(TTC,", "/ max(follower_speed, 0.001) # print(TTC, TTC) if TTC > ttc", "crash_rate, '\\nlevel-1-danger_rate: ', level_1_danger_rate, '\\nlevel-2-danger_rate: ', level_2_danger_rate, '\\ncollision_rate: ', coll_rate,", "else: follower_speed = env.ego.speed leader_dis = abs(ob[3 * 4 +", "print('danger rate: ', danger_rate_list) print('crash rate: ', crash_rate_list) print('level-1-danger_rate: ',", "env.ego.speed if env.ego.trgt_follower: follower_speed = env.ego.trgt_follower.speed else: follower_speed = env.ego.speed", "crash rate: [0.58, 0.33, 0.5, 1.24, 2.09, 2.09] # level-1-danger_rate:", "= 0 # return in current episode cur_ep_ret_detail = 0", "[] danger_rate_list = [] crash_rate_list = [] level_1_danger_list = []", "1])*239.8 follower_dis = abs(ob[4 * 4 + 0 + 1])*239.8", "0.05, 0.12, 0.2, 0.2] # collison rate: [0.0, 0.0, 0.02,", "= np.mean(level_2_danger) coll_rate = collision_num / num_eps success_rate = success_num", "= 0 randomseed = 0 pi = pi_baseline env =", "ttcs = [2] gap = 0 reward_list = [] danger_rate_list", "sumoseed=sumoseed, randomseed=randomseed) traci.vehicle.setColor(egoid, (255, 69, 0)) cur_ep_ret = 0 #", "ep_eval['ep_num_danger'] > 0 else 0) level_2_danger.append((1 if ep_eval['ep_num_crash'] > 0", "3.0, 4.0, 5.0, 10.0, 20.0] ttcs = [0.1, 0.3, 0.5,", "= [3.0] # [1.0, 2.0, 3.0, 4.0, 5.0, 10.0, 20.0]", "0.09, 0.14, 0.14] # success rate: [0.99, 0.99, 0.9, 0.6,", "gap set to seconds to collision if env.ego.trgt_leader: leader_speed =", "= (follower_dis - 5) / max(follower_speed, 0.001) # print(TTC, TTC)", "crash_rate = crash_num / num_eps level_1_danger_rate = np.mean(level_1_danger) level_2_danger_rate =", "0 for i in range(num_eps): ep_eval = episode_generator(pi, env, is_gui=is_gui,", "> ttc and leader_dis > gap and follower_dis > gap:", "environment variable 'SUMO_HOME'\") import traci def episode_generator(pi, env, is_gui, ttc,", "'\\ncollision_rate: ', coll_rate, '\\nsuccess_rate: ', success_rate, '\\nsucess_len: ', success_len) env.close()", "abort ac = ac_lat * 3 + 1 return ac", "for i in range(num_eps): ep_eval = episode_generator(pi, env, is_gui=is_gui, ttc=ttc,", "0.3, 0.5, 1, 2, 3] # ttcs = [2] gap", "cur_ep_ret_detail = 0 cur_ep_len = 0 # len of current", "> 0 else 0)) collision_num += ep_eval['ep_is_collision'] success_num += int(ep_eval['ep_is_success'])", "max(follower_speed, 0.001) # print(TTC, TTC) if TTC > ttc and", "else: ac_lat = 0 # abort ac = ac_lat *", "0.0, 0.02, 0.09, 0.14, 0.14] # success rate: [0.99, 0.99," ]
[ "pickle.dump(test_sequences, f) with open('test_expected_labels', 'wb') as f: pickle.dump(test_expected_labels, f) if", "= parse.parse_file('data/pendigits-test') centroids = training.get_digit_kmeans_centroids( train_digits, 256 - 3) training.set_digit_observations(", "f: pickle.dump(test_sequences, f) with open('test_expected_labels', 'wb') as f: pickle.dump(test_expected_labels, f)", "digit.label with open('train_sequences', 'wb') as f: pickle.dump(train_sequences, f) with open('test_sequences',", "centroids = training.get_digit_kmeans_centroids( train_digits, 256 - 3) training.set_digit_observations( train_digits, centroids,", "= parse.parse_file('data/pendigits-train'); test_digits = parse.parse_file('data/pendigits-test') centroids = training.get_digit_kmeans_centroids( train_digits, 256", "np import pickle from collections import defaultdict from parsing import", "open('test_expected_labels', 'wb') as f: pickle.dump(test_expected_labels, f) if __name__ == '__main__':", "parse.parse_file('data/pendigits-test') centroids = training.get_digit_kmeans_centroids( train_digits, 256 - 3) training.set_digit_observations( train_digits,", "from parsing import parser from analysis import training def main():", "enumerate(test_digits): test_sequences.append(digit.np_array_observations) test_expected_labels[i] = digit.label with open('train_sequences', 'wb') as f:", "- 3) training.set_digit_observations( train_digits, centroids, 256) training.set_digit_observations( test_digits, centroids, 256)", "with open('test_expected_labels', 'wb') as f: pickle.dump(test_expected_labels, f) if __name__ ==", "3) training.set_digit_observations( train_digits, centroids, 256) training.set_digit_observations( test_digits, centroids, 256) train_sequences", "len(test_digits) test_expected_labels = np.ndarray(shape=(n_test_sequences,)) for digit in train_digits: train_sequences[digit.label].append(digit.np_array_observations) for", "import numpy as np import pickle from collections import defaultdict", "from analysis import training def main(): parse = parser.Parser(); train_digits", "import training def main(): parse = parser.Parser(); train_digits = parse.parse_file('data/pendigits-train');", "as np import pickle from collections import defaultdict from parsing", "'wb') as f: pickle.dump(test_expected_labels, f) if __name__ == '__main__': main()", "in enumerate(test_digits): test_sequences.append(digit.np_array_observations) test_expected_labels[i] = digit.label with open('train_sequences', 'wb') as", "digit in train_digits: train_sequences[digit.label].append(digit.np_array_observations) for i, digit in enumerate(test_digits): test_sequences.append(digit.np_array_observations)", "256 - 3) training.set_digit_observations( train_digits, centroids, 256) training.set_digit_observations( test_digits, centroids,", "train_digits = parse.parse_file('data/pendigits-train'); test_digits = parse.parse_file('data/pendigits-test') centroids = training.get_digit_kmeans_centroids( train_digits,", "open('train_sequences', 'wb') as f: pickle.dump(train_sequences, f) with open('test_sequences', 'wb') as", "as f: pickle.dump(test_sequences, f) with open('test_expected_labels', 'wb') as f: pickle.dump(test_expected_labels,", "import parser from analysis import training def main(): parse =", "train_sequences[digit.label].append(digit.np_array_observations) for i, digit in enumerate(test_digits): test_sequences.append(digit.np_array_observations) test_expected_labels[i] = digit.label", "256) training.set_digit_observations( test_digits, centroids, 256) train_sequences = defaultdict(list) test_sequences =", "parse = parser.Parser(); train_digits = parse.parse_file('data/pendigits-train'); test_digits = parse.parse_file('data/pendigits-test') centroids", "centroids, 256) training.set_digit_observations( test_digits, centroids, 256) train_sequences = defaultdict(list) test_sequences", "open('test_sequences', 'wb') as f: pickle.dump(test_sequences, f) with open('test_expected_labels', 'wb') as", "= parser.Parser(); train_digits = parse.parse_file('data/pendigits-train'); test_digits = parse.parse_file('data/pendigits-test') centroids =", "i, digit in enumerate(test_digits): test_sequences.append(digit.np_array_observations) test_expected_labels[i] = digit.label with open('train_sequences',", "parser.Parser(); train_digits = parse.parse_file('data/pendigits-train'); test_digits = parse.parse_file('data/pendigits-test') centroids = training.get_digit_kmeans_centroids(", "collections import defaultdict from parsing import parser from analysis import", "np.ndarray(shape=(n_test_sequences,)) for digit in train_digits: train_sequences[digit.label].append(digit.np_array_observations) for i, digit in", "f) with open('test_sequences', 'wb') as f: pickle.dump(test_sequences, f) with open('test_expected_labels',", "test_digits, centroids, 256) train_sequences = defaultdict(list) test_sequences = [] n_test_sequences", "test_sequences = [] n_test_sequences = len(test_digits) test_expected_labels = np.ndarray(shape=(n_test_sequences,)) for", "train_sequences = defaultdict(list) test_sequences = [] n_test_sequences = len(test_digits) test_expected_labels", "parsing import parser from analysis import training def main(): parse", "training.set_digit_observations( train_digits, centroids, 256) training.set_digit_observations( test_digits, centroids, 256) train_sequences =", "'wb') as f: pickle.dump(train_sequences, f) with open('test_sequences', 'wb') as f:", "import defaultdict from parsing import parser from analysis import training", "test_digits = parse.parse_file('data/pendigits-test') centroids = training.get_digit_kmeans_centroids( train_digits, 256 - 3)", "train_digits: train_sequences[digit.label].append(digit.np_array_observations) for i, digit in enumerate(test_digits): test_sequences.append(digit.np_array_observations) test_expected_labels[i] =", "test_expected_labels[i] = digit.label with open('train_sequences', 'wb') as f: pickle.dump(train_sequences, f)", "from collections import defaultdict from parsing import parser from analysis", "analysis import training def main(): parse = parser.Parser(); train_digits =", "train_digits, 256 - 3) training.set_digit_observations( train_digits, centroids, 256) training.set_digit_observations( test_digits,", "training.set_digit_observations( test_digits, centroids, 256) train_sequences = defaultdict(list) test_sequences = []", "= [] n_test_sequences = len(test_digits) test_expected_labels = np.ndarray(shape=(n_test_sequences,)) for digit", "test_expected_labels = np.ndarray(shape=(n_test_sequences,)) for digit in train_digits: train_sequences[digit.label].append(digit.np_array_observations) for i,", "main(): parse = parser.Parser(); train_digits = parse.parse_file('data/pendigits-train'); test_digits = parse.parse_file('data/pendigits-test')", "train_digits, centroids, 256) training.set_digit_observations( test_digits, centroids, 256) train_sequences = defaultdict(list)", "numpy as np import pickle from collections import defaultdict from", "def main(): parse = parser.Parser(); train_digits = parse.parse_file('data/pendigits-train'); test_digits =", "'wb') as f: pickle.dump(test_sequences, f) with open('test_expected_labels', 'wb') as f:", "centroids, 256) train_sequences = defaultdict(list) test_sequences = [] n_test_sequences =", "defaultdict from parsing import parser from analysis import training def", "training.get_digit_kmeans_centroids( train_digits, 256 - 3) training.set_digit_observations( train_digits, centroids, 256) training.set_digit_observations(", "= len(test_digits) test_expected_labels = np.ndarray(shape=(n_test_sequences,)) for digit in train_digits: train_sequences[digit.label].append(digit.np_array_observations)", "test_sequences.append(digit.np_array_observations) test_expected_labels[i] = digit.label with open('train_sequences', 'wb') as f: pickle.dump(train_sequences,", "f) with open('test_expected_labels', 'wb') as f: pickle.dump(test_expected_labels, f) if __name__", "defaultdict(list) test_sequences = [] n_test_sequences = len(test_digits) test_expected_labels = np.ndarray(shape=(n_test_sequences,))", "for i, digit in enumerate(test_digits): test_sequences.append(digit.np_array_observations) test_expected_labels[i] = digit.label with", "parse.parse_file('data/pendigits-train'); test_digits = parse.parse_file('data/pendigits-test') centroids = training.get_digit_kmeans_centroids( train_digits, 256 -", "as f: pickle.dump(train_sequences, f) with open('test_sequences', 'wb') as f: pickle.dump(test_sequences,", "= defaultdict(list) test_sequences = [] n_test_sequences = len(test_digits) test_expected_labels =", "digit in enumerate(test_digits): test_sequences.append(digit.np_array_observations) test_expected_labels[i] = digit.label with open('train_sequences', 'wb')", "256) train_sequences = defaultdict(list) test_sequences = [] n_test_sequences = len(test_digits)", "training def main(): parse = parser.Parser(); train_digits = parse.parse_file('data/pendigits-train'); test_digits", "= training.get_digit_kmeans_centroids( train_digits, 256 - 3) training.set_digit_observations( train_digits, centroids, 256)", "f: pickle.dump(train_sequences, f) with open('test_sequences', 'wb') as f: pickle.dump(test_sequences, f)", "for digit in train_digits: train_sequences[digit.label].append(digit.np_array_observations) for i, digit in enumerate(test_digits):", "parser from analysis import training def main(): parse = parser.Parser();", "import pickle from collections import defaultdict from parsing import parser", "= digit.label with open('train_sequences', 'wb') as f: pickle.dump(train_sequences, f) with", "with open('test_sequences', 'wb') as f: pickle.dump(test_sequences, f) with open('test_expected_labels', 'wb')", "n_test_sequences = len(test_digits) test_expected_labels = np.ndarray(shape=(n_test_sequences,)) for digit in train_digits:", "in train_digits: train_sequences[digit.label].append(digit.np_array_observations) for i, digit in enumerate(test_digits): test_sequences.append(digit.np_array_observations) test_expected_labels[i]", "= np.ndarray(shape=(n_test_sequences,)) for digit in train_digits: train_sequences[digit.label].append(digit.np_array_observations) for i, digit", "with open('train_sequences', 'wb') as f: pickle.dump(train_sequences, f) with open('test_sequences', 'wb')", "pickle.dump(train_sequences, f) with open('test_sequences', 'wb') as f: pickle.dump(test_sequences, f) with", "pickle from collections import defaultdict from parsing import parser from", "[] n_test_sequences = len(test_digits) test_expected_labels = np.ndarray(shape=(n_test_sequences,)) for digit in" ]
[ "the Open 3D Engine Project. # For complete copyright and", "error_message.splitlines(): if first_line: first_line = False print(f'VALIDATOR_FAILED: {val_name} {line}') else:", "print() print(stats_str) return failed_count == 0 def IsFileSkipped(file_name) -> bool:", "that represents the changes made to that file for this", "commit\"\"\" @abc.abstractmethod def get_files(self) -> List[str]: \"\"\"Returns a list of", "'.m', '.mm', '.cs', '.java' ) \"\"\"File extensions for compiled source", "accessing details about a commit\"\"\" @abc.abstractmethod def get_files(self) -> List[str]:", "for both compiled and interpreted code\"\"\" BUILD_FILE_PATTERNS: Tuple[re.Pattern, ...] =", "module_name, is_package in pkgutil.iter_modules([validators_dir]): if not is_package: module = importlib.import_module('commit_validation.validators.'", "= ( '.py', '.lua', '.bat', '.cmd', '.sh', '.js' ) \"\"\"File", "of the commit\"\"\" pass @abc.abstractmethod def get_author(self) -> str: \"\"\"Returns", "author of the commit\"\"\" pass def validate_commit(commit: Commit, out_errors: List[str]", "out_errors: List[str] = None, ignore_validators: List[str] = None) -> bool:", "class Commit(abc.ABC): \"\"\"An interface for accessing details about a commit\"\"\"", "-> List[str]: \"\"\"Returns a list of local files added/modified by", "pay attention to added lines (with + in front) \"\"\"", "str: \"\"\" Given a file name, returns a string in", "files removed by the commit\"\"\" pass @abc.abstractmethod def get_file_diff(self, str)", "failed_count = 0 passed_count = 0 start_time = time.time() #", "BUILD_FILE_EXTENSIONS \"\"\"File extensions for both compiled and interpreted code\"\"\" BUILD_FILE_PATTERNS:", "of errors generated, append them to this list :return: True", "time from typing import Dict, List, Tuple VERBOSE = False", "= error_list end_time = time.time() if failed_count: print(\"VALIDATION FAILURE SUMMARY\")", "def get_file_diff(self, str) -> str: \"\"\" Given a file name,", "attention to added lines (with + in front) \"\"\" pass", "The commit to validate :param errors: List of errors generated,", "stats_strs.append(f'{failed_count} failed') if passed_count > 0: stats_strs.append(f'{passed_count} passed') stats_str =", "( '.py', '.lua', '.bat', '.cmd', '.sh', '.js' ) \"\"\"File extensions", "\"\"\"File extensions for both compiled and interpreted code\"\"\" BUILD_FILE_PATTERNS: Tuple[re.Pattern,", "( re.compile(r'.*CMakeLists\\.txt'), re.compile(r'.*Jenkinsfile') ) \"\"\"File patterns for build files\"\"\" SOURCE_AND_SCRIPT_FILE_PATTERNS:", "ignore, by class name :return: True if there are no", "\"\"\" pass @abc.abstractmethod def get_description(self) -> str: \"\"\"Returns the description", "by the commit\"\"\" pass @abc.abstractmethod def get_file_diff(self, str) -> str:", "BUILD_FILE_PATTERNS: Tuple[re.Pattern, ...] = ( re.compile(r'.*CMakeLists\\.txt'), re.compile(r'.*Jenkinsfile') ) \"\"\"File patterns", "is_package: module = importlib.import_module('commit_validation.validators.' + module_name) validator = module.get_validator() if", "= 0 start_time = time.time() # Find all the validators", "and False otherwise \"\"\" failed_count = 0 passed_count = 0", "pass def validate_commit(commit: Commit, out_errors: List[str] = None, ignore_validators: List[str]", "# For complete copyright and license terms please see the", "the changes made to that file for this commit. Most", "class CommitValidator(abc.ABC): \"\"\"A commit validator\"\"\" @abc.abstractmethod def run(self, commit: Commit,", "for accessing details about a commit\"\"\" @abc.abstractmethod def get_files(self) ->", "commit\"\"\" pass def validate_commit(commit: Commit, out_errors: List[str] = None, ignore_validators:", "[ '*/.git/*', '*/3rdParty/*', '*/__pycache__/*', '*/External/*', 'build', 'Cache', '*/Code/Framework/AzCore/azgnmx/azgnmx/*', 'Code/Tools/CryFXC', 'Code/Tools/HLSLCrossCompiler',", "print(f'VALIDATOR_FAILED: {val_name} {line}') else: print(f' {line}') # extra detail lines", "a commit :param commit: The commit to validate :param errors:", "re import time from typing import Dict, List, Tuple VERBOSE", "files added/modified by the commit\"\"\" pass @abc.abstractmethod def get_removed_files(self) ->", "at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0", "validate :param errors: List of errors generated, append them to", "added lines (with + in front) \"\"\" pass @abc.abstractmethod def", "validation for '{validator.__name__}'\") else: validator_classes.append(validator) error_summary = {} # Process", "(with + in front) \"\"\" pass @abc.abstractmethod def get_description(self) ->", "lines do not need machine parsing stats_strs = [] if", "pattern in SOURCE_AND_SCRIPT_FILE_PATTERNS: if pattern.match(file_name): skipped = False break return", "...] = ( '.c', '.cc', '.cpp', '.cxx', '.h', '.hpp', '.hxx',", "SOURCE_FILE_EXTENSIONS + SCRIPT_FILE_EXTENSIONS + BUILD_FILE_EXTENSIONS \"\"\"File extensions for both compiled", "a file name, returns a string in unified diff format", "\"\"\"Returns the author of the commit\"\"\" pass def validate_commit(commit: Commit,", "-> bool: \"\"\"Validates a commit against all validators :param commit:", "if failed_count: print(\"VALIDATION FAILURE SUMMARY\") for val_name in error_summary.keys(): errors", "'.join(stats_strs) + f' in {end_time - start_time:.2f}s' print() print(stats_str) return", "for pattern in SOURCE_AND_SCRIPT_FILE_PATTERNS: if pattern.match(file_name): skipped = False break", "license terms please see the LICENSE at the root of", "validator\"\"\" @abc.abstractmethod def run(self, commit: Commit, errors: List[str]) -> bool:", "SUMMARY\") for val_name in error_summary.keys(): errors = error_summary[val_name] if errors:", "first_line: first_line = False print(f'VALIDATOR_FAILED: {val_name} {line}') else: print(f' {line}')", "pattern.match(file_name): skipped = False break return skipped return False class", "this commit. Most validators will only pay attention to added", "(recursively) validator_classes = [] validators_dir = os.path.join(os.path.dirname(__file__), 'validators') for _,", "return False class CommitValidator(abc.ABC): \"\"\"A commit validator\"\"\" @abc.abstractmethod def run(self,", "pass @abc.abstractmethod def get_removed_files(self) -> List[str]: \"\"\"Returns a list of", "'.c', '.cc', '.cpp', '.cxx', '.h', '.hpp', '.hxx', '.inl', '.m', '.mm',", "local files added/modified by the commit\"\"\" pass @abc.abstractmethod def get_removed_files(self)", "SOURCE_AND_SCRIPT_FILE_PATTERNS: Tuple[re.Pattern, ...] = BUILD_FILE_PATTERNS EXCLUDED_VALIDATION_PATTERNS = [ '*/.git/*', '*/3rdParty/*',", "def get_removed_files(self) -> List[str]: \"\"\"Returns a list of local files", "commit\"\"\" pass @abc.abstractmethod def get_file_diff(self, str) -> str: \"\"\" Given", "Most validators will only pay attention to added lines (with", "for build files\"\"\" SOURCE_AND_SCRIPT_FILE_EXTENSIONS: Tuple[str, ...] = SOURCE_FILE_EXTENSIONS + SCRIPT_FILE_EXTENSIONS", "validator_class() validator_name = validator.__class__.__name__ error_list = [] passed = validator.run(commit,", "Tuple VERBOSE = False class Commit(abc.ABC): \"\"\"An interface for accessing", "commit validator\"\"\" @abc.abstractmethod def run(self, commit: Commit, errors: List[str]) ->", "code\"\"\" BUILD_FILE_PATTERNS: Tuple[re.Pattern, ...] = ( re.compile(r'.*CMakeLists\\.txt'), re.compile(r'.*Jenkinsfile') ) \"\"\"File", "The commit to validate :param out_errors: if not None, will", "for compiled source code\"\"\" SCRIPT_FILE_EXTENSIONS: Tuple[str, ...] = ( '.py',", "break return skipped return False class CommitValidator(abc.ABC): \"\"\"A commit validator\"\"\"", "the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR", "-> str: \"\"\" Given a file name, returns a string", "validators package (recursively) validator_classes = [] validators_dir = os.path.join(os.path.dirname(__file__), 'validators')", "failed_count == 0 def IsFileSkipped(file_name) -> bool: if os.path.splitext(file_name)[1].lower() not", "[] passed = validator.run(commit, errors = error_list) if passed: passed_count", "the commit is valid, and False otherwise \"\"\" pass SOURCE_FILE_EXTENSIONS:", "abc import importlib import os import pkgutil import re import", "validator.__name__ in ignore_validators: print(f\"Disabled validation for '{validator.__name__}'\") else: validator_classes.append(validator) error_summary", "with the list of errors given by the validators :param", "else: print(f' {line}') # extra detail lines do not need", "in pkgutil.iter_modules([validators_dir]): if not is_package: module = importlib.import_module('commit_validation.validators.' + module_name)", "FAILURE SUMMARY\") for val_name in error_summary.keys(): errors = error_summary[val_name] if", "to validate :param errors: List of errors generated, append them", "and license terms please see the LICENSE at the root", "commit is valid, and False otherwise \"\"\" pass SOURCE_FILE_EXTENSIONS: Tuple[str,", "True for line in error_message.splitlines(): if first_line: first_line = False", "stats_strs.append(f'{passed_count} passed') stats_str = ', '.join(stats_strs) + f' in {end_time", "lines (with + in front) \"\"\" pass @abc.abstractmethod def get_description(self)", "pass @abc.abstractmethod def get_author(self) -> str: \"\"\"Returns the author of", "\"\"\"File extensions for compiled source code\"\"\" SCRIPT_FILE_EXTENSIONS: Tuple[str, ...] =", "def IsFileSkipped(file_name) -> bool: if os.path.splitext(file_name)[1].lower() not in SOURCE_AND_SCRIPT_FILE_EXTENSIONS: skipped", "( '.cmake', ) \"\"\"File extensions for build files\"\"\" SOURCE_AND_SCRIPT_FILE_EXTENSIONS: Tuple[str,", "re.compile(r'.*Jenkinsfile') ) \"\"\"File patterns for build files\"\"\" SOURCE_AND_SCRIPT_FILE_PATTERNS: Tuple[re.Pattern, ...]", "only pay attention to added lines (with + in front)", "detail lines do not need machine parsing stats_strs = []", "SOURCE_AND_SCRIPT_FILE_PATTERNS: if pattern.match(file_name): skipped = False break return skipped return", "see the LICENSE at the root of this distribution. #", "in {end_time - start_time:.2f}s' print() print(stats_str) return failed_count == 0", "local files removed by the commit\"\"\" pass @abc.abstractmethod def get_file_diff(self,", "build files\"\"\" SOURCE_AND_SCRIPT_FILE_EXTENSIONS: Tuple[str, ...] = SOURCE_FILE_EXTENSIONS + SCRIPT_FILE_EXTENSIONS +", "in front) \"\"\" pass @abc.abstractmethod def get_description(self) -> str: \"\"\"Returns", "SOURCE_AND_SCRIPT_FILE_EXTENSIONS: Tuple[str, ...] = SOURCE_FILE_EXTENSIONS + SCRIPT_FILE_EXTENSIONS + BUILD_FILE_EXTENSIONS \"\"\"File", "0: stats_strs.append(f'{passed_count} passed') stats_str = ', '.join(stats_strs) + f' in", "'build', 'Cache', '*/Code/Framework/AzCore/azgnmx/azgnmx/*', 'Code/Tools/CryFXC', 'Code/Tools/HLSLCrossCompiler', 'Code/Tools/HLSLCrossCompilerMETAL', 'Docs', 'python/runtime', 'restricted/*/Tools/*RemoteControl', 'Tools/3dsmax',", "'.hpp', '.hxx', '.inl', '.m', '.mm', '.cs', '.java' ) \"\"\"File extensions", "pkgutil import re import time from typing import Dict, List,", "the commit\"\"\" pass @abc.abstractmethod def get_author(self) -> str: \"\"\"Returns the", "build files\"\"\" SOURCE_AND_SCRIPT_FILE_PATTERNS: Tuple[re.Pattern, ...] = BUILD_FILE_PATTERNS EXCLUDED_VALIDATION_PATTERNS = [", "if passed: passed_count += 1 print(f'{validator.__class__.__name__} PASSED') else: failed_count +=", "= None, ignore_validators: List[str] = None) -> bool: \"\"\"Validates a", "validator = module.get_validator() if ignore_validators and validator.__name__ in ignore_validators: print(f\"Disabled", "'Cache', '*/Code/Framework/AzCore/azgnmx/azgnmx/*', 'Code/Tools/CryFXC', 'Code/Tools/HLSLCrossCompiler', 'Code/Tools/HLSLCrossCompilerMETAL', 'Docs', 'python/runtime', 'restricted/*/Tools/*RemoteControl', 'Tools/3dsmax', '*/user/Cache/*',", "unified diff format that represents the changes made to that", "terms please see the LICENSE at the root of this", "1 print(f'{validator.__class__.__name__} FAILED') error_summary[validator_name] = error_list end_time = time.time() if", "os.path.join(os.path.dirname(__file__), 'validators') for _, module_name, is_package in pkgutil.iter_modules([validators_dir]): if not", "validators :param ignore_validators: Optional list of CommitValidator classes to ignore,", ":param commit: The commit to validate :param errors: List of", "for val_name in error_summary.keys(): errors = error_summary[val_name] if errors: for", "commit against all validators :param commit: The commit to validate", "in errors: first_line = True for line in error_message.splitlines(): if", "False class Commit(abc.ABC): \"\"\"An interface for accessing details about a", "if os.path.splitext(file_name)[1].lower() not in SOURCE_AND_SCRIPT_FILE_EXTENSIONS: skipped = True for pattern", "this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # #", "OR MIT # # import abc import importlib import os", "to this list :return: True if the commit is valid,", "'Code/Tools/CryFXC', 'Code/Tools/HLSLCrossCompiler', 'Code/Tools/HLSLCrossCompilerMETAL', 'Docs', 'python/runtime', 'restricted/*/Tools/*RemoteControl', 'Tools/3dsmax', '*/user/Cache/*', '*/user/log/*', ]", "-> str: \"\"\"Returns the description of the commit\"\"\" pass @abc.abstractmethod", "print(\"VALIDATION FAILURE SUMMARY\") for val_name in error_summary.keys(): errors = error_summary[val_name]", "pass @abc.abstractmethod def get_file_diff(self, str) -> str: \"\"\" Given a", "if not None, will populate with the list of errors", "get_author(self) -> str: \"\"\"Returns the author of the commit\"\"\" pass", "@abc.abstractmethod def get_removed_files(self) -> List[str]: \"\"\"Returns a list of local", "name, returns a string in unified diff format that represents", "import os import pkgutil import re import time from typing", "\"\"\"Returns the description of the commit\"\"\" pass @abc.abstractmethod def get_author(self)", "'validators') for _, module_name, is_package in pkgutil.iter_modules([validators_dir]): if not is_package:", "= os.path.join(os.path.dirname(__file__), 'validators') for _, module_name, is_package in pkgutil.iter_modules([validators_dir]): if", "interface for accessing details about a commit\"\"\" @abc.abstractmethod def get_files(self)", "'.js' ) \"\"\"File extensions for interpreted code\"\"\" BUILD_FILE_EXTENSIONS: Tuple[str, ...]", "@abc.abstractmethod def get_author(self) -> str: \"\"\"Returns the author of the", "extensions for both compiled and interpreted code\"\"\" BUILD_FILE_PATTERNS: Tuple[re.Pattern, ...]", "Open 3D Engine Project. # For complete copyright and license", "= {} # Process validators for validator_class in validator_classes: validator", "failed') if passed_count > 0: stats_strs.append(f'{passed_count} passed') stats_str = ',", "0 def IsFileSkipped(file_name) -> bool: if os.path.splitext(file_name)[1].lower() not in SOURCE_AND_SCRIPT_FILE_EXTENSIONS:", "False break return skipped return False class CommitValidator(abc.ABC): \"\"\"A commit", "by the validators :param ignore_validators: Optional list of CommitValidator classes", "return failed_count == 0 def IsFileSkipped(file_name) -> bool: if os.path.splitext(file_name)[1].lower()", "...] = SOURCE_FILE_EXTENSIONS + SCRIPT_FILE_EXTENSIONS + BUILD_FILE_EXTENSIONS \"\"\"File extensions for", "changes made to that file for this commit. Most validators", "time.time() # Find all the validators in the validators package", "print(f'{validator.__class__.__name__} PASSED') else: failed_count += 1 print(f'{validator.__class__.__name__} FAILED') error_summary[validator_name] =", "if first_line: first_line = False print(f'VALIDATOR_FAILED: {val_name} {line}') else: print(f'", "details about a commit\"\"\" @abc.abstractmethod def get_files(self) -> List[str]: \"\"\"Returns", "a string in unified diff format that represents the changes", "= ( '.c', '.cc', '.cpp', '.cxx', '.h', '.hpp', '.hxx', '.inl',", "passed = validator.run(commit, errors = error_list) if passed: passed_count +=", "= error_summary[val_name] if errors: for error_message in errors: first_line =", "removed by the commit\"\"\" pass @abc.abstractmethod def get_file_diff(self, str) ->", "not is_package: module = importlib.import_module('commit_validation.validators.' + module_name) validator = module.get_validator()", "failed_count += 1 print(f'{validator.__class__.__name__} FAILED') error_summary[validator_name] = error_list end_time =", "error_list) if passed: passed_count += 1 print(f'{validator.__class__.__name__} PASSED') else: failed_count", "import importlib import os import pkgutil import re import time", "line in error_message.splitlines(): if first_line: first_line = False print(f'VALIDATOR_FAILED: {val_name}", "-> bool: if os.path.splitext(file_name)[1].lower() not in SOURCE_AND_SCRIPT_FILE_EXTENSIONS: skipped = True", "in error_message.splitlines(): if first_line: first_line = False print(f'VALIDATOR_FAILED: {val_name} {line}')", "...] = BUILD_FILE_PATTERNS EXCLUDED_VALIDATION_PATTERNS = [ '*/.git/*', '*/3rdParty/*', '*/__pycache__/*', '*/External/*',", "# import abc import importlib import os import pkgutil import", "if the commit is valid, and False otherwise \"\"\" pass", "Commit, out_errors: List[str] = None, ignore_validators: List[str] = None) ->", "errors = error_summary[val_name] if errors: for error_message in errors: first_line", "a commit against all validators :param commit: The commit to", ") \"\"\"File extensions for compiled source code\"\"\" SCRIPT_FILE_EXTENSIONS: Tuple[str, ...]", "passed') stats_str = ', '.join(stats_strs) + f' in {end_time -", "of CommitValidator classes to ignore, by class name :return: True", "if passed_count > 0: stats_strs.append(f'{passed_count} passed') stats_str = ', '.join(stats_strs)", "SOURCE_AND_SCRIPT_FILE_EXTENSIONS: skipped = True for pattern in SOURCE_AND_SCRIPT_FILE_PATTERNS: if pattern.match(file_name):", "BUILD_FILE_EXTENSIONS: Tuple[str, ...] = ( '.cmake', ) \"\"\"File extensions for", "LICENSE at the root of this distribution. # # SPDX-License-Identifier:", "commit to validate :param out_errors: if not None, will populate", "Dict, List, Tuple VERBOSE = False class Commit(abc.ABC): \"\"\"An interface", "FAILED') error_summary[validator_name] = error_list end_time = time.time() if failed_count: print(\"VALIDATION", "need machine parsing stats_strs = [] if failed_count > 0:", "commit\"\"\" pass @abc.abstractmethod def get_author(self) -> str: \"\"\"Returns the author", "= error_list) if passed: passed_count += 1 print(f'{validator.__class__.__name__} PASSED') else:", "get_removed_files(self) -> List[str]: \"\"\"Returns a list of local files removed", "+ BUILD_FILE_EXTENSIONS \"\"\"File extensions for both compiled and interpreted code\"\"\"", "Contributors to the Open 3D Engine Project. # For complete", "\"\"\"A commit validator\"\"\" @abc.abstractmethod def run(self, commit: Commit, errors: List[str])", "{line}') # extra detail lines do not need machine parsing", "validate :param out_errors: if not None, will populate with the", "in error_summary.keys(): errors = error_summary[val_name] if errors: for error_message in", "+ in front) \"\"\" pass @abc.abstractmethod def get_description(self) -> str:", "generated, append them to this list :return: True if the", "returns a string in unified diff format that represents the", "= None) -> bool: \"\"\"Validates a commit against all validators", "@abc.abstractmethod def get_description(self) -> str: \"\"\"Returns the description of the", "List[str]) -> bool: \"\"\"Validates a commit :param commit: The commit", "made to that file for this commit. Most validators will", "ignore_validators: print(f\"Disabled validation for '{validator.__name__}'\") else: validator_classes.append(validator) error_summary = {}", "validate_commit(commit: Commit, out_errors: List[str] = None, ignore_validators: List[str] = None)", "'{validator.__name__}'\") else: validator_classes.append(validator) error_summary = {} # Process validators for", "file for this commit. Most validators will only pay attention", ") \"\"\"File extensions for build files\"\"\" SOURCE_AND_SCRIPT_FILE_EXTENSIONS: Tuple[str, ...] =", "do not need machine parsing stats_strs = [] if failed_count", "True if the commit is valid, and False otherwise \"\"\"", "Find all the validators in the validators package (recursively) validator_classes", "List of errors generated, append them to this list :return:", "the commit\"\"\" pass def validate_commit(commit: Commit, out_errors: List[str] = None,", "Engine Project. # For complete copyright and license terms please", "module_name) validator = module.get_validator() if ignore_validators and validator.__name__ in ignore_validators:", "extra detail lines do not need machine parsing stats_strs =", "List[str]: \"\"\"Returns a list of local files removed by the", "error_summary.keys(): errors = error_summary[val_name] if errors: for error_message in errors:", "passed: passed_count += 1 print(f'{validator.__class__.__name__} PASSED') else: failed_count += 1", "= validator.__class__.__name__ error_list = [] passed = validator.run(commit, errors =", "\"\"\"File extensions for build files\"\"\" SOURCE_AND_SCRIPT_FILE_EXTENSIONS: Tuple[str, ...] = SOURCE_FILE_EXTENSIONS", "@abc.abstractmethod def get_file_diff(self, str) -> str: \"\"\" Given a file", "commit: The commit to validate :param errors: List of errors", "+ SCRIPT_FILE_EXTENSIONS + BUILD_FILE_EXTENSIONS \"\"\"File extensions for both compiled and", "are no validation errors, and False otherwise \"\"\" failed_count =", "diff format that represents the changes made to that file", "# # Copyright (c) Contributors to the Open 3D Engine", ":return: True if the commit is valid, and False otherwise", "error_list end_time = time.time() if failed_count: print(\"VALIDATION FAILURE SUMMARY\") for", "first_line = False print(f'VALIDATOR_FAILED: {val_name} {line}') else: print(f' {line}') #", "by class name :return: True if there are no validation", "= True for line in error_message.splitlines(): if first_line: first_line =", "errors generated, append them to this list :return: True if", "files\"\"\" SOURCE_AND_SCRIPT_FILE_EXTENSIONS: Tuple[str, ...] = SOURCE_FILE_EXTENSIONS + SCRIPT_FILE_EXTENSIONS + BUILD_FILE_EXTENSIONS", "otherwise \"\"\" failed_count = 0 passed_count = 0 start_time =", "str: \"\"\"Returns the description of the commit\"\"\" pass @abc.abstractmethod def", "will only pay attention to added lines (with + in", "\"\"\" pass SOURCE_FILE_EXTENSIONS: Tuple[str, ...] = ( '.c', '.cc', '.cpp',", "\"\"\"File patterns for build files\"\"\" SOURCE_AND_SCRIPT_FILE_PATTERNS: Tuple[re.Pattern, ...] = BUILD_FILE_PATTERNS", "1 print(f'{validator.__class__.__name__} PASSED') else: failed_count += 1 print(f'{validator.__class__.__name__} FAILED') error_summary[validator_name]", "return skipped return False class CommitValidator(abc.ABC): \"\"\"A commit validator\"\"\" @abc.abstractmethod", "= time.time() # Find all the validators in the validators", "ignore_validators and validator.__name__ in ignore_validators: print(f\"Disabled validation for '{validator.__name__}'\") else:", "'.cs', '.java' ) \"\"\"File extensions for compiled source code\"\"\" SCRIPT_FILE_EXTENSIONS:", ") \"\"\"File patterns for build files\"\"\" SOURCE_AND_SCRIPT_FILE_PATTERNS: Tuple[re.Pattern, ...] =", "commit: Commit, errors: List[str]) -> bool: \"\"\"Validates a commit :param", "import Dict, List, Tuple VERBOSE = False class Commit(abc.ABC): \"\"\"An", "append them to this list :return: True if the commit", "errors = error_list) if passed: passed_count += 1 print(f'{validator.__class__.__name__} PASSED')", "CommitValidator classes to ignore, by class name :return: True if", "extensions for build files\"\"\" SOURCE_AND_SCRIPT_FILE_EXTENSIONS: Tuple[str, ...] = SOURCE_FILE_EXTENSIONS +", "format that represents the changes made to that file for", "failed_count: print(\"VALIDATION FAILURE SUMMARY\") for val_name in error_summary.keys(): errors =", "for interpreted code\"\"\" BUILD_FILE_EXTENSIONS: Tuple[str, ...] = ( '.cmake', )", "error_message in errors: first_line = True for line in error_message.splitlines():", "'.lua', '.bat', '.cmd', '.sh', '.js' ) \"\"\"File extensions for interpreted", "{} # Process validators for validator_class in validator_classes: validator =", "+= 1 print(f'{validator.__class__.__name__} FAILED') error_summary[validator_name] = error_list end_time = time.time()", "def run(self, commit: Commit, errors: List[str]) -> bool: \"\"\"Validates a", "the commit\"\"\" pass @abc.abstractmethod def get_removed_files(self) -> List[str]: \"\"\"Returns a", "classes to ignore, by class name :return: True if there", "# # SPDX-License-Identifier: Apache-2.0 OR MIT # # import abc", "'.h', '.hpp', '.hxx', '.inl', '.m', '.mm', '.cs', '.java' ) \"\"\"File", "validator_name = validator.__class__.__name__ error_list = [] passed = validator.run(commit, errors", "in unified diff format that represents the changes made to", "'.cmake', ) \"\"\"File extensions for build files\"\"\" SOURCE_AND_SCRIPT_FILE_EXTENSIONS: Tuple[str, ...]", "validator.__class__.__name__ error_list = [] passed = validator.run(commit, errors = error_list)", "[] validators_dir = os.path.join(os.path.dirname(__file__), 'validators') for _, module_name, is_package in", "> 0: stats_strs.append(f'{passed_count} passed') stats_str = ', '.join(stats_strs) + f'", "validators will only pay attention to added lines (with +", "# SPDX-License-Identifier: Apache-2.0 OR MIT # # import abc import", "interpreted code\"\"\" BUILD_FILE_PATTERNS: Tuple[re.Pattern, ...] = ( re.compile(r'.*CMakeLists\\.txt'), re.compile(r'.*Jenkinsfile') )", "@abc.abstractmethod def get_files(self) -> List[str]: \"\"\"Returns a list of local", "= False print(f'VALIDATOR_FAILED: {val_name} {line}') else: print(f' {line}') # extra", "will populate with the list of errors given by the", "in the validators package (recursively) validator_classes = [] validators_dir =", "of local files removed by the commit\"\"\" pass @abc.abstractmethod def", "that file for this commit. Most validators will only pay", "= validator_class() validator_name = validator.__class__.__name__ error_list = [] passed =", "pass SOURCE_FILE_EXTENSIONS: Tuple[str, ...] = ( '.c', '.cc', '.cpp', '.cxx',", "not None, will populate with the list of errors given", "of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT #", "Tuple[str, ...] = ( '.cmake', ) \"\"\"File extensions for build", "= importlib.import_module('commit_validation.validators.' + module_name) validator = module.get_validator() if ignore_validators and", ":param out_errors: if not None, will populate with the list", "errors: for error_message in errors: first_line = True for line", "- start_time:.2f}s' print() print(stats_str) return failed_count == 0 def IsFileSkipped(file_name)", "given by the validators :param ignore_validators: Optional list of CommitValidator", "\"\"\"An interface for accessing details about a commit\"\"\" @abc.abstractmethod def", "'.cmd', '.sh', '.js' ) \"\"\"File extensions for interpreted code\"\"\" BUILD_FILE_EXTENSIONS:", "errors: List of errors generated, append them to this list", "-> str: \"\"\"Returns the author of the commit\"\"\" pass def", "the validators in the validators package (recursively) validator_classes = []", "of local files added/modified by the commit\"\"\" pass @abc.abstractmethod def", "Copyright (c) Contributors to the Open 3D Engine Project. #", "commit. Most validators will only pay attention to added lines", "about a commit\"\"\" @abc.abstractmethod def get_files(self) -> List[str]: \"\"\"Returns a", "if errors: for error_message in errors: first_line = True for", ":param ignore_validators: Optional list of CommitValidator classes to ignore, by", "'.cpp', '.cxx', '.h', '.hpp', '.hxx', '.inl', '.m', '.mm', '.cs', '.java'", "distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # # import", "...] = ( '.cmake', ) \"\"\"File extensions for build files\"\"\"", "front) \"\"\" pass @abc.abstractmethod def get_description(self) -> str: \"\"\"Returns the", "\"\"\" Given a file name, returns a string in unified", "None, will populate with the list of errors given by", ":return: True if there are no validation errors, and False", "# extra detail lines do not need machine parsing stats_strs", "re.compile(r'.*CMakeLists\\.txt'), re.compile(r'.*Jenkinsfile') ) \"\"\"File patterns for build files\"\"\" SOURCE_AND_SCRIPT_FILE_PATTERNS: Tuple[re.Pattern,", "\"\"\"Validates a commit :param commit: The commit to validate :param", "list :return: True if the commit is valid, and False", "\"\"\"Returns a list of local files added/modified by the commit\"\"\"", "list of local files added/modified by the commit\"\"\" pass @abc.abstractmethod", "validator_classes = [] validators_dir = os.path.join(os.path.dirname(__file__), 'validators') for _, module_name,", "List, Tuple VERBOSE = False class Commit(abc.ABC): \"\"\"An interface for", "skipped = True for pattern in SOURCE_AND_SCRIPT_FILE_PATTERNS: if pattern.match(file_name): skipped", "if ignore_validators and validator.__name__ in ignore_validators: print(f\"Disabled validation for '{validator.__name__}'\")", "first_line = True for line in error_message.splitlines(): if first_line: first_line", "PASSED') else: failed_count += 1 print(f'{validator.__class__.__name__} FAILED') error_summary[validator_name] = error_list", "to the Open 3D Engine Project. # For complete copyright", "populate with the list of errors given by the validators", "Optional list of CommitValidator classes to ignore, by class name", "print(f' {line}') # extra detail lines do not need machine", "# Process validators for validator_class in validator_classes: validator = validator_class()", "importlib import os import pkgutil import re import time from", "valid, and False otherwise \"\"\" pass SOURCE_FILE_EXTENSIONS: Tuple[str, ...] =", "commit :param commit: The commit to validate :param errors: List", "pass @abc.abstractmethod def get_description(self) -> str: \"\"\"Returns the description of", "Tuple[re.Pattern, ...] = ( re.compile(r'.*CMakeLists\\.txt'), re.compile(r'.*Jenkinsfile') ) \"\"\"File patterns for", "{val_name} {line}') else: print(f' {line}') # extra detail lines do", "represents the changes made to that file for this commit.", "the list of errors given by the validators :param ignore_validators:", "copyright and license terms please see the LICENSE at the", "0 passed_count = 0 start_time = time.time() # Find all", "start_time:.2f}s' print() print(stats_str) return failed_count == 0 def IsFileSkipped(file_name) ->", "commit: The commit to validate :param out_errors: if not None,", "and interpreted code\"\"\" BUILD_FILE_PATTERNS: Tuple[re.Pattern, ...] = ( re.compile(r'.*CMakeLists\\.txt'), re.compile(r'.*Jenkinsfile')", "get_description(self) -> str: \"\"\"Returns the description of the commit\"\"\" pass", "the author of the commit\"\"\" pass def validate_commit(commit: Commit, out_errors:", "stats_strs = [] if failed_count > 0: stats_strs.append(f'{failed_count} failed') if", "'*/__pycache__/*', '*/External/*', 'build', 'Cache', '*/Code/Framework/AzCore/azgnmx/azgnmx/*', 'Code/Tools/CryFXC', 'Code/Tools/HLSLCrossCompiler', 'Code/Tools/HLSLCrossCompilerMETAL', 'Docs', 'python/runtime',", "failed_count > 0: stats_strs.append(f'{failed_count} failed') if passed_count > 0: stats_strs.append(f'{passed_count}", "False class CommitValidator(abc.ABC): \"\"\"A commit validator\"\"\" @abc.abstractmethod def run(self, commit:", "error_summary[validator_name] = error_list end_time = time.time() if failed_count: print(\"VALIDATION FAILURE", "SCRIPT_FILE_EXTENSIONS + BUILD_FILE_EXTENSIONS \"\"\"File extensions for both compiled and interpreted", "name :return: True if there are no validation errors, and", "no validation errors, and False otherwise \"\"\" failed_count = 0", "'.hxx', '.inl', '.m', '.mm', '.cs', '.java' ) \"\"\"File extensions for", "a list of local files added/modified by the commit\"\"\" pass", "interpreted code\"\"\" BUILD_FILE_EXTENSIONS: Tuple[str, ...] = ( '.cmake', ) \"\"\"File", "code\"\"\" BUILD_FILE_EXTENSIONS: Tuple[str, ...] = ( '.cmake', ) \"\"\"File extensions", "print(stats_str) return failed_count == 0 def IsFileSkipped(file_name) -> bool: if", "for line in error_message.splitlines(): if first_line: first_line = False print(f'VALIDATOR_FAILED:", "a commit\"\"\" @abc.abstractmethod def get_files(self) -> List[str]: \"\"\"Returns a list", "def get_description(self) -> str: \"\"\"Returns the description of the commit\"\"\"", "if there are no validation errors, and False otherwise \"\"\"", "import abc import importlib import os import pkgutil import re", "os import pkgutil import re import time from typing import", "for validator_class in validator_classes: validator = validator_class() validator_name = validator.__class__.__name__", "of errors given by the validators :param ignore_validators: Optional list", "'.mm', '.cs', '.java' ) \"\"\"File extensions for compiled source code\"\"\"", "= time.time() if failed_count: print(\"VALIDATION FAILURE SUMMARY\") for val_name in", "skipped = False break return skipped return False class CommitValidator(abc.ABC):", "against all validators :param commit: The commit to validate :param", "validator = validator_class() validator_name = validator.__class__.__name__ error_list = [] passed", "commit\"\"\" pass @abc.abstractmethod def get_removed_files(self) -> List[str]: \"\"\"Returns a list", "and validator.__name__ in ignore_validators: print(f\"Disabled validation for '{validator.__name__}'\") else: validator_classes.append(validator)", "please see the LICENSE at the root of this distribution.", "not need machine parsing stats_strs = [] if failed_count >", "get_files(self) -> List[str]: \"\"\"Returns a list of local files added/modified", "code\"\"\" SCRIPT_FILE_EXTENSIONS: Tuple[str, ...] = ( '.py', '.lua', '.bat', '.cmd',", "in validator_classes: validator = validator_class() validator_name = validator.__class__.__name__ error_list =", "error_summary = {} # Process validators for validator_class in validator_classes:", "root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT", "stats_str = ', '.join(stats_strs) + f' in {end_time - start_time:.2f}s'", "class name :return: True if there are no validation errors,", "-> List[str]: \"\"\"Returns a list of local files removed by", ") \"\"\"File extensions for interpreted code\"\"\" BUILD_FILE_EXTENSIONS: Tuple[str, ...] =", "Tuple[re.Pattern, ...] = BUILD_FILE_PATTERNS EXCLUDED_VALIDATION_PATTERNS = [ '*/.git/*', '*/3rdParty/*', '*/__pycache__/*',", "error_summary[val_name] if errors: for error_message in errors: first_line = True", "importlib.import_module('commit_validation.validators.' + module_name) validator = module.get_validator() if ignore_validators and validator.__name__", "file name, returns a string in unified diff format that", "'.sh', '.js' ) \"\"\"File extensions for interpreted code\"\"\" BUILD_FILE_EXTENSIONS: Tuple[str,", "str: \"\"\"Returns the author of the commit\"\"\" pass def validate_commit(commit:", "validator_class in validator_classes: validator = validator_class() validator_name = validator.__class__.__name__ error_list", "0: stats_strs.append(f'{failed_count} failed') if passed_count > 0: stats_strs.append(f'{passed_count} passed') stats_str", "\"\"\"Validates a commit against all validators :param commit: The commit", "in SOURCE_AND_SCRIPT_FILE_EXTENSIONS: skipped = True for pattern in SOURCE_AND_SCRIPT_FILE_PATTERNS: if", "3D Engine Project. # For complete copyright and license terms", "time.time() if failed_count: print(\"VALIDATION FAILURE SUMMARY\") for val_name in error_summary.keys():", "to added lines (with + in front) \"\"\" pass @abc.abstractmethod", "val_name in error_summary.keys(): errors = error_summary[val_name] if errors: for error_message", "list of CommitValidator classes to ignore, by class name :return:", "commit to validate :param errors: List of errors generated, append", "compiled source code\"\"\" SCRIPT_FILE_EXTENSIONS: Tuple[str, ...] = ( '.py', '.lua',", "\"\"\" failed_count = 0 passed_count = 0 start_time = time.time()", "the LICENSE at the root of this distribution. # #", "validator_classes: validator = validator_class() validator_name = validator.__class__.__name__ error_list = []", "+ module_name) validator = module.get_validator() if ignore_validators and validator.__name__ in", "passed_count > 0: stats_strs.append(f'{passed_count} passed') stats_str = ', '.join(stats_strs) +", "bool: if os.path.splitext(file_name)[1].lower() not in SOURCE_AND_SCRIPT_FILE_EXTENSIONS: skipped = True for", "False otherwise \"\"\" failed_count = 0 passed_count = 0 start_time", "error_list = [] passed = validator.run(commit, errors = error_list) if", "validators for validator_class in validator_classes: validator = validator_class() validator_name =", "errors: List[str]) -> bool: \"\"\"Validates a commit :param commit: The", "ignore_validators: List[str] = None) -> bool: \"\"\"Validates a commit against", "the description of the commit\"\"\" pass @abc.abstractmethod def get_author(self) ->", "= SOURCE_FILE_EXTENSIONS + SCRIPT_FILE_EXTENSIONS + BUILD_FILE_EXTENSIONS \"\"\"File extensions for both", "typing import Dict, List, Tuple VERBOSE = False class Commit(abc.ABC):", "Tuple[str, ...] = SOURCE_FILE_EXTENSIONS + SCRIPT_FILE_EXTENSIONS + BUILD_FILE_EXTENSIONS \"\"\"File extensions", "None) -> bool: \"\"\"Validates a commit against all validators :param", "in ignore_validators: print(f\"Disabled validation for '{validator.__name__}'\") else: validator_classes.append(validator) error_summary =", "import time from typing import Dict, List, Tuple VERBOSE =", "= ( re.compile(r'.*CMakeLists\\.txt'), re.compile(r'.*Jenkinsfile') ) \"\"\"File patterns for build files\"\"\"", "Process validators for validator_class in validator_classes: validator = validator_class() validator_name", "is valid, and False otherwise \"\"\" pass SOURCE_FILE_EXTENSIONS: Tuple[str, ...]", "for _, module_name, is_package in pkgutil.iter_modules([validators_dir]): if not is_package: module", "passed_count += 1 print(f'{validator.__class__.__name__} PASSED') else: failed_count += 1 print(f'{validator.__class__.__name__}", "this list :return: True if the commit is valid, and", "( '.c', '.cc', '.cpp', '.cxx', '.h', '.hpp', '.hxx', '.inl', '.m',", "...] = ( '.py', '.lua', '.bat', '.cmd', '.sh', '.js' )", "get_file_diff(self, str) -> str: \"\"\" Given a file name, returns", "'*/.git/*', '*/3rdParty/*', '*/__pycache__/*', '*/External/*', 'build', 'Cache', '*/Code/Framework/AzCore/azgnmx/azgnmx/*', 'Code/Tools/CryFXC', 'Code/Tools/HLSLCrossCompiler', 'Code/Tools/HLSLCrossCompilerMETAL',", "Given a file name, returns a string in unified diff", "skipped return False class CommitValidator(abc.ABC): \"\"\"A commit validator\"\"\" @abc.abstractmethod def", "Apache-2.0 OR MIT # # import abc import importlib import", "extensions for compiled source code\"\"\" SCRIPT_FILE_EXTENSIONS: Tuple[str, ...] = (", "else: failed_count += 1 print(f'{validator.__class__.__name__} FAILED') error_summary[validator_name] = error_list end_time", "out_errors: if not None, will populate with the list of", "'*/Code/Framework/AzCore/azgnmx/azgnmx/*', 'Code/Tools/CryFXC', 'Code/Tools/HLSLCrossCompiler', 'Code/Tools/HLSLCrossCompilerMETAL', 'Docs', 'python/runtime', 'restricted/*/Tools/*RemoteControl', 'Tools/3dsmax', '*/user/Cache/*', '*/user/log/*',", "'*/3rdParty/*', '*/__pycache__/*', '*/External/*', 'build', 'Cache', '*/Code/Framework/AzCore/azgnmx/azgnmx/*', 'Code/Tools/CryFXC', 'Code/Tools/HLSLCrossCompiler', 'Code/Tools/HLSLCrossCompilerMETAL', 'Docs',", "\"\"\"Returns a list of local files removed by the commit\"\"\"", "0 start_time = time.time() # Find all the validators in", "a list of local files removed by the commit\"\"\" pass", "from typing import Dict, List, Tuple VERBOSE = False class", "errors, and False otherwise \"\"\" failed_count = 0 passed_count =", "for error_message in errors: first_line = True for line in", "= [] if failed_count > 0: stats_strs.append(f'{failed_count} failed') if passed_count", "if pattern.match(file_name): skipped = False break return skipped return False", "if failed_count > 0: stats_strs.append(f'{failed_count} failed') if passed_count > 0:", "os.path.splitext(file_name)[1].lower() not in SOURCE_AND_SCRIPT_FILE_EXTENSIONS: skipped = True for pattern in", "both compiled and interpreted code\"\"\" BUILD_FILE_PATTERNS: Tuple[re.Pattern, ...] = (", "not in SOURCE_AND_SCRIPT_FILE_EXTENSIONS: skipped = True for pattern in SOURCE_AND_SCRIPT_FILE_PATTERNS:", "validators :param commit: The commit to validate :param out_errors: if", "validator_classes.append(validator) error_summary = {} # Process validators for validator_class in", "= [] passed = validator.run(commit, errors = error_list) if passed:", "'.cxx', '.h', '.hpp', '.hxx', '.inl', '.m', '.mm', '.cs', '.java' )", "'*/External/*', 'build', 'Cache', '*/Code/Framework/AzCore/azgnmx/azgnmx/*', 'Code/Tools/CryFXC', 'Code/Tools/HLSLCrossCompiler', 'Code/Tools/HLSLCrossCompilerMETAL', 'Docs', 'python/runtime', 'restricted/*/Tools/*RemoteControl',", "CommitValidator(abc.ABC): \"\"\"A commit validator\"\"\" @abc.abstractmethod def run(self, commit: Commit, errors:", "list of errors given by the validators :param ignore_validators: Optional", "> 0: stats_strs.append(f'{failed_count} failed') if passed_count > 0: stats_strs.append(f'{passed_count} passed')", "SOURCE_FILE_EXTENSIONS: Tuple[str, ...] = ( '.c', '.cc', '.cpp', '.cxx', '.h',", "patterns for build files\"\"\" SOURCE_AND_SCRIPT_FILE_PATTERNS: Tuple[re.Pattern, ...] = BUILD_FILE_PATTERNS EXCLUDED_VALIDATION_PATTERNS", "description of the commit\"\"\" pass @abc.abstractmethod def get_author(self) -> str:", "False print(f'VALIDATOR_FAILED: {val_name} {line}') else: print(f' {line}') # extra detail", "= BUILD_FILE_PATTERNS EXCLUDED_VALIDATION_PATTERNS = [ '*/.git/*', '*/3rdParty/*', '*/__pycache__/*', '*/External/*', 'build',", "List[str]: \"\"\"Returns a list of local files added/modified by the", "SPDX-License-Identifier: Apache-2.0 OR MIT # # import abc import importlib", "def validate_commit(commit: Commit, out_errors: List[str] = None, ignore_validators: List[str] =", "'.inl', '.m', '.mm', '.cs', '.java' ) \"\"\"File extensions for compiled", "= False class Commit(abc.ABC): \"\"\"An interface for accessing details about", "'.cc', '.cpp', '.cxx', '.h', '.hpp', '.hxx', '.inl', '.m', '.mm', '.cs',", "to ignore, by class name :return: True if there are", "def get_author(self) -> str: \"\"\"Returns the author of the commit\"\"\"", "{end_time - start_time:.2f}s' print() print(stats_str) return failed_count == 0 def", "the validators package (recursively) validator_classes = [] validators_dir = os.path.join(os.path.dirname(__file__),", "all the validators in the validators package (recursively) validator_classes =", "VERBOSE = False class Commit(abc.ABC): \"\"\"An interface for accessing details", "== 0 def IsFileSkipped(file_name) -> bool: if os.path.splitext(file_name)[1].lower() not in", "str) -> str: \"\"\" Given a file name, returns a", "IsFileSkipped(file_name) -> bool: if os.path.splitext(file_name)[1].lower() not in SOURCE_AND_SCRIPT_FILE_EXTENSIONS: skipped =", "parsing stats_strs = [] if failed_count > 0: stats_strs.append(f'{failed_count} failed')", "[] if failed_count > 0: stats_strs.append(f'{failed_count} failed') if passed_count >", "'.bat', '.cmd', '.sh', '.js' ) \"\"\"File extensions for interpreted code\"\"\"", "extensions for interpreted code\"\"\" BUILD_FILE_EXTENSIONS: Tuple[str, ...] = ( '.cmake',", "errors: first_line = True for line in error_message.splitlines(): if first_line:", "if not is_package: module = importlib.import_module('commit_validation.validators.' + module_name) validator =", "list of local files removed by the commit\"\"\" pass @abc.abstractmethod", "Commit, errors: List[str]) -> bool: \"\"\"Validates a commit :param commit:", "ignore_validators: Optional list of CommitValidator classes to ignore, by class", "= False break return skipped return False class CommitValidator(abc.ABC): \"\"\"A", "import pkgutil import re import time from typing import Dict,", "bool: \"\"\"Validates a commit :param commit: The commit to validate", "added/modified by the commit\"\"\" pass @abc.abstractmethod def get_removed_files(self) -> List[str]:", "= module.get_validator() if ignore_validators and validator.__name__ in ignore_validators: print(f\"Disabled validation", "errors given by the validators :param ignore_validators: Optional list of", "Tuple[str, ...] = ( '.c', '.cc', '.cpp', '.cxx', '.h', '.hpp',", "'.java' ) \"\"\"File extensions for compiled source code\"\"\" SCRIPT_FILE_EXTENSIONS: Tuple[str,", "start_time = time.time() # Find all the validators in the", "-> bool: \"\"\"Validates a commit :param commit: The commit to", "_, module_name, is_package in pkgutil.iter_modules([validators_dir]): if not is_package: module =", "validators in the validators package (recursively) validator_classes = [] validators_dir", "there are no validation errors, and False otherwise \"\"\" failed_count", "= 0 passed_count = 0 start_time = time.time() # Find", "BUILD_FILE_PATTERNS EXCLUDED_VALIDATION_PATTERNS = [ '*/.git/*', '*/3rdParty/*', '*/__pycache__/*', '*/External/*', 'build', 'Cache',", "else: validator_classes.append(validator) error_summary = {} # Process validators for validator_class", "'.py', '.lua', '.bat', '.cmd', '.sh', '.js' ) \"\"\"File extensions for", "{line}') else: print(f' {line}') # extra detail lines do not", "of the commit\"\"\" pass def validate_commit(commit: Commit, out_errors: List[str] =", "for this commit. Most validators will only pay attention to", "Commit(abc.ABC): \"\"\"An interface for accessing details about a commit\"\"\" @abc.abstractmethod", "the commit\"\"\" pass @abc.abstractmethod def get_file_diff(self, str) -> str: \"\"\"", "', '.join(stats_strs) + f' in {end_time - start_time:.2f}s' print() print(stats_str)", "Project. # For complete copyright and license terms please see", "Tuple[str, ...] = ( '.py', '.lua', '.bat', '.cmd', '.sh', '.js'", "by the commit\"\"\" pass @abc.abstractmethod def get_removed_files(self) -> List[str]: \"\"\"Returns", "module = importlib.import_module('commit_validation.validators.' + module_name) validator = module.get_validator() if ignore_validators", "= ', '.join(stats_strs) + f' in {end_time - start_time:.2f}s' print()", "def get_files(self) -> List[str]: \"\"\"Returns a list of local files", "= [ '*/.git/*', '*/3rdParty/*', '*/__pycache__/*', '*/External/*', 'build', 'Cache', '*/Code/Framework/AzCore/azgnmx/azgnmx/*', 'Code/Tools/CryFXC',", "run(self, commit: Commit, errors: List[str]) -> bool: \"\"\"Validates a commit", "otherwise \"\"\" pass SOURCE_FILE_EXTENSIONS: Tuple[str, ...] = ( '.c', '.cc',", "files\"\"\" SOURCE_AND_SCRIPT_FILE_PATTERNS: Tuple[re.Pattern, ...] = BUILD_FILE_PATTERNS EXCLUDED_VALIDATION_PATTERNS = [ '*/.git/*',", "True for pattern in SOURCE_AND_SCRIPT_FILE_PATTERNS: if pattern.match(file_name): skipped = False", "to that file for this commit. Most validators will only", "+= 1 print(f'{validator.__class__.__name__} PASSED') else: failed_count += 1 print(f'{validator.__class__.__name__} FAILED')", "For complete copyright and license terms please see the LICENSE", "EXCLUDED_VALIDATION_PATTERNS = [ '*/.git/*', '*/3rdParty/*', '*/__pycache__/*', '*/External/*', 'build', 'Cache', '*/Code/Framework/AzCore/azgnmx/azgnmx/*',", "import re import time from typing import Dict, List, Tuple", "True if there are no validation errors, and False otherwise", "string in unified diff format that represents the changes made", "SCRIPT_FILE_EXTENSIONS: Tuple[str, ...] = ( '.py', '.lua', '.bat', '.cmd', '.sh',", "pkgutil.iter_modules([validators_dir]): if not is_package: module = importlib.import_module('commit_validation.validators.' + module_name) validator", ":param commit: The commit to validate :param out_errors: if not", "the validators :param ignore_validators: Optional list of CommitValidator classes to", "= True for pattern in SOURCE_AND_SCRIPT_FILE_PATTERNS: if pattern.match(file_name): skipped =", "them to this list :return: True if the commit is", "...] = ( re.compile(r'.*CMakeLists\\.txt'), re.compile(r'.*Jenkinsfile') ) \"\"\"File patterns for build", ":param errors: List of errors generated, append them to this", "module.get_validator() if ignore_validators and validator.__name__ in ignore_validators: print(f\"Disabled validation for", "= ( '.cmake', ) \"\"\"File extensions for build files\"\"\" SOURCE_AND_SCRIPT_FILE_EXTENSIONS:", "validators_dir = os.path.join(os.path.dirname(__file__), 'validators') for _, module_name, is_package in pkgutil.iter_modules([validators_dir]):", "validator.run(commit, errors = error_list) if passed: passed_count += 1 print(f'{validator.__class__.__name__}", "f' in {end_time - start_time:.2f}s' print() print(stats_str) return failed_count ==", "machine parsing stats_strs = [] if failed_count > 0: stats_strs.append(f'{failed_count}", "+ f' in {end_time - start_time:.2f}s' print() print(stats_str) return failed_count", "package (recursively) validator_classes = [] validators_dir = os.path.join(os.path.dirname(__file__), 'validators') for", "print(f'{validator.__class__.__name__} FAILED') error_summary[validator_name] = error_list end_time = time.time() if failed_count:", "(c) Contributors to the Open 3D Engine Project. # For", "complete copyright and license terms please see the LICENSE at", "MIT # # import abc import importlib import os import", "# # import abc import importlib import os import pkgutil", "List[str] = None, ignore_validators: List[str] = None) -> bool: \"\"\"Validates", "to validate :param out_errors: if not None, will populate with", "source code\"\"\" SCRIPT_FILE_EXTENSIONS: Tuple[str, ...] = ( '.py', '.lua', '.bat',", "bool: \"\"\"Validates a commit against all validators :param commit: The", "= validator.run(commit, errors = error_list) if passed: passed_count += 1", "None, ignore_validators: List[str] = None) -> bool: \"\"\"Validates a commit", "# Copyright (c) Contributors to the Open 3D Engine Project.", "\"\"\"File extensions for interpreted code\"\"\" BUILD_FILE_EXTENSIONS: Tuple[str, ...] = (", "List[str] = None) -> bool: \"\"\"Validates a commit against all", "validation errors, and False otherwise \"\"\" failed_count = 0 passed_count", "end_time = time.time() if failed_count: print(\"VALIDATION FAILURE SUMMARY\") for val_name", "and False otherwise \"\"\" pass SOURCE_FILE_EXTENSIONS: Tuple[str, ...] = (", "all validators :param commit: The commit to validate :param out_errors:", "compiled and interpreted code\"\"\" BUILD_FILE_PATTERNS: Tuple[re.Pattern, ...] = ( re.compile(r'.*CMakeLists\\.txt'),", "in SOURCE_AND_SCRIPT_FILE_PATTERNS: if pattern.match(file_name): skipped = False break return skipped", "for '{validator.__name__}'\") else: validator_classes.append(validator) error_summary = {} # Process validators", "= [] validators_dir = os.path.join(os.path.dirname(__file__), 'validators') for _, module_name, is_package", "print(f\"Disabled validation for '{validator.__name__}'\") else: validator_classes.append(validator) error_summary = {} #", "is_package in pkgutil.iter_modules([validators_dir]): if not is_package: module = importlib.import_module('commit_validation.validators.' +", "passed_count = 0 start_time = time.time() # Find all the", "# Find all the validators in the validators package (recursively)", "for build files\"\"\" SOURCE_AND_SCRIPT_FILE_PATTERNS: Tuple[re.Pattern, ...] = BUILD_FILE_PATTERNS EXCLUDED_VALIDATION_PATTERNS =", "@abc.abstractmethod def run(self, commit: Commit, errors: List[str]) -> bool: \"\"\"Validates", "False otherwise \"\"\" pass SOURCE_FILE_EXTENSIONS: Tuple[str, ...] = ( '.c'," ]
[ "distances[index] snippets.append({ 'index': actual_index, 'snippet': snippet, 'distance': snippet_distance }) if", "zeros num_zeros = int(snippet_size * np.ceil(n / snippet_size) - n)", "= len(ts) if not isinstance(snippet_size, int) or snippet_size < 4:", "actual_index, 'snippet': snippet, 'distance': snippet_distance }) if isinstance(total_min, type(None)): total_min", "snippets(ts, snippet_size, num_snippets=2, window_size=None): \"\"\" The snippets algorithm is used", "from __future__ import division from __future__ import print_function from __future__", "/ 2) The window size. Returns ------- list : snippets", "absolute_import from __future__ import division from __future__ import print_function from", "range(num_snippets): minims = np.inf for i in range(len(indices)): s =", "# pad end of time series with zeros num_zeros =", "indices = np.arange(0, len(ts) - snippet_size, snippet_size) distances = []", "(len(ts) - snippet_size) total_min = total_min - mask del snippet['distance']", "import unicode_literals range = getattr(__builtins__, 'xrange', range) # end of", "Default 2 The number of snippets you would like to", "is too short relative to snippet length') if not window_size:", "window_size >= snippet_size: raise ValueError('window_size must be smaller than snippet_size')", "from matrixprofile import core from matrixprofile.algorithms.mpdist import mpdist_vector def snippets(ts,", "in range(num_snippets): minims = np.inf for i in range(len(indices)): s", "time series. snippet_size : int The size of snippet desired.", "Parameters ---------- ts : array_like The time series. snippet_size :", "from __future__ import unicode_literals range = getattr(__builtins__, 'xrange', range) #", "snippets.append({ 'index': actual_index, 'snippet': snippet, 'distance': snippet_distance }) if isinstance(total_min,", "smaller than snippet_size') # pad end of time series with", "mask.sum() / (len(ts) - snippet_size) total_min = total_min - mask", "raise ValueError('snippet_size must be an integer >= 4') if n", "must be smaller than snippet_size') # pad end of time", "of snippets as dictionary objects with the following structure. >>>", "minims > s: minims = s index = i minis", ">= snippet_size: raise ValueError('window_size must be smaller than snippet_size') #", "is the algorithm to use. Parameters ---------- ts : array_like", "__future__ import print_function from __future__ import unicode_literals range = getattr(__builtins__,", "number of snippets you would like to find. window_size :", "the index of the snippet, >>> snippet: the snippet values", "ts = core.to_np_array(ts).astype('d') n = len(ts) if not isinstance(snippet_size, int)", "}) if isinstance(total_min, type(None)): total_min = snippet_distance else: total_min =", "unicode_literals range = getattr(__builtins__, 'xrange', range) # end of py2", "> s: minims = s index = i minis =", "= np.inf total_min = None for n in range(num_snippets): minims", "mpdist_vector def snippets(ts, snippet_size, num_snippets=2, window_size=None): \"\"\" The snippets algorithm", "np from matrixprofile import core from matrixprofile.algorithms.mpdist import mpdist_vector def", "if isinstance(total_min, type(None)): total_min = snippet_distance else: total_min = np.minimum(total_min,", "isinstance(snippet_size, int) or snippet_size < 4: raise ValueError('snippet_size must be", "import core from matrixprofile.algorithms.mpdist import mpdist_vector def snippets(ts, snippet_size, num_snippets=2,", "relative to snippet length') if not window_size: window_size = int(np.floor(snippet_size", "be smaller than snippet_size') # pad end of time series", "int(snippet_size * np.ceil(n / snippet_size) - n) ts = np.append(ts,", "int(np.floor(snippet_size / 2)) if window_size >= snippet_size: raise ValueError('window_size must", "snippet = ts[actual_index:actual_index + snippet_size] snippet_distance = distances[index] snippets.append({ 'index':", "snippet length') if not window_size: window_size = int(np.floor(snippet_size / 2))", "= snippet_distance else: total_min = np.minimum(total_min, snippet_distance) # compute the", "snippet_size') # pad end of time series with zeros num_zeros", "mask = (snippet['distance'] <= total_min) snippet['fraction'] = mask.sum() / (len(ts)", "= [] minis = np.inf total_min = None for n", "n) ts = np.append(ts, np.zeros(num_zeros)) # compute all profiles indices", "use. Parameters ---------- ts : array_like The time series. snippet_size", "s index = i minis = np.minimum(distances[index, :], minis) actual_index", "window_size: window_size = int(np.floor(snippet_size / 2)) if window_size >= snippet_size:", "from __future__ import print_function from __future__ import unicode_literals range =", "in your time series, then this is the algorithm to", "np.ceil(n / snippet_size) - n) ts = np.append(ts, np.zeros(num_zeros)) #", "* np.ceil(n / snippet_size) - n) ts = np.append(ts, np.zeros(num_zeros))", "in range(len(indices)): s = np.sum(np.minimum(distances[i, :], minis)) if minims >", "from __future__ import absolute_import from __future__ import division from __future__", "total_min = snippet_distance else: total_min = np.minimum(total_min, snippet_distance) # compute", "python # -*- coding: utf-8 -*- from __future__ import absolute_import", "distances = [] for j, i in enumerate(indices): distance =", "fraction: fraction of the snippet, >>> index: the index of", "np.arange(0, len(ts) - snippet_size, snippet_size) distances = [] for j,", "snippet_size): raise ValueError('Time series is too short relative to snippet", "size of snippet desired. num_snippets : int, Default 2 The", "index: the index of the snippet, >>> snippet: the snippet", "snippet_size) - n) ts = np.append(ts, np.zeros(num_zeros)) # compute all", "# compute the fraction of each snippet for snippet in", "utf-8 -*- from __future__ import absolute_import from __future__ import division", "not window_size: window_size = int(np.floor(snippet_size / 2)) if window_size >=", "must be an integer >= 4') if n < (2", "find N snippets snippets = [] minis = np.inf total_min", "snippet, >>> index: the index of the snippet, >>> snippet:", "integer >= 4') if n < (2 * snippet_size): raise", "dictionary objects with the following structure. >>> { >>> fraction:", "total_min = np.minimum(total_min, snippet_distance) # compute the fraction of each", "i in range(len(indices)): s = np.sum(np.minimum(distances[i, :], minis)) if minims", "= np.minimum(total_min, snippet_distance) # compute the fraction of each snippet", "series by identifying N number of representative subsequences. If you", "= s index = i minis = np.minimum(distances[index, :], minis)", "boilerplate import numpy as np from matrixprofile import core from", "length') if not window_size: window_size = int(np.floor(snippet_size / 2)) if", ": snippets A list of snippets as dictionary objects with", "short relative to snippet length') if not window_size: window_size =", "window_size = int(np.floor(snippet_size / 2)) if window_size >= snippet_size: raise", "time series by identifying N number of representative subsequences. If", "the fraction of each snippet for snippet in snippets: mask", "= np.arange(0, len(ts) - snippet_size, snippet_size) distances = [] for", "patterns in your time series, then this is the algorithm", "[] for j, i in enumerate(indices): distance = mpdist_vector(ts, ts[i:(i", "np.zeros(num_zeros)) # compute all profiles indices = np.arange(0, len(ts) -", "#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import", "np.append(ts, np.zeros(num_zeros)) # compute all profiles indices = np.arange(0, len(ts)", "# compute all profiles indices = np.arange(0, len(ts) - snippet_size,", "minis = np.inf total_min = None for n in range(num_snippets):", "s = np.sum(np.minimum(distances[i, :], minis)) if minims > s: minims", "+ snippet_size - 1)], int(window_size)) distances.append(distance) distances = np.array(distances) #", "if not isinstance(snippet_size, int) or snippet_size < 4: raise ValueError('snippet_size", "snippet values >>> } \"\"\" ts = core.to_np_array(ts).astype('d') n =", "the algorithm to use. Parameters ---------- ts : array_like The", "snippet_size : int The size of snippet desired. num_snippets :", "= [] for j, i in enumerate(indices): distance = mpdist_vector(ts,", "time series, then this is the algorithm to use. Parameters", "core.to_np_array(ts).astype('d') n = len(ts) if not isinstance(snippet_size, int) or snippet_size", "= mpdist_vector(ts, ts[i:(i + snippet_size - 1)], int(window_size)) distances.append(distance) distances", "np.minimum(distances[index, :], minis) actual_index = indices[index] snippet = ts[actual_index:actual_index +", ": int The size of snippet desired. num_snippets : int,", "end of time series with zeros num_zeros = int(snippet_size *", "snippets = [] minis = np.inf total_min = None for", "snippet_size) distances = [] for j, i in enumerate(indices): distance", "np.sum(np.minimum(distances[i, :], minis)) if minims > s: minims = s", "series, then this is the algorithm to use. Parameters ----------", "4') if n < (2 * snippet_size): raise ValueError('Time series", "not isinstance(snippet_size, int) or snippet_size < 4: raise ValueError('snippet_size must", "the snippet values >>> } \"\"\" ts = core.to_np_array(ts).astype('d') n", "minims = np.inf for i in range(len(indices)): s = np.sum(np.minimum(distances[i,", "len(ts) if not isinstance(snippet_size, int) or snippet_size < 4: raise", "= indices[index] snippet = ts[actual_index:actual_index + snippet_size] snippet_distance = distances[index]", "= int(snippet_size * np.ceil(n / snippet_size) - n) ts =", "with zeros num_zeros = int(snippet_size * np.ceil(n / snippet_size) -", "- 1)], int(window_size)) distances.append(distance) distances = np.array(distances) # find N", "num_snippets : int, Default 2 The number of snippets you", ": int, Default 2 The number of snippets you would", "distances.append(distance) distances = np.array(distances) # find N snippets snippets =", "/ (len(ts) - snippet_size) total_min = total_min - mask del", "desired. num_snippets : int, Default 2 The number of snippets", "ts : array_like The time series. snippet_size : int The", "for snippet in snippets: mask = (snippet['distance'] <= total_min) snippet['fraction']", "be an integer >= 4') if n < (2 *", "= np.inf for i in range(len(indices)): s = np.sum(np.minimum(distances[i, :],", "np.minimum(total_min, snippet_distance) # compute the fraction of each snippet for", "None for n in range(num_snippets): minims = np.inf for i", "- snippet_size) total_min = total_min - mask del snippet['distance'] return", "than snippet_size') # pad end of time series with zeros", "snippet_distance) # compute the fraction of each snippet for snippet", "you want to identify typical patterns in your time series,", "import numpy as np from matrixprofile import core from matrixprofile.algorithms.mpdist", "range) # end of py2 compatability boilerplate import numpy as", "} \"\"\" ts = core.to_np_array(ts).astype('d') n = len(ts) if not", "summarize your time series by identifying N number of representative", "= getattr(__builtins__, 'xrange', range) # end of py2 compatability boilerplate", "total_min) snippet['fraction'] = mask.sum() / (len(ts) - snippet_size) total_min =", "# end of py2 compatability boilerplate import numpy as np", "/ 2)) if window_size >= snippet_size: raise ValueError('window_size must be", "n in range(num_snippets): minims = np.inf for i in range(len(indices)):", "time series with zeros num_zeros = int(snippet_size * np.ceil(n /", "compute the fraction of each snippet for snippet in snippets:", "'snippet': snippet, 'distance': snippet_distance }) if isinstance(total_min, type(None)): total_min =", "to identify typical patterns in your time series, then this", "1)], int(window_size)) distances.append(distance) distances = np.array(distances) # find N snippets", "of representative subsequences. If you want to identify typical patterns", "snippet desired. num_snippets : int, Default 2 The number of", "If you want to identify typical patterns in your time", "mpdist_vector(ts, ts[i:(i + snippet_size - 1)], int(window_size)) distances.append(distance) distances =", "of snippets you would like to find. window_size : int,", "i in enumerate(indices): distance = mpdist_vector(ts, ts[i:(i + snippet_size -", "representative subsequences. If you want to identify typical patterns in", "snippet_distance else: total_min = np.minimum(total_min, snippet_distance) # compute the fraction", "snippet['fraction'] = mask.sum() / (len(ts) - snippet_size) total_min = total_min", "snippets: mask = (snippet['distance'] <= total_min) snippet['fraction'] = mask.sum() /", "algorithm is used to summarize your time series by identifying", "len(ts) - snippet_size, snippet_size) distances = [] for j, i", "\"\"\" The snippets algorithm is used to summarize your time", "in snippets: mask = (snippet['distance'] <= total_min) snippet['fraction'] = mask.sum()", "snippets snippets = [] minis = np.inf total_min = None", "import division from __future__ import print_function from __future__ import unicode_literals", "this is the algorithm to use. Parameters ---------- ts :", "snippets you would like to find. window_size : int, Default", ">>> index: the index of the snippet, >>> snippet: the", "ts[actual_index:actual_index + snippet_size] snippet_distance = distances[index] snippets.append({ 'index': actual_index, 'snippet':", "minis = np.minimum(distances[index, :], minis) actual_index = indices[index] snippet =", "int(window_size)) distances.append(distance) distances = np.array(distances) # find N snippets snippets", "array_like The time series. snippet_size : int The size of", "snippet_size] snippet_distance = distances[index] snippets.append({ 'index': actual_index, 'snippet': snippet, 'distance':", "= int(np.floor(snippet_size / 2)) if window_size >= snippet_size: raise ValueError('window_size", "isinstance(total_min, type(None)): total_min = snippet_distance else: total_min = np.minimum(total_min, snippet_distance)", "series with zeros num_zeros = int(snippet_size * np.ceil(n / snippet_size)", "range(len(indices)): s = np.sum(np.minimum(distances[i, :], minis)) if minims > s:", "if n < (2 * snippet_size): raise ValueError('Time series is", "of py2 compatability boilerplate import numpy as np from matrixprofile", "py2 compatability boilerplate import numpy as np from matrixprofile import", "snippets A list of snippets as dictionary objects with the", ">>> fraction: fraction of the snippet, >>> index: the index", "i minis = np.minimum(distances[index, :], minis) actual_index = indices[index] snippet", "identifying N number of representative subsequences. If you want to", "ValueError('snippet_size must be an integer >= 4') if n <", ": int, Default (snippet_size / 2) The window size. Returns", "import absolute_import from __future__ import division from __future__ import print_function", "you would like to find. window_size : int, Default (snippet_size", "\"\"\" ts = core.to_np_array(ts).astype('d') n = len(ts) if not isinstance(snippet_size,", "if minims > s: minims = s index = i", "s: minims = s index = i minis = np.minimum(distances[index,", "core from matrixprofile.algorithms.mpdist import mpdist_vector def snippets(ts, snippet_size, num_snippets=2, window_size=None):", "- snippet_size, snippet_size) distances = [] for j, i in", "ValueError('Time series is too short relative to snippet length') if", "= np.minimum(distances[index, :], minis) actual_index = indices[index] snippet = ts[actual_index:actual_index", "---------- ts : array_like The time series. snippet_size : int", "index of the snippet, >>> snippet: the snippet values >>>", "- n) ts = np.append(ts, np.zeros(num_zeros)) # compute all profiles", "= np.array(distances) # find N snippets snippets = [] minis", "< (2 * snippet_size): raise ValueError('Time series is too short", "The time series. snippet_size : int The size of snippet", "= ts[actual_index:actual_index + snippet_size] snippet_distance = distances[index] snippets.append({ 'index': actual_index,", "like to find. window_size : int, Default (snippet_size / 2)", "series is too short relative to snippet length') if not", "distances = np.array(distances) # find N snippets snippets = []", "snippet_size, snippet_size) distances = [] for j, i in enumerate(indices):", "The size of snippet desired. num_snippets : int, Default 2", "N snippets snippets = [] minis = np.inf total_min =", ">>> } \"\"\" ts = core.to_np_array(ts).astype('d') n = len(ts) if", "snippet_size < 4: raise ValueError('snippet_size must be an integer >=", "import mpdist_vector def snippets(ts, snippet_size, num_snippets=2, window_size=None): \"\"\" The snippets", "4: raise ValueError('snippet_size must be an integer >= 4') if", "of each snippet for snippet in snippets: mask = (snippet['distance']", "subsequences. If you want to identify typical patterns in your", "coding: utf-8 -*- from __future__ import absolute_import from __future__ import", "Returns ------- list : snippets A list of snippets as", "__future__ import division from __future__ import print_function from __future__ import", "int) or snippet_size < 4: raise ValueError('snippet_size must be an", "all profiles indices = np.arange(0, len(ts) - snippet_size, snippet_size) distances", "The number of snippets you would like to find. window_size", "int, Default 2 The number of snippets you would like", "Default (snippet_size / 2) The window size. Returns ------- list", "getattr(__builtins__, 'xrange', range) # end of py2 compatability boilerplate import", "structure. >>> { >>> fraction: fraction of the snippet, >>>", "the following structure. >>> { >>> fraction: fraction of the", "int The size of snippet desired. num_snippets : int, Default", "<= total_min) snippet['fraction'] = mask.sum() / (len(ts) - snippet_size) total_min", "an integer >= 4') if n < (2 * snippet_size):", "snippet_size: raise ValueError('window_size must be smaller than snippet_size') # pad", "# find N snippets snippets = [] minis = np.inf", "import print_function from __future__ import unicode_literals range = getattr(__builtins__, 'xrange',", "int, Default (snippet_size / 2) The window size. Returns -------", "numpy as np from matrixprofile import core from matrixprofile.algorithms.mpdist import", "compute all profiles indices = np.arange(0, len(ts) - snippet_size, snippet_size)", "snippet, 'distance': snippet_distance }) if isinstance(total_min, type(None)): total_min = snippet_distance", "raise ValueError('window_size must be smaller than snippet_size') # pad end", "range = getattr(__builtins__, 'xrange', range) # end of py2 compatability", "= np.sum(np.minimum(distances[i, :], minis)) if minims > s: minims =", "'xrange', range) # end of py2 compatability boilerplate import numpy", "snippet_size, num_snippets=2, window_size=None): \"\"\" The snippets algorithm is used to", "identify typical patterns in your time series, then this is", "= distances[index] snippets.append({ 'index': actual_index, 'snippet': snippet, 'distance': snippet_distance })", "(2 * snippet_size): raise ValueError('Time series is too short relative", "np.inf total_min = None for n in range(num_snippets): minims =", "window_size : int, Default (snippet_size / 2) The window size.", "2)) if window_size >= snippet_size: raise ValueError('window_size must be smaller", "end of py2 compatability boilerplate import numpy as np from", "type(None)): total_min = snippet_distance else: total_min = np.minimum(total_min, snippet_distance) #", "list : snippets A list of snippets as dictionary objects", "pad end of time series with zeros num_zeros = int(snippet_size", "else: total_min = np.minimum(total_min, snippet_distance) # compute the fraction of", "ts[i:(i + snippet_size - 1)], int(window_size)) distances.append(distance) distances = np.array(distances)", "/ snippet_size) - n) ts = np.append(ts, np.zeros(num_zeros)) # compute", "'distance': snippet_distance }) if isinstance(total_min, type(None)): total_min = snippet_distance else:", "[] minis = np.inf total_min = None for n in", "index = i minis = np.minimum(distances[index, :], minis) actual_index =", "matrixprofile.algorithms.mpdist import mpdist_vector def snippets(ts, snippet_size, num_snippets=2, window_size=None): \"\"\" The", "__future__ import absolute_import from __future__ import division from __future__ import", "division from __future__ import print_function from __future__ import unicode_literals range", "< 4: raise ValueError('snippet_size must be an integer >= 4')", "2 The number of snippets you would like to find.", "= core.to_np_array(ts).astype('d') n = len(ts) if not isinstance(snippet_size, int) or", "num_snippets=2, window_size=None): \"\"\" The snippets algorithm is used to summarize", "minis)) if minims > s: minims = s index =", "with the following structure. >>> { >>> fraction: fraction of", "n = len(ts) if not isinstance(snippet_size, int) or snippet_size <", "= np.append(ts, np.zeros(num_zeros)) # compute all profiles indices = np.arange(0,", "algorithm to use. Parameters ---------- ts : array_like The time", "for n in range(num_snippets): minims = np.inf for i in", ">>> { >>> fraction: fraction of the snippet, >>> index:", "find. window_size : int, Default (snippet_size / 2) The window", "your time series, then this is the algorithm to use.", "indices[index] snippet = ts[actual_index:actual_index + snippet_size] snippet_distance = distances[index] snippets.append({", "fraction of the snippet, >>> index: the index of the", "num_zeros = int(snippet_size * np.ceil(n / snippet_size) - n) ts", "to summarize your time series by identifying N number of", "snippets algorithm is used to summarize your time series by", "{ >>> fraction: fraction of the snippet, >>> index: the", "for i in range(len(indices)): s = np.sum(np.minimum(distances[i, :], minis)) if", "snippet, >>> snippet: the snippet values >>> } \"\"\" ts", "used to summarize your time series by identifying N number", "def snippets(ts, snippet_size, num_snippets=2, window_size=None): \"\"\" The snippets algorithm is", "minis) actual_index = indices[index] snippet = ts[actual_index:actual_index + snippet_size] snippet_distance", "window_size=None): \"\"\" The snippets algorithm is used to summarize your", "2) The window size. Returns ------- list : snippets A", "list of snippets as dictionary objects with the following structure.", "values >>> } \"\"\" ts = core.to_np_array(ts).astype('d') n = len(ts)", "of the snippet, >>> index: the index of the snippet,", "np.inf for i in range(len(indices)): s = np.sum(np.minimum(distances[i, :], minis))", "------- list : snippets A list of snippets as dictionary", "ts = np.append(ts, np.zeros(num_zeros)) # compute all profiles indices =", "(snippet['distance'] <= total_min) snippet['fraction'] = mask.sum() / (len(ts) - snippet_size)", "= (snippet['distance'] <= total_min) snippet['fraction'] = mask.sum() / (len(ts) -", "series. snippet_size : int The size of snippet desired. num_snippets", "size. Returns ------- list : snippets A list of snippets", "to snippet length') if not window_size: window_size = int(np.floor(snippet_size /", ":], minis)) if minims > s: minims = s index", "snippet_size - 1)], int(window_size)) distances.append(distance) distances = np.array(distances) # find", "snippet_distance = distances[index] snippets.append({ 'index': actual_index, 'snippet': snippet, 'distance': snippet_distance", "__future__ import unicode_literals range = getattr(__builtins__, 'xrange', range) # end", "The snippets algorithm is used to summarize your time series", "snippet: the snippet values >>> } \"\"\" ts = core.to_np_array(ts).astype('d')", "The window size. Returns ------- list : snippets A list", "as dictionary objects with the following structure. >>> { >>>", "enumerate(indices): distance = mpdist_vector(ts, ts[i:(i + snippet_size - 1)], int(window_size))", "if not window_size: window_size = int(np.floor(snippet_size / 2)) if window_size", ">>> snippet: the snippet values >>> } \"\"\" ts =", "fraction of each snippet for snippet in snippets: mask =", "total_min = None for n in range(num_snippets): minims = np.inf", "is used to summarize your time series by identifying N", "ValueError('window_size must be smaller than snippet_size') # pad end of", ":], minis) actual_index = indices[index] snippet = ts[actual_index:actual_index + snippet_size]", "n < (2 * snippet_size): raise ValueError('Time series is too", "from matrixprofile.algorithms.mpdist import mpdist_vector def snippets(ts, snippet_size, num_snippets=2, window_size=None): \"\"\"", "# -*- coding: utf-8 -*- from __future__ import absolute_import from", "the snippet, >>> index: the index of the snippet, >>>", "j, i in enumerate(indices): distance = mpdist_vector(ts, ts[i:(i + snippet_size", "each snippet for snippet in snippets: mask = (snippet['distance'] <=", "or snippet_size < 4: raise ValueError('snippet_size must be an integer", "np.array(distances) # find N snippets snippets = [] minis =", "profiles indices = np.arange(0, len(ts) - snippet_size, snippet_size) distances =", "= i minis = np.minimum(distances[index, :], minis) actual_index = indices[index]", "want to identify typical patterns in your time series, then", "too short relative to snippet length') if not window_size: window_size", "snippet_distance }) if isinstance(total_min, type(None)): total_min = snippet_distance else: total_min", "+ snippet_size] snippet_distance = distances[index] snippets.append({ 'index': actual_index, 'snippet': snippet,", "objects with the following structure. >>> { >>> fraction: fraction", "* snippet_size): raise ValueError('Time series is too short relative to", "-*- from __future__ import absolute_import from __future__ import division from", "your time series by identifying N number of representative subsequences.", "compatability boilerplate import numpy as np from matrixprofile import core", "for j, i in enumerate(indices): distance = mpdist_vector(ts, ts[i:(i +", "-*- coding: utf-8 -*- from __future__ import absolute_import from __future__", "to find. window_size : int, Default (snippet_size / 2) The", "the snippet, >>> snippet: the snippet values >>> } \"\"\"", "actual_index = indices[index] snippet = ts[actual_index:actual_index + snippet_size] snippet_distance =", "of the snippet, >>> snippet: the snippet values >>> }", "of snippet desired. num_snippets : int, Default 2 The number", "distance = mpdist_vector(ts, ts[i:(i + snippet_size - 1)], int(window_size)) distances.append(distance)", "<filename>matrixprofile/algorithms/snippets.py #!/usr/bin/env python # -*- coding: utf-8 -*- from __future__", "A list of snippets as dictionary objects with the following", "following structure. >>> { >>> fraction: fraction of the snippet,", "to use. Parameters ---------- ts : array_like The time series.", "raise ValueError('Time series is too short relative to snippet length')", "by identifying N number of representative subsequences. If you want", "snippets as dictionary objects with the following structure. >>> {", "= mask.sum() / (len(ts) - snippet_size) total_min = total_min -", "'index': actual_index, 'snippet': snippet, 'distance': snippet_distance }) if isinstance(total_min, type(None)):", "(snippet_size / 2) The window size. Returns ------- list :", "snippet for snippet in snippets: mask = (snippet['distance'] <= total_min)", "matrixprofile import core from matrixprofile.algorithms.mpdist import mpdist_vector def snippets(ts, snippet_size,", ": array_like The time series. snippet_size : int The size", "in enumerate(indices): distance = mpdist_vector(ts, ts[i:(i + snippet_size - 1)],", "N number of representative subsequences. If you want to identify", "number of representative subsequences. If you want to identify typical", "window size. Returns ------- list : snippets A list of", "if window_size >= snippet_size: raise ValueError('window_size must be smaller than", "= None for n in range(num_snippets): minims = np.inf for", "as np from matrixprofile import core from matrixprofile.algorithms.mpdist import mpdist_vector", "then this is the algorithm to use. Parameters ---------- ts", "of time series with zeros num_zeros = int(snippet_size * np.ceil(n", "would like to find. window_size : int, Default (snippet_size /", "minims = s index = i minis = np.minimum(distances[index, :],", ">= 4') if n < (2 * snippet_size): raise ValueError('Time", "snippet in snippets: mask = (snippet['distance'] <= total_min) snippet['fraction'] =", "typical patterns in your time series, then this is the", "print_function from __future__ import unicode_literals range = getattr(__builtins__, 'xrange', range)", "snippet_size) total_min = total_min - mask del snippet['distance'] return snippets" ]
[ "json import re from copy import copy from logging import", "512 \"\"\" def format(self, record): cr = copy(record) if isinstance(cr.msg,", "import json import re from copy import copy from logging", "record): cr = copy(record) cr.msg = re.sub(r'\\u001b\\[.*?[@-~]', '', str(cr.msg)) return", "copy(record) cr.msg = re.sub(r'\\u001b\\[.*?[@-~]', '', str(cr.msg)) return json.dumps( {k: getattr(cr,", "'SUCCESS': dict(color='green', on_color=None), # white on red bg } #:", "= copy(record) seq = self.MAPPING.get(cr.levelname, self.MAPPING['INFO']) # default white cr.msg", "control chars from the log and format it as plain", "\"\"\"Format the log message as JSON object and add the", "dict): cr.msg.update({k: getattr(cr, k) for k in ['created', 'module', 'process',", "on_color=None), # cyan 'WARNING': dict(color='yellow', on_color='on_grey'), # yellow 'ERROR': dict(color='red',", "def format(self, record): cr = copy(record) cr.msg = re.sub(r'\\u001b\\[.*?[@-~]', '',", "dict(color='yellow', on_color='on_grey'), # yellow 'ERROR': dict(color='red', on_color=None), # 31 for", "logs based on the log-level. \"\"\" MAPPING = { 'DEBUG':", "= colored(cr.msg, **seq) return super().format(cr) class PlainFormatter(Formatter): \"\"\"Remove all control", "from logging import Formatter from .profile import used_memory from ..helper", "..helper import colored class ColorFormatter(Formatter): \"\"\"Format the log into colored", "object so that it can be later used/parsed in browser", "ColorFormatter(Formatter): \"\"\"Format the log into colored logs based on the", "plain text Also restrict the max-length of msg to 512", "record): cr = copy(record) if isinstance(cr.msg, str): cr.msg = re.sub(r'\\u001b\\[.*?[@-~]',", "it\"\"\" def format(self, record): cr = copy(record) if isinstance(cr.msg, dict):", "\"\"\" MAPPING = { 'DEBUG': dict(color='white', on_color=None), # white 'INFO':", "so that it can be later used/parsed in browser with", "from copy import copy from logging import Formatter from .profile", "copy import copy from logging import Formatter from .profile import", "the log-level. \"\"\" MAPPING = { 'DEBUG': dict(color='white', on_color=None), #", "cyan 'WARNING': dict(color='yellow', on_color='on_grey'), # yellow 'ERROR': dict(color='red', on_color=None), #", "seq = self.MAPPING.get(cr.levelname, self.MAPPING['INFO']) # default white cr.msg = colored(cr.msg,", "'funcName', 'levelname', 'lineno', 'msg', 'module', 'name', 'pathname', 'process', 'thread', 'processName',", "colored logs based on the log-level. \"\"\" MAPPING = {", "bg 'SUCCESS': dict(color='green', on_color=None), # white on red bg }", "yellow 'ERROR': dict(color='red', on_color=None), # 31 for red 'CRITICAL': dict(color='white',", "cr = copy(record) if isinstance(cr.msg, dict): cr.msg.update({k: getattr(cr, k) for", "isinstance(cr.msg, str): cr.msg = re.sub(r'\\u001b\\[.*?[@-~]', '', str(cr.msg))[:512] return super().format(cr) class", "'ERROR': dict(color='red', on_color=None), # 31 for red 'CRITICAL': dict(color='white', on_color='on_red'),", "= self.MAPPING.get(cr.levelname, self.MAPPING['INFO']) # default white cr.msg = colored(cr.msg, **seq)", "class JsonFormatter(Formatter): \"\"\"Format the log message as a JSON object", "record): cr = copy(record) if isinstance(cr.msg, dict): cr.msg.update({k: getattr(cr, k)", "red bg 'SUCCESS': dict(color='green', on_color=None), # white on red bg", "\"\"\"Format the log into colored logs based on the log-level.", "'', str(cr.msg))[:512] return super().format(cr) class JsonFormatter(Formatter): \"\"\"Format the log message", "isinstance(cr.msg, dict): cr.msg.update({k: getattr(cr, k) for k in ['created', 'module',", "to 512 \"\"\" def format(self, record): cr = copy(record) if", "from ..helper import colored class ColorFormatter(Formatter): \"\"\"Format the log into", "format it as plain text Also restrict the max-length of", "add the current used memory into it\"\"\" def format(self, record):", "used memory into it\"\"\" def format(self, record): cr = copy(record)", "def format(self, record): cr = copy(record) if isinstance(cr.msg, dict): cr.msg.update({k:", "on_color='on_grey'), # yellow 'ERROR': dict(color='red', on_color=None), # 31 for red", "to extract from the log def format(self, record): cr =", "= copy(record) if isinstance(cr.msg, dict): cr.msg.update({k: getattr(cr, k) for k", "\"\"\"Format the log message as a JSON object so that", "on red bg } #: log-level to color mapping def", "str(cr.msg))[:512] return super().format(cr) class JsonFormatter(Formatter): \"\"\"Format the log message as", "return super().format(cr) class JsonFormatter(Formatter): \"\"\"Format the log message as a", "all control chars from the log and format it as", "dict(color='red', on_color=None), # 31 for red 'CRITICAL': dict(color='white', on_color='on_red'), #", "on red bg 'SUCCESS': dict(color='green', on_color=None), # white on red", "json.dumps( {k: getattr(cr, k) for k in self.KEYS if hasattr(cr,", "as plain text Also restrict the max-length of msg to", "\"\"\" def format(self, record): cr = copy(record) if isinstance(cr.msg, str):", "'lineno', 'msg', 'module', 'name', 'pathname', 'process', 'thread', 'processName', 'threadName', 'log_id'}", "sort_keys=True) class ProfileFormatter(Formatter): \"\"\"Format the log message as JSON object", "'WARNING': dict(color='yellow', on_color='on_grey'), # yellow 'ERROR': dict(color='red', on_color=None), # 31", "mapping def format(self, record): cr = copy(record) seq = self.MAPPING.get(cr.levelname,", "cr = copy(record) seq = self.MAPPING.get(cr.levelname, self.MAPPING['INFO']) # default white", "memory into it\"\"\" def format(self, record): cr = copy(record) if", "'module', 'name', 'pathname', 'process', 'thread', 'processName', 'threadName', 'log_id'} #: keys", "and format it as plain text Also restrict the max-length", "getattr(cr, k) for k in self.KEYS if hasattr(cr, k)}, sort_keys=True)", "'INFO': dict(color='white', on_color=None), # cyan 'WARNING': dict(color='yellow', on_color='on_grey'), # yellow", "re from copy import copy from logging import Formatter from", "'log_id'} #: keys to extract from the log def format(self,", "colored class ColorFormatter(Formatter): \"\"\"Format the log into colored logs based", "for k in ['created', 'module', 'process', 'thread']}) cr.msg['memory'] = used_memory(unit=1)", "extract from the log def format(self, record): cr = copy(record)", "k in ['created', 'module', 'process', 'thread']}) cr.msg['memory'] = used_memory(unit=1) return", "'process', 'thread']}) cr.msg['memory'] = used_memory(unit=1) return json.dumps(cr.msg, sort_keys=True) else: return", "into colored logs based on the log-level. \"\"\" MAPPING =", "import used_memory from ..helper import colored class ColorFormatter(Formatter): \"\"\"Format the", "message as JSON object and add the current used memory", "log-level to color mapping def format(self, record): cr = copy(record)", "def format(self, record): cr = copy(record) if isinstance(cr.msg, str): cr.msg", "cr.msg = colored(cr.msg, **seq) return super().format(cr) class PlainFormatter(Formatter): \"\"\"Remove all", "# 31 for red 'CRITICAL': dict(color='white', on_color='on_red'), # white on", "# white 'INFO': dict(color='white', on_color=None), # cyan 'WARNING': dict(color='yellow', on_color='on_grey'),", "chars from the log and format it as plain text", "'name', 'pathname', 'process', 'thread', 'processName', 'threadName', 'log_id'} #: keys to", "import copy from logging import Formatter from .profile import used_memory", "Formatter from .profile import used_memory from ..helper import colored class", "be later used/parsed in browser with javascript. \"\"\" KEYS =", "format(self, record): cr = copy(record) if isinstance(cr.msg, str): cr.msg =", "in browser with javascript. \"\"\" KEYS = {'created', 'filename', 'funcName',", "from .profile import used_memory from ..helper import colored class ColorFormatter(Formatter):", "cr.msg = re.sub(r'\\u001b\\[.*?[@-~]', '', str(cr.msg))[:512] return super().format(cr) class JsonFormatter(Formatter): \"\"\"Format", "# white on red bg 'SUCCESS': dict(color='green', on_color=None), # white", "dict(color='green', on_color=None), # white on red bg } #: log-level", "log message as JSON object and add the current used", "for k in self.KEYS if hasattr(cr, k)}, sort_keys=True) class ProfileFormatter(Formatter):", "a JSON object so that it can be later used/parsed", "format(self, record): cr = copy(record) cr.msg = re.sub(r'\\u001b\\[.*?[@-~]', '', str(cr.msg))", "PlainFormatter(Formatter): \"\"\"Remove all control chars from the log and format", "it as plain text Also restrict the max-length of msg", "KEYS = {'created', 'filename', 'funcName', 'levelname', 'lineno', 'msg', 'module', 'name',", "MAPPING = { 'DEBUG': dict(color='white', on_color=None), # white 'INFO': dict(color='white',", "with javascript. \"\"\" KEYS = {'created', 'filename', 'funcName', 'levelname', 'lineno',", "current used memory into it\"\"\" def format(self, record): cr =", "record): cr = copy(record) seq = self.MAPPING.get(cr.levelname, self.MAPPING['INFO']) # default", "the log into colored logs based on the log-level. \"\"\"", "super().format(cr) class JsonFormatter(Formatter): \"\"\"Format the log message as a JSON", "log message as a JSON object so that it can", "'levelname', 'lineno', 'msg', 'module', 'name', 'pathname', 'process', 'thread', 'processName', 'threadName',", "{ 'DEBUG': dict(color='white', on_color=None), # white 'INFO': dict(color='white', on_color=None), #", "log and format it as plain text Also restrict the", "cr.msg = re.sub(r'\\u001b\\[.*?[@-~]', '', str(cr.msg)) return json.dumps( {k: getattr(cr, k)", "'', str(cr.msg)) return json.dumps( {k: getattr(cr, k) for k in", "JsonFormatter(Formatter): \"\"\"Format the log message as a JSON object so", "'pathname', 'process', 'thread', 'processName', 'threadName', 'log_id'} #: keys to extract", "self.KEYS if hasattr(cr, k)}, sort_keys=True) class ProfileFormatter(Formatter): \"\"\"Format the log", "ProfileFormatter(Formatter): \"\"\"Format the log message as JSON object and add", "the log message as a JSON object so that it", "on_color=None), # white on red bg } #: log-level to", "super().format(cr) class PlainFormatter(Formatter): \"\"\"Remove all control chars from the log", "k)}, sort_keys=True) class ProfileFormatter(Formatter): \"\"\"Format the log message as JSON", "can be later used/parsed in browser with javascript. \"\"\" KEYS", "log-level. \"\"\" MAPPING = { 'DEBUG': dict(color='white', on_color=None), # white", "javascript. \"\"\" KEYS = {'created', 'filename', 'funcName', 'levelname', 'lineno', 'msg',", "cr.msg.update({k: getattr(cr, k) for k in ['created', 'module', 'process', 'thread']})", "white 'INFO': dict(color='white', on_color=None), # cyan 'WARNING': dict(color='yellow', on_color='on_grey'), #", "in ['created', 'module', 'process', 'thread']}) cr.msg['memory'] = used_memory(unit=1) return json.dumps(cr.msg,", "if isinstance(cr.msg, str): cr.msg = re.sub(r'\\u001b\\[.*?[@-~]', '', str(cr.msg))[:512] return super().format(cr)", "format(self, record): cr = copy(record) if isinstance(cr.msg, dict): cr.msg.update({k: getattr(cr,", "to color mapping def format(self, record): cr = copy(record) seq", "re.sub(r'\\u001b\\[.*?[@-~]', '', str(cr.msg)) return json.dumps( {k: getattr(cr, k) for k", "log def format(self, record): cr = copy(record) cr.msg = re.sub(r'\\u001b\\[.*?[@-~]',", "the current used memory into it\"\"\" def format(self, record): cr", "for red 'CRITICAL': dict(color='white', on_color='on_red'), # white on red bg", "\"\"\"Remove all control chars from the log and format it", "in self.KEYS if hasattr(cr, k)}, sort_keys=True) class ProfileFormatter(Formatter): \"\"\"Format the", "restrict the max-length of msg to 512 \"\"\" def format(self,", "'module', 'process', 'thread']}) cr.msg['memory'] = used_memory(unit=1) return json.dumps(cr.msg, sort_keys=True) else:", "self.MAPPING['INFO']) # default white cr.msg = colored(cr.msg, **seq) return super().format(cr)", "the log and format it as plain text Also restrict", "self.MAPPING.get(cr.levelname, self.MAPPING['INFO']) # default white cr.msg = colored(cr.msg, **seq) return", "# white on red bg } #: log-level to color", "JSON object and add the current used memory into it\"\"\"", "dict(color='white', on_color=None), # cyan 'WARNING': dict(color='yellow', on_color='on_grey'), # yellow 'ERROR':", "white cr.msg = colored(cr.msg, **seq) return super().format(cr) class PlainFormatter(Formatter): \"\"\"Remove", "'DEBUG': dict(color='white', on_color=None), # white 'INFO': dict(color='white', on_color=None), # cyan", "copy from logging import Formatter from .profile import used_memory from", "colored(cr.msg, **seq) return super().format(cr) class PlainFormatter(Formatter): \"\"\"Remove all control chars", "it can be later used/parsed in browser with javascript. \"\"\"", "on_color='on_red'), # white on red bg 'SUCCESS': dict(color='green', on_color=None), #", "= {'created', 'filename', 'funcName', 'levelname', 'lineno', 'msg', 'module', 'name', 'pathname',", "'filename', 'funcName', 'levelname', 'lineno', 'msg', 'module', 'name', 'pathname', 'process', 'thread',", "object and add the current used memory into it\"\"\" def", "default white cr.msg = colored(cr.msg, **seq) return super().format(cr) class PlainFormatter(Formatter):", "= re.sub(r'\\u001b\\[.*?[@-~]', '', str(cr.msg))[:512] return super().format(cr) class JsonFormatter(Formatter): \"\"\"Format the", "hasattr(cr, k)}, sort_keys=True) class ProfileFormatter(Formatter): \"\"\"Format the log message as", "later used/parsed in browser with javascript. \"\"\" KEYS = {'created',", "of msg to 512 \"\"\" def format(self, record): cr =", "browser with javascript. \"\"\" KEYS = {'created', 'filename', 'funcName', 'levelname',", "Also restrict the max-length of msg to 512 \"\"\" def", "and add the current used memory into it\"\"\" def format(self,", "based on the log-level. \"\"\" MAPPING = { 'DEBUG': dict(color='white',", "'CRITICAL': dict(color='white', on_color='on_red'), # white on red bg 'SUCCESS': dict(color='green',", "**seq) return super().format(cr) class PlainFormatter(Formatter): \"\"\"Remove all control chars from", "on_color=None), # 31 for red 'CRITICAL': dict(color='white', on_color='on_red'), # white", "msg to 512 \"\"\" def format(self, record): cr = copy(record)", "the max-length of msg to 512 \"\"\" def format(self, record):", "re.sub(r'\\u001b\\[.*?[@-~]', '', str(cr.msg))[:512] return super().format(cr) class JsonFormatter(Formatter): \"\"\"Format the log", ".profile import used_memory from ..helper import colored class ColorFormatter(Formatter): \"\"\"Format", "{k: getattr(cr, k) for k in self.KEYS if hasattr(cr, k)},", "as JSON object and add the current used memory into", "into it\"\"\" def format(self, record): cr = copy(record) if isinstance(cr.msg,", "import colored class ColorFormatter(Formatter): \"\"\"Format the log into colored logs", "from the log and format it as plain text Also", "['created', 'module', 'process', 'thread']}) cr.msg['memory'] = used_memory(unit=1) return json.dumps(cr.msg, sort_keys=True)", "white on red bg 'SUCCESS': dict(color='green', on_color=None), # white on", "cr = copy(record) if isinstance(cr.msg, str): cr.msg = re.sub(r'\\u001b\\[.*?[@-~]', '',", "copy(record) if isinstance(cr.msg, str): cr.msg = re.sub(r'\\u001b\\[.*?[@-~]', '', str(cr.msg))[:512] return", "bg } #: log-level to color mapping def format(self, record):", "= re.sub(r'\\u001b\\[.*?[@-~]', '', str(cr.msg)) return json.dumps( {k: getattr(cr, k) for", "if hasattr(cr, k)}, sort_keys=True) class ProfileFormatter(Formatter): \"\"\"Format the log message", "#: log-level to color mapping def format(self, record): cr =", "on_color=None), # white 'INFO': dict(color='white', on_color=None), # cyan 'WARNING': dict(color='yellow',", "import re from copy import copy from logging import Formatter", "# default white cr.msg = colored(cr.msg, **seq) return super().format(cr) class", "#: keys to extract from the log def format(self, record):", "dict(color='white', on_color='on_red'), # white on red bg 'SUCCESS': dict(color='green', on_color=None),", "log into colored logs based on the log-level. \"\"\" MAPPING", "color mapping def format(self, record): cr = copy(record) seq =", "as a JSON object so that it can be later", "keys to extract from the log def format(self, record): cr", "# yellow 'ERROR': dict(color='red', on_color=None), # 31 for red 'CRITICAL':", "str(cr.msg)) return json.dumps( {k: getattr(cr, k) for k in self.KEYS", "copy(record) if isinstance(cr.msg, dict): cr.msg.update({k: getattr(cr, k) for k in", "} #: log-level to color mapping def format(self, record): cr", "str): cr.msg = re.sub(r'\\u001b\\[.*?[@-~]', '', str(cr.msg))[:512] return super().format(cr) class JsonFormatter(Formatter):", "text Also restrict the max-length of msg to 512 \"\"\"", "dict(color='white', on_color=None), # white 'INFO': dict(color='white', on_color=None), # cyan 'WARNING':", "class ColorFormatter(Formatter): \"\"\"Format the log into colored logs based on", "# cyan 'WARNING': dict(color='yellow', on_color='on_grey'), # yellow 'ERROR': dict(color='red', on_color=None),", "31 for red 'CRITICAL': dict(color='white', on_color='on_red'), # white on red", "\"\"\" KEYS = {'created', 'filename', 'funcName', 'levelname', 'lineno', 'msg', 'module',", "'process', 'thread', 'processName', 'threadName', 'log_id'} #: keys to extract from", "'thread', 'processName', 'threadName', 'log_id'} #: keys to extract from the", "k) for k in self.KEYS if hasattr(cr, k)}, sort_keys=True) class", "the log def format(self, record): cr = copy(record) cr.msg =", "cr = copy(record) cr.msg = re.sub(r'\\u001b\\[.*?[@-~]', '', str(cr.msg)) return json.dumps(", "'msg', 'module', 'name', 'pathname', 'process', 'thread', 'processName', 'threadName', 'log_id'} #:", "on the log-level. \"\"\" MAPPING = { 'DEBUG': dict(color='white', on_color=None),", "import Formatter from .profile import used_memory from ..helper import colored", "def format(self, record): cr = copy(record) seq = self.MAPPING.get(cr.levelname, self.MAPPING['INFO'])", "used/parsed in browser with javascript. \"\"\" KEYS = {'created', 'filename',", "getattr(cr, k) for k in ['created', 'module', 'process', 'thread']}) cr.msg['memory']", "white on red bg } #: log-level to color mapping", "{'created', 'filename', 'funcName', 'levelname', 'lineno', 'msg', 'module', 'name', 'pathname', 'process',", "'processName', 'threadName', 'log_id'} #: keys to extract from the log", "red 'CRITICAL': dict(color='white', on_color='on_red'), # white on red bg 'SUCCESS':", "k in self.KEYS if hasattr(cr, k)}, sort_keys=True) class ProfileFormatter(Formatter): \"\"\"Format", "copy(record) seq = self.MAPPING.get(cr.levelname, self.MAPPING['INFO']) # default white cr.msg =", "message as a JSON object so that it can be", "return json.dumps( {k: getattr(cr, k) for k in self.KEYS if", "'thread']}) cr.msg['memory'] = used_memory(unit=1) return json.dumps(cr.msg, sort_keys=True) else: return ''", "class ProfileFormatter(Formatter): \"\"\"Format the log message as JSON object and", "= copy(record) cr.msg = re.sub(r'\\u001b\\[.*?[@-~]', '', str(cr.msg)) return json.dumps( {k:", "the log message as JSON object and add the current", "used_memory from ..helper import colored class ColorFormatter(Formatter): \"\"\"Format the log", "logging import Formatter from .profile import used_memory from ..helper import", "max-length of msg to 512 \"\"\" def format(self, record): cr", "= { 'DEBUG': dict(color='white', on_color=None), # white 'INFO': dict(color='white', on_color=None),", "JSON object so that it can be later used/parsed in", "k) for k in ['created', 'module', 'process', 'thread']}) cr.msg['memory'] =", "format(self, record): cr = copy(record) seq = self.MAPPING.get(cr.levelname, self.MAPPING['INFO']) #", "that it can be later used/parsed in browser with javascript.", "class PlainFormatter(Formatter): \"\"\"Remove all control chars from the log and", "= copy(record) if isinstance(cr.msg, str): cr.msg = re.sub(r'\\u001b\\[.*?[@-~]', '', str(cr.msg))[:512]", "return super().format(cr) class PlainFormatter(Formatter): \"\"\"Remove all control chars from the", "red bg } #: log-level to color mapping def format(self,", "from the log def format(self, record): cr = copy(record) cr.msg", "'threadName', 'log_id'} #: keys to extract from the log def", "if isinstance(cr.msg, dict): cr.msg.update({k: getattr(cr, k) for k in ['created'," ]
[ "sys sys.setrecursionlimit(10000000) input=lambda : sys.stdin.readline().rstrip() n,x=map(int,input().split()) a=list(map(int,input().split())) aa=list(filter(lambda b:b!=x,a)) print(*aa)", "import sys sys.setrecursionlimit(10000000) input=lambda : sys.stdin.readline().rstrip() n,x=map(int,input().split()) a=list(map(int,input().split())) aa=list(filter(lambda b:b!=x,a))" ]
[ "change in the BE but don't send the event. #", "split change event.\"\"\" return {'id':'TVUsxaabHs:0:0'} def make_occupancy(channel, publishers): \"\"\"Make an", "some_apikey' # SyncAll on push down req = split_backend_requests.get() assert", "'GET' assert req.path == '/api/splitChanges?since=4' assert req.headers['authorization'] == 'Bearer some_apikey'", "not task.running() # Validate the SSE request sse_request = sse_requests.get()", "1) assert path == '/event-stream' qs = parse_qs(qs) assert qs['accessToken'][0]", "the event. # After dropping occupancy, the sdk should switch", "False, 'off', 'user', True)] } split_changes[3] = {'since': 3, 'till':", "some_apikey' # Fetch after second notification req = split_backend_requests.get() assert", "sse_server.publish(make_occupancy('control_pri', 2)) sse_server.publish(make_occupancy('control_sec', 2)) kwargs = { 'sdk_api_base_url': 'http://localhost:%d/api' %", "split_backend.stop() def make_split_change_event(change_number): \"\"\"Make a split change event.\"\"\" return {", "not task.running() time.sleep(1) split_changes[1] = { 'since': 1, 'till': 2,", "= get_factory('some_apikey', **kwargs) factory.block_until_ready(1) assert factory.ready assert factory.client().get_treatment('maldo', 'split1') ==", "= SSEMockServer(sse_requests) split_backend.start() sse_server.start() sse_server.publish(make_initial_event()) sse_server.publish(make_occupancy('control_pri', 0)) sse_server.publish(make_occupancy('control_sec', 0)) kwargs", "'till': 1} sse_server.publish(make_split_change_event(3)) time.sleep(1) sse_server.publish(make_segment_change_event('segment1', 1)) time.sleep(1) assert factory.client().get_treatment('pindon', 'split2')", "% sse_server.port(), 'config': {'connectTimeout': 10000, 'featuresRefreshRate': 10} } factory =", "'splits': []} } segment_changes = {} split_backend_requests = Queue() split_backend", "previous syncAll req = split_backend_requests.get() assert req.method == 'GET' assert", "} split_changes[5] = {'since': 5, 'till': 5, 'splits': []} sse_server.publish(make_control_event('STREAMING_DISABLED',", "split_changes[2] = {'since': 2, 'till': 2, 'splits': []} sse_server.publish(make_control_event('STREAMING_PAUSED', 1))", "push is up req = split_backend_requests.get() assert req.method == 'GET'", "sse_server.stop() split_backend.stop() def test_server_closes_connection(self): \"\"\"Test that if the server closes", "task.running() assert factory.client().get_treatment('maldo', 'split1') == 'on' # Make a change", "# We'll send an ignorable error and check it has", "split_changes[2] = { 'since': 2, 'till': 3, 'splits': [make_split_with_segment('split2', 2,", "True, 'frula', 'user', False)] } split_changes[5] = {'since': 5, 'till':", "factory._sync_manager._synchronizer._split_tasks.split_task._task # pylint:disable=protected-access assert not task.running() assert factory.client().get_treatment('maldo', 'split1') ==", "1, 'till': 1} sse_server.publish(make_split_change_event(3)) time.sleep(1) sse_server.publish(make_segment_change_event('segment1', 1)) time.sleep(1) assert factory.client().get_treatment('pindon',", "[]} sse_server.publish(make_split_change_event(3)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'on' assert not", "enabled, paused and disabled.\"\"\" auth_server_response = { 'pushEnabled': True, 'token':", "polling & streaming properly.\"\"\" auth_server_response = { 'pushEnabled': True, 'token':", "control event.\"\"\" return { 'event': 'message', 'data': json.dumps({ 'id':'TVUsxaabHs:0:0', 'clientId':'pri:MzM0ODI1MTkxMw==',", "splits fetch req = split_backend_requests.get() assert req.method == 'GET' assert", "= split_backend_requests.get() assert req.method == 'GET' assert req.path == '/api/splitChanges?since=3'", "% sse_server.port(), 'config': {'connectTimeout': 10000, 'featuresRefreshRate': 100, 'segmentsRefreshRate': 100, 'metricsRefreshRate':", "'/api/splitChanges?since=3' assert req.headers['authorization'] == 'Bearer some_apikey' # Cleanup destroy_event =", "'since': -1, 'till': 1, 'splits': [make_simple_split('split1', 1, True, False, 'off',", "{ 'matcherType': 'IN_SEGMENT', 'negate': False, 'userDefinedSegmentMatcherData': {'segmentName': segment}, 'whitelistMatcherData': None", "destroy_event.wait() sse_server.publish(sse_server.GRACEFUL_REQUEST_END) sse_server.stop() split_backend.stop() def test_start_without_occupancy(self): \"\"\"Test an SDK starting", "& splits/segment updates.\"\"\" auth_server_response = { 'pushEnabled': True, 'token': ('<KEY>", "factory.client().get_treatment('maldo', 'split1') == 'on' time.sleep(1) split_changes[1] = { 'since': 1,", "some_apikey' # Auth after connection breaks req = split_backend_requests.get() assert", "SyncAll after push restored req = split_backend_requests.get() assert req.method ==", "splits/segment updates.\"\"\" auth_server_response = { 'pushEnabled': True, 'token': ('<KEY> '<KEY>'", "}) } def make_split_kill_event(name, default_treatment, change_number): \"\"\"Make a split change", "2, 'splits': []} sse_server.publish(make_occupancy('control_pri', 0)) sse_server.publish(make_occupancy('control_sec', 0)) time.sleep(2) assert factory.client().get_treatment('maldo',", "'splits': [make_simple_split('split1', 3, True, False, 'off', 'user', True)] } split_changes[3]", "not task.running() sse_server.publish(make_ably_error_event(40145, 401)) sse_server.publish(sse_server.GRACEFUL_REQUEST_END) time.sleep(3) assert task.running() assert factory.client().get_treatment('maldo',", "{'since': 3, 'till': 3, 'splits': []} sse_server.publish(make_occupancy('control_pri', 1)) time.sleep(2) assert", "'GET' assert req.path == '/api/splitChanges?since=2' assert req.headers['authorization'] == 'Bearer some_apikey'", "the server closes the connection, the whole flow is retried", "('<KEY> '<KEY>' '<KEY>' '<KEY>' '<KEY>' '<KEY>' '<KEY>' 'CI6MTYwNDEwMDU5MSwiaWF0IjoxNjA0MDk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5E' 'vJh17WlOlAKhcD0') }", "'since': 1, 'till': 1} sse_server.publish(make_split_change_event(3)) time.sleep(1) sse_server.publish(make_segment_change_event('segment1', 1)) time.sleep(1) assert", "and failover.\"\"\" def test_happiness(self): \"\"\"Test initialization & splits/segment updates.\"\"\" auth_server_response", "} def make_control_event(control_type, timestamp): \"\"\"Make a control event.\"\"\" return {", "kwargs = { 'sdk_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'events_api_base_url': 'http://localhost:%d/api' %", "== '1.1' sse_request = sse_requests.get() assert sse_request.method == 'GET' path,", "SyncAll after streaming connected again req = split_backend_requests.get() assert req.method", "2, 'till': 2, 'splits': []} sse_server.publish(make_control_event('STREAMING_PAUSED', 1)) time.sleep(2) assert factory.client().get_treatment('maldo',", "'since': 4, 'till': 5, 'splits': [make_simple_split('split1', 5, True, True, 'frula',", "# SyncAll after streaming connected again req = split_backend_requests.get() assert", "retried with BO.\"\"\" auth_server_response = { 'pushEnabled': True, 'token': ('<KEY>", "auth_server_response = { 'pushEnabled': True, 'token': ('<KEY> '<KEY>' '<KEY>' '<KEY>'", "handler.setFormatter(formatter) logger.addHandler(handler) logger.setLevel(logging.DEBUG) auth_server_response = { 'pushEnabled': True, 'token': ('<KEY>", "we can query its status task = factory._sync_manager._synchronizer._split_tasks.split_task._task # pylint:disable=protected-access", "= {'since': 3, 'till': 3, 'splits': []} sse_server.publish(make_split_change_event(3)) time.sleep(1) assert", "'<KEY>' '<KEY>' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' 'HktY2xpZW<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' )", "'2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXC<KEY>' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' '<KEY>' 'Dk2OTkxfQ.<KEY>' ) assert set(qs['channels'][0].split(',')) == set(['MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments',", "split_backend_requests, auth_server_response) sse_requests = Queue() sse_server = SSEMockServer(sse_requests) split_backend.start() sse_server.start()", "'<KEY>' '<KEY>' '<KEY>' '<KEY>' '<KEY>' 'vJh17WlOlAKhcD0') } split_changes = {", "split_backend_requests.get() assert req.method == 'GET' assert req.path == '/api/splitChanges?since=2' assert", "assert qs['accessToken'][0] == ( '<KEY>' '<KEY>' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' '<KEY>UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV<KEY>I' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaV<KEY>' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXC<KEY>'", "import Queue from splitio.client.factory import get_factory from tests.helpers.mockserver import SSEMockServer,", "restoring occupancy, the sdk should switch to polling # and", "'2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' 'HktY2xpZW50SWQiOiJjbG<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert set(qs['channels'][0].split(',')) == set(['MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments',", "Fetch after notification req = split_backend_requests.get() assert req.method == 'GET'", "2, 'till': 2, 'splits': []} sse_server.publish(make_occupancy('control_pri', 0)) sse_server.publish(make_occupancy('control_sec', 0)) time.sleep(2)", "'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert set(qs['channels'][0].split(',')) == set(['MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments', '[?occupancy=metrics.publishers]control_pri', '[?occupancy=metrics.publishers]control_sec']) assert", "task.running() time.sleep(2) # wait for the backoff to expire so", "0)) kwargs = { 'sdk_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'events_api_base_url': 'http://localhost:%d/api'", "event AND occupancy sse_server.publish(make_initial_event()) sse_server.publish(make_occupancy('control_pri', 2)) sse_server.publish(make_occupancy('control_sec', 2)) time.sleep(2) assert", "= factory._sync_manager._synchronizer._split_tasks.split_task._task # pylint:disable=protected-access assert not task.running() time.sleep(1) split_changes[1] =", "False)] } split_changes[5] = {'since': 5, 'till': 5, 'splits': []}", "change event.\"\"\" return { 'event': 'message', 'data': json.dumps({ 'id':'TVUsxaabHs:0:0', 'clientId':'pri:MzM0ODI1MTkxMw==',", "is working properly split_changes[2] = { 'since': 2, 'till': 3,", "2, 'splits': []} sse_server.publish(make_control_event('STREAMING_PAUSED', 1)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') ==", "factory.block_until_ready(1) assert factory.ready time.sleep(2) # Get a hook of the", "split_backend_requests.get() assert req.method == 'GET' assert req.path == '/api/auth' assert", "parse_qs except ImportError: from urlparse import parse_qs class StreamingIntegrationTests(object): \"\"\"Test", "assert factory.client().get_treatment('maldo', 'split1') == 'on' assert not task.running() # Now", "'http://localhost:%d/api' % split_backend.port(), 'streaming_api_base_url': 'http://localhost:%d' % sse_server.port(), 'config': {'connectTimeout': 10000}", "False)] } split_changes[4] = {'since': 4, 'till': 4, 'splits': []}", "3, 'splits': []} sse_server.publish(make_occupancy('control_pri', 1)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') ==", "with a segment.\"\"\" return { 'trafficTypeName': tt, 'name': name, 'seed':", "'since': 1, 'till': 1, 'splits': [] } } segment_changes =", "{ 'since': 1, 'till': 2, 'splits': [make_simple_split('split1', 2, True, False,", "sse_server.publish(make_split_change_event(3)) time.sleep(1) assert factory.client().get_treatment('maldo', 'split1') == 'on' assert not task.running()", "and don't send the event. # We restore occupancy, and", "'IN_SEGMENT', 'negate': False, 'userDefinedSegmentMatcherData': {'segmentName': segment}, 'whitelistMatcherData': None } ]", "occupancy event.\"\"\" return { 'event': 'message', 'data': json.dumps({ 'id':'aP6EuhrcUm:0:0', 'timestamp':1604325712734,", "'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' 'HktY2xpZW50SWQiOiJjbGllbnRJZCIsImV4cCI6MTYwNDEwMDU5MSwiaWF0IjoxNjA0M' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert set(qs['channels'][0].split(',')) == set(['MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits',", "req.method == 'GET' assert req.path == '/api/segmentChanges/__SOME_INVALID_SEGMENT__?since=-1' assert req.headers['authorization'] ==", "True)] } split_changes[5] = {'since': 5, 'till': 5, 'splits': []}", "= sse_request.path.split('?', 1) assert path == '/event-stream' qs = parse_qs(qs)", "handling.\"\"\" import logging logger = logging.getLogger('splitio') handler = logging.StreamHandler() formatter", "**kwargs) factory.block_until_ready(1) assert factory.ready assert factory.client().get_treatment('maldo', 'split1') == 'on' task", "sse_request.method == 'GET' path, qs = sse_request.path.split('?', 1) assert path", "SyncAll after push down req = split_backend_requests.get() assert req.method ==", "== 'GET' assert req.path == '/api/segmentChanges/segment1?since=-1' assert req.headers['authorization'] == 'Bearer", "= {'since': 4, 'till': 4, 'splits': []} sse_server.publish(make_split_change_event(4)) time.sleep(2) assert", "'<KEY>' '<KEY>' 'dGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFibHktY2xpZW50SWQiOiJjbGllbnRJZCIsImV4c' 'CI6MTYwNDEwMDU5MSwiaWF0IjoxNjA0MDk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5E' 'vJh17WlOlAKhcD0') } split_changes = { -1:", "assert factory.client().get_treatment('maldo', 'split1') == 'off' assert task.running() time.sleep(2) # wait", "till req = split_backend_requests.get() assert req.method == 'GET' assert req.path", "'<KEY>' 'vJh17WlOlAKhcD0') } split_changes = { -1: { 'since': -1,", "time.sleep(1) assert factory.client().get_treatment('maldo', 'split1') == 'off' sse_server.publish(SSEMockServer.GRACEFUL_REQUEST_END) time.sleep(1) assert factory.client().get_treatment('maldo',", "'ARCHIVED', 'changeNumber': cn, 'killed': killed, 'defaultTreatment': default_treatment, 'configurations': { 'on':", "# pylint:disable=protected-access assert not task.running() assert factory.client().get_treatment('maldo', 'split1') == 'on'", "'split1') == 'off' assert task.running() time.sleep(2) # wait for the", "} factory = get_factory('some_apikey', **kwargs) factory.block_until_ready(1) assert factory.ready time.sleep(2) #", "'off' sse_server.publish(SSEMockServer.GRACEFUL_REQUEST_END) time.sleep(1) assert factory.client().get_treatment('maldo', 'split1') == 'off' assert task.running()", "= sse_requests.get() assert sse_request.method == 'GET' path, qs = sse_request.path.split('?',", "True, False, 'off', 'user', True)] }, 1: {'since': 1, 'till':", "2, 'splits': []} sse_server.publish(make_ably_error_event(60000, 600)) time.sleep(1) assert factory.client().get_treatment('maldo', 'split1') ==", "'data': json.dumps({'metrics': {'publishers': publishers}}), 'name':'[meta]occupancy' }) } def make_segment_change_event(name, change_number):", "}, 'partitions': [{ 'treatment': 'on' if on else 'off', 'size':", "split_backend.port(), 'auth_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'streaming_api_base_url': 'http://localhost:%d' % sse_server.port(), 'config':", "set(['MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments', '[?occupancy=metrics.publishers]control_pri', '[?occupancy=metrics.publishers]control_sec']) assert qs['v'][0] == '1.1' sse_request =", "switch to polling # and perform a syncAll that gets", "factory.client().get_treatment('maldo', 'split1') == 'off' # Kill the split split_changes[4] =", "non recoverable ably error req = split_backend_requests.get() assert req.method ==", "name, 'seed': cn, 'status': 'ACTIVE' if active else 'ARCHIVED', 'changeNumber':", "[]} sse_server.publish(make_split_change_event(4)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'off' assert not", "== 'GET' assert req.path == '/api/splitChanges?since=1' assert req.headers['authorization'] == 'Bearer", "factory.client().get_treatment('maldo', 'split1') == 'off' assert task.running() time.sleep(2) # wait for", "4, 'till': 5, 'splits': [make_simple_split('split1', 5, True, False, 'off', 'user',", "after streaming disabled req = split_backend_requests.get() assert req.method == 'GET'", "after push down req = split_backend_requests.get() assert req.method == 'GET'", "0} ] } ] } def make_split_with_segment(name, cn, active, killed,", "[] } } segment_changes = {} split_backend_requests = Queue() split_backend", "destroy_event.wait() sse_server.publish(sse_server.GRACEFUL_REQUEST_END) sse_server.stop() split_backend.stop() def test_streaming_status_changes(self): \"\"\"Test changes between streaming", "SyncAll on retryable error handling req = split_backend_requests.get() assert req.method", "assert req.method == 'GET' assert req.path == '/api/splitChanges?since=5' assert req.headers['authorization']", "status, 'href':\"https://help.ably.io/error/%d\" % code }) } def make_simple_split(name, cn, active,", "# Fetch after first notification req = split_backend_requests.get() assert req.method", "first notification req = split_backend_requests.get() assert req.method == 'GET' assert", "{ 'since': 2, 'till': 3, 'splits': [make_split_with_segment('split2', 2, True, False,", "'user', True)] } split_changes[5] = {'since': 5, 'till': 5, 'splits':", "'/api/splitChanges?since=2' assert req.headers['authorization'] == 'Bearer some_apikey' # Auth again req", "401)) sse_server.publish(sse_server.GRACEFUL_REQUEST_END) time.sleep(3) assert task.running() assert factory.client().get_treatment('maldo', 'split1') == 'off'", "ImportError: from urlparse import parse_qs class StreamingIntegrationTests(object): \"\"\"Test streaming operation", "'/event-stream' qs = parse_qs(qs) assert qs['accessToken'][0] == ( '<KEY>' 'US45QnJtR<KEY>'", "'on' assert not task.running() # Now we make another change", "-1, 'till': 1, 'splits': [make_simple_split('split1', 1, True, False, 'off', 'user',", "factory.ready assert factory.client().get_treatment('maldo', 'split1') == 'on' time.sleep(1) split_changes[1] = {", "= {'since': 3, 'till': 3, 'splits': []} sse_server.publish(make_split_change_event(3)) time.sleep(2) assert", "an event so it's propagated split_changes[3] = { 'since': 3,", "-1)] = { 'name': 'segment1', 'added': ['maldo'], 'removed': [], 'since':", "'splits': []} sse_server.publish(make_split_change_event(2)) time.sleep(1) assert factory.client().get_treatment('maldo', 'split1') == 'off' sse_server.publish(SSEMockServer.GRACEFUL_REQUEST_END)", "sse_request = sse_requests.get() assert sse_request.method == 'GET' path, qs =", "until segment1 since == till req = split_backend_requests.get() assert req.method", "1)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'on' assert not task.running()", "== '/api/auth' assert req.headers['authorization'] == 'Bearer some_apikey' # SyncAll after", "path == '/event-stream' qs = parse_qs(qs) assert qs['accessToken'][0] == (", "} def make_ably_error_event(code, status): \"\"\"Make a control event.\"\"\" return {", "request: sarasa', 'code': code, 'statusCode': status, 'href':\"https://help.ably.io/error/%d\" % code })", "the BE but don't send the event. # After restoring", "= Queue() split_backend = SplitMockServer(split_changes, segment_changes, split_backend_requests, auth_server_response) sse_requests =", "check it has nothing happened split_changes[1] = { 'since': 1,", "'till': 3, 'splits': []} sse_server.publish(make_split_change_event(3)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') ==", "properly.\"\"\" auth_server_response = { 'pushEnabled': True, 'token': ('<KEY> '<KEY>' '<KEY>'", "code, 'statusCode': status, 'href':\"https://help.ably.io/error/%d\" % code }) } def make_simple_split(name,", "'splits': []} sse_server.publish(make_ably_error_event(60000, 600)) time.sleep(1) assert factory.client().get_treatment('maldo', 'split1') == 'on'", "'split1') == 'off' # Re-publish initial events so that the", "urllib.parse import parse_qs except ImportError: from urlparse import parse_qs class", "SSEMockServer, SplitMockServer try: # try to import python3 names. fallback", "'userDefinedSegmentMatcherData': {'segmentName': segment}, 'whitelistMatcherData': None } ] }, 'partitions': [{", "make_split_change_event(change_number): \"\"\"Make a split change event.\"\"\" return { 'event': 'message',", "# SyncAll after push is up req = split_backend_requests.get() assert", "== 'frula' # Validate the SSE request sse_request = sse_requests.get()", "'controlType': control_type, }) }) } def make_ably_error_event(code, status): \"\"\"Make a", "second notification req = split_backend_requests.get() assert req.method == 'GET' assert", "'splits': []} sse_server.publish(make_split_change_event(4)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'off' assert", "'matcherType': 'IN_SEGMENT', 'negate': False, 'userDefinedSegmentMatcherData': {'segmentName': segment}, 'whitelistMatcherData': None }", "'GET' assert req.path == '/api/splitChanges?since=3' assert req.headers['authorization'] == 'Bearer some_apikey'", "should be fetched by the # sync all after streaming", "assert task.running() # We make another chagne in the BE", "'frula', 'user', False)] } split_changes[5] = {'since': 5, 'till': 5,", "time.sleep(2) # Get a hook of the task so we", "and send an event so it's propagated split_changes[3] = {", "Assert sync-task is running and the streaming status handler thread", "after streaming connected again req = split_backend_requests.get() assert req.method ==", "timestamp): \"\"\"Make a control event.\"\"\" return { 'event': 'message', 'data':", "[ { 'matcherType': 'IN_SEGMENT', 'negate': False, 'userDefinedSegmentMatcherData': {'segmentName': segment}, 'whitelistMatcherData':", "iteration of previous syncAll req = split_backend_requests.get() assert req.method ==", "and check it has nothing happened split_changes[1] = { 'since':", "'channel':'[?occupancy=metrics.publishers]control_pri', 'data': json.dumps({ 'type': 'CONTROL', 'controlType': control_type, }) }) }", "[]} sse_server.publish(make_split_change_event(2)) time.sleep(1) assert factory.client().get_treatment('maldo', 'split1') == 'off' split_changes[2] =", "== 'on' assert not task.running() # Send a non-retryable ably", "== '/api/splitChanges?since=4' assert req.headers['authorization'] == 'Bearer some_apikey' # Iteration until", "}) }) } def make_initial_event(): \"\"\"Make a split change event.\"\"\"", "Validate the SSE requests sse_request = sse_requests.get() assert sse_request.method ==", "'seed': 1699838640, 'status': 'ACTIVE' if active else 'ARCHIVED', 'changeNumber': cn,", "qs['accessToken'][0] == ( '<KEY>' 'US45QnJtR<KEY>' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' '<KEY>WJ<KEY>' '<KEY>' '<KEY>'", "%(levelname)-8s %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) logger.setLevel(logging.DEBUG) auth_server_response = { 'pushEnabled': True,", "def test_server_closes_connection(self): \"\"\"Test that if the server closes the connection,", "Assert streaming is working properly split_changes[2] = { 'since': 2,", "the SSE requests sse_request = sse_requests.get() assert sse_request.method == 'GET'", "streaming connected again req = split_backend_requests.get() assert req.method == 'GET'", "assert task.running() assert 'PushStatusHandler' not in [t.name for t in", "qs['accessToken'][0] == ( '<KEY>' '<KEY>' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib'", "to polling # and perform a syncAll that gets this", "default_treatment, 'changeNumber': change_number }) }) } def make_initial_event(): \"\"\"Make a", "'splits': []} sse_server.publish(make_control_event('STREAMING_DISABLED', 2)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'on'", "active, killed, default_treatment, tt, on): \"\"\"Make a simple split.\"\"\" return", "recoverable ably error req = split_backend_requests.get() assert req.method == 'GET'", "We'll send an ignorable error and check it has nothing", "{'publishers': publishers}}), 'name':'[meta]occupancy' }) } def make_segment_change_event(name, change_number): \"\"\"Make a", "'off' if on else 'on', 'size': 0} ] } ]", "# Assert streaming is working properly split_changes[2] = { 'since':", "fallback to python2 from urllib.parse import parse_qs except ImportError: from", "some_apikey' # SyncAll after push restored req = split_backend_requests.get() assert", "} split_changes[3] = {'since': 3, 'till': 3, 'splits': []} sse_server.publish(make_split_change_event(3))", "req.path == '/api/splitChanges?since=1' assert req.headers['authorization'] == 'Bearer some_apikey' # SyncAll", "control event.\"\"\" return { 'event': 'error', 'data': json.dumps({ 'message':'Invalid accessToken", "an SDK starting with occupancy on 0 and switching to", "'{\\'size\\':15,\\'test\\':20}' }, 'conditions': [ { 'matcherGroup': { 'combiner': 'AND', 'matchers':", "'event': 'error', 'data': json.dumps({ 'message':'Invalid accessToken in request: sarasa', 'code':", "sse_server.publish(SSEMockServer.GRACEFUL_REQUEST_END) time.sleep(1) assert factory.client().get_treatment('maldo', 'split1') == 'off' assert task.running() time.sleep(2)", "error sse_server.publish(make_ably_error_event(40200, 402)) sse_server.publish(sse_server.GRACEFUL_REQUEST_END) time.sleep(3) # Assert sync-task is running", "'user', False)] } split_changes[4] = {'since': 4, 'till': 4, 'splits':", "== 'Bearer some_apikey' # Cleanup destroy_event = threading.Event() factory.destroy(destroy_event) destroy_event.wait()", "Segment change notification req = split_backend_requests.get() assert req.method == 'GET'", "'GET' assert req.path == '/api/segmentChanges/segment1?since=-1' assert req.headers['authorization'] == 'Bearer some_apikey'", "req.headers['authorization'] == 'Bearer some_apikey' # Split kill req = split_backend_requests.get()", "assert req.headers['authorization'] == 'Bearer some_apikey' # Auth again req =", "json from queue import Queue from splitio.client.factory import get_factory from", "assert req.method == 'GET' assert req.path == '/api/splitChanges?since=-1' assert req.headers['authorization']", "after push restored req = split_backend_requests.get() assert req.method == 'GET'", "and the streaming status handler thread is over assert task.running()", "{ 'pushEnabled': True, 'token': ('<KEY> '<KEY>' '<KEY>' 'T1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcIjpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm' '9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJ' 'zXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzdWJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRh'", "return { 'event': 'message', 'data': json.dumps({ 'id':'TVUsxaabHs:0:0', 'clientId':'pri:MzM0ODI1MTkxMw==', 'timestamp': change_number-1,", "Auth again req = split_backend_requests.get() assert req.method == 'GET' assert", "some_apikey' # Iteration until segment1 since == till req =", "the # sync all after streaming is restored. split_changes[2] =", "} split_changes[3] = {'since': 3, 'till': 3, 'splits': []} sse_server.publish(make_occupancy('control_pri',", "'/api/splitChanges?since=4' assert req.headers['authorization'] == 'Bearer some_apikey' # Split kill req", "occupancy, the sdk should switch to polling # and perform", "# Re-publish initial events so that the retry succeeds sse_server.publish(make_initial_event())", "req.path == '/api/splitChanges?since=1' assert req.headers['authorization'] == 'Bearer some_apikey' # Second", "until since == till req = split_backend_requests.get() assert req.method ==", "sse_server.publish(make_segment_change_event('segment1', 1)) time.sleep(1) assert factory.client().get_treatment('pindon', 'split2') == 'off' assert factory.client().get_treatment('maldo',", "'matchers': [ { 'matcherType': 'ALL_KEYS', 'negate': False, 'userDefinedSegmentMatcherData': None, 'whitelistMatcherData':", "'event': 'message', 'data': json.dumps({ 'id':'TVUsxaabHs:0:0', 'clientId':'pri:MzM0ODI1MTkxMw==', 'timestamp': change_number-1, 'encoding':'json', 'channel':'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments',", "'zXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzdWJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRh' 'dGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFibHktY2xpZW50SWQiOiJjbGllbnRJZCIsImV4c' 'CI6MTYwNDEwMDU5MSwiaWF0IjoxNjA0MDk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5E' '<KEY>') } split_changes = { -1: {", "Queue from splitio.client.factory import get_factory from tests.helpers.mockserver import SSEMockServer, SplitMockServer", "[], 'removed': [], 'since': 1, 'till': 1} sse_server.publish(make_split_change_event(3)) time.sleep(1) sse_server.publish(make_segment_change_event('segment1',", "time.sleep(2) assert not task.running() split_changes[2] = { 'since': 2, 'till':", "} split_changes[2] = {'since': 2, 'till': 2, 'splits': []} sse_server.publish(make_occupancy('control_sec',", "import logging logger = logging.getLogger('splitio') handler = logging.StreamHandler() formatter =", "from tests.helpers.mockserver import SSEMockServer, SplitMockServer try: # try to import", "BO.\"\"\" auth_server_response = { 'pushEnabled': True, 'token': ('<KEY> '<KEY>' '<KEY>'", "task so we can query its status task = factory._sync_manager._synchronizer._split_tasks.split_task._task", "} def make_initial_event(): \"\"\"Make a split change event.\"\"\" return {'id':'TVUsxaabHs:0:0'}", "make_split_kill_event(name, default_treatment, change_number): \"\"\"Make a split change event.\"\"\" return {", "import time import json from queue import Queue from splitio.client.factory", "so we can query its status task = factory._sync_manager._synchronizer._split_tasks.split_task._task #", "1)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'off' assert task.running() #", "'off' assert task.running() time.sleep(2) # wait for the backoff to", "] }, 'partitions': [{ 'treatment': 'on' if on else 'off',", "'on', 'user', True)] }, 1: { 'since': 1, 'till': 1,", "'conditions': [ { 'matcherGroup': { 'combiner': 'AND', 'matchers': [ {", "100, 'impressionsRefreshRate': 100, 'eventsPushRate': 100} } factory = get_factory('some_apikey', **kwargs)", "since == till req = split_backend_requests.get() assert req.method == 'GET'", "parse_qs(qs) assert qs['accessToken'][0] == ( '<KEY>' '<KEY>' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' '<KEY>UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV<KEY>I' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaV<KEY>'", "req.headers['authorization'] == 'Bearer some_apikey' # Iteration until since == till", "time import json from queue import Queue from splitio.client.factory import", "'on' task = factory._sync_manager._synchronizer._split_tasks.split_task._task # pylint:disable=protected-access assert not task.running() time.sleep(1)", "== 'Bearer some_apikey' # Auth req = split_backend_requests.get() assert req.method", "'till': 5, 'splits': [make_simple_split('split1', 5, True, False, 'off', 'user', True)]", "req.method == 'GET' assert req.path == '/api/segmentChanges/segment1?since=1' assert req.headers['authorization'] ==", "task.running() assert 'PushStatusHandler' not in [t.name for t in threading.enumerate()]", "Send a non-retryable ably error sse_server.publish(make_ably_error_event(40200, 402)) sse_server.publish(sse_server.GRACEFUL_REQUEST_END) time.sleep(3) #", "We make another chagne in the BE and don't send", "'encoding':'json', 'channel':'[?occupancy=metrics.publishers]control_pri', 'data': json.dumps({ 'type': 'CONTROL', 'controlType': control_type, }) })", "('<KEY> '<KEY>' '<KEY>' '<KEY>' '<KEY>' '<KEY>' 'dGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFibHktY2xpZW50SWQiOiJjbGllbnRJZCIsImV4c' 'CI6MTYwNDEwMDU5MSwiaWF0IjoxNjA0MDk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5E' 'vJh17WlOlAKhcD0') }", "SyncAll after streaming connected req = split_backend_requests.get() assert req.method ==", "active else 'ARCHIVED', 'changeNumber': cn, 'killed': killed, 'defaultTreatment': default_treatment, 'conditions':", "def make_split_kill_event(name, default_treatment, change_number): \"\"\"Make a split change event.\"\"\" return", "assert not task.running() # Validate the SSE request sse_request =", "}) } def make_initial_event(): \"\"\"Make a split change event.\"\"\" return", "sse_server.publish(make_split_change_event(2)) time.sleep(1) assert factory.client().get_treatment('maldo', 'split1') == 'off' split_changes[2] = {", "split_changes[2] = {'since': 2, 'till': 2, 'splits': []} sse_server.publish(make_occupancy('control_sec', 1))", "validate its handling.\"\"\" import logging logger = logging.getLogger('splitio') handler =", "'Bearer some_apikey' # Initial splits fetch req = split_backend_requests.get() assert", "} ] }, 'partitions': [{ 'treatment': 'on' if on else", "# Make a change in the BE but don't send", "\"\"\"Test that if the server closes the connection, the whole", "0)) sse_server.publish(make_occupancy('control_sec', 0)) kwargs = { 'sdk_api_base_url': 'http://localhost:%d/api' % split_backend.port(),", "== '/api/splitChanges?since=2' assert req.headers['authorization'] == 'Bearer some_apikey' # Fetch after", "event. # After dropping occupancy, the sdk should switch to", "== 'Bearer some_apikey' # SyncAll after push down req =", "split_changes[4] = { 'since': 4, 'till': 5, 'splits': [make_simple_split('split1', 5,", "after streaming is restored. split_changes[2] = { 'since': 2, 'till':", "after push is up req = split_backend_requests.get() assert req.method ==", "destroy_event = threading.Event() factory.destroy(destroy_event) destroy_event.wait() sse_server.publish(sse_server.GRACEFUL_REQUEST_END) sse_server.stop() split_backend.stop() def test_ably_errors_handling(self):", "== 'on' assert not task.running() sse_server.publish(make_ably_error_event(40145, 401)) sse_server.publish(sse_server.GRACEFUL_REQUEST_END) time.sleep(3) assert", "another change and send an event so it's propagated split_changes[3]", "'splits': [make_simple_split('split1', 4, True, False, 'off', 'user', False)] } split_changes[4]", "import json from queue import Queue from splitio.client.factory import get_factory", "'Bearer some_apikey' # Fetch after notification req = split_backend_requests.get() assert", "# SyncAll after non recoverable ably error req = split_backend_requests.get()", "'/api/splitChanges?since=3' assert req.headers['authorization'] == 'Bearer some_apikey' # Fetch after notification", "'pushEnabled': True, 'token': ('<KEY> '<KEY>' '<KEY>' 'T1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcIjpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm' '9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJ' 'zXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzdWJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRh' 'dGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFibHktY2xpZW50SWQiOiJjbGllbnRJZCIsImV4c'", "req.path == '/api/segmentChanges/__SOME_INVALID_SEGMENT__?since=-1' assert req.headers['authorization'] == 'Bearer some_apikey' # Initial", "'type': 'CONTROL', 'controlType': control_type, }) }) } def make_ably_error_event(code, status):", "assert req.method == 'GET' assert req.path == '/api/splitChanges?since=2' assert req.headers['authorization']", "and disabled.\"\"\" auth_server_response = { 'pushEnabled': True, 'token': ('<KEY> '<KEY>'", "'<KEY>' '<KEY>' '<KEY>' 'dGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFibHktY2xpZW50SWQiOiJjbGllbnRJZCIsImV4c' 'CI6MTYwNDEwMDU5MSwiaWF0IjoxNjA0MDk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5E' 'vJh17WlOlAKhcD0') } split_changes = {", "syncAll req = split_backend_requests.get() assert req.method == 'GET' assert req.path", "time.sleep(3) assert task.running() assert factory.client().get_treatment('maldo', 'split1') == 'off' # Re-publish", "'size': 100}, {'treatment': 'off' if on else 'on', 'size': 0}", "assert not task.running() assert factory.client().get_treatment('maldo', 'split1') == 'on' # Make", "return {'id':'TVUsxaabHs:0:0'} def make_occupancy(channel, publishers): \"\"\"Make an occupancy event.\"\"\" return", "sse_server.stop() split_backend.stop() def make_split_change_event(change_number): \"\"\"Make a split change event.\"\"\" return", "{ 'pushEnabled': True, 'token': ('<KEY> '<KEY>' '<KEY>' '<KEY>' '<KEY>' '<KEY>'", "polling # and perform a syncAll that gets this change", "'Bearer some_apikey' # Fetch after first notification req = split_backend_requests.get()", "1)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'off' assert not task.running()", "def make_ably_error_event(code, status): \"\"\"Make a control event.\"\"\" return { 'event':", "Queue() sse_server = SSEMockServer(sse_requests) split_backend.start() sse_server.start() sse_server.publish(make_initial_event()) sse_server.publish(make_occupancy('control_pri', 0)) sse_server.publish(make_occupancy('control_sec',", "'split1') == 'on' assert not task.running() # Now we make", "'killed': killed, 'defaultTreatment': default_treatment, 'configurations': { 'on': '{\\'size\\':15,\\'test\\':20}' }, 'conditions':", "'splits': []} sse_server.publish(make_split_change_event(3)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'on' assert", "def test_happiness(self): \"\"\"Test initialization & splits/segment updates.\"\"\" auth_server_response = {", "integration tests.\"\"\" # pylint:disable=no-self-use,invalid-name,too-many-arguments,too-few-public-methods,line-too-long # pylint:disable=too-many-statements,too-many-locals,too-many-lines import threading import time", "assert req.headers['authorization'] == 'Bearer some_apikey' # SyncAll after push is", "with BO.\"\"\" auth_server_response = { 'pushEnabled': True, 'token': ('<KEY> '<KEY>'", "'/api/splitChanges?since=3' assert req.headers['authorization'] == 'Bearer some_apikey' # Iteration until since", "event.\"\"\" return {'id':'TVUsxaabHs:0:0'} def make_occupancy(channel, publishers): \"\"\"Make an occupancy event.\"\"\"", "'encoding':'json', 'channel':'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments', 'data': json.dumps({ 'type': 'SEGMENT_UPDATE', 'segmentName': name, 'changeNumber': change_number", "'user', 'off', 'segment1')] } split_changes[3] = {'since': 3, 'till': 3,", "split with a segment.\"\"\" return { 'trafficTypeName': tt, 'name': name,", "'off' # Re-publish initial events so that the retry succeeds", "= { 'sdk_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'events_api_base_url': 'http://localhost:%d/api' % split_backend.port(),", "1, 'splits': []} } segment_changes = {} split_backend_requests = Queue()", "split_changes[3] = {'since': 3, 'till': 3, 'splits': []} segment_changes[('segment1', -1)]", "[]} sse_server.publish(make_control_event('STREAMING_PAUSED', 1)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'off' assert", "'encoding':'json', 'channel':'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'data': json.dumps({ 'type': 'SPLIT_UPDATE', 'changeNumber': change_number }) })", "split change event.\"\"\" return { 'event': 'message', 'data': json.dumps({ 'id':'TVUsxaabHs:0:0',", "disabled.\"\"\" auth_server_response = { 'pushEnabled': True, 'token': ('<KEY> '<KEY>' '<KEY>'", "assert path == '/event-stream' qs = parse_qs(qs) assert qs['accessToken'][0] ==", "req.headers['authorization'] == 'Bearer some_apikey' # Initial splits fetch req =", "gets re-attached # re-send initial event AND occupancy sse_server.publish(make_initial_event()) sse_server.publish(make_occupancy('control_pri',", "} } segment_changes = {} split_backend_requests = Queue() split_backend =", "not task.running() # Now we make another change and send", "'splits': [make_split_with_segment('split2', 2, True, False, 'off', 'user', 'off', 'segment1')] }", "assert req.headers['authorization'] == 'Bearer some_apikey' # Fetch after first notification", "the split split_changes[4] = { 'since': 4, 'till': 5, 'splits':", "'/api/auth' assert req.headers['authorization'] == 'Bearer some_apikey' # SyncAll after streaming", "'split1') == 'off' assert not task.running() # Validate the SSE", "fetched by the # sync all after streaming is restored.", "True, False, 'off', 'user', True)] } split_changes[5] = {'since': 5,", "'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpY<KEY>bWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' '<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert set(qs['channels'][0].split(','))", "don't send the event. # After restoring occupancy, the sdk", "'since': 2, 'till': 3, 'splits': [make_simple_split('split1', 3, True, False, 'off',", "send the event. # After dropping occupancy, the sdk should", "whole flow is retried with BO.\"\"\" auth_server_response = { 'pushEnabled':", "'HktY2xpZW50SWQiOiJjbG<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert set(qs['channels'][0].split(',')) == set(['MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments', '[?occupancy=metrics.publishers]control_pri', '[?occupancy=metrics.publishers]control_sec'])", "destroy_event = threading.Event() factory.destroy(destroy_event) destroy_event.wait() sse_server.publish(sse_server.GRACEFUL_REQUEST_END) sse_server.stop() split_backend.stop() def test_start_without_occupancy(self):", "'name': name, 'seed': 1699838640, 'status': 'ACTIVE' if active else 'ARCHIVED',", "== '/api/splitChanges?since=3' assert req.headers['authorization'] == 'Bearer some_apikey' # SyncAll after", "{ 'event': 'message', 'data': json.dumps({ 'id':'TVUsxaabHs:0:0', 'clientId':'pri:MzM0ODI1MTkxMw==', 'timestamp': timestamp, 'encoding':'json',", "'configurations': { 'on': '{\\'size\\':15,\\'test\\':20}' }, 'conditions': [ { 'matcherGroup': {", "assert qs['accessToken'][0] == ( '<KEY>' '<KEY>2FwYWJpbGl0eSI6IntcIk1UW' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd'", "so it's propagated split_changes[3] = { 'since': 3, 'till': 4,", "'error', 'data': json.dumps({ 'message':'Invalid accessToken in request: sarasa', 'code': code,", "make_segment_change_event(name, change_number): \"\"\"Make a split change event.\"\"\" return { 'event':", "{ 'matcherGroup': { 'combiner': 'AND', 'matchers': [ { 'matcherType': 'ALL_KEYS',", "'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpY<KEY>bWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' '<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert set(qs['channels'][0].split(',')) == set(['MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits',", "sse_server.publish(make_occupancy('control_pri', 1)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'on' assert not", "# Second iteration of previous syncAll req = split_backend_requests.get() assert", "( '<KEY>' '<KEY>' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' '<KEY>UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV<KEY>I' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaV<KEY>' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXC<KEY>' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' '<KEY>' 'Dk2OTkxfQ.<KEY>'", "'since': 4, 'till': 5, 'splits': [make_simple_split('split1', 5, True, False, 'off',", "the task so we can query its status task =", "'http://localhost:%d/api' % split_backend.port(), 'auth_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'streaming_api_base_url': 'http://localhost:%d' %", "split_backend_requests.get() assert req.method == 'GET' assert req.path == '/api/segmentChanges/__SOME_INVALID_SEGMENT__?since=-1' assert", "sse_server.start() sse_server.publish(make_initial_event()) sse_server.publish(make_occupancy('control_pri', 0)) sse_server.publish(make_occupancy('control_sec', 0)) kwargs = { 'sdk_api_base_url':", "{ 'event': 'message', 'data': json.dumps({ 'id':'aP6EuhrcUm:0:0', 'timestamp':1604325712734, 'encoding': 'json', 'channel':", "req.headers['authorization'] == 'Bearer some_apikey' # SyncAll after push is up", "def test_streaming_status_changes(self): \"\"\"Test changes between streaming enabled, paused and disabled.\"\"\"", "'till': 2, 'splits': []} sse_server.publish(make_control_event('STREAMING_PAUSED', 1)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1')", "'<KEY>' '<KEY>' 'T1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcIjpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm' '9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJ' 'zXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzdWJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRh' 'dGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFibHktY2xpZW50SWQiOiJjbGllbnRJZCIsImV4c' 'CI6MTYwNDEwMDU5MSwiaWF0IjoxNjA0MDk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5E' '<KEY>') } split_changes", "'token': ('<KEY> '<KEY>' '<KEY>' '<KEY>' '<KEY>' '<KEY>' '<KEY>' '<KEY>' 'vJh17WlOlAKhcD0')", "disabled req = split_backend_requests.get() assert req.method == 'GET' assert req.path", "\"\"\"Test streaming operation and failover.\"\"\" def test_happiness(self): \"\"\"Test initialization &", "auth_server_response) sse_requests = Queue() sse_server = SSEMockServer(sse_requests) split_backend.start() sse_server.start() sse_server.publish(make_initial_event())", "threading.enumerate()] # Validate the SSE requests sse_request = sse_requests.get() assert", "'GET' assert req.path == '/api/splitChanges?since=-1' assert req.headers['authorization'] == 'Bearer some_apikey'", "{ 'since': 3, 'till': 4, 'splits': [make_simple_split('split1', 4, True, False,", "if the server closes the connection, the whole flow is", "segment1 since == till req = split_backend_requests.get() assert req.method ==", "= {'since': 3, 'till': 3, 'splits': []} sse_server.publish(make_occupancy('control_pri', 1)) time.sleep(2)", "some_apikey' # SyncAll after non recoverable ably error req =", "{'since': 3, 'till': 3, 'splits': []} segment_changes[('segment1', -1)] = {", "occupancy switch between polling & streaming properly.\"\"\" auth_server_response = {", "} segment_changes = {} split_backend_requests = Queue() split_backend = SplitMockServer(split_changes,", "sse_server.publish(sse_server.GRACEFUL_REQUEST_END) sse_server.stop() split_backend.stop() def test_occupancy_flicker(self): \"\"\"Test that changes in occupancy", "Second iteration of previous syncAll req = split_backend_requests.get() assert req.method", "factory.client().get_treatment('maldo', 'split1') == 'on' # Make a change in the", "'user', False)] } split_changes[5] = {'since': 5, 'till': 5, 'splits':", "False, 'userDefinedSegmentMatcherData': {'segmentName': segment}, 'whitelistMatcherData': None } ] }, 'partitions':", "'[?occupancy=metrics.publishers]control_sec']) assert qs['v'][0] == '1.1' assert sse_request.method == 'GET' path,", "req.path == '/api/splitChanges?since=1' assert req.headers['authorization'] == 'Bearer some_apikey' # Iteration", "some_apikey' # Iteration until since == till req = split_backend_requests.get()", "== ( '<KEY>' '<KEY>' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' 'HktY2xpZW<KEY>'", "SDK starting with occupancy on 0 and switching to streamin", "Re-publish initial events so that the retry succeeds sse_server.publish(make_initial_event()) sse_server.publish(make_occupancy('control_pri',", "'splitName': name, 'defaultTreatment': default_treatment, 'changeNumber': change_number }) }) } def", "We restore occupancy, and it should be fetched by the", "== 'on' # Make a change in the BE but", "'/api/splitChanges?since=1' assert req.headers['authorization'] == 'Bearer some_apikey' # SyncAll retriable error", "another chagne in the BE and don't send the event.", "req.headers['authorization'] == 'Bearer some_apikey' # Iteration until segment1 since ==", "'off', 'user', True)] }, 1: {'since': 1, 'till': 1, 'splits':", "t in threading.enumerate()] # Validate the SSE requests sse_request =", "event. # We'll send an ignorable error and check it", "changes in occupancy switch between polling & streaming properly.\"\"\" auth_server_response", "factory.destroy(destroy_event) destroy_event.wait() sse_server.publish(sse_server.GRACEFUL_REQUEST_END) sse_server.stop() split_backend.stop() def test_occupancy_flicker(self): \"\"\"Test that changes", "3, 'till': 3, 'splits': []} segment_changes[('segment1', -1)] = { 'name':", "send the event. # We'll send an ignorable error and", "'clientId':'pri:MzM0ODI1MTkxMw==', 'timestamp': change_number-1, 'encoding':'json', 'channel':'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'data': json.dumps({ 'type': 'SPLIT_KILL', 'splitName':", "'ALL_KEYS', 'negate': False, 'userDefinedSegmentMatcherData': None, 'whitelistMatcherData': None } ] },", "'till': 3, 'splits': [make_split_with_segment('split2', 2, True, False, 'off', 'user', 'off',", "'<KEY>' 'dGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFibHktY2xpZW50SWQiOiJjbGllbnRJZCIsImV4c' 'CI6MTYwNDEwMDU5MSwiaWF0IjoxNjA0MDk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5E' 'vJh17WlOlAKhcD0') } split_changes = { -1: {", "sync-task is running and the streaming status handler thread is", "killed, default_treatment, tt, on, segment): \"\"\"Make a split with a", "factory.client().get_treatment('maldo', 'split1') == 'off' assert not task.running() # Validate the", "def test_start_without_occupancy(self): \"\"\"Test an SDK starting with occupancy on 0", "SSE requests sse_request = sse_requests.get() assert sse_request.method == 'GET' path,", "nothing happened split_changes[1] = { 'since': 1, 'till': 2, 'splits':", "logging.getLogger('splitio') handler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')", "assert req.path == '/api/splitChanges?since=4' assert req.headers['authorization'] == 'Bearer some_apikey' #", "'split1') == 'on' assert not task.running() sse_server.publish(make_ably_error_event(40145, 401)) sse_server.publish(sse_server.GRACEFUL_REQUEST_END) time.sleep(3)", "= split_backend_requests.get() assert req.method == 'GET' assert req.path == '/api/splitChanges?since=1'", "qs['v'][0] == '1.1' assert sse_request.method == 'GET' path, qs =", "split_backend.port(), 'events_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'auth_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'streaming_api_base_url':", "factory.block_until_ready(1) assert factory.ready assert factory.client().get_treatment('maldo', 'split1') == 'on' time.sleep(1) split_changes[1]", "sse_server.publish(make_control_event('STREAMING_ENABLED', 2)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'on' assert not", "'<KEY>' 'T1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcIjpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm' '9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJ' 'zXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzdWJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRh' 'dGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFibHktY2xpZW50SWQiOiJjbGllbnRJZCIsImV4c' 'CI6MTYwNDEwMDU5MSwiaWF0IjoxNjA0MDk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5E' '<KEY>') } split_changes =", "AND occupancy sse_server.publish(make_initial_event()) sse_server.publish(make_occupancy('control_pri', 2)) sse_server.publish(make_occupancy('control_sec', 2)) time.sleep(2) assert not", "task.running() assert factory.client().get_treatment('maldo', 'split1') == 'off' # Re-publish initial events", "'partitions': [{ 'treatment': 'on' if on else 'off', 'size': 100", "is up req = split_backend_requests.get() assert req.method == 'GET' assert", "'off', 'user', True)] } split_changes[3] = {'since': 3, 'till': 3,", "# Auth again req = split_backend_requests.get() assert req.method == 'GET'", "'streaming_api_base_url': 'http://localhost:%d' % sse_server.port(), 'config': {'connectTimeout': 10000, 'featuresRefreshRate': 10} }", "is retried with BO.\"\"\" auth_server_response = { 'pushEnabled': True, 'token':", "qs['accessToken'][0] == ( '<KEY>' '<KEY>2FwYWJpbGl0eSI6IntcIk1UW' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpY<KEY>bWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib'", "restored req = split_backend_requests.get() assert req.method == 'GET' assert req.path", "'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' '<KEY>' 'Dk2OTkxfQ.<KEY>' ) assert set(qs['channels'][0].split(',')) == set(['MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments', '[?occupancy=metrics.publishers]control_pri',", "json.dumps({ 'id':'TVUsxaabHs:0:0', 'clientId':'pri:MzM0ODI1MTkxMw==', 'timestamp': timestamp, 'encoding':'json', 'channel':'[?occupancy=metrics.publishers]control_pri', 'data': json.dumps({ 'type':", "= parse_qs(qs) assert qs['accessToken'][0] == ( '<KEY>' '<KEY>' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' '<KEY>UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV<KEY>I'", "'till': 1, 'splits': [make_simple_split('split1', 1, True, False, 'on', 'user', True)]", "% split_backend.port(), 'auth_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'streaming_api_base_url': 'http://localhost:%d' % sse_server.port(),", "try to import python3 names. fallback to python2 from urllib.parse", "'split1') == 'on' task = factory._sync_manager._synchronizer._split_tasks.split_task._task # pylint:disable=protected-access assert not", "req.path == '/api/splitChanges?since=1' assert req.headers['authorization'] == 'Bearer some_apikey' # Auth", "'off', 'user', False)] } split_changes[4] = {'since': 4, 'till': 4,", "return { 'event': 'message', 'data': json.dumps({ 'id':'aP6EuhrcUm:0:0', 'timestamp':1604325712734, 'encoding': 'json',", "the whole flow is retried with BO.\"\"\" auth_server_response = {", "sse_server.publish(sse_server.GRACEFUL_REQUEST_END) sse_server.stop() split_backend.stop() def test_start_without_occupancy(self): \"\"\"Test an SDK starting with", "'whitelistMatcherData': None } ] }, 'partitions': [{ 'treatment': 'on' if", "2)) time.sleep(3) assert not task.running() # Assert streaming is working", "assert req.method == 'GET' assert req.path == '/api/auth' assert req.headers['authorization']", "factory = get_factory('some_apikey', **kwargs) factory.block_until_ready(1) assert factory.ready assert factory.client().get_treatment('maldo', 'split1')", "req.method == 'GET' assert req.path == '/api/auth' assert req.headers['authorization'] ==", "active else 'ARCHIVED', 'changeNumber': cn, 'killed': killed, 'defaultTreatment': default_treatment, 'configurations':", "status task = factory._sync_manager._synchronizer._split_tasks.split_task._task # pylint:disable=protected-access assert task.running() assert factory.client().get_treatment('maldo',", "assert req.path == '/api/segmentChanges/segment1?since=1' assert req.headers['authorization'] == 'Bearer some_apikey' #", "'negate': False, 'userDefinedSegmentMatcherData': {'segmentName': segment}, 'whitelistMatcherData': None } ] },", "'till': 2, 'splits': []} sse_server.publish(make_ably_error_event(60000, 600)) time.sleep(1) assert factory.client().get_treatment('maldo', 'split1')", "assert factory.client().get_treatment('maldo', 'split1') == 'off' assert not task.running() # Validate", "time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'off' # Kill the split", "\"\"\"Test an SDK starting with occupancy on 0 and switching", "assert req.method == 'GET' assert req.path == '/api/splitChanges?since=4' assert req.headers['authorization']", "except ImportError: from urlparse import parse_qs class StreamingIntegrationTests(object): \"\"\"Test streaming", "retryable error handling req = split_backend_requests.get() assert req.method == 'GET'", "'encoding':'json', 'channel':'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'data': json.dumps({ 'type': 'SPLIT_KILL', 'splitName': name, 'defaultTreatment': default_treatment,", "'Dk2OTkxfQ.<KEY>' ) assert set(qs['channels'][0].split(',')) == set(['MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments', '[?occupancy=metrics.publishers]control_pri', '[?occupancy=metrics.publishers]control_sec']) assert", "'till': 1, 'splits': [make_simple_split('split1', 1, True, False, 'off', 'user', True)]", "assert factory.client().get_treatment('maldo', 'split1') == 'off' assert not task.running() split_changes[4] =", "default_treatment, 'configurations': { 'on': '{\\'size\\':15,\\'test\\':20}' }, 'conditions': [ { 'matcherGroup':", "time.sleep(1) sse_server.publish(make_segment_change_event('segment1', 1)) time.sleep(1) assert factory.client().get_treatment('pindon', 'split2') == 'off' assert", "# Segment change notification req = split_backend_requests.get() assert req.method ==", "'splits': []} sse_server.publish(make_split_change_event(4)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'off' #", "sse_request.path.split('?', 1) assert path == '/event-stream' qs = parse_qs(qs) assert", "'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpY<KEY>bWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' '<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert set(qs['channels'][0].split(',')) ==", "'added': ['maldo'], 'removed': [], 'since': -1, 'till': 1 } segment_changes[('segment1',", "assert req.path == '/api/segmentChanges/__SOME_INVALID_SEGMENT__?since=-1' assert req.headers['authorization'] == 'Bearer some_apikey' #", "= split_backend_requests.get() assert req.method == 'GET' assert req.path == '/api/splitChanges?since=2'", "'splits': [make_simple_split('split1', 1, True, False, 'on', 'user', True)] }, 1:", "'user', True)] } split_changes[3] = {'since': 3, 'till': 3, 'splits':", "'channel':'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments', 'data': json.dumps({ 'type': 'SEGMENT_UPDATE', 'segmentName': name, 'changeNumber': change_number })", "= split_backend_requests.get() assert req.method == 'GET' assert req.path == '/api/auth'", "split_backend.port(), 'streaming_api_base_url': 'http://localhost:%d' % sse_server.port(), 'config': {'connectTimeout': 10000, 'featuresRefreshRate': 10}", "event.\"\"\" return { 'event': 'message', 'data': json.dumps({ 'id':'aP6EuhrcUm:0:0', 'timestamp':1604325712734, 'encoding':", "assert req.headers['authorization'] == 'Bearer some_apikey' # Second iteration of previous", "} factory = get_factory('some_apikey', **kwargs) factory.block_until_ready(1) assert factory.ready assert factory.client().get_treatment('maldo',", "req.headers['authorization'] == 'Bearer some_apikey' # Fetch after new notification req", "switch between polling & streaming properly.\"\"\" auth_server_response = { 'pushEnabled':", "req.headers['authorization'] == 'Bearer some_apikey' # Fetch after notification req =", "'<KEY>' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' '<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert", "req.path == '/api/splitChanges?since=2' assert req.headers['authorization'] == 'Bearer some_apikey' # Iteration", "'splits': []} sse_server.publish(make_split_kill_event('split1', 'frula', 5)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') ==", "True, False, 'off', 'user', False)] } split_changes[2] = {'since': 2,", "( '<KEY>' 'US45QnJtR0EiLCJ0eXAiOiJKV1QifQ.eyJ4LWFibHktY2FwYWJpbGl0eSI6IntcIk1UW' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' '<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0'", "between streaming enabled, paused and disabled.\"\"\" auth_server_response = { 'pushEnabled':", "from urlparse import parse_qs class StreamingIntegrationTests(object): \"\"\"Test streaming operation and", "False)] } split_changes[2] = {'since': 2, 'till': 2, 'splits': []}", "'<KEY>' '<KEY>' '<KEY>' '<KEY>' 'vJh17WlOlAKhcD0') } split_changes = { -1:", "assert req.path == '/api/splitChanges?since=5' assert req.headers['authorization'] == 'Bearer some_apikey' #", "( '<KEY>' '<KEY>' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' '<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0'", "'data': json.dumps({ 'message':'Invalid accessToken in request: sarasa', 'code': code, 'statusCode':", "# Fetch after second notification req = split_backend_requests.get() assert req.method", "change and send an event so it's propagated split_changes[3] =", "'<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert set(qs['channels'][0].split(',')) == set(['MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments', '[?occupancy=metrics.publishers]control_pri', '[?occupancy=metrics.publishers]control_sec'])", "{'since': 2, 'till': 2, 'splits': []} sse_server.publish(make_occupancy('control_sec', 1)) time.sleep(2) assert", "name, 'defaultTreatment': default_treatment, 'changeNumber': change_number }) }) } def make_initial_event():", "flow is retried with BO.\"\"\" auth_server_response = { 'pushEnabled': True,", "5, True, False, 'off', 'user', True)] } split_changes[5] = {'since':", "'changeNumber': cn, 'killed': killed, 'defaultTreatment': default_treatment, 'conditions': [ { 'matcherGroup':", "'till': 5, 'splits': [make_simple_split('split1', 5, True, True, 'frula', 'user', False)]", "the sdk should switch to polling # and perform a", "wait for the backoff to expire so streaming gets re-attached", "'events_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'auth_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'streaming_api_base_url': 'http://localhost:%d'", "Queue() sse_server = SSEMockServer(sse_requests) split_backend.start() sse_server.start() sse_server.publish(make_initial_event()) sse_server.publish(make_occupancy('control_pri', 2)) sse_server.publish(make_occupancy('control_sec',", "else 'ARCHIVED', 'changeNumber': cn, 'killed': killed, 'defaultTreatment': default_treatment, 'configurations': {", "ably error req = split_backend_requests.get() assert req.method == 'GET' assert", "== 'off' sse_server.publish(SSEMockServer.GRACEFUL_REQUEST_END) time.sleep(1) assert factory.client().get_treatment('maldo', 'split1') == 'off' assert", "== ( '<KEY>' '<KEY>2FwYWJpbGl0eSI6IntcIk1UW' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpY<KEY>bWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' '<KEY>'", "'data': json.dumps({ 'id':'aP6EuhrcUm:0:0', 'timestamp':1604325712734, 'encoding': 'json', 'channel': \"[?occupancy=metrics.publishers]%s\" % channel,", "} split_changes[3] = {'since': 3, 'till': 3, 'splits': []} sse_server.publish(make_control_event('STREAMING_ENABLED',", "path, qs = sse_request.path.split('?', 1) assert path == '/event-stream' qs", "assert req.method == 'GET' assert req.path == '/api/splitChanges?since=3' assert req.headers['authorization']", "assert task.running() assert factory.client().get_treatment('maldo', 'split1') == 'on' # Make a", "5, 'splits': []} sse_server.publish(make_control_event('STREAMING_DISABLED', 2)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') ==", "return { 'trafficTypeName': tt, 'name': name, 'seed': 1699838640, 'status': 'ACTIVE'", "} split_changes[2] = {'since': 2, 'till': 2, 'splits': []} sse_server.publish(make_occupancy('control_pri',", "assert factory.client().get_treatment('maldo', 'split2') == 'on' # Validate the SSE request", "make_occupancy(channel, publishers): \"\"\"Make an occupancy event.\"\"\" return { 'event': 'message',", "'event': 'message', 'data': json.dumps({ 'id':'TVUsxaabHs:0:0', 'clientId':'pri:MzM0ODI1MTkxMw==', 'timestamp': timestamp, 'encoding':'json', 'channel':'[?occupancy=metrics.publishers]control_pri',", "}, 'conditions': [ { 'matcherGroup': { 'combiner': 'AND', 'matchers': [", "factory.client().get_treatment('maldo', 'split1') == 'on' assert not task.running() # Now we", "task.running() # Now we make another change and send an", "assert req.headers['authorization'] == 'Bearer some_apikey' # SyncAll after push down", "assert req.path == '/api/splitChanges?since=1' assert req.headers['authorization'] == 'Bearer some_apikey' #", "'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' 'HktY2xpZW50SWQiOiJjbG<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert set(qs['channels'][0].split(',')) == set(['MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits',", "req.path == '/api/splitChanges?since=3' assert req.headers['authorization'] == 'Bearer some_apikey' # Segment", "status): \"\"\"Make a control event.\"\"\" return { 'event': 'error', 'data':", "'pushEnabled': True, 'token': ('<KEY> '<KEY>' '<KEY>' '<KEY>' '<KEY>' '<KEY>' '<KEY>'", "default_treatment, tt, on): \"\"\"Make a simple split.\"\"\" return { 'trafficTypeName':", "time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'on' assert not task.running() #", "{'name': 'segment1', 'added': [], 'removed': [], 'since': 1, 'till': 1}", "{ 'on': '{\\'size\\':15,\\'test\\':20}' }, 'conditions': [ { 'matcherGroup': { 'combiner':", "paused and disabled.\"\"\" auth_server_response = { 'pushEnabled': True, 'token': ('<KEY>", "event.\"\"\" return { 'event': 'error', 'data': json.dumps({ 'message':'Invalid accessToken in", "= threading.Event() factory.destroy(destroy_event) destroy_event.wait() sse_server.publish(sse_server.GRACEFUL_REQUEST_END) sse_server.stop() split_backend.stop() def test_ably_errors_handling(self): \"\"\"Test", "= Queue() sse_server = SSEMockServer(sse_requests) split_backend.start() sse_server.start() sse_server.publish(make_initial_event()) sse_server.publish(make_occupancy('control_pri', 2))", "{ 'since': 4, 'till': 5, 'splits': [make_simple_split('split1', 5, True, False,", "change split_changes[1] = { 'since': 1, 'till': 2, 'splits': [make_simple_split('split1',", "assert task.running() time.sleep(2) # wait for the backoff to expire", "True, 'token': ('<KEY> '<KEY>' '<KEY>' '<KEY>' '<KEY>' '<KEY>' 'dGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFibHktY2xpZW50SWQiOiJjbGllbnRJZCIsImV4c' 'CI6MTYwNDEwMDU5MSwiaWF0IjoxNjA0MDk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5E'", "assert factory.client().get_treatment('maldo', 'split1') == 'on' time.sleep(1) split_changes[1] = { 'since':", "'streaming_api_base_url': 'http://localhost:%d' % sse_server.port(), 'config': {'connectTimeout': 10000, 'featuresRefreshRate': 100, 'segmentsRefreshRate':", "'on' if on else 'off', 'size': 100 }] } ]", "expire so streaming gets re-attached # re-send initial event AND", "== '/api/splitChanges?since=1' assert req.headers['authorization'] == 'Bearer some_apikey' # SyncAll on", "queue import Queue from splitio.client.factory import get_factory from tests.helpers.mockserver import", "the SSE request sse_request = sse_requests.get() assert sse_request.method == 'GET'", "'/api/splitChanges?since=4' assert req.headers['authorization'] == 'Bearer some_apikey' # SyncAll after streaming", "on push down req = split_backend_requests.get() assert req.method == 'GET'", "'split1') == 'on' # Make a change in the BE", "cn, 'status': 'ACTIVE' if active else 'ARCHIVED', 'changeNumber': cn, 'killed':", "] }, 'partitions': [ {'treatment': 'on' if on else 'off',", "req.method == 'GET' assert req.path == '/api/segmentChanges/segment1?since=-1' assert req.headers['authorization'] ==", "}) }) } def make_control_event(control_type, timestamp): \"\"\"Make a control event.\"\"\"", "'till': 3, 'splits': [make_simple_split('split1', 3, True, False, 'off', 'user', True)]", "logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) logger.setLevel(logging.DEBUG) auth_server_response = {", "2)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'on' assert not task.running()", "= threading.Event() factory.destroy(destroy_event) destroy_event.wait() sse_server.publish(sse_server.GRACEFUL_REQUEST_END) sse_server.stop() split_backend.stop() def test_start_without_occupancy(self): \"\"\"Test", "task.running() # Assert streaming is working properly split_changes[2] = {", "but don't send the event. # After restoring occupancy, the", "some_apikey' # SyncAll after streaming connected req = split_backend_requests.get() assert", "== '/api/splitChanges?since=4' assert req.headers['authorization'] == 'Bearer some_apikey' # Split kill", "'config': {'connectTimeout': 10000} } factory = get_factory('some_apikey', **kwargs) factory.block_until_ready(1) assert", "streaming disabled req = split_backend_requests.get() assert req.method == 'GET' assert", "'segment1', 'added': ['maldo'], 'removed': [], 'since': -1, 'till': 1 }", "('<KEY> '<KEY>' '<KEY>' 'T1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcIjpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm' '9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJ' 'zXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzdWJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRh' 'dGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFibHktY2xpZW50SWQiOiJjbGllbnRJZCIsImV4c' 'CI6MTYwNDEwMDU5MSwiaWF0IjoxNjA0MDk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5E' '<KEY>') }", "== 'Bearer some_apikey' # Initial splits fetch req = split_backend_requests.get()", "1, 'till': 1, 'splits': []} } segment_changes = {} split_backend_requests", "'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' 'HktY2xpZW50SWQiOiJjbG<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert set(qs['channels'][0].split(',')) == set(['MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments', '[?occupancy=metrics.publishers]control_pri',", "req.path == '/api/splitChanges?since=3' assert req.headers['authorization'] == 'Bearer some_apikey' # SyncAll", "Kill the split split_changes[4] = { 'since': 4, 'till': 5,", "'type': 'SPLIT_UPDATE', 'changeNumber': change_number }) }) } def make_split_kill_event(name, default_treatment,", "== '/api/splitChanges?since=1' assert req.headers['authorization'] == 'Bearer some_apikey' # Auth req", "validation req = split_backend_requests.get() assert req.method == 'GET' assert req.path", "assert qs['accessToken'][0] == ( '<KEY>' 'US45QnJtR0EiLCJ0eXAiOiJKV1QifQ.eyJ4LWFibHktY2FwYWJpbGl0eSI6IntcIk1UW' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd'", "= { 'since': 4, 'till': 5, 'splits': [make_simple_split('split1', 5, True,", "send the event. # We restore occupancy, and it should", "to expire so streaming gets re-attached # re-send initial event", "sse_requests = Queue() sse_server = SSEMockServer(sse_requests) split_backend.start() sse_server.start() sse_server.publish(make_initial_event()) sse_server.publish(make_occupancy('control_pri',", "== '/api/segmentChanges/__SOME_INVALID_SEGMENT__?since=-1' assert req.headers['authorization'] == 'Bearer some_apikey' # Initial splits", "task = factory._sync_manager._synchronizer._split_tasks.split_task._task # pylint:disable=protected-access assert not task.running() time.sleep(1) split_changes[1]", "\"\"\"Make a split with a segment.\"\"\" return { 'trafficTypeName': tt,", "'splits': []} sse_server.publish(make_occupancy('control_pri', 0)) sse_server.publish(make_occupancy('control_sec', 0)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1')", "sse_server.publish(make_initial_event()) sse_server.publish(make_occupancy('control_pri', 2)) sse_server.publish(make_occupancy('control_sec', 2)) kwargs = { 'sdk_api_base_url': 'http://localhost:%d/api'", "'<KEY>' '<KEY>' '<KEY>' '<KEY>' '<KEY>' 'CI6MTYwNDEwMDU5MSwiaWF0IjoxNjA0MDk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5E' 'vJh17WlOlAKhcD0') } split_changes =", "a split change event.\"\"\" return { 'event': 'message', 'data': json.dumps({", "== '/api/splitChanges?since=3' assert req.headers['authorization'] == 'Bearer some_apikey' # Fetch after", "'Bearer some_apikey' # Split kill req = split_backend_requests.get() assert req.method", "sse_server = SSEMockServer(sse_requests) split_backend.start() sse_server.start() sse_server.publish(make_initial_event()) sse_server.publish(make_occupancy('control_pri', 0)) sse_server.publish(make_occupancy('control_sec', 0))", "'till': 2, 'splits': []} sse_server.publish(make_split_change_event(2)) time.sleep(1) assert factory.client().get_treatment('maldo', 'split1') ==", "split_backend.start() sse_server.start() sse_server.publish(make_initial_event()) sse_server.publish(make_occupancy('control_pri', 0)) sse_server.publish(make_occupancy('control_sec', 0)) kwargs = {", "apikey validation req = split_backend_requests.get() assert req.method == 'GET' assert", "== 'Bearer some_apikey' # SyncAll retriable error req = split_backend_requests.get()", "push down req = split_backend_requests.get() assert req.method == 'GET' assert", "'splits': []} sse_server.publish(make_occupancy('control_sec', 1)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'off'", "== 'Bearer some_apikey' # Fetch after new notification req =", "'Bearer some_apikey' # Segment change notification req = split_backend_requests.get() assert", "split_backend_requests.get() assert req.method == 'GET' assert req.path == '/api/splitChanges?since=4' assert", "the BE but don't send the event. # We'll send", "json.dumps({ 'id':'TVUsxaabHs:0:0', 'clientId':'pri:MzM0ODI1MTkxMw==', 'timestamp': change_number-1, 'encoding':'json', 'channel':'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'data': json.dumps({ 'type':", "'vJh17WlOlAKhcD0') } split_changes = { -1: { 'since': -1, 'till':", "{ 'trafficTypeName': tt, 'name': name, 'seed': 1699838640, 'status': 'ACTIVE' if", "assert factory.ready assert factory.client().get_treatment('maldo', 'split1') == 'on' task = factory._sync_manager._synchronizer._split_tasks.split_task._task", "'id':'aP6EuhrcUm:0:0', 'timestamp':1604325712734, 'encoding': 'json', 'channel': \"[?occupancy=metrics.publishers]%s\" % channel, 'data': json.dumps({'metrics':", "'split1') == 'off' split_changes[2] = { 'since': 2, 'till': 3,", "retriable error req = split_backend_requests.get() assert req.method == 'GET' assert", "'href':\"https://help.ably.io/error/%d\" % code }) } def make_simple_split(name, cn, active, killed,", "req.headers['authorization'] == 'Bearer some_apikey' # Cleanup destroy_event = threading.Event() factory.destroy(destroy_event)", "Fetch after second notification req = split_backend_requests.get() assert req.method ==", "assert qs['v'][0] == '1.1' # Initial apikey validation req =", "event so it's propagated split_changes[3] = { 'since': 3, 'till':", "req.headers['authorization'] == 'Bearer some_apikey' # Second iteration of previous syncAll", "'/api/auth' assert req.headers['authorization'] == 'Bearer some_apikey' # SyncAll after push", "error and check it has nothing happened split_changes[1] = {", "'negate': False, 'userDefinedSegmentMatcherData': None, 'whitelistMatcherData': None } ] }, 'partitions':", "'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' '<KEY>UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV<KEY>I' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaV<KEY>' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXC<KEY>' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' '<KEY>' 'Dk2OTkxfQ.<KEY>' ) assert set(qs['channels'][0].split(','))", "factory.block_until_ready(1) assert factory.ready assert factory.client().get_treatment('maldo', 'split1') == 'on' task =", "'GET' path, qs = sse_request.path.split('?', 1) assert path == '/event-stream'", "SyncAll after streaming disabled req = split_backend_requests.get() assert req.method ==", "assert set(qs['channels'][0].split(',')) == set(['MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments', '[?occupancy=metrics.publishers]control_pri', '[?occupancy=metrics.publishers]control_sec']) assert qs['v'][0] ==", "change_number): \"\"\"Make a split change event.\"\"\" return { 'event': 'message',", "== 'GET' assert req.path == '/api/splitChanges?since=2' assert req.headers['authorization'] == 'Bearer", "1, 'splits': [] } } segment_changes = {} split_backend_requests =", "get_factory from tests.helpers.mockserver import SSEMockServer, SplitMockServer try: # try to", "tests.helpers.mockserver import SSEMockServer, SplitMockServer try: # try to import python3", "split_changes[2] = {'since': 2, 'till': 2, 'splits': []} sse_server.publish(make_occupancy('control_pri', 0))", "'message', 'data': json.dumps({ 'id':'TVUsxaabHs:0:0', 'clientId':'pri:MzM0ODI1MTkxMw==', 'timestamp': change_number-1, 'encoding':'json', 'channel':'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments', 'data':", "can query its status task = factory._sync_manager._synchronizer._split_tasks.split_task._task # pylint:disable=protected-access assert", "in the BE and don't send the event. # We", "req.method == 'GET' assert req.path == '/api/splitChanges?since=2' assert req.headers['authorization'] ==", "# Cleanup destroy_event = threading.Event() factory.destroy(destroy_event) destroy_event.wait() sse_server.publish(sse_server.GRACEFUL_REQUEST_END) sse_server.stop() split_backend.stop()", "'off', 'segment1')] } split_changes[3] = {'since': 3, 'till': 3, 'splits':", "import parse_qs except ImportError: from urlparse import parse_qs class StreamingIntegrationTests(object):", "'2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' 'HktY2xpZW<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert set(qs['channels'][0].split(',')) == set(['MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments',", "from urllib.parse import parse_qs except ImportError: from urlparse import parse_qs", "} def make_split_with_segment(name, cn, active, killed, default_treatment, tt, on, segment):", "3, 'splits': []} sse_server.publish(make_control_event('STREAMING_ENABLED', 2)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') ==", "'clientId':'pri:MzM0ODI1MTkxMw==', 'timestamp': change_number-1, 'encoding':'json', 'channel':'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments', 'data': json.dumps({ 'type': 'SEGMENT_UPDATE', 'segmentName':", "errors and validate its handling.\"\"\" import logging logger = logging.getLogger('splitio')", "2, 'till': 3, 'splits': [make_split_with_segment('split2', 2, True, False, 'off', 'user',", "== 'Bearer some_apikey' # Fetch after second notification req =", "} def make_split_kill_event(name, default_treatment, change_number): \"\"\"Make a split change event.\"\"\"", "'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' 'HktY2xpZW<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert set(qs['channels'][0].split(','))", "\"\"\"Test changes between streaming enabled, paused and disabled.\"\"\" auth_server_response =", "so that the retry succeeds sse_server.publish(make_initial_event()) sse_server.publish(make_occupancy('control_pri', 2)) sse_server.publish(make_occupancy('control_sec', 2))", "the BE but don't send the event. # After dropping", "req.path == '/api/splitChanges?since=3' assert req.headers['authorization'] == 'Bearer some_apikey' # Fetch", "= {'since': 5, 'till': 5, 'splits': []} sse_server.publish(make_control_event('STREAMING_DISABLED', 2)) time.sleep(2)", "formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) logger.setLevel(logging.DEBUG) auth_server_response", "splitio.client.factory import get_factory from tests.helpers.mockserver import SSEMockServer, SplitMockServer try: #", "'/event-stream' qs = parse_qs(qs) assert qs['accessToken'][0] == ( '<KEY>' '<KEY>'", "SplitMockServer(split_changes, segment_changes, split_backend_requests, auth_server_response) sse_requests = Queue() sse_server = SSEMockServer(sse_requests)", "sse_server.publish(make_occupancy('control_sec', 2)) kwargs = { 'sdk_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'events_api_base_url':", "backoff to expire so streaming gets re-attached # re-send initial", "'killed': killed, 'defaultTreatment': default_treatment, 'conditions': [ { 'matcherGroup': { 'combiner':", "it has nothing happened split_changes[1] = { 'since': 1, 'till':", "{'since': 2, 'till': 2, 'splits': []} sse_server.publish(make_ably_error_event(60000, 600)) time.sleep(1) assert", "Iteration until segment1 since == till req = split_backend_requests.get() assert", "tests.\"\"\" # pylint:disable=no-self-use,invalid-name,too-many-arguments,too-few-public-methods,line-too-long # pylint:disable=too-many-statements,too-many-locals,too-many-lines import threading import time import", "= split_backend_requests.get() assert req.method == 'GET' assert req.path == '/api/segmentChanges/segment1?since=-1'", "'whitelistMatcherData': None } ] }, 'partitions': [ {'treatment': 'on' if", "factory.ready time.sleep(2) # Get a hook of the task so", "== 'on' assert not task.running() # Now we make another", "gets this change split_changes[1] = { 'since': 1, 'till': 2,", "change_number-1, 'encoding':'json', 'channel':'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'data': json.dumps({ 'type': 'SPLIT_KILL', 'splitName': name, 'defaultTreatment':", "== 'GET' assert req.path == '/api/splitChanges?since=-1' assert req.headers['authorization'] == 'Bearer", "{'connectTimeout': 10000, 'featuresRefreshRate': 10} } factory = get_factory('some_apikey', **kwargs) factory.block_until_ready(1)", "# Get a hook of the task so we can", "{'since': 3, 'till': 3, 'splits': []} sse_server.publish(make_split_change_event(3)) time.sleep(1) assert factory.client().get_treatment('maldo',", "'config': {'connectTimeout': 10000, 'featuresRefreshRate': 100, 'segmentsRefreshRate': 100, 'metricsRefreshRate': 100, 'impressionsRefreshRate':", "in the BE but don't send the event. # After", "SSE request sse_request = sse_requests.get() assert sse_request.method == 'GET' path,", "'Bearer some_apikey' # SyncAll after streaming disabled req = split_backend_requests.get()", "2, 'till': 2, 'splits': []} sse_server.publish(make_split_change_event(2)) time.sleep(1) assert factory.client().get_treatment('maldo', 'split1')", "3, 'splits': [make_split_with_segment('split2', 2, True, False, 'off', 'user', 'off', 'segment1')]", "'/api/splitChanges?since=2' assert req.headers['authorization'] == 'Bearer some_apikey' # SyncAll on retryable", "= parse_qs(qs) assert qs['accessToken'][0] == ( '<KEY>' 'US45QnJtR0EiLCJ0eXAiOiJKV1QifQ.eyJ4LWFibHktY2FwYWJpbGl0eSI6IntcIk1UW' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI'", "'type': 'SEGMENT_UPDATE', 'segmentName': name, 'changeNumber': change_number }) }) } def", "new notification req = split_backend_requests.get() assert req.method == 'GET' assert", "change notification req = split_backend_requests.get() assert req.method == 'GET' assert", "== '/api/splitChanges?since=3' assert req.headers['authorization'] == 'Bearer some_apikey' # Cleanup destroy_event", "streaming status handler thread is over assert task.running() assert 'PushStatusHandler'", "[]} sse_server.publish(make_control_event('STREAMING_ENABLED', 2)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'on' assert", "{'connectTimeout': 10000} } factory = get_factory('some_apikey', **kwargs) factory.block_until_ready(1) assert factory.ready", "a syncAll that gets this change split_changes[1] = { 'since':", "== 'GET' assert req.path == '/api/segmentChanges/segment1?since=1' assert req.headers['authorization'] == 'Bearer", "breaks req = split_backend_requests.get() assert req.method == 'GET' assert req.path", "== 'on' time.sleep(1) split_changes[1] = { 'since': 1, 'till': 2,", "'split2') == 'off' assert factory.client().get_treatment('maldo', 'split2') == 'on' # Validate", "change_number-1, 'encoding':'json', 'channel':'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'data': json.dumps({ 'type': 'SPLIT_UPDATE', 'changeNumber': change_number })", "in threading.enumerate()] # Validate the SSE requests sse_request = sse_requests.get()", "propagated split_changes[3] = { 'since': 3, 'till': 4, 'splits': [make_simple_split('split1',", "{ 'sdk_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'events_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'auth_api_base_url':", "factory.destroy(destroy_event) destroy_event.wait() sse_server.publish(sse_server.GRACEFUL_REQUEST_END) sse_server.stop() split_backend.stop() def test_ably_errors_handling(self): \"\"\"Test incoming ably", "= {'since': 5, 'till': 5, 'splits': []} sse_server.publish(make_split_kill_event('split1', 'frula', 5))", "2)) time.sleep(2) assert not task.running() split_changes[2] = { 'since': 2,", "Now we make another change and send an event so", "time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'off' assert task.running() # We", "== 'off' assert task.running() time.sleep(2) # wait for the backoff", "sse_server.stop() split_backend.stop() def test_start_without_occupancy(self): \"\"\"Test an SDK starting with occupancy", "2, True, False, 'off', 'user', 'off', 'segment1')] } split_changes[3] =", "make_simple_split(name, cn, active, killed, default_treatment, tt, on): \"\"\"Make a simple", "segment_changes[('segment1', 1)] = {'name': 'segment1', 'added': [], 'removed': [], 'since':", "}, 'partitions': [ {'treatment': 'on' if on else 'off', 'size':", "5, True, True, 'frula', 'user', False)] } split_changes[5] = {'since':", "'code': code, 'statusCode': status, 'href':\"https://help.ably.io/error/%d\" % code }) } def", "over assert task.running() assert 'PushStatusHandler' not in [t.name for t", "killed, default_treatment, tt, on): \"\"\"Make a simple split.\"\"\" return {", "afterwards.\"\"\" auth_server_response = { 'pushEnabled': True, 'token': ('<KEY> '<KEY>' '<KEY>'", "pylint:disable=protected-access assert task.running() assert factory.client().get_treatment('maldo', 'split1') == 'on' # Make", "100, 'eventsPushRate': 100} } factory = get_factory('some_apikey', **kwargs) factory.block_until_ready(1) assert", "1 } segment_changes[('segment1', 1)] = {'name': 'segment1', 'added': [], 'removed':", "test_server_closes_connection(self): \"\"\"Test that if the server closes the connection, the", "'<KEY>' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' 'HktY2xpZW<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert", "} split_changes[4] = {'since': 4, 'till': 4, 'splits': []} sse_server.publish(make_split_change_event(4))", "# Validate the SSE request sse_request = sse_requests.get() assert sse_request.method", "'[?occupancy=metrics.publishers]control_sec']) assert qs['v'][0] == '1.1' sse_request = sse_requests.get() assert sse_request.method", "'/api/segmentChanges/segment1?since=1' assert req.headers['authorization'] == 'Bearer some_apikey' # Cleanup destroy_event =", "factory.client().get_treatment('maldo', 'split1') == 'on' assert not task.running() sse_server.publish(make_ably_error_event(40145, 401)) sse_server.publish(sse_server.GRACEFUL_REQUEST_END)", "'sdk_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'events_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'auth_api_base_url': 'http://localhost:%d/api'", "req.headers['authorization'] == 'Bearer some_apikey' # Fetch after second notification req", "publishers}}), 'name':'[meta]occupancy' }) } def make_segment_change_event(name, change_number): \"\"\"Make a split", "'impressionsRefreshRate': 100, 'eventsPushRate': 100} } factory = get_factory('some_apikey', **kwargs) factory.block_until_ready(1)", "'token': ('<KEY> '<KEY>' '<KEY>' 'T1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcIjpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm' '9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJ' 'zXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzdWJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRh' 'dGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFibHktY2xpZW50SWQiOiJjbGllbnRJZCIsImV4c' 'CI6MTYwNDEwMDU5MSwiaWF0IjoxNjA0MDk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5E' '<KEY>')", "BE but don't send the event. # After restoring occupancy,", "change_number-1, 'encoding':'json', 'channel':'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments', 'data': json.dumps({ 'type': 'SEGMENT_UPDATE', 'segmentName': name, 'changeNumber':", "'split1') == 'on' assert not task.running() # Validate the SSE", "SSEMockServer(sse_requests) split_backend.start() sse_server.start() sse_server.publish(make_initial_event()) sse_server.publish(make_occupancy('control_pri', 0)) sse_server.publish(make_occupancy('control_sec', 0)) kwargs =", "def make_occupancy(channel, publishers): \"\"\"Make an occupancy event.\"\"\" return { 'event':", "sse_server.publish(make_split_change_event(3)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'on' assert not task.running()", "3, 'splits': []} sse_server.publish(make_split_change_event(3)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'on'", "'GET' assert req.path == '/api/auth' assert req.headers['authorization'] == 'Bearer some_apikey'", "'<KEY>' '<KEY>' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' '<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' )", "'defaultTreatment': default_treatment, 'conditions': [ { 'matcherGroup': { 'combiner': 'AND', 'matchers':", "= split_backend_requests.get() assert req.method == 'GET' assert req.path == '/api/segmentChanges/segment1?since=1'", "return { 'event': 'message', 'data': json.dumps({ 'id':'TVUsxaabHs:0:0', 'clientId':'pri:MzM0ODI1MTkxMw==', 'timestamp': timestamp,", "initial events so that the retry succeeds sse_server.publish(make_initial_event()) sse_server.publish(make_occupancy('control_pri', 2))", "[]} sse_server.publish(make_occupancy('control_pri', 0)) sse_server.publish(make_occupancy('control_sec', 0)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') ==", "make another change and send an event so it's propagated", "% code }) } def make_simple_split(name, cn, active, killed, default_treatment,", "task.running() # Validate the SSE request sse_request = sse_requests.get() assert", "that the retry succeeds sse_server.publish(make_initial_event()) sse_server.publish(make_occupancy('control_pri', 2)) sse_server.publish(make_occupancy('control_sec', 2)) time.sleep(3)", "== '/api/splitChanges?since=2' assert req.headers['authorization'] == 'Bearer some_apikey' # SyncAll after", "req.headers['authorization'] == 'Bearer some_apikey' # Fetch after first notification req", "= {'since': 2, 'till': 2, 'splits': []} sse_server.publish(make_occupancy('control_pri', 0)) sse_server.publish(make_occupancy('control_sec',", "== '/api/splitChanges?since=2' assert req.headers['authorization'] == 'Bearer some_apikey' # Cleanup destroy_event", "python2 from urllib.parse import parse_qs except ImportError: from urlparse import", "a simple split.\"\"\" return { 'trafficTypeName': tt, 'name': name, 'seed':", "sse_server.publish(make_ably_error_event(40200, 402)) sse_server.publish(sse_server.GRACEFUL_REQUEST_END) time.sleep(3) # Assert sync-task is running and", "[]} sse_server.publish(make_control_event('STREAMING_DISABLED', 2)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'on' assert", "'splits': [make_simple_split('split1', 5, True, False, 'off', 'user', True)] } split_changes[5]", "[]} sse_server.publish(make_ably_error_event(60000, 600)) time.sleep(1) assert factory.client().get_treatment('maldo', 'split1') == 'on' assert", "split_backend.stop() def test_streaming_status_changes(self): \"\"\"Test changes between streaming enabled, paused and", "'frula' # Validate the SSE request sse_request = sse_requests.get() assert", "\"[?occupancy=metrics.publishers]%s\" % channel, 'data': json.dumps({'metrics': {'publishers': publishers}}), 'name':'[meta]occupancy' }) }", "def make_segment_change_event(name, change_number): \"\"\"Make a split change event.\"\"\" return {", "'clientId':'pri:MzM0ODI1MTkxMw==', 'timestamp': timestamp, 'encoding':'json', 'channel':'[?occupancy=metrics.publishers]control_pri', 'data': json.dumps({ 'type': 'CONTROL', 'controlType':", "== '/api/splitChanges?since=1' assert req.headers['authorization'] == 'Bearer some_apikey' # Second iteration", "import threading import time import json from queue import Queue", "# SyncAll on retryable error handling req = split_backend_requests.get() assert", "== '1.1' # Initial apikey validation req = split_backend_requests.get() assert", "{ 'since': -1, 'till': 1, 'splits': [make_simple_split('split1', 1, True, False,", "'/event-stream' qs = parse_qs(qs) assert qs['accessToken'][0] == ( '<KEY>' '<KEY>2FwYWJpbGl0eSI6IntcIk1UW'", "control_type, }) }) } def make_ably_error_event(code, status): \"\"\"Make a control", "destroy_event.wait() sse_server.publish(sse_server.GRACEFUL_REQUEST_END) sse_server.stop() split_backend.stop() def make_split_change_event(change_number): \"\"\"Make a split change", "{'connectTimeout': 10000, 'featuresRefreshRate': 100, 'segmentsRefreshRate': 100, 'metricsRefreshRate': 100, 'impressionsRefreshRate': 100,", "10000, 'featuresRefreshRate': 10} } factory = get_factory('some_apikey', **kwargs) factory.block_until_ready(1) assert", "'Bearer some_apikey' # Iteration until segment1 since == till req", "# Initial splits fetch req = split_backend_requests.get() assert req.method ==", "== '/api/splitChanges?since=2' assert req.headers['authorization'] == 'Bearer some_apikey' # SyncAll on", "a hook of the task so we can query its", "'userDefinedSegmentMatcherData': None, 'whitelistMatcherData': None } ] }, 'partitions': [ {'treatment':", "test_ably_errors_handling(self): \"\"\"Test incoming ably errors and validate its handling.\"\"\" import", "'timestamp': change_number-1, 'encoding':'json', 'channel':'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'data': json.dumps({ 'type': 'SPLIT_UPDATE', 'changeNumber': change_number", "qs['accessToken'][0] == ( '<KEY>' 'US45QnJtR0EiLCJ0eXAiOiJKV1QifQ.eyJ4LWFibHktY2FwYWJpbGl0eSI6IntcIk1UW' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib'", "'channel':'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'data': json.dumps({ 'type': 'SPLIT_KILL', 'splitName': name, 'defaultTreatment': default_treatment, 'changeNumber':", "'/api/splitChanges?since=1' assert req.headers['authorization'] == 'Bearer some_apikey' # Auth req =", "urlparse import parse_qs class StreamingIntegrationTests(object): \"\"\"Test streaming operation and failover.\"\"\"", "'data': json.dumps({ 'id':'TVUsxaabHs:0:0', 'clientId':'pri:MzM0ODI1MTkxMw==', 'timestamp': change_number-1, 'encoding':'json', 'channel':'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments', 'data': json.dumps({", "2, 'till': 3, 'splits': [make_simple_split('split1', 3, True, False, 'off', 'user',", "'since': 2, 'till': 3, 'splits': [make_split_with_segment('split2', 2, True, False, 'off',", "'2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpY<KEY>bWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' '<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert set(qs['channels'][0].split(',')) == set(['MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments',", "split_changes[2] = { 'since': 2, 'till': 3, 'splits': [make_simple_split('split1', 3,", "split split_changes[4] = { 'since': 4, 'till': 5, 'splits': [make_simple_split('split1',", "name, 'seed': 1699838640, 'status': 'ACTIVE' if active else 'ARCHIVED', 'changeNumber':", "split_changes[4] = {'since': 4, 'till': 4, 'splits': []} sse_server.publish(make_split_change_event(4)) time.sleep(2)", "] } def make_split_with_segment(name, cn, active, killed, default_treatment, tt, on,", "== 'GET' assert req.path == '/api/splitChanges?since=5' assert req.headers['authorization'] == 'Bearer", "# re-send initial event AND occupancy sse_server.publish(make_initial_event()) sse_server.publish(make_occupancy('control_pri', 2)) sse_server.publish(make_occupancy('control_sec',", "def make_simple_split(name, cn, active, killed, default_treatment, tt, on): \"\"\"Make a", "True)] } split_changes[3] = {'since': 3, 'till': 3, 'splits': []}", "3, 'till': 3, 'splits': []} sse_server.publish(make_split_change_event(3)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1')", "killed, 'defaultTreatment': default_treatment, 'configurations': { 'on': '{\\'size\\':15,\\'test\\':20}' }, 'conditions': [", "streaming enabled, paused and disabled.\"\"\" auth_server_response = { 'pushEnabled': True,", "time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'on' assert task.running() assert 'PushStatusHandler'", "sse_server.publish(make_occupancy('control_sec', 2)) time.sleep(2) assert not task.running() split_changes[2] = { 'since':", "destroy_event = threading.Event() factory.destroy(destroy_event) destroy_event.wait() sse_server.publish(sse_server.GRACEFUL_REQUEST_END) sse_server.stop() split_backend.stop() def test_server_closes_connection(self):", "assert req.headers['authorization'] == 'Bearer some_apikey' # Fetch after new notification", "{ 'combiner': 'AND', 'matchers': [ { 'matcherType': 'ALL_KEYS', 'negate': False,", "\"\"\"Streaming integration tests.\"\"\" # pylint:disable=no-self-use,invalid-name,too-many-arguments,too-few-public-methods,line-too-long # pylint:disable=too-many-statements,too-many-locals,too-many-lines import threading import", "== 'Bearer some_apikey' # SyncAll on push down req =", "on retryable error handling req = split_backend_requests.get() assert req.method ==", "[t.name for t in threading.enumerate()] # Validate the SSE requests", "0 and switching to streamin afterwards.\"\"\" auth_server_response = { 'pushEnabled':", "req.headers['authorization'] == 'Bearer some_apikey' # SyncAll after streaming disabled req", "{ 'combiner': 'AND', 'matchers': [ { 'matcherType': 'IN_SEGMENT', 'negate': False,", "'<KEY>' '<KEY>' '<KEY>' 'CI6MTYwNDEwMDU5MSwiaWF0IjoxNjA0MDk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5E' 'vJh17WlOlAKhcD0') } split_changes = { -1:", "split_changes[1] = { 'since': 1, 'till': 2, 'splits': [make_simple_split('split1', 2,", "assert req.headers['authorization'] == 'Bearer some_apikey' # Split kill req =", "'splits': [] } } segment_changes = {} split_backend_requests = Queue()", "occupancy on 0 and switching to streamin afterwards.\"\"\" auth_server_response =", "assert qs['accessToken'][0] == ( '<KEY>' '<KEY>' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd'", "'data': json.dumps({ 'type': 'CONTROL', 'controlType': control_type, }) }) } def", "a split change event.\"\"\" return {'id':'TVUsxaabHs:0:0'} def make_occupancy(channel, publishers): \"\"\"Make", "is over assert task.running() assert 'PushStatusHandler' not in [t.name for", "= split_backend_requests.get() assert req.method == 'GET' assert req.path == '/api/splitChanges?since=-1'", "factory._sync_manager._synchronizer._split_tasks.split_task._task # pylint:disable=protected-access assert not task.running() time.sleep(1) split_changes[1] = {", "tt, 'name': name, 'seed': cn, 'status': 'ACTIVE' if active else", "'size': 0} ] } ] } def make_split_with_segment(name, cn, active,", "== 'Bearer some_apikey' # Iteration until since == till req", "[], 'since': -1, 'till': 1 } segment_changes[('segment1', 1)] = {'name':", "make_ably_error_event(code, status): \"\"\"Make a control event.\"\"\" return { 'event': 'error',", "-1: { 'since': -1, 'till': 1, 'splits': [make_simple_split('split1', 1, True,", "assert factory.ready time.sleep(2) # Get a hook of the task", "req.method == 'GET' assert req.path == '/api/splitChanges?since=4' assert req.headers['authorization'] ==", "req.path == '/api/splitChanges?since=2' assert req.headers['authorization'] == 'Bearer some_apikey' # SyncAll", "assert req.headers['authorization'] == 'Bearer some_apikey' # SyncAll after push restored", "BE but don't send the event. # After dropping occupancy,", "'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' '<KEY>WJ<KEY>' '<KEY>' '<KEY>' '<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert set(qs['channels'][0].split(',')) ==", "'on' assert not task.running() # Send a non-retryable ably error", "# Fetch after new notification req = split_backend_requests.get() assert req.method", "sse_server.publish(sse_server.GRACEFUL_REQUEST_END) sse_server.stop() split_backend.stop() def test_server_closes_connection(self): \"\"\"Test that if the server", "req.path == '/api/splitChanges?since=5' assert req.headers['authorization'] == 'Bearer some_apikey' # Cleanup", "default_treatment, 'conditions': [ { 'matcherGroup': { 'combiner': 'AND', 'matchers': [", "== set(['MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments', '[?occupancy=metrics.publishers]control_pri', '[?occupancy=metrics.publishers]control_sec']) assert qs['v'][0] == '1.1' #", "{ 'event': 'error', 'data': json.dumps({ 'message':'Invalid accessToken in request: sarasa',", "'name': 'segment1', 'added': ['maldo'], 'removed': [], 'since': -1, 'till': 1", "req.headers['authorization'] == 'Bearer some_apikey' # SyncAll after push restored req", "auth_server_response = { 'pushEnabled': True, 'token': ('<KEY> '<KEY>' '<KEY>' 'T1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcIjpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm'", "factory.client().get_treatment('maldo', 'split1') == 'on' assert not task.running() # Send a", "for t in threading.enumerate()] # Validate the SSE requests sse_request", "'splits': []} sse_server.publish(make_split_change_event(3)) time.sleep(1) assert factory.client().get_treatment('maldo', 'split1') == 'on' assert", "'timestamp': change_number-1, 'encoding':'json', 'channel':'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments', 'data': json.dumps({ 'type': 'SEGMENT_UPDATE', 'segmentName': name,", "occupancy, and it should be fetched by the # sync", "# Fetch after notification req = split_backend_requests.get() assert req.method ==", "'segment1', 'added': [], 'removed': [], 'since': 1, 'till': 1} sse_server.publish(make_split_change_event(3))", "\"\"\"Make a split change event.\"\"\" return { 'event': 'message', 'data':", "task = factory._sync_manager._synchronizer._split_tasks.split_task._task # pylint:disable=protected-access assert task.running() assert factory.client().get_treatment('maldo', 'split1')", "'till': 2, 'splits': []} sse_server.publish(make_occupancy('control_sec', 1)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1')", "assert factory.client().get_treatment('maldo', 'split1') == 'on' assert task.running() assert 'PushStatusHandler' not", "# pylint:disable=no-self-use,invalid-name,too-many-arguments,too-few-public-methods,line-too-long # pylint:disable=too-many-statements,too-many-locals,too-many-lines import threading import time import json", "{'since': 2, 'till': 2, 'splits': []} sse_server.publish(make_occupancy('control_pri', 0)) sse_server.publish(make_occupancy('control_sec', 0))", "'<KEY>' '<KEY>' 'vJh17WlOlAKhcD0') } split_changes = { -1: { 'since':", "logger.setLevel(logging.DEBUG) auth_server_response = { 'pushEnabled': True, 'token': ('<KEY> '<KEY>' '<KEY>'", "[{ 'treatment': 'on' if on else 'off', 'size': 100 }]", "factory.client().get_treatment('maldo', 'split1') == 'on' assert not task.running() # Validate the", "sse_server.publish(make_ably_error_event(40145, 401)) sse_server.publish(sse_server.GRACEFUL_REQUEST_END) time.sleep(3) assert task.running() assert factory.client().get_treatment('maldo', 'split1') ==", "assert req.method == 'GET' assert req.path == '/api/splitChanges?since=1' assert req.headers['authorization']", "5, 'splits': [make_simple_split('split1', 5, True, False, 'off', 'user', True)] }", "split_backend_requests.get() assert req.method == 'GET' assert req.path == '/api/splitChanges?since=3' assert", "'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' '<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert set(qs['channels'][0].split(',')) == set(['MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments', '[?occupancy=metrics.publishers]control_pri',", "threading.Event() factory.destroy(destroy_event) destroy_event.wait() sse_server.publish(sse_server.GRACEFUL_REQUEST_END) sse_server.stop() split_backend.stop() def make_split_change_event(change_number): \"\"\"Make a", "'since': 3, 'till': 4, 'splits': [make_simple_split('split1', 4, True, False, 'off',", "'split1') == 'frula' # Validate the SSE request sse_request =", "'split1') == 'on' assert not task.running() # Send a non-retryable", "default_treatment, change_number): \"\"\"Make a split change event.\"\"\" return { 'event':", "'splits': []} segment_changes[('segment1', -1)] = { 'name': 'segment1', 'added': ['maldo'],", "'/api/splitChanges?since=3' assert req.headers['authorization'] == 'Bearer some_apikey' # SyncAll after non", "} split_changes[5] = {'since': 5, 'till': 5, 'splits': []} sse_server.publish(make_split_kill_event('split1',", "sse_server.publish(sse_server.GRACEFUL_REQUEST_END) time.sleep(3) assert task.running() assert factory.client().get_treatment('maldo', 'split1') == 'off' #", "'data': json.dumps({ 'type': 'SPLIT_UPDATE', 'changeNumber': change_number }) }) } def", "== ( '<KEY>' '<KEY>' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' '<KEY>UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV<KEY>I' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaV<KEY>' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXC<KEY>' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' '<KEY>'", "assert factory.client().get_treatment('maldo', 'split1') == 'on' task = factory._sync_manager._synchronizer._split_tasks.split_task._task # pylint:disable=protected-access", "= {'since': 2, 'till': 2, 'splits': []} sse_server.publish(make_control_event('STREAMING_PAUSED', 1)) time.sleep(2)", "}, 1: { 'since': 1, 'till': 1, 'splits': [] }", "SyncAll on push down req = split_backend_requests.get() assert req.method ==", "None } ] }, 'partitions': [ {'treatment': 'on' if on", "threading.Event() factory.destroy(destroy_event) destroy_event.wait() sse_server.publish(sse_server.GRACEFUL_REQUEST_END) sse_server.stop() split_backend.stop() def test_start_without_occupancy(self): \"\"\"Test an", "qs['accessToken'][0] == ( '<KEY>' '<KEY>' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' '<KEY>UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV<KEY>I' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaV<KEY>' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXC<KEY>' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib'", "100} } factory = get_factory('some_apikey', **kwargs) factory.block_until_ready(1) assert factory.ready assert", "{ 'since': 4, 'till': 5, 'splits': [make_simple_split('split1', 5, True, True,", "perform a syncAll that gets this change split_changes[1] = {", "'AND', 'matchers': [ { 'matcherType': 'ALL_KEYS', 'negate': False, 'userDefinedSegmentMatcherData': None,", "# SyncAll after push down req = split_backend_requests.get() assert req.method", "'off' assert not task.running() split_changes[4] = { 'since': 4, 'till':", "'<KEY>' '<KEY>' '<KEY>' '<KEY>' '<KEY>' '<KEY>' 'CI6MTYwNDEwMDU5MSwiaWF0IjoxNjA0MDk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5E' 'vJh17WlOlAKhcD0') } split_changes", "after notification req = split_backend_requests.get() assert req.method == 'GET' assert", "a non-retryable ably error sse_server.publish(make_ably_error_event(40200, 402)) sse_server.publish(sse_server.GRACEFUL_REQUEST_END) time.sleep(3) # Assert", "the event. # We'll send an ignorable error and check", "'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments', '[?occupancy=metrics.publishers]control_pri', '[?occupancy=metrics.publishers]control_sec']) assert qs['v'][0] == '1.1' assert sse_request.method ==", "{'treatment': 'off' if on else 'on', 'size': 0} ] }", "not task.running() split_changes[2] = { 'since': 2, 'till': 3, 'splits':", "assert not task.running() split_changes[4] = { 'since': 4, 'till': 5,", "req.headers['authorization'] == 'Bearer some_apikey' # SyncAll retriable error req =", "'on' if on else 'off', 'size': 100}, {'treatment': 'off' if", "== 'Bearer some_apikey' # Segment change notification req = split_backend_requests.get()", "logger = logging.getLogger('splitio') handler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s %(name)-12s", "'<KEY>' '<KEY>' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' 'HktY2xpZW50SWQiOiJjbG<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' )", "sse_server.publish(make_ably_error_event(60000, 600)) time.sleep(1) assert factory.client().get_treatment('maldo', 'split1') == 'on' assert not", "# wait for the backoff to expire so streaming gets", "10} } factory = get_factory('some_apikey', **kwargs) factory.block_until_ready(1) assert factory.ready time.sleep(2)", "qs = parse_qs(qs) assert qs['accessToken'][0] == ( '<KEY>' 'US45QnJtR<KEY>' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc'", "restored. split_changes[2] = { 'since': 2, 'till': 3, 'splits': [make_simple_split('split1',", "segment_changes[('segment1', -1)] = { 'name': 'segment1', 'added': ['maldo'], 'removed': [],", "sse_server.publish(make_initial_event()) sse_server.publish(make_occupancy('control_pri', 2)) sse_server.publish(make_occupancy('control_sec', 2)) time.sleep(2) assert not task.running() split_changes[2]", "req.path == '/api/auth' assert req.headers['authorization'] == 'Bearer some_apikey' # SyncAll", "'on' # Make a change in the BE but don't", "sse_server.port(), 'config': {'connectTimeout': 10000} } factory = get_factory('some_apikey', **kwargs) factory.block_until_ready(1)", "== ( '<KEY>' '<KEY>' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' 'HktY2xpZW50SWQiOiJjbG<KEY>'", "'Bearer some_apikey' # Iteration until since == till req =", "assert req.headers['authorization'] == 'Bearer some_apikey' # Iteration until segment1 since", "threading.Event() factory.destroy(destroy_event) destroy_event.wait() sse_server.publish(sse_server.GRACEFUL_REQUEST_END) sse_server.stop() split_backend.stop() def test_streaming_status_changes(self): \"\"\"Test changes", "'[?occupancy=metrics.publishers]control_sec']) assert qs['v'][0] == '1.1' # Initial apikey validation req", "4, 'splits': []} sse_server.publish(make_split_change_event(4)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'off'", "sse_server.publish(make_occupancy('control_pri', 2)) sse_server.publish(make_occupancy('control_sec', 2)) time.sleep(2) assert not task.running() split_changes[2] =", "req.path == '/api/splitChanges?since=3' assert req.headers['authorization'] == 'Bearer some_apikey' # Iteration", "segment.\"\"\" return { 'trafficTypeName': tt, 'name': name, 'seed': cn, 'status':", "streaming connected req = split_backend_requests.get() assert req.method == 'GET' assert", "split_changes[2] = {'since': 2, 'till': 2, 'splits': []} sse_server.publish(make_split_change_event(2)) time.sleep(1)", "fetch req = split_backend_requests.get() assert req.method == 'GET' assert req.path", "time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'off' assert not task.running() split_changes[4]", "time.sleep(1) assert factory.client().get_treatment('maldo', 'split1') == 'off' assert task.running() time.sleep(2) #", "make_initial_event(): \"\"\"Make a split change event.\"\"\" return {'id':'TVUsxaabHs:0:0'} def make_occupancy(channel,", "destroy_event = threading.Event() factory.destroy(destroy_event) destroy_event.wait() sse_server.publish(sse_server.GRACEFUL_REQUEST_END) sse_server.stop() split_backend.stop() def test_occupancy_flicker(self):", "True, False, 'off', 'user', False)] } split_changes[4] = {'since': 4,", "'/api/splitChanges?since=2' assert req.headers['authorization'] == 'Bearer some_apikey' # Auth after connection", "5, 'till': 5, 'splits': []} sse_server.publish(make_control_event('STREAMING_DISABLED', 2)) time.sleep(2) assert factory.client().get_treatment('maldo',", "== '/api/splitChanges?since=4' assert req.headers['authorization'] == 'Bearer some_apikey' # SyncAll after", "sse_server.publish(make_split_change_event(2)) time.sleep(1) assert factory.client().get_treatment('maldo', 'split1') == 'off' sse_server.publish(SSEMockServer.GRACEFUL_REQUEST_END) time.sleep(1) assert", "that if the server closes the connection, the whole flow", "req.headers['authorization'] == 'Bearer some_apikey' # SyncAll on retryable error handling", "on else 'on', 'size': 0} ] } ] } def", "'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' '<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert set(qs['channels'][0].split(','))", "'dGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFibHktY2xpZW50SWQiOiJjbGllbnRJZCIsImV4c' 'CI6MTYwNDEwMDU5MSwiaWF0IjoxNjA0MDk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5E' '<KEY>') } split_changes = { -1: { 'since':", "'user', True)] }, 1: {'since': 1, 'till': 1, 'splits': []}", "def make_split_change_event(change_number): \"\"\"Make a split change event.\"\"\" return { 'event':", "}, 1: {'since': 1, 'till': 1, 'splits': []} } segment_changes", "sync all after streaming is restored. split_changes[2] = { 'since':", "'message', 'data': json.dumps({ 'id':'TVUsxaabHs:0:0', 'clientId':'pri:MzM0ODI1MTkxMw==', 'timestamp': change_number-1, 'encoding':'json', 'channel':'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'data':", "re-send initial event AND occupancy sse_server.publish(make_initial_event()) sse_server.publish(make_occupancy('control_pri', 2)) sse_server.publish(make_occupancy('control_sec', 2))", "= threading.Event() factory.destroy(destroy_event) destroy_event.wait() sse_server.publish(sse_server.GRACEFUL_REQUEST_END) sse_server.stop() split_backend.stop() def make_split_change_event(change_number): \"\"\"Make", "== '/api/splitChanges?since=5' assert req.headers['authorization'] == 'Bearer some_apikey' # Cleanup destroy_event", "'on' assert task.running() assert 'PushStatusHandler' not in [t.name for t", "assert qs['v'][0] == '1.1' sse_request = sse_requests.get() assert sse_request.method ==", "'till': 5, 'splits': []} sse_server.publish(make_split_kill_event('split1', 'frula', 5)) time.sleep(2) assert factory.client().get_treatment('maldo',", "After dropping occupancy, the sdk should switch to polling #", "0)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'off' assert task.running() #", "'on': '{\\'size\\':15,\\'test\\':20}' }, 'conditions': [ { 'matcherGroup': { 'combiner': 'AND',", "'matcherGroup': { 'combiner': 'AND', 'matchers': [ { 'matcherType': 'IN_SEGMENT', 'negate':", "'Bearer some_apikey' # Fetch after second notification req = split_backend_requests.get()", "parse_qs class StreamingIntegrationTests(object): \"\"\"Test streaming operation and failover.\"\"\" def test_happiness(self):", "== '/api/splitChanges?since=3' assert req.headers['authorization'] == 'Bearer some_apikey' # Iteration until", "publishers): \"\"\"Make an occupancy event.\"\"\" return { 'event': 'message', 'data':", "split_backend.port(), 'streaming_api_base_url': 'http://localhost:%d' % sse_server.port(), 'config': {'connectTimeout': 10000, 'featuresRefreshRate': 100,", "'till': 3, 'splits': []} sse_server.publish(make_occupancy('control_pri', 1)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1')", "[]} segment_changes[('segment1', -1)] = { 'name': 'segment1', 'added': ['maldo'], 'removed':", "100}, {'treatment': 'off' if on else 'on', 'size': 0} ]", "4, 'till': 5, 'splits': [make_simple_split('split1', 5, True, True, 'frula', 'user',", "'token': ('<KEY> '<KEY>' '<KEY>' '<KEY>' '<KEY>' '<KEY>' '<KEY>' 'CI6MTYwNDEwMDU5MSwiaWF0IjoxNjA0MDk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5E' 'vJh17WlOlAKhcD0')", "'2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' 'HktY2xpZW50SWQiOiJjbGllbnRJZCIsImV4cCI6MTYwNDEwMDU5MSwiaWF0IjoxNjA0M' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert set(qs['channels'][0].split(',')) == set(['MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments',", "== 'off' assert factory.client().get_treatment('maldo', 'split2') == 'on' # Validate the", "'defaultTreatment': default_treatment, 'configurations': { 'on': '{\\'size\\':15,\\'test\\':20}' }, 'conditions': [ {", "req.method == 'GET' assert req.path == '/api/splitChanges?since=-1' assert req.headers['authorization'] ==", "'/api/splitChanges?since=2' assert req.headers['authorization'] == 'Bearer some_apikey' # Iteration until since", "} split_changes[3] = {'since': 3, 'till': 3, 'splits': []} segment_changes[('segment1',", "True)] }, 1: { 'since': 1, 'till': 1, 'splits': []", "qs = sse_request.path.split('?', 1) assert path == '/event-stream' qs =", "# Auth req = split_backend_requests.get() assert req.method == 'GET' assert", "# Split kill req = split_backend_requests.get() assert req.method == 'GET'", "False, 'off', 'user', True)] } split_changes[5] = {'since': 5, 'till':", "% split_backend.port(), 'streaming_api_base_url': 'http://localhost:%d' % sse_server.port(), 'config': {'connectTimeout': 10000} }", "hook of the task so we can query its status", "'featuresRefreshRate': 10} } factory = get_factory('some_apikey', **kwargs) factory.block_until_ready(1) assert factory.ready", "'Bearer some_apikey' # Auth again req = split_backend_requests.get() assert req.method", "'till': 1, 'splits': [] } } segment_changes = {} split_backend_requests", "not task.running() # Send a non-retryable ably error sse_server.publish(make_ably_error_event(40200, 402))", "factory.client().get_treatment('maldo', 'split2') == 'on' # Validate the SSE request sse_request", "== 'Bearer some_apikey' # SyncAll after non recoverable ably error", "\"\"\"Test incoming ably errors and validate its handling.\"\"\" import logging", "False, 'off', 'user', True)] }, 1: {'since': 1, 'till': 1,", "'<KEY>2FwYWJpbGl0eSI6IntcIk1UW' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpY<KEY>bWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' '<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert", "'Bearer some_apikey' # Auth req = split_backend_requests.get() assert req.method ==", "a split with a segment.\"\"\" return { 'trafficTypeName': tt, 'name':", "syncAll that gets this change split_changes[1] = { 'since': 1,", "'1.1' assert sse_request.method == 'GET' path, qs = sse_request.path.split('?', 1)", "sse_server.start() sse_server.publish(make_initial_event()) sse_server.publish(make_occupancy('control_pri', 2)) sse_server.publish(make_occupancy('control_sec', 2)) kwargs = { 'sdk_api_base_url':", "'till': 3, 'splits': []} sse_server.publish(make_control_event('STREAMING_ENABLED', 2)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1')", "\"\"\"Test that changes in occupancy switch between polling & streaming", "set(['MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments', '[?occupancy=metrics.publishers]control_pri', '[?occupancy=metrics.publishers]control_sec']) assert qs['v'][0] == '1.1' assert sse_request.method", "default_treatment, tt, on, segment): \"\"\"Make a split with a segment.\"\"\"", "1, 'till': 1, 'splits': [] } } segment_changes = {}", "'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' 'HktY2xpZW50SWQiOiJjbG<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert set(qs['channels'][0].split(','))", "'<KEY>' '<KEY>' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' 'HktY2xpZW50SWQiOiJjbGllbnRJZCIsImV4cCI6MTYwNDEwMDU5MSwiaWF0IjoxNjA0M' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' )", "accessToken in request: sarasa', 'code': code, 'statusCode': status, 'href':\"https://help.ably.io/error/%d\" %", "pylint:disable=too-many-statements,too-many-locals,too-many-lines import threading import time import json from queue import", "# Iteration until segment1 since == till req = split_backend_requests.get()", "updates.\"\"\" auth_server_response = { 'pushEnabled': True, 'token': ('<KEY> '<KEY>' '<KEY>'", "some_apikey' # SyncAll retriable error req = split_backend_requests.get() assert req.method", "SplitMockServer try: # try to import python3 names. fallback to", "'GET' assert req.path == '/api/splitChanges?since=1' assert req.headers['authorization'] == 'Bearer some_apikey'", "== '/api/splitChanges?since=2' assert req.headers['authorization'] == 'Bearer some_apikey' # Auth after", "make another chagne in the BE and don't send the", "'<KEY>' '<KEY>' '<KEY>' '<KEY>' '<KEY>' 'dGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFibHktY2xpZW50SWQiOiJjbGllbnRJZCIsImV4c' 'CI6MTYwNDEwMDU5MSwiaWF0IjoxNjA0MDk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5E' 'vJh17WlOlAKhcD0') } split_changes", "sdk should switch to polling # and perform a syncAll", "'changeNumber': change_number }) }) } def make_control_event(control_type, timestamp): \"\"\"Make a", "segment}, 'whitelistMatcherData': None } ] }, 'partitions': [{ 'treatment': 'on'", "req.headers['authorization'] == 'Bearer some_apikey' # Segment change notification req =", "'SPLIT_UPDATE', 'changeNumber': change_number }) }) } def make_split_kill_event(name, default_treatment, change_number):", "'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' 'HktY2xpZW50SWQiOiJjbGllbnRJZCIsImV4cCI6MTYwNDEwMDU5MSwiaWF0IjoxNjA0M' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert set(qs['channels'][0].split(','))", "connection breaks req = split_backend_requests.get() assert req.method == 'GET' assert", "so streaming gets re-attached # re-send initial event AND occupancy", "split_changes[2] = {'since': 2, 'till': 2, 'splits': []} sse_server.publish(make_ably_error_event(60000, 600))", "'/api/splitChanges?since=2' assert req.headers['authorization'] == 'Bearer some_apikey' # Fetch after notification", "( '<KEY>' '<KEY>2FwYWJpbGl0eSI6IntcIk1UW' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpY<KEY>bWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' '<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0'", "== '/api/splitChanges?since=-1' assert req.headers['authorization'] == 'Bearer some_apikey' # Iteration until", "'split2') == 'on' # Validate the SSE request sse_request =", "make_control_event(control_type, timestamp): \"\"\"Make a control event.\"\"\" return { 'event': 'message',", "split_backend.stop() def test_server_closes_connection(self): \"\"\"Test that if the server closes the", "assert task.running() assert factory.client().get_treatment('maldo', 'split1') == 'off' # Re-publish initial", "sse_server.publish(make_control_event('STREAMING_DISABLED', 2)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'on' assert task.running()", "'till': 3, 'splits': []} sse_server.publish(make_split_change_event(3)) time.sleep(1) assert factory.client().get_treatment('maldo', 'split1') ==", "# Kill the split split_changes[4] = { 'since': 4, 'till':", "'split1') == 'off' assert not task.running() split_changes[4] = { 'since':", "'[?occupancy=metrics.publishers]control_pri', '[?occupancy=metrics.publishers]control_sec']) assert qs['v'][0] == '1.1' sse_request = sse_requests.get() assert", "# pylint:disable=protected-access assert not task.running() time.sleep(1) split_changes[1] = { 'since':", "not task.running() # Assert streaming is working properly split_changes[2] =", "'/api/segmentChanges/__SOME_INVALID_SEGMENT__?since=-1' assert req.headers['authorization'] == 'Bearer some_apikey' # Initial splits fetch", "True, True, 'frula', 'user', False)] } split_changes[5] = {'since': 5,", "'event': 'message', 'data': json.dumps({ 'id':'aP6EuhrcUm:0:0', 'timestamp':1604325712734, 'encoding': 'json', 'channel': \"[?occupancy=metrics.publishers]%s\"", "'json', 'channel': \"[?occupancy=metrics.publishers]%s\" % channel, 'data': json.dumps({'metrics': {'publishers': publishers}}), 'name':'[meta]occupancy'", "'frula', 5)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'frula' # Validate", "channel, 'data': json.dumps({'metrics': {'publishers': publishers}}), 'name':'[meta]occupancy' }) } def make_segment_change_event(name,", "the event. # We restore occupancy, and it should be", "req.path == '/api/splitChanges?since=1' assert req.headers['authorization'] == 'Bearer some_apikey' # Fetch", "600)) time.sleep(1) assert factory.client().get_treatment('maldo', 'split1') == 'on' assert not task.running()", "req.method == 'GET' assert req.path == '/api/splitChanges?since=5' assert req.headers['authorization'] ==", "that gets this change split_changes[1] = { 'since': 1, 'till':", "5)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'frula' # Validate the", "qs['v'][0] == '1.1' sse_request = sse_requests.get() assert sse_request.method == 'GET'", "[], 'since': 1, 'till': 1} sse_server.publish(make_split_change_event(3)) time.sleep(1) sse_server.publish(make_segment_change_event('segment1', 1)) time.sleep(1)", "# sync all after streaming is restored. split_changes[2] = {", "== '/api/splitChanges?since=3' assert req.headers['authorization'] == 'Bearer some_apikey' # Segment change", "simple split.\"\"\" return { 'trafficTypeName': tt, 'name': name, 'seed': 1699838640,", "t in threading.enumerate()] # Validate the SSE request sse_request =", "handler thread is over assert task.running() assert 'PushStatusHandler' not in", "after non recoverable ably error req = split_backend_requests.get() assert req.method", "# We make another chagne in the BE and don't", "'encoding': 'json', 'channel': \"[?occupancy=metrics.publishers]%s\" % channel, 'data': json.dumps({'metrics': {'publishers': publishers}}),", "assert factory.client().get_treatment('maldo', 'split1') == 'off' split_changes[2] = { 'since': 2,", "query its status task = factory._sync_manager._synchronizer._split_tasks.split_task._task # pylint:disable=protected-access assert task.running()", "True, False, 'off', 'user', True)] } split_changes[3] = {'since': 3,", "'trafficTypeName': tt, 'name': name, 'seed': cn, 'status': 'ACTIVE' if active", "assert factory.client().get_treatment('maldo', 'split1') == 'off' assert task.running() # We make", "should switch to polling # and perform a syncAll that", "succeeds sse_server.publish(make_initial_event()) sse_server.publish(make_occupancy('control_pri', 2)) sse_server.publish(make_occupancy('control_sec', 2)) time.sleep(3) assert not task.running()", "for the backoff to expire so streaming gets re-attached #", "{ 'since': 1, 'till': 1, 'splits': [] } } segment_changes", "1)] = {'name': 'segment1', 'added': [], 'removed': [], 'since': 1,", "don't send the event. # We restore occupancy, and it", "after connection breaks req = split_backend_requests.get() assert req.method == 'GET'", "{'since': 1, 'till': 1, 'splits': []} } segment_changes = {}", "'message':'Invalid accessToken in request: sarasa', 'code': code, 'statusCode': status, 'href':\"https://help.ably.io/error/%d\"", "threading.Event() factory.destroy(destroy_event) destroy_event.wait() sse_server.publish(sse_server.GRACEFUL_REQUEST_END) sse_server.stop() split_backend.stop() def test_occupancy_flicker(self): \"\"\"Test that", "'segmentName': name, 'changeNumber': change_number }) }) } def make_control_event(control_type, timestamp):", "some_apikey' # SyncAll after streaming disabled req = split_backend_requests.get() assert", "req.headers['authorization'] == 'Bearer some_apikey' # Auth again req = split_backend_requests.get()", "it should be fetched by the # sync all after", "some_apikey' # Auth req = split_backend_requests.get() assert req.method == 'GET'", "assert req.method == 'GET' assert req.path == '/api/segmentChanges/segment1?since=-1' assert req.headers['authorization']", "== 'Bearer some_apikey' # Split kill req = split_backend_requests.get() assert", "status handler thread is over assert task.running() assert 'PushStatusHandler' not", "3, 'splits': [make_simple_split('split1', 3, True, False, 'off', 'user', True)] }", "'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' 'HktY2xpZW50SWQiOiJjbGllbnRJZCIsImV4cCI6MTYwNDEwMDU5MSwiaWF0IjoxNjA0M' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert set(qs['channels'][0].split(',')) == set(['MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments', '[?occupancy=metrics.publishers]control_pri',", "{'since': 2, 'till': 2, 'splits': []} sse_server.publish(make_split_change_event(2)) time.sleep(1) assert factory.client().get_treatment('maldo',", "req.path == '/api/splitChanges?since=2' assert req.headers['authorization'] == 'Bearer some_apikey' # Cleanup", "= parse_qs(qs) assert qs['accessToken'][0] == ( '<KEY>' '<KEY>2FwYWJpbGl0eSI6IntcIk1UW' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI'", "assert factory.client().get_treatment('maldo', 'split1') == 'on' assert not task.running() # Send", "in the BE but don't send the event. # We'll", "== 'Bearer some_apikey' # Iteration until segment1 since == till", "req.path == '/api/splitChanges?since=3' assert req.headers['authorization'] == 'Bearer some_apikey' # Cleanup", "assert req.path == '/api/splitChanges?since=3' assert req.headers['authorization'] == 'Bearer some_apikey' #", "= Queue() sse_server = SSEMockServer(sse_requests) split_backend.start() sse_server.start() sse_server.publish(make_initial_event()) sse_server.publish(make_occupancy('control_pri', 0))", "== 'Bearer some_apikey' # Second iteration of previous syncAll req", "Iteration until since == till req = split_backend_requests.get() assert req.method", "[make_simple_split('split1', 1, True, False, 'off', 'user', True)] }, 1: {'since':", "sse_server = SSEMockServer(sse_requests) split_backend.start() sse_server.start() sse_server.publish(make_initial_event()) sse_server.publish(make_occupancy('control_pri', 2)) sse_server.publish(make_occupancy('control_sec', 2))", "destroy_event = threading.Event() factory.destroy(destroy_event) destroy_event.wait() sse_server.publish(sse_server.GRACEFUL_REQUEST_END) sse_server.stop() split_backend.stop() def make_split_change_event(change_number):", "'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' '<KEY>WJ<KEY>' '<KEY>' '<KEY>' '<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert set(qs['channels'][0].split(','))", "2)) sse_server.publish(make_occupancy('control_sec', 2)) kwargs = { 'sdk_api_base_url': 'http://localhost:%d/api' % split_backend.port(),", "'seed': cn, 'status': 'ACTIVE' if active else 'ARCHIVED', 'changeNumber': cn,", "After restoring occupancy, the sdk should switch to polling #", "its status task = factory._sync_manager._synchronizer._split_tasks.split_task._task # pylint:disable=protected-access assert not task.running()", "'type': 'SPLIT_KILL', 'splitName': name, 'defaultTreatment': default_treatment, 'changeNumber': change_number }) })", "connection, the whole flow is retried with BO.\"\"\" auth_server_response =", "Fetch after first notification req = split_backend_requests.get() assert req.method ==", "[make_simple_split('split1', 1, True, False, 'on', 'user', True)] }, 1: {", "split_backend_requests.get() assert req.method == 'GET' assert req.path == '/api/segmentChanges/segment1?since=-1' assert", "of previous syncAll req = split_backend_requests.get() assert req.method == 'GET'", "tt, 'name': name, 'seed': 1699838640, 'status': 'ACTIVE' if active else", "== ( '<KEY>' 'US45QnJtR<KEY>' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' '<KEY>WJ<KEY>' '<KEY>' '<KEY>' '<KEY>'", "again req = split_backend_requests.get() assert req.method == 'GET' assert req.path", "'/api/splitChanges?since=4' assert req.headers['authorization'] == 'Bearer some_apikey' # Iteration until since", "retry succeeds sse_server.publish(make_initial_event()) sse_server.publish(make_occupancy('control_pri', 2)) sse_server.publish(make_occupancy('control_sec', 2)) time.sleep(3) assert not", "'config': {'connectTimeout': 10000, 'featuresRefreshRate': 10} } factory = get_factory('some_apikey', **kwargs)", "== '/api/splitChanges?since=1' assert req.headers['authorization'] == 'Bearer some_apikey' # SyncAll after", "threading.Event() factory.destroy(destroy_event) destroy_event.wait() sse_server.publish(sse_server.GRACEFUL_REQUEST_END) sse_server.stop() split_backend.stop() def test_server_closes_connection(self): \"\"\"Test that", "the streaming status handler thread is over assert task.running() assert", "assert req.headers['authorization'] == 'Bearer some_apikey' # Auth req = split_backend_requests.get()", "Fetch after new notification req = split_backend_requests.get() assert req.method ==", "<gh_stars>0 \"\"\"Streaming integration tests.\"\"\" # pylint:disable=no-self-use,invalid-name,too-many-arguments,too-few-public-methods,line-too-long # pylint:disable=too-many-statements,too-many-locals,too-many-lines import threading", "2)) sse_server.publish(make_occupancy('control_sec', 2)) time.sleep(2) assert not task.running() split_changes[2] = {", "time.sleep(1) assert factory.client().get_treatment('maldo', 'split1') == 'on' assert not task.running() #", "'on' assert not task.running() # Validate the SSE requests sse_request", "[make_simple_split('split1', 3, True, False, 'off', 'user', True)] } split_changes[3] =", "'US45QnJtR<KEY>' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' '<KEY>WJ<KEY>' '<KEY>' '<KEY>' '<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert", "[ { 'matcherType': 'ALL_KEYS', 'negate': False, 'userDefinedSegmentMatcherData': None, 'whitelistMatcherData': None", "'<KEY>' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' 'HktY2xpZW50SWQiOiJjbG<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert", "'data': json.dumps({ 'id':'TVUsxaabHs:0:0', 'clientId':'pri:MzM0ODI1MTkxMw==', 'timestamp': timestamp, 'encoding':'json', 'channel':'[?occupancy=metrics.publishers]control_pri', 'data': json.dumps({", "= parse_qs(qs) assert qs['accessToken'][0] == ( '<KEY>' 'US45QnJtR<KEY>' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI'", "'<KEY>UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV<KEY>I' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaV<KEY>' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXC<KEY>' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' '<KEY>' 'Dk2OTkxfQ.<KEY>' ) assert set(qs['channels'][0].split(',')) ==", "# After restoring occupancy, the sdk should switch to polling", "= {'since': 3, 'till': 3, 'splits': []} sse_server.publish(make_control_event('STREAMING_ENABLED', 2)) time.sleep(2)", "( '<KEY>' '<KEY>' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' 'HktY2xpZW50SWQiOiJjbGllbnRJZCIsImV4cCI6MTYwNDEwMDU5MSwiaWF0IjoxNjA0M' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0'", "qs = parse_qs(qs) assert qs['accessToken'][0] == ( '<KEY>' 'US45QnJtR0EiLCJ0eXAiOiJKV1QifQ.eyJ4LWFibHktY2FwYWJpbGl0eSI6IntcIk1UW' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc'", "= { 'since': 3, 'till': 4, 'splits': [make_simple_split('split1', 4, True,", "'status': 'ACTIVE' if active else 'ARCHIVED', 'changeNumber': cn, 'killed': killed,", "sse_server.publish(make_split_change_event(4)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'off' assert not task.running()", "{'treatment': 'on' if on else 'off', 'size': 100}, {'treatment': 'off'", "Auth req = split_backend_requests.get() assert req.method == 'GET' assert req.path", "'[?occupancy=metrics.publishers]control_pri', '[?occupancy=metrics.publishers]control_sec']) assert qs['v'][0] == '1.1' assert sse_request.method == 'GET'", "\"\"\"Make an occupancy event.\"\"\" return { 'event': 'message', 'data': json.dumps({", "sse_server.publish(make_initial_event()) sse_server.publish(make_occupancy('control_pri', 0)) sse_server.publish(make_occupancy('control_sec', 0)) kwargs = { 'sdk_api_base_url': 'http://localhost:%d/api'", "sse_server.publish(make_occupancy('control_sec', 2)) time.sleep(3) assert not task.running() # Assert streaming is", "'splits': []} sse_server.publish(make_occupancy('control_pri', 1)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'on'", "== 'GET' path, qs = sse_request.path.split('?', 1) assert path ==", "{ 'since': 2, 'till': 3, 'splits': [make_simple_split('split1', 3, True, False,", "3, 'till': 4, 'splits': [make_simple_split('split1', 4, True, False, 'off', 'user',", "'timestamp':1604325712734, 'encoding': 'json', 'channel': \"[?occupancy=metrics.publishers]%s\" % channel, 'data': json.dumps({'metrics': {'publishers':", "'<KEY>' '<KEY>' '<KEY>' '<KEY>' '<KEY>' '<KEY>' 'vJh17WlOlAKhcD0') } split_changes =", "5, 'till': 5, 'splits': []} sse_server.publish(make_split_kill_event('split1', 'frula', 5)) time.sleep(2) assert", "req.headers['authorization'] == 'Bearer some_apikey' # SyncAll after streaming connected req", "[make_simple_split('split1', 4, True, False, 'off', 'user', False)] } split_changes[4] =", "on 0 and switching to streamin afterwards.\"\"\" auth_server_response = {", "split_backend_requests.get() assert req.method == 'GET' assert req.path == '/api/splitChanges?since=1' assert", "def make_split_with_segment(name, cn, active, killed, default_treatment, tt, on, segment): \"\"\"Make", "'ARCHIVED', 'changeNumber': cn, 'killed': killed, 'defaultTreatment': default_treatment, 'conditions': [ {", "assert req.headers['authorization'] == 'Bearer some_apikey' # Cleanup destroy_event = threading.Event()", "{ 'trafficTypeName': tt, 'name': name, 'seed': cn, 'status': 'ACTIVE' if", "split_backend.port(), 'streaming_api_base_url': 'http://localhost:%d' % sse_server.port(), 'config': {'connectTimeout': 10000} } factory", "'matcherType': 'ALL_KEYS', 'negate': False, 'userDefinedSegmentMatcherData': None, 'whitelistMatcherData': None } ]", "some_apikey' # SyncAll after push down req = split_backend_requests.get() assert", "== 'GET' assert req.path == '/api/auth' assert req.headers['authorization'] == 'Bearer", "= factory._sync_manager._synchronizer._split_tasks.split_task._task # pylint:disable=protected-access assert task.running() assert factory.client().get_treatment('maldo', 'split1') ==", "sse_server.stop() split_backend.stop() def test_occupancy_flicker(self): \"\"\"Test that changes in occupancy switch", "pylint:disable=protected-access assert not task.running() time.sleep(1) split_changes[1] = { 'since': 1,", "to streamin afterwards.\"\"\" auth_server_response = { 'pushEnabled': True, 'token': ('<KEY>", "} ] }, 'partitions': [ {'treatment': 'on' if on else", "'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' 'HktY2xpZW50SWQiOiJjbGllbnRJZCIsImV4cCI6MTYwNDEwMDU5MSwiaWF0IjoxNjA0M' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert set(qs['channels'][0].split(',')) ==", "test_start_without_occupancy(self): \"\"\"Test an SDK starting with occupancy on 0 and", "if on else 'off', 'size': 100 }] } ] }", "request sse_request = sse_requests.get() assert sse_request.method == 'GET' path, qs", "# Send a non-retryable ably error sse_server.publish(make_ably_error_event(40200, 402)) sse_server.publish(sse_server.GRACEFUL_REQUEST_END) time.sleep(3)", "'added': [], 'removed': [], 'since': 1, 'till': 1} sse_server.publish(make_split_change_event(3)) time.sleep(1)", "StreamingIntegrationTests(object): \"\"\"Test streaming operation and failover.\"\"\" def test_happiness(self): \"\"\"Test initialization", "req = split_backend_requests.get() assert req.method == 'GET' assert req.path ==", "threading import time import json from queue import Queue from", "402)) sse_server.publish(sse_server.GRACEFUL_REQUEST_END) time.sleep(3) # Assert sync-task is running and the", "killed, 'defaultTreatment': default_treatment, 'conditions': [ { 'matcherGroup': { 'combiner': 'AND',", "% sse_server.port(), 'config': {'connectTimeout': 10000} } factory = get_factory('some_apikey', **kwargs)", "'/api/splitChanges?since=3' assert req.headers['authorization'] == 'Bearer some_apikey' # Segment change notification", "[make_simple_split('split1', 2, True, False, 'off', 'user', False)] } split_changes[2] =", "'off' split_changes[2] = { 'since': 2, 'till': 3, 'splits': [make_split_with_segment('split2',", "2, 'splits': [make_simple_split('split1', 2, True, False, 'off', 'user', False)] }", "%(name)-12s %(levelname)-8s %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) logger.setLevel(logging.DEBUG) auth_server_response = { 'pushEnabled':", "1: { 'since': 1, 'till': 1, 'splits': [] } }", "streaming is working properly split_changes[2] = { 'since': 2, 'till':", "}) }) } def make_ably_error_event(code, status): \"\"\"Make a control event.\"\"\"", "== 'Bearer some_apikey' # SyncAll on retryable error handling req", "to import python3 names. fallback to python2 from urllib.parse import", "assert req.headers['authorization'] == 'Bearer some_apikey' # SyncAll after streaming connected", "in threading.enumerate()] # Validate the SSE request sse_request = sse_requests.get()", "'Bearer some_apikey' # SyncAll after streaming connected req = split_backend_requests.get()", "be fetched by the # sync all after streaming is", "1: {'since': 1, 'till': 1, 'splits': []} } segment_changes =", "a control event.\"\"\" return { 'event': 'message', 'data': json.dumps({ 'id':'TVUsxaabHs:0:0',", "factory.client().get_treatment('maldo', 'split1') == 'on' task = factory._sync_manager._synchronizer._split_tasks.split_task._task # pylint:disable=protected-access assert", "req.path == '/api/splitChanges?since=4' assert req.headers['authorization'] == 'Bearer some_apikey' # Iteration", "& streaming properly.\"\"\" auth_server_response = { 'pushEnabled': True, 'token': ('<KEY>", "sse_server.publish(make_initial_event()) sse_server.publish(make_occupancy('control_pri', 2)) sse_server.publish(make_occupancy('control_sec', 2)) time.sleep(3) assert not task.running() #", "{} split_backend_requests = Queue() split_backend = SplitMockServer(split_changes, segment_changes, split_backend_requests, auth_server_response)", "'name': name, 'seed': cn, 'status': 'ACTIVE' if active else 'ARCHIVED',", "\"\"\"Make a control event.\"\"\" return { 'event': 'message', 'data': json.dumps({", "else 'on', 'size': 0} ] } ] } def make_split_with_segment(name,", "'user', True)] }, 1: { 'since': 1, 'till': 1, 'splits':", "factory.client().get_treatment('maldo', 'split1') == 'frula' # Validate the SSE request sse_request", "= {} split_backend_requests = Queue() split_backend = SplitMockServer(split_changes, segment_changes, split_backend_requests,", "'pushEnabled': True, 'token': ('<KEY> '<KEY>' '<KEY>' '<KEY>' '<KEY>' '<KEY>' 'dGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFibHktY2xpZW50SWQiOiJjbGllbnRJZCIsImV4c'", "has nothing happened split_changes[1] = { 'since': 1, 'till': 2,", "'token': ('<KEY> '<KEY>' '<KEY>' '<KEY>' '<KEY>' '<KEY>' 'dGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFibHktY2xpZW50SWQiOiJjbGllbnRJZCIsImV4c' 'CI6MTYwNDEwMDU5MSwiaWF0IjoxNjA0MDk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5E' 'vJh17WlOlAKhcD0')", "switching to streamin afterwards.\"\"\" auth_server_response = { 'pushEnabled': True, 'token':", "'segmentsRefreshRate': 100, 'metricsRefreshRate': 100, 'impressionsRefreshRate': 100, 'eventsPushRate': 100} } factory", "[make_split_with_segment('split2', 2, True, False, 'off', 'user', 'off', 'segment1')] } split_changes[3]", "'off', 'user', True)] } split_changes[5] = {'since': 5, 'till': 5,", "'<KEY>' '<KEY>' '<KEY>' '<KEY>' 'dGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFibHktY2xpZW50SWQiOiJjbGllbnRJZCIsImV4c' 'CI6MTYwNDEwMDU5MSwiaWF0IjoxNjA0MDk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5E' 'vJh17WlOlAKhcD0') } split_changes =", "it's propagated split_changes[3] = { 'since': 3, 'till': 4, 'splits':", "== set(['MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments', '[?occupancy=metrics.publishers]control_pri', '[?occupancy=metrics.publishers]control_sec']) assert qs['v'][0] == '1.1' sse_request", "code }) } def make_simple_split(name, cn, active, killed, default_treatment, tt,", "split_changes = { -1: { 'since': -1, 'till': 1, 'splits':", "'metricsRefreshRate': 100, 'impressionsRefreshRate': 100, 'eventsPushRate': 100} } factory = get_factory('some_apikey',", "SyncAll retriable error req = split_backend_requests.get() assert req.method == 'GET'", "'Bearer some_apikey' # Cleanup destroy_event = threading.Event() factory.destroy(destroy_event) destroy_event.wait() sse_server.publish(sse_server.GRACEFUL_REQUEST_END)", "assert not task.running() time.sleep(1) split_changes[1] = { 'since': 1, 'till':", "] } ] } def make_split_with_segment(name, cn, active, killed, default_treatment,", "assert qs['v'][0] == '1.1' assert sse_request.method == 'GET' path, qs", "import get_factory from tests.helpers.mockserver import SSEMockServer, SplitMockServer try: # try", "class StreamingIntegrationTests(object): \"\"\"Test streaming operation and failover.\"\"\" def test_happiness(self): \"\"\"Test", "'<KEY>' 'US45QnJtR<KEY>' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' '<KEY>WJ<KEY>' '<KEY>' '<KEY>' '<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' )", "'/api/splitChanges?since=2' assert req.headers['authorization'] == 'Bearer some_apikey' # Fetch after new", "split_changes[5] = {'since': 5, 'till': 5, 'splits': []} sse_server.publish(make_control_event('STREAMING_DISABLED', 2))", "'Bearer some_apikey' # SyncAll after non recoverable ably error req", "and it should be fetched by the # sync all", "4, 'splits': [make_simple_split('split1', 4, True, False, 'off', 'user', False)] }", "assert factory.client().get_treatment('maldo', 'split1') == 'off' # Re-publish initial events so", "# Initial apikey validation req = split_backend_requests.get() assert req.method ==", "split_changes[3] = {'since': 3, 'till': 3, 'splits': []} sse_server.publish(make_occupancy('control_pri', 1))", "qs['v'][0] == '1.1' # Initial apikey validation req = split_backend_requests.get()", "def make_control_event(control_type, timestamp): \"\"\"Make a control event.\"\"\" return { 'event':", "test_happiness(self): \"\"\"Test initialization & splits/segment updates.\"\"\" auth_server_response = { 'pushEnabled':", "'off', 'size': 100}, {'treatment': 'off' if on else 'on', 'size':", "time.sleep(1) split_changes[1] = { 'since': 1, 'till': 2, 'splits': [make_simple_split('split1',", "== '/api/segmentChanges/segment1?since=1' assert req.headers['authorization'] == 'Bearer some_apikey' # Cleanup destroy_event", "4, 'till': 4, 'splits': []} sse_server.publish(make_split_change_event(4)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1')", "to python2 from urllib.parse import parse_qs except ImportError: from urlparse", "some_apikey' # SyncAll after push is up req = split_backend_requests.get()", "don't send the event. # After dropping occupancy, the sdk", "= factory._sync_manager._synchronizer._split_tasks.split_task._task # pylint:disable=protected-access assert not task.running() assert factory.client().get_treatment('maldo', 'split1')", "'<KEY>' '<KEY>2FwYWJpbGl0eSI6IntcIk1UW' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpY<KEY>bWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' '<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' )", "'split1') == 'on' time.sleep(1) split_changes[1] = { 'since': 1, 'till':", "get_factory('some_apikey', **kwargs) factory.block_until_ready(1) assert factory.ready time.sleep(2) # Get a hook", "# and perform a syncAll that gets this change split_changes[1]", "'/api/splitChanges?since=2' assert req.headers['authorization'] == 'Bearer some_apikey' # SyncAll after push", "'GET' assert req.path == '/api/segmentChanges/__SOME_INVALID_SEGMENT__?since=-1' assert req.headers['authorization'] == 'Bearer some_apikey'", "assert req.headers['authorization'] == 'Bearer some_apikey' # SyncAll after streaming disabled", "BE but don't send the event. # We'll send an", "}) } def make_simple_split(name, cn, active, killed, default_treatment, tt, on):", "3, 'till': 3, 'splits': []} sse_server.publish(make_split_change_event(3)) time.sleep(1) assert factory.client().get_treatment('maldo', 'split1')", "== '/event-stream' qs = parse_qs(qs) assert qs['accessToken'][0] == ( '<KEY>'", "= { 'since': 2, 'till': 3, 'splits': [make_split_with_segment('split2', 2, True,", "= logging.StreamHandler() formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s') handler.setFormatter(formatter) logger.addHandler(handler)", "'splits': []} sse_server.publish(make_split_change_event(2)) time.sleep(1) assert factory.client().get_treatment('maldo', 'split1') == 'off' split_changes[2]", "notification req = split_backend_requests.get() assert req.method == 'GET' assert req.path", "'split1') == 'off' assert task.running() # We make another chagne", "'id':'TVUsxaabHs:0:0', 'clientId':'pri:MzM0ODI1MTkxMw==', 'timestamp': timestamp, 'encoding':'json', 'channel':'[?occupancy=metrics.publishers]control_pri', 'data': json.dumps({ 'type': 'CONTROL',", "'till': 1, 'splits': []} } segment_changes = {} split_backend_requests =", "tt, on): \"\"\"Make a simple split.\"\"\" return { 'trafficTypeName': tt,", "assert factory.client().get_treatment('maldo', 'split1') == 'on' # Make a change in", "happened split_changes[1] = { 'since': 1, 'till': 2, 'splits': [make_simple_split('split1',", "assert qs['accessToken'][0] == ( '<KEY>' 'US45QnJtR<KEY>' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' '<KEY>WJ<KEY>' '<KEY>'", "'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' 'HktY2xpZW<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert set(qs['channels'][0].split(',')) == set(['MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits',", "parse_qs(qs) assert qs['accessToken'][0] == ( '<KEY>' 'US45QnJtR0EiLCJ0eXAiOiJKV1QifQ.eyJ4LWFibHktY2FwYWJpbGl0eSI6IntcIk1UW' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY'", "== 'off' split_changes[2] = { 'since': 2, 'till': 3, 'splits':", "Cleanup destroy_event = threading.Event() factory.destroy(destroy_event) destroy_event.wait() sse_server.publish(sse_server.GRACEFUL_REQUEST_END) sse_server.stop() split_backend.stop() def", "'off', 'user', False)] } split_changes[2] = {'since': 2, 'till': 2,", "assert not task.running() split_changes[2] = { 'since': 2, 'till': 3,", "streamin afterwards.\"\"\" auth_server_response = { 'pushEnabled': True, 'token': ('<KEY> '<KEY>'", "None, 'whitelistMatcherData': None } ] }, 'partitions': [ {'treatment': 'on'", "assert factory.client().get_treatment('maldo', 'split1') == 'on' assert not task.running() sse_server.publish(make_ably_error_event(40145, 401))", "'till': 4, 'splits': []} sse_server.publish(make_split_change_event(4)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') ==", "[]} sse_server.publish(make_split_change_event(2)) time.sleep(1) assert factory.client().get_treatment('maldo', 'split1') == 'off' sse_server.publish(SSEMockServer.GRACEFUL_REQUEST_END) time.sleep(1)", "the BE and don't send the event. # We restore", "10000, 'featuresRefreshRate': 100, 'segmentsRefreshRate': 100, 'metricsRefreshRate': 100, 'impressionsRefreshRate': 100, 'eventsPushRate':", "def make_initial_event(): \"\"\"Make a split change event.\"\"\" return {'id':'TVUsxaabHs:0:0'} def", "True, 'token': ('<KEY> '<KEY>' '<KEY>' '<KEY>' '<KEY>' '<KEY>' '<KEY>' '<KEY>'", "properly split_changes[2] = { 'since': 2, 'till': 3, 'splits': [make_simple_split('split1',", "cn, active, killed, default_treatment, tt, on, segment): \"\"\"Make a split", "True)] }, 1: {'since': 1, 'till': 1, 'splits': []} }", "'<KEY>' 'US45QnJtR0EiLCJ0eXAiOiJKV1QifQ.eyJ4LWFibHktY2FwYWJpbGl0eSI6IntcIk1UW' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' '<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' )", "sse_server.publish(sse_server.GRACEFUL_REQUEST_END) time.sleep(3) # Assert sync-task is running and the streaming", "req.headers['authorization'] == 'Bearer some_apikey' # SyncAll after non recoverable ably", "json.dumps({ 'type': 'CONTROL', 'controlType': control_type, }) }) } def make_ably_error_event(code,", "assert factory.ready assert factory.client().get_treatment('maldo', 'split1') == 'on' time.sleep(1) split_changes[1] =", "1, True, False, 'on', 'user', True)] }, 1: { 'since':", "= { 'name': 'segment1', 'added': ['maldo'], 'removed': [], 'since': -1,", "get_factory('some_apikey', **kwargs) factory.block_until_ready(1) assert factory.ready assert factory.client().get_treatment('maldo', 'split1') == 'on'", "req.path == '/api/splitChanges?since=4' assert req.headers['authorization'] == 'Bearer some_apikey' # SyncAll", "from splitio.client.factory import get_factory from tests.helpers.mockserver import SSEMockServer, SplitMockServer try:", "task.running() # Send a non-retryable ably error sse_server.publish(make_ably_error_event(40200, 402)) sse_server.publish(sse_server.GRACEFUL_REQUEST_END)", "= { 'since': 1, 'till': 2, 'splits': [make_simple_split('split1', 2, True,", "'till': 3, 'splits': []} segment_changes[('segment1', -1)] = { 'name': 'segment1',", "sse_server.publish(make_occupancy('control_sec', 0)) kwargs = { 'sdk_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'events_api_base_url':", "'<KEY>' '<KEY>' '<KEY>' '<KEY>' '<KEY>' '<KEY>' '<KEY>' 'vJh17WlOlAKhcD0') } split_changes", "if on else 'on', 'size': 0} ] } ] }", "'on' assert not task.running() sse_server.publish(make_ably_error_event(40145, 401)) sse_server.publish(sse_server.GRACEFUL_REQUEST_END) time.sleep(3) assert task.running()", "= {'since': 2, 'till': 2, 'splits': []} sse_server.publish(make_ably_error_event(60000, 600)) time.sleep(1)", "'changeNumber': change_number }) }) } def make_initial_event(): \"\"\"Make a split", "is running and the streaming status handler thread is over", "== 'off' assert not task.running() # Validate the SSE request", "event. # We restore occupancy, and it should be fetched", "a change in the BE but don't send the event.", "False, 'userDefinedSegmentMatcherData': None, 'whitelistMatcherData': None } ] }, 'partitions': [", "not in [t.name for t in threading.enumerate()] # Validate the", "'auth_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'streaming_api_base_url': 'http://localhost:%d' % sse_server.port(), 'config': {'connectTimeout':", "running and the streaming status handler thread is over assert", "assert factory.client().get_treatment('pindon', 'split2') == 'off' assert factory.client().get_treatment('maldo', 'split2') == 'on'", "factory.destroy(destroy_event) destroy_event.wait() sse_server.publish(sse_server.GRACEFUL_REQUEST_END) sse_server.stop() split_backend.stop() def test_streaming_status_changes(self): \"\"\"Test changes between", "task.running() split_changes[2] = { 'since': 2, 'till': 3, 'splits': [make_simple_split('split1',", "'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments', '[?occupancy=metrics.publishers]control_pri', '[?occupancy=metrics.publishers]control_sec']) assert qs['v'][0] == '1.1' sse_request = sse_requests.get()", "the connection, the whole flow is retried with BO.\"\"\" auth_server_response", "\"\"\"Make a split change event.\"\"\" return {'id':'TVUsxaabHs:0:0'} def make_occupancy(channel, publishers):", "assert factory.client().get_treatment('maldo', 'split1') == 'frula' # Validate the SSE request", "a segment.\"\"\" return { 'trafficTypeName': tt, 'name': name, 'seed': cn,", "all after streaming is restored. split_changes[2] = { 'since': 2,", "'splits': [make_simple_split('split1', 2, True, False, 'off', 'user', False)] } split_changes[2]", "'[?occupancy=metrics.publishers]control_pri', '[?occupancy=metrics.publishers]control_sec']) assert qs['v'][0] == '1.1' # Initial apikey validation", "assert req.headers['authorization'] == 'Bearer some_apikey' # SyncAll on retryable error", "1} sse_server.publish(make_split_change_event(3)) time.sleep(1) sse_server.publish(make_segment_change_event('segment1', 1)) time.sleep(1) assert factory.client().get_treatment('pindon', 'split2') ==", "'removed': [], 'since': 1, 'till': 1} sse_server.publish(make_split_change_event(3)) time.sleep(1) sse_server.publish(make_segment_change_event('segment1', 1))", "Queue() split_backend = SplitMockServer(split_changes, segment_changes, split_backend_requests, auth_server_response) sse_requests = Queue()", "[make_simple_split('split1', 5, True, False, 'off', 'user', True)] } split_changes[5] =", "'channel': \"[?occupancy=metrics.publishers]%s\" % channel, 'data': json.dumps({'metrics': {'publishers': publishers}}), 'name':'[meta]occupancy' })", "python3 names. fallback to python2 from urllib.parse import parse_qs except", "json.dumps({ 'message':'Invalid accessToken in request: sarasa', 'code': code, 'statusCode': status,", "True, 'token': ('<KEY> '<KEY>' '<KEY>' '<KEY>' '<KEY>' '<KEY>' '<KEY>' 'CI6MTYwNDEwMDU5MSwiaWF0IjoxNjA0MDk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5E'", "[]} sse_server.publish(make_split_change_event(4)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'off' # Kill", "time.sleep(3) assert not task.running() # Assert streaming is working properly", "logging.StreamHandler() formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) logger.setLevel(logging.DEBUG)", "initial event AND occupancy sse_server.publish(make_initial_event()) sse_server.publish(make_occupancy('control_pri', 2)) sse_server.publish(make_occupancy('control_sec', 2)) time.sleep(2)", "pylint:disable=protected-access assert not task.running() assert factory.client().get_treatment('maldo', 'split1') == 'on' #", "some_apikey' # Split kill req = split_backend_requests.get() assert req.method ==", "**kwargs) factory.block_until_ready(1) assert factory.ready assert factory.client().get_treatment('maldo', 'split1') == 'on' time.sleep(1)", "some_apikey' # Fetch after first notification req = split_backend_requests.get() assert", "= parse_qs(qs) assert qs['accessToken'][0] == ( '<KEY>' '<KEY>' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI'", "pylint:disable=no-self-use,invalid-name,too-many-arguments,too-few-public-methods,line-too-long # pylint:disable=too-many-statements,too-many-locals,too-many-lines import threading import time import json from", "'id':'TVUsxaabHs:0:0', 'clientId':'pri:MzM0ODI1MTkxMw==', 'timestamp': change_number-1, 'encoding':'json', 'channel':'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments', 'data': json.dumps({ 'type': 'SEGMENT_UPDATE',", "'<KEY>' 'Dk2OTkxfQ.<KEY>' ) assert set(qs['channels'][0].split(',')) == set(['MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments', '[?occupancy=metrics.publishers]control_pri', '[?occupancy=metrics.publishers]control_sec'])", "'Bearer some_apikey' # SyncAll after push down req = split_backend_requests.get()", "= {'name': 'segment1', 'added': [], 'removed': [], 'since': 1, 'till':", "json.dumps({ 'type': 'SPLIT_UPDATE', 'changeNumber': change_number }) }) } def make_split_kill_event(name,", "sse_server.publish(sse_server.GRACEFUL_REQUEST_END) sse_server.stop() split_backend.stop() def test_streaming_status_changes(self): \"\"\"Test changes between streaming enabled,", "2, 'splits': []} sse_server.publish(make_split_change_event(2)) time.sleep(1) assert factory.client().get_treatment('maldo', 'split1') == 'off'", "'/api/splitChanges?since=1' assert req.headers['authorization'] == 'Bearer some_apikey' # Iteration until since", "== '/api/splitChanges?since=1' assert req.headers['authorization'] == 'Bearer some_apikey' # SyncAll retriable", "in occupancy switch between polling & streaming properly.\"\"\" auth_server_response =", "== '1.1' assert sse_request.method == 'GET' path, qs = sse_request.path.split('?',", "'data': json.dumps({ 'id':'TVUsxaabHs:0:0', 'clientId':'pri:MzM0ODI1MTkxMw==', 'timestamp': change_number-1, 'encoding':'json', 'channel':'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'data': json.dumps({", "[]} sse_server.publish(make_split_kill_event('split1', 'frula', 5)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'frula'", "Auth after connection breaks req = split_backend_requests.get() assert req.method ==", "but don't send the event. # After dropping occupancy, the", "connected again req = split_backend_requests.get() assert req.method == 'GET' assert", "'<KEY>' '<KEY>' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' '<KEY>UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV<KEY>I' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaV<KEY>' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXC<KEY>' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' '<KEY>' 'Dk2OTkxfQ.<KEY>' )", "== ( '<KEY>' 'US45QnJtR0EiLCJ0eXAiOiJKV1QifQ.eyJ4LWFibHktY2FwYWJpbGl0eSI6IntcIk1UW' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' '<KEY>'", "parse_qs(qs) assert qs['accessToken'][0] == ( '<KEY>' '<KEY>2FwYWJpbGl0eSI6IntcIk1UW' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY'", "'HktY2xpZW<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert set(qs['channels'][0].split(',')) == set(['MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments', '[?occupancy=metrics.publishers]control_pri', '[?occupancy=metrics.publishers]control_sec'])", "split_changes[3] = {'since': 3, 'till': 3, 'splits': []} sse_server.publish(make_split_change_event(3)) time.sleep(1)", "working properly split_changes[2] = { 'since': 2, 'till': 3, 'splits':", "assert factory.client().get_treatment('maldo', 'split1') == 'on' assert not task.running() # Validate", "== 'off' assert not task.running() split_changes[4] = { 'since': 4,", "'channel':'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'data': json.dumps({ 'type': 'SPLIT_UPDATE', 'changeNumber': change_number }) }) }", "Initial splits fetch req = split_backend_requests.get() assert req.method == 'GET'", "if on else 'off', 'size': 100}, {'treatment': 'off' if on", "2, True, False, 'off', 'user', False)] } split_changes[2] = {'since':", "'CI6MTYwNDEwMDU5MSwiaWF0IjoxNjA0MDk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5E' '<KEY>') } split_changes = { -1: { 'since': -1,", "incoming ably errors and validate its handling.\"\"\" import logging logger", "# pylint:disable=too-many-statements,too-many-locals,too-many-lines import threading import time import json from queue", "== '/api/splitChanges?since=1' assert req.headers['authorization'] == 'Bearer some_apikey' # Fetch after", "Split kill req = split_backend_requests.get() assert req.method == 'GET' assert", "handling req = split_backend_requests.get() assert req.method == 'GET' assert req.path", "== 'on' task = factory._sync_manager._synchronizer._split_tasks.split_task._task # pylint:disable=protected-access assert not task.running()", "'data': json.dumps({ 'type': 'SPLIT_KILL', 'splitName': name, 'defaultTreatment': default_treatment, 'changeNumber': change_number", "'treatment': 'on' if on else 'off', 'size': 100 }] }", "active, killed, default_treatment, tt, on, segment): \"\"\"Make a split with", "sse_server.port(), 'config': {'connectTimeout': 10000, 'featuresRefreshRate': 100, 'segmentsRefreshRate': 100, 'metricsRefreshRate': 100,", "'trafficTypeName': tt, 'name': name, 'seed': 1699838640, 'status': 'ACTIVE' if active", "on, segment): \"\"\"Make a split with a segment.\"\"\" return {", "assert not task.running() sse_server.publish(make_ably_error_event(40145, 401)) sse_server.publish(sse_server.GRACEFUL_REQUEST_END) time.sleep(3) assert task.running() assert", "'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' 'HktY2xpZW<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert set(qs['channels'][0].split(',')) ==", "= { -1: { 'since': -1, 'till': 1, 'splits': [make_simple_split('split1',", "'dGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFibHktY2xpZW50SWQiOiJjbGllbnRJZCIsImV4c' 'CI6MTYwNDEwMDU5MSwiaWF0IjoxNjA0MDk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5E' 'vJh17WlOlAKhcD0') } split_changes = { -1: { 'since':", "req.path == '/api/splitChanges?since=-1' assert req.headers['authorization'] == 'Bearer some_apikey' # Iteration", "tt, on, segment): \"\"\"Make a split with a segment.\"\"\" return", "'since': -1, 'till': 1 } segment_changes[('segment1', 1)] = {'name': 'segment1',", "'name':'[meta]occupancy' }) } def make_segment_change_event(name, change_number): \"\"\"Make a split change", "req.headers['authorization'] == 'Bearer some_apikey' # SyncAll after push down req", "'SPLIT_KILL', 'splitName': name, 'defaultTreatment': default_treatment, 'changeNumber': change_number }) }) }", "cn, active, killed, default_treatment, tt, on): \"\"\"Make a simple split.\"\"\"", "after new notification req = split_backend_requests.get() assert req.method == 'GET'", "return { 'event': 'error', 'data': json.dumps({ 'message':'Invalid accessToken in request:", "initialization & splits/segment updates.\"\"\" auth_server_response = { 'pushEnabled': True, 'token':", "1699838640, 'status': 'ACTIVE' if active else 'ARCHIVED', 'changeNumber': cn, 'killed':", "some_apikey' # Second iteration of previous syncAll req = split_backend_requests.get()", "'Bearer some_apikey' # Auth after connection breaks req = split_backend_requests.get()", "'featuresRefreshRate': 100, 'segmentsRefreshRate': 100, 'metricsRefreshRate': 100, 'impressionsRefreshRate': 100, 'eventsPushRate': 100}", "factory.client().get_treatment('maldo', 'split1') == 'off' assert not task.running() split_changes[4] = {", "['maldo'], 'removed': [], 'since': -1, 'till': 1 } segment_changes[('segment1', 1)]", "non-retryable ably error sse_server.publish(make_ably_error_event(40200, 402)) sse_server.publish(sse_server.GRACEFUL_REQUEST_END) time.sleep(3) # Assert sync-task", "'message', 'data': json.dumps({ 'id':'aP6EuhrcUm:0:0', 'timestamp':1604325712734, 'encoding': 'json', 'channel': \"[?occupancy=metrics.publishers]%s\" %", "split_backend_requests = Queue() split_backend = SplitMockServer(split_changes, segment_changes, split_backend_requests, auth_server_response) sse_requests", "task.running() sse_server.publish(make_ably_error_event(40145, 401)) sse_server.publish(sse_server.GRACEFUL_REQUEST_END) time.sleep(3) assert task.running() assert factory.client().get_treatment('maldo', 'split1')", "True, False, 'off', 'user', 'off', 'segment1')] } split_changes[3] = {'since':", "{'id':'TVUsxaabHs:0:0'} def make_occupancy(channel, publishers): \"\"\"Make an occupancy event.\"\"\" return {", "# SyncAll after streaming disabled req = split_backend_requests.get() assert req.method", "== 'Bearer some_apikey' # SyncAll after streaming connected again req", "== 'GET' assert req.path == '/api/segmentChanges/__SOME_INVALID_SEGMENT__?since=-1' assert req.headers['authorization'] == 'Bearer", "split.\"\"\" return { 'trafficTypeName': tt, 'name': name, 'seed': 1699838640, 'status':", "changes between streaming enabled, paused and disabled.\"\"\" auth_server_response = {", "True, False, 'on', 'user', True)] }, 1: { 'since': 1,", "and perform a syncAll that gets this change split_changes[1] =", "sse_server.publish(make_occupancy('control_sec', 0)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'off' assert task.running()", "== ( '<KEY>' '<KEY>' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' 'HktY2xpZW50SWQiOiJjbGllbnRJZCIsImV4cCI6MTYwNDEwMDU5MSwiaWF0IjoxNjA0M'", "streaming properly.\"\"\" auth_server_response = { 'pushEnabled': True, 'token': ('<KEY> '<KEY>'", "error handling req = split_backend_requests.get() assert req.method == 'GET' assert", "'split1') == 'off' sse_server.publish(SSEMockServer.GRACEFUL_REQUEST_END) time.sleep(1) assert factory.client().get_treatment('maldo', 'split1') == 'off'", "\"\"\"Make a control event.\"\"\" return { 'event': 'error', 'data': json.dumps({", "json.dumps({ 'id':'aP6EuhrcUm:0:0', 'timestamp':1604325712734, 'encoding': 'json', 'channel': \"[?occupancy=metrics.publishers]%s\" % channel, 'data':", "factory.destroy(destroy_event) destroy_event.wait() sse_server.publish(sse_server.GRACEFUL_REQUEST_END) sse_server.stop() split_backend.stop() def test_start_without_occupancy(self): \"\"\"Test an SDK", "assert not task.running() # Assert streaming is working properly split_changes[2]", "= logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) logger.setLevel(logging.DEBUG) auth_server_response =", "} split_changes = { -1: { 'since': -1, 'till': 1,", "time.sleep(1) assert factory.client().get_treatment('maldo', 'split1') == 'off' split_changes[2] = { 'since':", "'off' # Kill the split split_changes[4] = { 'since': 4,", "send an ignorable error and check it has nothing happened", "timestamp, 'encoding':'json', 'channel':'[?occupancy=metrics.publishers]control_pri', 'data': json.dumps({ 'type': 'CONTROL', 'controlType': control_type, })", "else 'ARCHIVED', 'changeNumber': cn, 'killed': killed, 'defaultTreatment': default_treatment, 'conditions': [", "'AND', 'matchers': [ { 'matcherType': 'IN_SEGMENT', 'negate': False, 'userDefinedSegmentMatcherData': {'segmentName':", "else 'off', 'size': 100}, {'treatment': 'off' if on else 'on',", "time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'off' assert not task.running() #", "destroy_event.wait() sse_server.publish(sse_server.GRACEFUL_REQUEST_END) sse_server.stop() split_backend.stop() def test_server_closes_connection(self): \"\"\"Test that if the", "'http://localhost:%d' % sse_server.port(), 'config': {'connectTimeout': 10000} } factory = get_factory('some_apikey',", "'WJzY3JpY<KEY>bWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' '<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert set(qs['channels'][0].split(',')) == set(['MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments', '[?occupancy=metrics.publishers]control_pri',", "factory.client().get_treatment('maldo', 'split1') == 'off' # Re-publish initial events so that", "== 'Bearer some_apikey' # Fetch after notification req = split_backend_requests.get()", "2, 'splits': []} sse_server.publish(make_occupancy('control_sec', 1)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') ==", "not task.running() assert factory.client().get_treatment('maldo', 'split1') == 'on' # Make a", "# SyncAll on push down req = split_backend_requests.get() assert req.method", "'http://localhost:%d' % sse_server.port(), 'config': {'connectTimeout': 10000, 'featuresRefreshRate': 100, 'segmentsRefreshRate': 100,", "2, 'till': 2, 'splits': []} sse_server.publish(make_occupancy('control_sec', 1)) time.sleep(2) assert factory.client().get_treatment('maldo',", "'since': -1, 'till': 1, 'splits': [make_simple_split('split1', 1, True, False, 'on',", "segment): \"\"\"Make a split with a segment.\"\"\" return { 'trafficTypeName':", "task = factory._sync_manager._synchronizer._split_tasks.split_task._task # pylint:disable=protected-access assert not task.running() assert factory.client().get_treatment('maldo',", "Make a change in the BE but don't send the", "push restored req = split_backend_requests.get() assert req.method == 'GET' assert", "= {'since': 2, 'till': 2, 'splits': []} sse_server.publish(make_split_change_event(2)) time.sleep(1) assert", "'1.1' # Initial apikey validation req = split_backend_requests.get() assert req.method", "streaming operation and failover.\"\"\" def test_happiness(self): \"\"\"Test initialization & splits/segment", "re-attached # re-send initial event AND occupancy sse_server.publish(make_initial_event()) sse_server.publish(make_occupancy('control_pri', 2))", "'matchers': [ { 'matcherType': 'IN_SEGMENT', 'negate': False, 'userDefinedSegmentMatcherData': {'segmentName': segment},", "assert req.headers['authorization'] == 'Bearer some_apikey' # Auth after connection breaks", "assert req.headers['authorization'] == 'Bearer some_apikey' # Initial splits fetch req", "= split_backend_requests.get() assert req.method == 'GET' assert req.path == '/api/segmentChanges/__SOME_INVALID_SEGMENT__?since=-1'", "the event. # After restoring occupancy, the sdk should switch", "[ {'treatment': 'on' if on else 'off', 'size': 100}, {'treatment':", "sse_server.publish(make_occupancy('control_pri', 0)) sse_server.publish(make_occupancy('control_sec', 0)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'off'", "2)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'on' assert task.running() assert", "an ignorable error and check it has nothing happened split_changes[1]", "'SEGMENT_UPDATE', 'segmentName': name, 'changeNumber': change_number }) }) } def make_control_event(control_type,", "qs = parse_qs(qs) assert qs['accessToken'][0] == ( '<KEY>' '<KEY>2FwYWJpbGl0eSI6IntcIk1UW' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc'", "restore occupancy, and it should be fetched by the #", "and switching to streamin afterwards.\"\"\" auth_server_response = { 'pushEnabled': True,", "== 'on' # Validate the SSE request sse_request = sse_requests.get()", "qs = parse_qs(qs) assert qs['accessToken'][0] == ( '<KEY>' '<KEY>' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc'", "'event': 'message', 'data': json.dumps({ 'id':'TVUsxaabHs:0:0', 'clientId':'pri:MzM0ODI1MTkxMw==', 'timestamp': change_number-1, 'encoding':'json', 'channel':'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits',", "} split_changes[2] = {'since': 2, 'till': 2, 'splits': []} sse_server.publish(make_split_change_event(2))", "assert req.headers['authorization'] == 'Bearer some_apikey' # SyncAll after non recoverable", "import SSEMockServer, SplitMockServer try: # try to import python3 names.", ") assert set(qs['channels'][0].split(',')) == set(['MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments', '[?occupancy=metrics.publishers]control_pri', '[?occupancy=metrics.publishers]control_sec']) assert qs['v'][0]", "'CI6MTYwNDEwMDU5MSwiaWF0IjoxNjA0MDk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5E' 'vJh17WlOlAKhcD0') } split_changes = { -1: { 'since': -1,", "'till': 2, 'splits': []} sse_server.publish(make_occupancy('control_pri', 0)) sse_server.publish(make_occupancy('control_sec', 0)) time.sleep(2) assert", "sse_server.publish(make_split_change_event(4)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'off' # Kill the", "'Bearer some_apikey' # SyncAll after streaming connected again req =", "== 'Bearer some_apikey' # SyncAll after streaming connected req =", "'clientId':'pri:MzM0ODI1MTkxMw==', 'timestamp': change_number-1, 'encoding':'json', 'channel':'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'data': json.dumps({ 'type': 'SPLIT_UPDATE', 'changeNumber':", "}) } def make_segment_change_event(name, change_number): \"\"\"Make a split change event.\"\"\"", "assert req.headers['authorization'] == 'Bearer some_apikey' # SyncAll on push down", "this change split_changes[1] = { 'since': 1, 'till': 2, 'splits':", "3, 'splits': []} sse_server.publish(make_split_change_event(3)) time.sleep(1) assert factory.client().get_treatment('maldo', 'split1') == 'on'", "assert 'PushStatusHandler' not in [t.name for t in threading.enumerate()] #", "kill req = split_backend_requests.get() assert req.method == 'GET' assert req.path", "1, 'till': 2, 'splits': [make_simple_split('split1', 2, True, False, 'off', 'user',", "== 'Bearer some_apikey' # Auth after connection breaks req =", "False, 'off', 'user', 'off', 'segment1')] } split_changes[3] = {'since': 3,", "= split_backend_requests.get() assert req.method == 'GET' assert req.path == '/api/splitChanges?since=4'", "assert req.headers['authorization'] == 'Bearer some_apikey' # Fetch after notification req", "send the event. # After restoring occupancy, the sdk should", "SSEMockServer(sse_requests) split_backend.start() sse_server.start() sse_server.publish(make_initial_event()) sse_server.publish(make_occupancy('control_pri', 2)) sse_server.publish(make_occupancy('control_sec', 2)) kwargs =", "}) } def make_ably_error_event(code, status): \"\"\"Make a control event.\"\"\" return", "from queue import Queue from splitio.client.factory import get_factory from tests.helpers.mockserver", "req.path == '/api/splitChanges?since=2' assert req.headers['authorization'] == 'Bearer some_apikey' # Fetch", "'<KEY>' 'CI6MTYwNDEwMDU5MSwiaWF0IjoxNjA0MDk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5E' 'vJh17WlOlAKhcD0') } split_changes = { -1: { 'since':", "a control event.\"\"\" return { 'event': 'error', 'data': json.dumps({ 'message':'Invalid", "Initial apikey validation req = split_backend_requests.get() assert req.method == 'GET'", "-1, 'till': 1, 'splits': [make_simple_split('split1', 1, True, False, 'on', 'user',", "{ 'matcherType': 'ALL_KEYS', 'negate': False, 'userDefinedSegmentMatcherData': None, 'whitelistMatcherData': None }", "'on' time.sleep(1) split_changes[1] = { 'since': 1, 'till': 2, 'splits':", "cn, 'killed': killed, 'defaultTreatment': default_treatment, 'conditions': [ { 'matcherGroup': {", "= {'since': 2, 'till': 2, 'splits': []} sse_server.publish(make_occupancy('control_sec', 1)) time.sleep(2)", "time.sleep(1) assert factory.client().get_treatment('pindon', 'split2') == 'off' assert factory.client().get_treatment('maldo', 'split2') ==", "time.sleep(2) # wait for the backoff to expire so streaming", "SyncAll after push is up req = split_backend_requests.get() assert req.method", "req.headers['authorization'] == 'Bearer some_apikey' # SyncAll after streaming connected again", "False, 'off', 'user', False)] } split_changes[2] = {'since': 2, 'till':", "factory = get_factory('some_apikey', **kwargs) factory.block_until_ready(1) assert factory.ready time.sleep(2) # Get", "sse_server.publish(make_occupancy('control_sec', 1)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'off' assert not", "} segment_changes[('segment1', 1)] = {'name': 'segment1', 'added': [], 'removed': [],", "'/event-stream' qs = parse_qs(qs) assert qs['accessToken'][0] == ( '<KEY>' 'US45QnJtR0EiLCJ0eXAiOiJKV1QifQ.eyJ4LWFibHktY2FwYWJpbGl0eSI6IntcIk1UW'", "not task.running() # Validate the SSE requests sse_request = sse_requests.get()", "assert req.path == '/api/splitChanges?since=-1' assert req.headers['authorization'] == 'Bearer some_apikey' #", "'1.1' sse_request = sse_requests.get() assert sse_request.method == 'GET' path, qs", "[]} } segment_changes = {} split_backend_requests = Queue() split_backend =", "2)) kwargs = { 'sdk_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'events_api_base_url': 'http://localhost:%d/api'", "status task = factory._sync_manager._synchronizer._split_tasks.split_task._task # pylint:disable=protected-access assert not task.running() assert", "'<KEY>') } split_changes = { -1: { 'since': -1, 'till':", "import parse_qs class StreamingIntegrationTests(object): \"\"\"Test streaming operation and failover.\"\"\" def", "== '/api/splitChanges?since=2' assert req.headers['authorization'] == 'Bearer some_apikey' # Auth again", "split_backend_requests.get() assert req.method == 'GET' assert req.path == '/api/segmentChanges/segment1?since=1' assert", "sse_requests.get() assert sse_request.method == 'GET' path, qs = sse_request.path.split('?', 1)", "dropping occupancy, the sdk should switch to polling # and", "# We restore occupancy, and it should be fetched by", "'splits': [make_simple_split('split1', 5, True, True, 'frula', 'user', False)] } split_changes[5]", "'GET' assert req.path == '/api/segmentChanges/segment1?since=1' assert req.headers['authorization'] == 'Bearer some_apikey'", "time.sleep(1) assert factory.client().get_treatment('maldo', 'split1') == 'on' assert not task.running() sse_server.publish(make_ably_error_event(40145,", "task.running() # Validate the SSE requests sse_request = sse_requests.get() assert", "'Bearer some_apikey' # SyncAll retriable error req = split_backend_requests.get() assert", "[make_simple_split('split1', 5, True, True, 'frula', 'user', False)] } split_changes[5] =", "'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaV<KEY>' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXC<KEY>' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' '<KEY>' 'Dk2OTkxfQ.<KEY>' ) assert set(qs['channels'][0].split(',')) == set(['MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits',", "time.sleep(3) # Assert sync-task is running and the streaming status", "sse_server.publish(make_control_event('STREAMING_PAUSED', 1)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'off' assert task.running()", "'Bearer some_apikey' # SyncAll after push restored req = split_backend_requests.get()", "# Iteration until since == till req = split_backend_requests.get() assert", "}) }) } def make_split_kill_event(name, default_treatment, change_number): \"\"\"Make a split", "assert req.path == '/api/auth' assert req.headers['authorization'] == 'Bearer some_apikey' #", "split_backend.stop() def test_ably_errors_handling(self): \"\"\"Test incoming ably errors and validate its", "split_backend.stop() def test_start_without_occupancy(self): \"\"\"Test an SDK starting with occupancy on", "SyncAll after non recoverable ably error req = split_backend_requests.get() assert", "'<KEY>' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' '<KEY>UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV<KEY>I' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaV<KEY>' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXC<KEY>' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' '<KEY>' 'Dk2OTkxfQ.<KEY>' ) assert", "[]} sse_server.publish(make_split_change_event(3)) time.sleep(1) assert factory.client().get_treatment('maldo', 'split1') == 'on' assert not", "} split_changes[2] = {'since': 2, 'till': 2, 'splits': []} sse_server.publish(make_control_event('STREAMING_PAUSED',", "'2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' '<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert set(qs['channels'][0].split(',')) == set(['MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments',", "% channel, 'data': json.dumps({'metrics': {'publishers': publishers}}), 'name':'[meta]occupancy' }) } def", "'US45QnJtR0EiLCJ0eXAiOiJKV1QifQ.eyJ4LWFibHktY2FwYWJpbGl0eSI6IntcIk1UW' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' '<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert", "'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments', '[?occupancy=metrics.publishers]control_pri', '[?occupancy=metrics.publishers]control_sec']) assert qs['v'][0] == '1.1' # Initial apikey", "in [t.name for t in threading.enumerate()] # Validate the SSE", "sse_server.publish(sse_server.GRACEFUL_REQUEST_END) sse_server.stop() split_backend.stop() def test_ably_errors_handling(self): \"\"\"Test incoming ably errors and", "{ 'name': 'segment1', 'added': ['maldo'], 'removed': [], 'since': -1, 'till':", "sse_server.publish(make_split_kill_event('split1', 'frula', 5)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'frula' #", "'off' assert factory.client().get_treatment('maldo', 'split2') == 'on' # Validate the SSE", "sse_server.publish(make_occupancy('control_pri', 0)) sse_server.publish(make_occupancy('control_sec', 0)) kwargs = { 'sdk_api_base_url': 'http://localhost:%d/api' %", "# Now we make another change and send an event", "= threading.Event() factory.destroy(destroy_event) destroy_event.wait() sse_server.publish(sse_server.GRACEFUL_REQUEST_END) sse_server.stop() split_backend.stop() def test_streaming_status_changes(self): \"\"\"Test", "task.running() time.sleep(1) split_changes[1] = { 'since': 1, 'till': 2, 'splits':", "== set(['MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments', '[?occupancy=metrics.publishers]control_pri', '[?occupancy=metrics.publishers]control_sec']) assert qs['v'][0] == '1.1' assert", "== 'off' # Kill the split split_changes[4] = { 'since':", "'/api/splitChanges?since=5' assert req.headers['authorization'] == 'Bearer some_apikey' # Cleanup destroy_event =", "'till': 1 } segment_changes[('segment1', 1)] = {'name': 'segment1', 'added': [],", "factory.client().get_treatment('maldo', 'split1') == 'off' split_changes[2] = { 'since': 2, 'till':", "'partitions': [ {'treatment': 'on' if on else 'off', 'size': 100},", "of the task so we can query its status task", "factory.destroy(destroy_event) destroy_event.wait() sse_server.publish(sse_server.GRACEFUL_REQUEST_END) sse_server.stop() split_backend.stop() def make_split_change_event(change_number): \"\"\"Make a split", "split_backend_requests.get() assert req.method == 'GET' assert req.path == '/api/splitChanges?since=-1' assert", "assert req.method == 'GET' assert req.path == '/api/segmentChanges/segment1?since=1' assert req.headers['authorization']", "sse_server.port(), 'config': {'connectTimeout': 10000, 'featuresRefreshRate': 10} } factory = get_factory('some_apikey',", "= SplitMockServer(split_changes, segment_changes, split_backend_requests, auth_server_response) sse_requests = Queue() sse_server =", "parse_qs(qs) assert qs['accessToken'][0] == ( '<KEY>' 'US45QnJtR<KEY>' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' '<KEY>WJ<KEY>'", "'segment1')] } split_changes[3] = {'since': 3, 'till': 3, 'splits': []}", "'/api/splitChanges?since=1' assert req.headers['authorization'] == 'Bearer some_apikey' # SyncAll after push", "don't send the event. # We'll send an ignorable error", "= threading.Event() factory.destroy(destroy_event) destroy_event.wait() sse_server.publish(sse_server.GRACEFUL_REQUEST_END) sse_server.stop() split_backend.stop() def test_server_closes_connection(self): \"\"\"Test", "} def make_segment_change_event(name, change_number): \"\"\"Make a split change event.\"\"\" return", "some_apikey' # Auth again req = split_backend_requests.get() assert req.method ==", "'/api/segmentChanges/segment1?since=-1' assert req.headers['authorization'] == 'Bearer some_apikey' # Iteration until segment1", "\"\"\"Test initialization & splits/segment updates.\"\"\" auth_server_response = { 'pushEnabled': True,", "streaming gets re-attached # re-send initial event AND occupancy sse_server.publish(make_initial_event())", "%(message)s') handler.setFormatter(formatter) logger.addHandler(handler) logger.setLevel(logging.DEBUG) auth_server_response = { 'pushEnabled': True, 'token':", "we make another change and send an event so it's", "'matcherGroup': { 'combiner': 'AND', 'matchers': [ { 'matcherType': 'ALL_KEYS', 'negate':", "'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' '<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert set(qs['channels'][0].split(',')) == set(['MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits',", "'id':'TVUsxaabHs:0:0', 'clientId':'pri:MzM0ODI1MTkxMw==', 'timestamp': change_number-1, 'encoding':'json', 'channel':'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'data': json.dumps({ 'type': 'SPLIT_UPDATE',", "'off' assert task.running() # We make another chagne in the", "2)) sse_server.publish(make_occupancy('control_sec', 2)) time.sleep(3) assert not task.running() # Assert streaming", "destroy_event = threading.Event() factory.destroy(destroy_event) destroy_event.wait() sse_server.publish(sse_server.GRACEFUL_REQUEST_END) sse_server.stop() split_backend.stop() def test_streaming_status_changes(self):", "if active else 'ARCHIVED', 'changeNumber': cn, 'killed': killed, 'defaultTreatment': default_treatment,", "req.headers['authorization'] == 'Bearer some_apikey' # Auth req = split_backend_requests.get() assert", "% split_backend.port(), 'streaming_api_base_url': 'http://localhost:%d' % sse_server.port(), 'config': {'connectTimeout': 10000, 'featuresRefreshRate':", "== 'Bearer some_apikey' # Fetch after first notification req =", "factory.client().get_treatment('maldo', 'split1') == 'off' assert task.running() # We make another", "\"\"\"Make a simple split.\"\"\" return { 'trafficTypeName': tt, 'name': name,", "assert req.method == 'GET' assert req.path == '/api/segmentChanges/__SOME_INVALID_SEGMENT__?since=-1' assert req.headers['authorization']", "assert req.path == '/api/segmentChanges/segment1?since=-1' assert req.headers['authorization'] == 'Bearer some_apikey' #", "chagne in the BE and don't send the event. #", "'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' 'HktY2xpZW50SWQiOiJjbG<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert set(qs['channels'][0].split(',')) ==", "'9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJ' 'zXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzdWJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRh' 'dGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFibHktY2xpZW50SWQiOiJjbGllbnRJZCIsImV4c' 'CI6MTYwNDEwMDU5MSwiaWF0IjoxNjA0MDk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5E' '<KEY>') } split_changes = { -1:", "segment_changes = {} split_backend_requests = Queue() split_backend = SplitMockServer(split_changes, segment_changes,", "'till': 4, 'splits': [make_simple_split('split1', 4, True, False, 'off', 'user', False)]", "} def make_simple_split(name, cn, active, killed, default_treatment, tt, on): \"\"\"Make", "is restored. split_changes[2] = { 'since': 2, 'till': 3, 'splits':", "some_apikey' # SyncAll after streaming connected again req = split_backend_requests.get()", "Get a hook of the task so we can query", "'Bearer some_apikey' # Second iteration of previous syncAll req =", "in request: sarasa', 'code': code, 'statusCode': status, 'href':\"https://help.ably.io/error/%d\" % code", "Validate the SSE request sse_request = sse_requests.get() assert sse_request.method ==", "'<KEY>' '<KEY>' '<KEY>' 'vJh17WlOlAKhcD0') } split_changes = { -1: {", "change event.\"\"\" return {'id':'TVUsxaabHs:0:0'} def make_occupancy(channel, publishers): \"\"\"Make an occupancy", "logging logger = logging.getLogger('splitio') handler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s", "some_apikey' # SyncAll on retryable error handling req = split_backend_requests.get()", "down req = split_backend_requests.get() assert req.method == 'GET' assert req.path", "test_occupancy_flicker(self): \"\"\"Test that changes in occupancy switch between polling &", "test_streaming_status_changes(self): \"\"\"Test changes between streaming enabled, paused and disabled.\"\"\" auth_server_response", "event.\"\"\" return { 'event': 'message', 'data': json.dumps({ 'id':'TVUsxaabHs:0:0', 'clientId':'pri:MzM0ODI1MTkxMw==', 'timestamp':", "'data': json.dumps({ 'type': 'SEGMENT_UPDATE', 'segmentName': name, 'changeNumber': change_number }) })", "{'since': 5, 'till': 5, 'splits': []} sse_server.publish(make_control_event('STREAMING_DISABLED', 2)) time.sleep(2) assert", "( '<KEY>' 'US45QnJtR<KEY>' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' '<KEY>WJ<KEY>' '<KEY>' '<KEY>' '<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0'", "split_changes[3] = {'since': 3, 'till': 3, 'splits': []} sse_server.publish(make_split_change_event(3)) time.sleep(2)", "task.running() # We make another chagne in the BE and", "} split_changes[2] = {'since': 2, 'till': 2, 'splits': []} sse_server.publish(make_ably_error_event(60000,", "'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' 'HktY2xpZW<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert set(qs['channels'][0].split(',')) == set(['MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments', '[?occupancy=metrics.publishers]control_pri',", "{ -1: { 'since': -1, 'till': 1, 'splits': [make_simple_split('split1', 1,", "'removed': [], 'since': -1, 'till': 1 } segment_changes[('segment1', 1)] =", "5, 'splits': []} sse_server.publish(make_split_kill_event('split1', 'frula', 5)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1')", "factory.client().get_treatment('pindon', 'split2') == 'off' assert factory.client().get_treatment('maldo', 'split2') == 'on' #", "up req = split_backend_requests.get() assert req.method == 'GET' assert req.path", "# try to import python3 names. fallback to python2 from", "'combiner': 'AND', 'matchers': [ { 'matcherType': 'ALL_KEYS', 'negate': False, 'userDefinedSegmentMatcherData':", "'<KEY>' '<KEY>' '<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert set(qs['channels'][0].split(',')) == set(['MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments',", "3, 'till': 3, 'splits': []} sse_server.publish(make_occupancy('control_pri', 1)) time.sleep(2) assert factory.client().get_treatment('maldo',", "ably error sse_server.publish(make_ably_error_event(40200, 402)) sse_server.publish(sse_server.GRACEFUL_REQUEST_END) time.sleep(3) # Assert sync-task is", "logger.addHandler(handler) logger.setLevel(logging.DEBUG) auth_server_response = { 'pushEnabled': True, 'token': ('<KEY> '<KEY>'", "query its status task = factory._sync_manager._synchronizer._split_tasks.split_task._task # pylint:disable=protected-access assert not", "assert not task.running() # Validate the SSE requests sse_request =", "req.headers['authorization'] == 'Bearer some_apikey' # SyncAll on push down req", "'http://localhost:%d/api' % split_backend.port(), 'events_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'auth_api_base_url': 'http://localhost:%d/api' %", "4, True, False, 'off', 'user', False)] } split_changes[4] = {'since':", "failover.\"\"\" def test_happiness(self): \"\"\"Test initialization & splits/segment updates.\"\"\" auth_server_response =", "for t in threading.enumerate()] # Validate the SSE request sse_request", "= { 'pushEnabled': True, 'token': ('<KEY> '<KEY>' '<KEY>' 'T1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcIjpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm' '9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJ'", "set(qs['channels'][0].split(',')) == set(['MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments', '[?occupancy=metrics.publishers]control_pri', '[?occupancy=metrics.publishers]control_sec']) assert qs['v'][0] == '1.1'", "split_backend = SplitMockServer(split_changes, segment_changes, split_backend_requests, auth_server_response) sse_requests = Queue() sse_server", "after first notification req = split_backend_requests.get() assert req.method == 'GET'", "ably errors and validate its handling.\"\"\" import logging logger =", "'PushStatusHandler' not in [t.name for t in threading.enumerate()] # Validate", "'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' '<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert set(qs['channels'][0].split(',')) ==", "== '/api/splitChanges?since=1' assert req.headers['authorization'] == 'Bearer some_apikey' # Iteration until", "ignorable error and check it has nothing happened split_changes[1] =", "# Assert sync-task is running and the streaming status handler", "'changeNumber': change_number }) }) } def make_split_kill_event(name, default_treatment, change_number): \"\"\"Make", "factory.client().get_treatment('maldo', 'split1') == 'on' assert task.running() assert 'PushStatusHandler' not in", "'/api/splitChanges?since=1' assert req.headers['authorization'] == 'Bearer some_apikey' # Second iteration of", "names. fallback to python2 from urllib.parse import parse_qs except ImportError:", "def test_ably_errors_handling(self): \"\"\"Test incoming ably errors and validate its handling.\"\"\"", "destroy_event.wait() sse_server.publish(sse_server.GRACEFUL_REQUEST_END) sse_server.stop() split_backend.stop() def test_ably_errors_handling(self): \"\"\"Test incoming ably errors", "[]} sse_server.publish(make_occupancy('control_pri', 1)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'on' assert", "name, 'changeNumber': change_number }) }) } def make_control_event(control_type, timestamp): \"\"\"Make", "== 'Bearer some_apikey' # SyncAll after streaming disabled req =", "# SyncAll retriable error req = split_backend_requests.get() assert req.method ==", "'<KEY>' '<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert set(qs['channels'][0].split(',')) == set(['MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments', '[?occupancy=metrics.publishers]control_pri',", "100, 'metricsRefreshRate': 100, 'impressionsRefreshRate': 100, 'eventsPushRate': 100} } factory =", "'CONTROL', 'controlType': control_type, }) }) } def make_ably_error_event(code, status): \"\"\"Make", "sse_server.publish(sse_server.GRACEFUL_REQUEST_END) sse_server.stop() split_backend.stop() def make_split_change_event(change_number): \"\"\"Make a split change event.\"\"\"", "but don't send the event. # We'll send an ignorable", "'/api/splitChanges?since=2' assert req.headers['authorization'] == 'Bearer some_apikey' # Fetch after second", "{ 'matcherGroup': { 'combiner': 'AND', 'matchers': [ { 'matcherType': 'IN_SEGMENT',", "= { 'pushEnabled': True, 'token': ('<KEY> '<KEY>' '<KEY>' '<KEY>' '<KEY>'", "factory.ready assert factory.client().get_treatment('maldo', 'split1') == 'on' task = factory._sync_manager._synchronizer._split_tasks.split_task._task #", "the retry succeeds sse_server.publish(make_initial_event()) sse_server.publish(make_occupancy('control_pri', 2)) sse_server.publish(make_occupancy('control_sec', 2)) time.sleep(3) assert", "sse_server.stop() split_backend.stop() def test_ably_errors_handling(self): \"\"\"Test incoming ably errors and validate", "'off' assert not task.running() # Validate the SSE request sse_request", "'eventsPushRate': 100} } factory = get_factory('some_apikey', **kwargs) factory.block_until_ready(1) assert factory.ready", "segment_changes, split_backend_requests, auth_server_response) sse_requests = Queue() sse_server = SSEMockServer(sse_requests) split_backend.start()", "'/api/splitChanges?since=2' assert req.headers['authorization'] == 'Bearer some_apikey' # Cleanup destroy_event =", "destroy_event.wait() sse_server.publish(sse_server.GRACEFUL_REQUEST_END) sse_server.stop() split_backend.stop() def test_occupancy_flicker(self): \"\"\"Test that changes in", "server closes the connection, the whole flow is retried with", "'user', False)] } split_changes[2] = {'since': 2, 'till': 2, 'splits':", "'http://localhost:%d' % sse_server.port(), 'config': {'connectTimeout': 10000, 'featuresRefreshRate': 10} } factory", "streaming is restored. split_changes[2] = { 'since': 2, 'till': 3,", "'till': 2, 'splits': [make_simple_split('split1', 2, True, False, 'off', 'user', False)]", "== 'off' assert task.running() # We make another chagne in", "'statusCode': status, 'href':\"https://help.ably.io/error/%d\" % code }) } def make_simple_split(name, cn,", "def test_occupancy_flicker(self): \"\"\"Test that changes in occupancy switch between polling", "assert req.path == '/api/splitChanges?since=2' assert req.headers['authorization'] == 'Bearer some_apikey' #", "'defaultTreatment': default_treatment, 'changeNumber': change_number }) }) } def make_initial_event(): \"\"\"Make", "= split_backend_requests.get() assert req.method == 'GET' assert req.path == '/api/splitChanges?since=5'", "req.headers['authorization'] == 'Bearer some_apikey' # Auth after connection breaks req", "assert factory.client().get_treatment('maldo', 'split1') == 'off' sse_server.publish(SSEMockServer.GRACEFUL_REQUEST_END) time.sleep(1) assert factory.client().get_treatment('maldo', 'split1')", "= {'since': 3, 'till': 3, 'splits': []} segment_changes[('segment1', -1)] =", "'Bearer some_apikey' # SyncAll on push down req = split_backend_requests.get()", "'http://localhost:%d/api' % split_backend.port(), 'streaming_api_base_url': 'http://localhost:%d' % sse_server.port(), 'config': {'connectTimeout': 10000,", "}) } def make_control_event(control_type, timestamp): \"\"\"Make a control event.\"\"\" return", "'<KEY>' '<KEY>' '<KEY>' '<KEY>' 'CI6MTYwNDEwMDU5MSwiaWF0IjoxNjA0MDk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5E' 'vJh17WlOlAKhcD0') } split_changes = {", "assert not task.running() # Now we make another change and", "# pylint:disable=protected-access assert task.running() assert factory.client().get_treatment('maldo', 'split1') == 'on' #", "'combiner': 'AND', 'matchers': [ { 'matcherType': 'IN_SEGMENT', 'negate': False, 'userDefinedSegmentMatcherData':", "sse_server.publish(make_split_change_event(3)) time.sleep(1) sse_server.publish(make_segment_change_event('segment1', 1)) time.sleep(1) assert factory.client().get_treatment('pindon', 'split2') == 'off'", "req.method == 'GET' assert req.path == '/api/splitChanges?since=1' assert req.headers['authorization'] ==", "after streaming connected req = split_backend_requests.get() assert req.method == 'GET'", "'till': 5, 'splits': []} sse_server.publish(make_control_event('STREAMING_DISABLED', 2)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1')", "cn, 'killed': killed, 'defaultTreatment': default_treatment, 'configurations': { 'on': '{\\'size\\':15,\\'test\\':20}' },", "req.path == '/api/splitChanges?since=4' assert req.headers['authorization'] == 'Bearer some_apikey' # Split", "= get_factory('some_apikey', **kwargs) factory.block_until_ready(1) assert factory.ready time.sleep(2) # Get a", "'Bearer some_apikey' # Fetch after new notification req = split_backend_requests.get()", "'splits': []} sse_server.publish(make_control_event('STREAMING_PAUSED', 1)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'off'", "requests sse_request = sse_requests.get() assert sse_request.method == 'GET' path, qs", "operation and failover.\"\"\" def test_happiness(self): \"\"\"Test initialization & splits/segment updates.\"\"\"", "that changes in occupancy switch between polling & streaming properly.\"\"\"", "thread is over assert task.running() assert 'PushStatusHandler' not in [t.name", "send an event so it's propagated split_changes[3] = { 'since':", "task.running() split_changes[4] = { 'since': 4, 'till': 5, 'splits': [make_simple_split('split1',", "split_changes[3] = { 'since': 3, 'till': 4, 'splits': [make_simple_split('split1', 4,", "and validate its handling.\"\"\" import logging logger = logging.getLogger('splitio') handler", "json.dumps({'metrics': {'publishers': publishers}}), 'name':'[meta]occupancy' }) } def make_segment_change_event(name, change_number): \"\"\"Make", "# After dropping occupancy, the sdk should switch to polling", "('<KEY> '<KEY>' '<KEY>' '<KEY>' '<KEY>' '<KEY>' '<KEY>' '<KEY>' 'vJh17WlOlAKhcD0') }", "1, 'splits': [make_simple_split('split1', 1, True, False, 'off', 'user', True)] },", "== 'Bearer some_apikey' # Auth again req = split_backend_requests.get() assert", "== '/api/segmentChanges/segment1?since=-1' assert req.headers['authorization'] == 'Bearer some_apikey' # Iteration until", "{'since': 3, 'till': 3, 'splits': []} sse_server.publish(make_split_change_event(3)) time.sleep(2) assert factory.client().get_treatment('maldo',", "{'since': 3, 'till': 3, 'splits': []} sse_server.publish(make_control_event('STREAMING_ENABLED', 2)) time.sleep(2) assert", "'off', 'user', 'off', 'segment1')] } split_changes[3] = {'since': 3, 'till':", "== 'on' assert not task.running() # Validate the SSE requests", "= { 'since': 2, 'till': 3, 'splits': [make_simple_split('split1', 3, True,", "factory.destroy(destroy_event) destroy_event.wait() sse_server.publish(sse_server.GRACEFUL_REQUEST_END) sse_server.stop() split_backend.stop() def test_server_closes_connection(self): \"\"\"Test that if", "the backoff to expire so streaming gets re-attached # re-send", "'changeNumber': cn, 'killed': killed, 'defaultTreatment': default_treatment, 'configurations': { 'on': '{\\'size\\':15,\\'test\\':20}'", "[ { 'matcherGroup': { 'combiner': 'AND', 'matchers': [ { 'matcherType':", "try: # try to import python3 names. fallback to python2", "# Auth after connection breaks req = split_backend_requests.get() assert req.method", "assert req.headers['authorization'] == 'Bearer some_apikey' # Segment change notification req", "False, 'off', 'user', False)] } split_changes[4] = {'since': 4, 'till':", "split_backend.stop() def test_occupancy_flicker(self): \"\"\"Test that changes in occupancy switch between", "import python3 names. fallback to python2 from urllib.parse import parse_qs", "closes the connection, the whole flow is retried with BO.\"\"\"", "'ACTIVE' if active else 'ARCHIVED', 'changeNumber': cn, 'killed': killed, 'defaultTreatment':", "'/api/splitChanges?since=1' assert req.headers['authorization'] == 'Bearer some_apikey' # Fetch after first", "# SyncAll after push restored req = split_backend_requests.get() assert req.method", "'streaming_api_base_url': 'http://localhost:%d' % sse_server.port(), 'config': {'connectTimeout': 10000} } factory =", "on): \"\"\"Make a simple split.\"\"\" return { 'trafficTypeName': tt, 'name':", "== 'GET' assert req.path == '/api/splitChanges?since=3' assert req.headers['authorization'] == 'Bearer", "'split1') == 'off' # Kill the split split_changes[4] = {", "3, True, False, 'off', 'user', True)] } split_changes[3] = {'since':", "100, 'segmentsRefreshRate': 100, 'metricsRefreshRate': 100, 'impressionsRefreshRate': 100, 'eventsPushRate': 100} }", "some_apikey' # Fetch after new notification req = split_backend_requests.get() assert", "1, True, False, 'off', 'user', True)] }, 1: {'since': 1,", "assert req.headers['authorization'] == 'Bearer some_apikey' # SyncAll retriable error req", "'/api/splitChanges?since=-1' assert req.headers['authorization'] == 'Bearer some_apikey' # Iteration until since", "'split1') == 'on' assert task.running() assert 'PushStatusHandler' not in [t.name", "== 'GET' assert req.path == '/api/splitChanges?since=4' assert req.headers['authorization'] == 'Bearer", "some_apikey' # Fetch after notification req = split_backend_requests.get() assert req.method", "sse_server.stop() split_backend.stop() def test_streaming_status_changes(self): \"\"\"Test changes between streaming enabled, paused", "req.method == 'GET' assert req.path == '/api/splitChanges?since=3' assert req.headers['authorization'] ==", "sse_server.publish(make_occupancy('control_pri', 2)) sse_server.publish(make_occupancy('control_sec', 2)) time.sleep(3) assert not task.running() # Assert", "with occupancy on 0 and switching to streamin afterwards.\"\"\" auth_server_response", "time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'frula' # Validate the SSE", "return { 'trafficTypeName': tt, 'name': name, 'seed': cn, 'status': 'ACTIVE'", "after second notification req = split_backend_requests.get() assert req.method == 'GET'", "False, 'on', 'user', True)] }, 1: { 'since': 1, 'till':", "'on', 'size': 0} ] } ] } def make_split_with_segment(name, cn,", "= SSEMockServer(sse_requests) split_backend.start() sse_server.start() sse_server.publish(make_initial_event()) sse_server.publish(make_occupancy('control_pri', 2)) sse_server.publish(make_occupancy('control_sec', 2)) kwargs", "= threading.Event() factory.destroy(destroy_event) destroy_event.wait() sse_server.publish(sse_server.GRACEFUL_REQUEST_END) sse_server.stop() split_backend.stop() def test_occupancy_flicker(self): \"\"\"Test", "[t.name for t in threading.enumerate()] # Validate the SSE request", "'Bearer some_apikey' # SyncAll after push is up req =", "'<KEY>WJ<KEY>' '<KEY>' '<KEY>' '<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert set(qs['channels'][0].split(',')) == set(['MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits',", "# SyncAll after streaming connected req = split_backend_requests.get() assert req.method", "some_apikey' # Cleanup destroy_event = threading.Event() factory.destroy(destroy_event) destroy_event.wait() sse_server.publish(sse_server.GRACEFUL_REQUEST_END) sse_server.stop()", "events so that the retry succeeds sse_server.publish(make_initial_event()) sse_server.publish(make_occupancy('control_pri', 2)) sse_server.publish(make_occupancy('control_sec',", "# Validate the SSE requests sse_request = sse_requests.get() assert sse_request.method", "'splits': [make_simple_split('split1', 1, True, False, 'off', 'user', True)] }, 1:", "'timestamp': timestamp, 'encoding':'json', 'channel':'[?occupancy=metrics.publishers]control_pri', 'data': json.dumps({ 'type': 'CONTROL', 'controlType': control_type,", "'on' # Validate the SSE request sse_request = sse_requests.get() assert", "= logging.getLogger('splitio') handler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s", "make_split_with_segment(name, cn, active, killed, default_treatment, tt, on, segment): \"\"\"Make a", "req.path == '/api/splitChanges?since=2' assert req.headers['authorization'] == 'Bearer some_apikey' # Auth", "1, 'splits': [make_simple_split('split1', 1, True, False, 'on', 'user', True)] },", "req.path == '/api/segmentChanges/segment1?since=-1' assert req.headers['authorization'] == 'Bearer some_apikey' # Iteration", "{'since': 5, 'till': 5, 'splits': []} sse_server.publish(make_split_kill_event('split1', 'frula', 5)) time.sleep(2)", "split_backend.start() sse_server.start() sse_server.publish(make_initial_event()) sse_server.publish(make_occupancy('control_pri', 2)) sse_server.publish(make_occupancy('control_sec', 2)) kwargs = {", "'T1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcIjpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm' '9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJ' 'zXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzdWJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRh' 'dGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFibHktY2xpZW50SWQiOiJjbGllbnRJZCIsImV4c' 'CI6MTYwNDEwMDU5MSwiaWF0IjoxNjA0MDk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5E' '<KEY>') } split_changes = {", "'since': 1, 'till': 2, 'splits': [make_simple_split('split1', 2, True, False, 'off',", "assert sse_request.method == 'GET' path, qs = sse_request.path.split('?', 1) assert", "req.path == '/api/segmentChanges/segment1?since=1' assert req.headers['authorization'] == 'Bearer some_apikey' # Cleanup", "== 'off' # Re-publish initial events so that the retry", "json.dumps({ 'id':'TVUsxaabHs:0:0', 'clientId':'pri:MzM0ODI1MTkxMw==', 'timestamp': change_number-1, 'encoding':'json', 'channel':'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments', 'data': json.dumps({ 'type':", "None } ] }, 'partitions': [{ 'treatment': 'on' if on", "== ( '<KEY>' '<KEY>' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' '<KEY>'", "json.dumps({ 'type': 'SPLIT_KILL', 'splitName': name, 'defaultTreatment': default_treatment, 'changeNumber': change_number })", "event. # After restoring occupancy, the sdk should switch to", "connected req = split_backend_requests.get() assert req.method == 'GET' assert req.path", "'message', 'data': json.dumps({ 'id':'TVUsxaabHs:0:0', 'clientId':'pri:MzM0ODI1MTkxMw==', 'timestamp': timestamp, 'encoding':'json', 'channel':'[?occupancy=metrics.publishers]control_pri', 'data':", "json.dumps({ 'type': 'SEGMENT_UPDATE', 'segmentName': name, 'changeNumber': change_number }) }) }", "split_backend_requests.get() assert req.method == 'GET' assert req.path == '/api/splitChanges?since=5' assert", "3, 'splits': []} segment_changes[('segment1', -1)] = { 'name': 'segment1', 'added':", "assert factory.client().get_treatment('maldo', 'split1') == 'off' # Kill the split split_changes[4]", "assert not task.running() # Send a non-retryable ably error sse_server.publish(make_ably_error_event(40200,", "== till req = split_backend_requests.get() assert req.method == 'GET' assert", "5, 'splits': [make_simple_split('split1', 5, True, True, 'frula', 'user', False)] }", "split_changes[5] = {'since': 5, 'till': 5, 'splits': []} sse_server.publish(make_split_kill_event('split1', 'frula',", "{'since': 2, 'till': 2, 'splits': []} sse_server.publish(make_control_event('STREAMING_PAUSED', 1)) time.sleep(2) assert", "{'since': 4, 'till': 4, 'splits': []} sse_server.publish(make_split_change_event(4)) time.sleep(2) assert factory.client().get_treatment('maldo',", "% split_backend.port(), 'events_api_base_url': 'http://localhost:%d/api' % split_backend.port(), 'auth_api_base_url': 'http://localhost:%d/api' % split_backend.port(),", "3, 'till': 3, 'splits': []} sse_server.publish(make_control_event('STREAMING_ENABLED', 2)) time.sleep(2) assert factory.client().get_treatment('maldo',", "split_changes[3] = {'since': 3, 'till': 3, 'splits': []} sse_server.publish(make_control_event('STREAMING_ENABLED', 2))", "== 'on' assert task.running() assert 'PushStatusHandler' not in [t.name for", "{ 'event': 'message', 'data': json.dumps({ 'id':'TVUsxaabHs:0:0', 'clientId':'pri:MzM0ODI1MTkxMw==', 'timestamp': change_number-1, 'encoding':'json',", "0)) sse_server.publish(make_occupancy('control_sec', 0)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'off' assert", "not task.running() split_changes[4] = { 'since': 4, 'till': 5, 'splits':", "change_number }) }) } def make_split_kill_event(name, default_treatment, change_number): \"\"\"Make a", "10000} } factory = get_factory('some_apikey', **kwargs) factory.block_until_ready(1) assert factory.ready assert", "'/api/splitChanges?since=1' assert req.headers['authorization'] == 'Bearer some_apikey' # SyncAll on push", "starting with occupancy on 0 and switching to streamin afterwards.\"\"\"", "its status task = factory._sync_manager._synchronizer._split_tasks.split_task._task # pylint:disable=protected-access assert task.running() assert", "BE and don't send the event. # We restore occupancy,", "**kwargs) factory.block_until_ready(1) assert factory.ready time.sleep(2) # Get a hook of", "between polling & streaming properly.\"\"\" auth_server_response = { 'pushEnabled': True,", "== 'Bearer some_apikey' # SyncAll after push is up req", "'<KEY>' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' 'HktY2xpZW50SWQiOiJjbGllbnRJZCIsImV4cCI6MTYwNDEwMDU5MSwiaWF0IjoxNjA0M' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert", "an occupancy event.\"\"\" return { 'event': 'message', 'data': json.dumps({ 'id':'aP6EuhrcUm:0:0',", "assert req.headers['authorization'] == 'Bearer some_apikey' # Iteration until since ==", "True, 'token': ('<KEY> '<KEY>' '<KEY>' 'T1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcIjpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm' '9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJ' 'zXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzdWJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRh' 'dGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFibHktY2xpZW50SWQiOiJjbGllbnRJZCIsImV4c' 'CI6MTYwNDEwMDU5MSwiaWF0IjoxNjA0MDk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5E'", "factory._sync_manager._synchronizer._split_tasks.split_task._task # pylint:disable=protected-access assert task.running() assert factory.client().get_treatment('maldo', 'split1') == 'on'", "some_apikey' # Segment change notification req = split_backend_requests.get() assert req.method", "change_number }) }) } def make_control_event(control_type, timestamp): \"\"\"Make a control", "'<KEY>' '<KEY>' 'CI6MTYwNDEwMDU5MSwiaWF0IjoxNjA0MDk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5E' 'vJh17WlOlAKhcD0') } split_changes = { -1: {", "error req = split_backend_requests.get() assert req.method == 'GET' assert req.path", "'splits': []} sse_server.publish(make_control_event('STREAMING_ENABLED', 2)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'on'", "} ] } def make_split_with_segment(name, cn, active, killed, default_treatment, tt,", "( '<KEY>' '<KEY>' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' 'HktY2xpZW<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0'", "factory.client().get_treatment('maldo', 'split1') == 'off' sse_server.publish(SSEMockServer.GRACEFUL_REQUEST_END) time.sleep(1) assert factory.client().get_treatment('maldo', 'split1') ==", "its handling.\"\"\" import logging logger = logging.getLogger('splitio') handler = logging.StreamHandler()", "set(['MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments', '[?occupancy=metrics.publishers]control_pri', '[?occupancy=metrics.publishers]control_sec']) assert qs['v'][0] == '1.1' # Initial", "'timestamp': change_number-1, 'encoding':'json', 'channel':'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'data': json.dumps({ 'type': 'SPLIT_KILL', 'splitName': name,", "== '/api/splitChanges?since=2' assert req.headers['authorization'] == 'Bearer some_apikey' # Iteration until", "parse_qs(qs) assert qs['accessToken'][0] == ( '<KEY>' '<KEY>' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY'", "threading.enumerate()] # Validate the SSE request sse_request = sse_requests.get() assert", "( '<KEY>' '<KEY>' 'XlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zZWdtZW50c1wiOltcInN1YnNjc' 'mliZVwiXSxcIk1UWXlNVGN4T1RRNE13PT1fTWpBNE16Y3pORFUxTWc9PV9zcGxpdHNcI' 'jpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sX3ByaVwiOltcInN1YnNjcmliZVwiLFwiY' '2hhbm5lbC1tZXRhZGF0YTpwdWJsaXNoZXJzXCJdLFwiY29udHJvbF9zZWNcIjpbXCJzd' 'WJzY3JpYmVcIixcImNoYW5uZWwtbWV0YWRhdGE6cHVibGlzaGVyc1wiXX0iLCJ4LWFib' 'HktY2xpZW50SWQiOiJjbG<KEY>' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0'", "== 'Bearer some_apikey' # SyncAll after push restored req =", "occupancy sse_server.publish(make_initial_event()) sse_server.publish(make_occupancy('control_pri', 2)) sse_server.publish(make_occupancy('control_sec', 2)) time.sleep(2) assert not task.running()", "sarasa', 'code': code, 'statusCode': status, 'href':\"https://help.ably.io/error/%d\" % code }) }", "on else 'off', 'size': 100}, {'treatment': 'off' if on else", "[]} sse_server.publish(make_occupancy('control_sec', 1)) time.sleep(2) assert factory.client().get_treatment('maldo', 'split1') == 'off' assert", "2, 'till': 2, 'splits': []} sse_server.publish(make_ably_error_event(60000, 600)) time.sleep(1) assert factory.client().get_treatment('maldo',", "threading.Event() factory.destroy(destroy_event) destroy_event.wait() sse_server.publish(sse_server.GRACEFUL_REQUEST_END) sse_server.stop() split_backend.stop() def test_ably_errors_handling(self): \"\"\"Test incoming", "some_apikey' # Initial splits fetch req = split_backend_requests.get() assert req.method", "'GET' assert req.path == '/api/splitChanges?since=5' assert req.headers['authorization'] == 'Bearer some_apikey'", "1)) time.sleep(1) assert factory.client().get_treatment('pindon', 'split2') == 'off' assert factory.client().get_treatment('maldo', 'split2')", "by the # sync all after streaming is restored. split_changes[2]", "'id':'TVUsxaabHs:0:0', 'clientId':'pri:MzM0ODI1MTkxMw==', 'timestamp': change_number-1, 'encoding':'json', 'channel':'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'data': json.dumps({ 'type': 'SPLIT_KILL',", "'Bearer some_apikey' # SyncAll on retryable error handling req =", "assert req.headers['authorization'] == 'Bearer some_apikey' # Fetch after second notification", "change_number }) }) } def make_initial_event(): \"\"\"Make a split change", "{'segmentName': segment}, 'whitelistMatcherData': None } ] }, 'partitions': [{ 'treatment':", "handler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s') handler.setFormatter(formatter)", "'HktY2xpZW50SWQiOiJjbGllbnRJZCIsImV4cCI6MTYwNDEwMDU5MSwiaWF0IjoxNjA0M' 'Dk2OTkxfQ.aP9BfR534K6J9h8gfDWg_CQgpz5EvJh17WlOlAKhcD0' ) assert set(qs['channels'][0].split(',')) == set(['MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_segments', '[?occupancy=metrics.publishers]control_pri', '[?occupancy=metrics.publishers]control_sec'])", "-1, 'till': 1 } segment_changes[('segment1', 1)] = {'name': 'segment1', 'added':" ]
[ "continue prices.append(\"\".join(parsed_price)) if len(prices) == 0: return \"0€\" elif len(prices)", "re.compile(\"[0-9.,]+\") def get_venue_name(self) -> str: return self.name def get_city(self) ->", "= \"\" self.pricepat_monetary = re.compile(\"[0-9.,]+.€\") self.pricepat_plain = re.compile(\"[0-9.,]+\") def get_venue_name(self)", "event_sqlentity(self) -> Dict[str, str]: return {\"name\": self.name, \"city\": self.city, \"country\":", "self.name = \"\" self.city = \"\" self.country = \"\" self.pricepat_monetary", "other.url == self.url @abstractmethod def parse_events(self, data: Any) \\ ->", "price in prices_with_mon: parsed_price = self.pricepat_plain.findall(price) if len(parsed_price) == 0:", "in_advance, from_door = prices[0], prices[1] return f\"{in_advance}€/{from_door}€\" return \"{}€\".format(\"\".join(prices)) #", "get_city(self) -> str: return self.city def get_country(self) -> str: return", "re from abc import ABC, abstractmethod from typing import Any,", "self.city, \"country\": self.country} def parse_price(self, info_tag: str) -> str: prices_with_mon", "class IncorrectVenueImplementation(Exception): pass # class AbstractVenue(metaclass=ABC): class AbstractVenue(ABC): def __init__(self):", "from typing import Any, Dict, Generator class IncorrectVenueImplementation(Exception): pass #", "def parse_events(self, data: Any) \\ -> Generator[Dict[str, Any], None, None]:", "return self.country def event_sqlentity(self) -> Dict[str, str]: return {\"name\": self.name,", "if len(parsed_price) == 0: continue prices.append(\"\".join(parsed_price)) if len(prices) == 0:", "self.country def event_sqlentity(self) -> Dict[str, str]: return {\"name\": self.name, \"city\":", "return self.city def get_country(self) -> str: return self.country def event_sqlentity(self)", "Any, Dict, Generator class IncorrectVenueImplementation(Exception): pass # class AbstractVenue(metaclass=ABC): class", "0: continue prices.append(\"\".join(parsed_price)) if len(prices) == 0: return \"0€\" elif", "len(prices) == 2: in_advance, from_door = prices[0], prices[1] return f\"{in_advance}€/{from_door}€\"", "FIXME Proper class type checking def __eq__(self, other): return hasattr(other,", "= prices[0], prices[1] return f\"{in_advance}€/{from_door}€\" return \"{}€\".format(\"\".join(prices)) # FIXME Proper", "elif len(prices) == 2: in_advance, from_door = prices[0], prices[1] return", "\"\" self.name = \"\" self.city = \"\" self.country = \"\"", "str: return self.city def get_country(self) -> str: return self.country def", "from abc import ABC, abstractmethod from typing import Any, Dict,", "== 2: in_advance, from_door = prices[0], prices[1] return f\"{in_advance}€/{from_door}€\" return", "parse_events(self, data: Any) \\ -> Generator[Dict[str, Any], None, None]: pass", "\"country\": self.country} def parse_price(self, info_tag: str) -> str: prices_with_mon =", "class AbstractVenue(ABC): def __init__(self): self.url = \"\" self.name = \"\"", "= self.pricepat_monetary.findall(info_tag) prices = [] for price in prices_with_mon: parsed_price", "typing import Any, Dict, Generator class IncorrectVenueImplementation(Exception): pass # class", "Dict, Generator class IncorrectVenueImplementation(Exception): pass # class AbstractVenue(metaclass=ABC): class AbstractVenue(ABC):", "if len(prices) == 0: return \"0€\" elif len(prices) == 2:", "Proper class type checking def __eq__(self, other): return hasattr(other, \"url\")", "checking def __eq__(self, other): return hasattr(other, \"url\") \\ and other.url", "self.city def get_country(self) -> str: return self.country def event_sqlentity(self) ->", "[] for price in prices_with_mon: parsed_price = self.pricepat_plain.findall(price) if len(parsed_price)", "pass # class AbstractVenue(metaclass=ABC): class AbstractVenue(ABC): def __init__(self): self.url =", "\"\" self.country = \"\" self.pricepat_monetary = re.compile(\"[0-9.,]+.€\") self.pricepat_plain = re.compile(\"[0-9.,]+\")", "Dict[str, str]: return {\"name\": self.name, \"city\": self.city, \"country\": self.country} def", "# FIXME Proper class type checking def __eq__(self, other): return", "len(parsed_price) == 0: continue prices.append(\"\".join(parsed_price)) if len(prices) == 0: return", "prices = [] for price in prices_with_mon: parsed_price = self.pricepat_plain.findall(price)", "abc import ABC, abstractmethod from typing import Any, Dict, Generator", "== self.url @abstractmethod def parse_events(self, data: Any) \\ -> Generator[Dict[str,", "info_tag: str) -> str: prices_with_mon = self.pricepat_monetary.findall(info_tag) prices = []", "Generator class IncorrectVenueImplementation(Exception): pass # class AbstractVenue(metaclass=ABC): class AbstractVenue(ABC): def", "import ABC, abstractmethod from typing import Any, Dict, Generator class", "def get_country(self) -> str: return self.country def event_sqlentity(self) -> Dict[str,", "# class AbstractVenue(metaclass=ABC): class AbstractVenue(ABC): def __init__(self): self.url = \"\"", "self.url @abstractmethod def parse_events(self, data: Any) \\ -> Generator[Dict[str, Any],", "def parse_price(self, info_tag: str) -> str: prices_with_mon = self.pricepat_monetary.findall(info_tag) prices", "@abstractmethod def parse_events(self, data: Any) \\ -> Generator[Dict[str, Any], None,", "prices.append(\"\".join(parsed_price)) if len(prices) == 0: return \"0€\" elif len(prices) ==", "-> Dict[str, str]: return {\"name\": self.name, \"city\": self.city, \"country\": self.country}", "== 0: continue prices.append(\"\".join(parsed_price)) if len(prices) == 0: return \"0€\"", "self.name, \"city\": self.city, \"country\": self.country} def parse_price(self, info_tag: str) ->", "f\"{in_advance}€/{from_door}€\" return \"{}€\".format(\"\".join(prices)) # FIXME Proper class type checking def", "and other.url == self.url @abstractmethod def parse_events(self, data: Any) \\", "class AbstractVenue(metaclass=ABC): class AbstractVenue(ABC): def __init__(self): self.url = \"\" self.name", "-> str: return self.city def get_country(self) -> str: return self.country", "\"url\") \\ and other.url == self.url @abstractmethod def parse_events(self, data:", "= re.compile(\"[0-9.,]+\") def get_venue_name(self) -> str: return self.name def get_city(self)", "str: return self.country def event_sqlentity(self) -> Dict[str, str]: return {\"name\":", "\"\" self.pricepat_monetary = re.compile(\"[0-9.,]+.€\") self.pricepat_plain = re.compile(\"[0-9.,]+\") def get_venue_name(self) ->", "parsed_price = self.pricepat_plain.findall(price) if len(parsed_price) == 0: continue prices.append(\"\".join(parsed_price)) if", "= self.pricepat_plain.findall(price) if len(parsed_price) == 0: continue prices.append(\"\".join(parsed_price)) if len(prices)", "def get_venue_name(self) -> str: return self.name def get_city(self) -> str:", "import Any, Dict, Generator class IncorrectVenueImplementation(Exception): pass # class AbstractVenue(metaclass=ABC):", "0: return \"0€\" elif len(prices) == 2: in_advance, from_door =", "return f\"{in_advance}€/{from_door}€\" return \"{}€\".format(\"\".join(prices)) # FIXME Proper class type checking", "self.city = \"\" self.country = \"\" self.pricepat_monetary = re.compile(\"[0-9.,]+.€\") self.pricepat_plain", "IncorrectVenueImplementation(Exception): pass # class AbstractVenue(metaclass=ABC): class AbstractVenue(ABC): def __init__(self): self.url", "hasattr(other, \"url\") \\ and other.url == self.url @abstractmethod def parse_events(self,", "return \"{}€\".format(\"\".join(prices)) # FIXME Proper class type checking def __eq__(self,", "AbstractVenue(ABC): def __init__(self): self.url = \"\" self.name = \"\" self.city", "{\"name\": self.name, \"city\": self.city, \"country\": self.country} def parse_price(self, info_tag: str)", "parse_price(self, info_tag: str) -> str: prices_with_mon = self.pricepat_monetary.findall(info_tag) prices =", "str: return self.name def get_city(self) -> str: return self.city def", "= \"\" self.name = \"\" self.city = \"\" self.country =", "other): return hasattr(other, \"url\") \\ and other.url == self.url @abstractmethod", "self.url = \"\" self.name = \"\" self.city = \"\" self.country", "prices_with_mon: parsed_price = self.pricepat_plain.findall(price) if len(parsed_price) == 0: continue prices.append(\"\".join(parsed_price))", "get_venue_name(self) -> str: return self.name def get_city(self) -> str: return", "get_country(self) -> str: return self.country def event_sqlentity(self) -> Dict[str, str]:", "prices[0], prices[1] return f\"{in_advance}€/{from_door}€\" return \"{}€\".format(\"\".join(prices)) # FIXME Proper class", "self.country} def parse_price(self, info_tag: str) -> str: prices_with_mon = self.pricepat_monetary.findall(info_tag)", "self.pricepat_monetary.findall(info_tag) prices = [] for price in prices_with_mon: parsed_price =", "abstractmethod from typing import Any, Dict, Generator class IncorrectVenueImplementation(Exception): pass", "= [] for price in prices_with_mon: parsed_price = self.pricepat_plain.findall(price) if", "def get_city(self) -> str: return self.city def get_country(self) -> str:", "__init__(self): self.url = \"\" self.name = \"\" self.city = \"\"", "str: prices_with_mon = self.pricepat_monetary.findall(info_tag) prices = [] for price in", "-> str: return self.name def get_city(self) -> str: return self.city", "\\ and other.url == self.url @abstractmethod def parse_events(self, data: Any)", "return {\"name\": self.name, \"city\": self.city, \"country\": self.country} def parse_price(self, info_tag:", "prices[1] return f\"{in_advance}€/{from_door}€\" return \"{}€\".format(\"\".join(prices)) # FIXME Proper class type", "return self.name def get_city(self) -> str: return self.city def get_country(self)", "return hasattr(other, \"url\") \\ and other.url == self.url @abstractmethod def", "self.name def get_city(self) -> str: return self.city def get_country(self) ->", "\"{}€\".format(\"\".join(prices)) # FIXME Proper class type checking def __eq__(self, other):", "__eq__(self, other): return hasattr(other, \"url\") \\ and other.url == self.url", "self.pricepat_plain.findall(price) if len(parsed_price) == 0: continue prices.append(\"\".join(parsed_price)) if len(prices) ==", "len(prices) == 0: return \"0€\" elif len(prices) == 2: in_advance,", "2: in_advance, from_door = prices[0], prices[1] return f\"{in_advance}€/{from_door}€\" return \"{}€\".format(\"\".join(prices))", "def __eq__(self, other): return hasattr(other, \"url\") \\ and other.url ==", "def event_sqlentity(self) -> Dict[str, str]: return {\"name\": self.name, \"city\": self.city,", "re.compile(\"[0-9.,]+.€\") self.pricepat_plain = re.compile(\"[0-9.,]+\") def get_venue_name(self) -> str: return self.name", "\"city\": self.city, \"country\": self.country} def parse_price(self, info_tag: str) -> str:", "self.pricepat_monetary = re.compile(\"[0-9.,]+.€\") self.pricepat_plain = re.compile(\"[0-9.,]+\") def get_venue_name(self) -> str:", "import re from abc import ABC, abstractmethod from typing import", "def __init__(self): self.url = \"\" self.name = \"\" self.city =", "type checking def __eq__(self, other): return hasattr(other, \"url\") \\ and", "ABC, abstractmethod from typing import Any, Dict, Generator class IncorrectVenueImplementation(Exception):", "self.country = \"\" self.pricepat_monetary = re.compile(\"[0-9.,]+.€\") self.pricepat_plain = re.compile(\"[0-9.,]+\") def", "== 0: return \"0€\" elif len(prices) == 2: in_advance, from_door", "prices_with_mon = self.pricepat_monetary.findall(info_tag) prices = [] for price in prices_with_mon:", "AbstractVenue(metaclass=ABC): class AbstractVenue(ABC): def __init__(self): self.url = \"\" self.name =", "return \"0€\" elif len(prices) == 2: in_advance, from_door = prices[0],", "str) -> str: prices_with_mon = self.pricepat_monetary.findall(info_tag) prices = [] for", "\"\" self.city = \"\" self.country = \"\" self.pricepat_monetary = re.compile(\"[0-9.,]+.€\")", "self.pricepat_plain = re.compile(\"[0-9.,]+\") def get_venue_name(self) -> str: return self.name def", "from_door = prices[0], prices[1] return f\"{in_advance}€/{from_door}€\" return \"{}€\".format(\"\".join(prices)) # FIXME", "= \"\" self.country = \"\" self.pricepat_monetary = re.compile(\"[0-9.,]+.€\") self.pricepat_plain =", "-> str: return self.country def event_sqlentity(self) -> Dict[str, str]: return", "= re.compile(\"[0-9.,]+.€\") self.pricepat_plain = re.compile(\"[0-9.,]+\") def get_venue_name(self) -> str: return", "\"0€\" elif len(prices) == 2: in_advance, from_door = prices[0], prices[1]", "in prices_with_mon: parsed_price = self.pricepat_plain.findall(price) if len(parsed_price) == 0: continue", "-> str: prices_with_mon = self.pricepat_monetary.findall(info_tag) prices = [] for price", "for price in prices_with_mon: parsed_price = self.pricepat_plain.findall(price) if len(parsed_price) ==", "str]: return {\"name\": self.name, \"city\": self.city, \"country\": self.country} def parse_price(self,", "= \"\" self.city = \"\" self.country = \"\" self.pricepat_monetary =", "class type checking def __eq__(self, other): return hasattr(other, \"url\") \\" ]
[ "= feature_map self._batch_size = batch_size self._static_max_length = static_max_length # Initialize", "2.0 (the \"License\"); # you may not use this file", "self._result = result def pad(self, t): s = tf.shape(t) paddings", "num_epochs is None: dataset = dataset.repeat() # repeat indefinitely elif", "and # limitations under the License. # ============================================================================== from __future__", "x = tf.reshape(x, [s[0], self._static_max_length]) assert x.get_shape().as_list()[1] is self._static_max_length return", "isinstance(val, sparse_tensor_lib.SparseTensor): dense_tensor = tf.sparse_tensor_to_dense(val) if self._static_max_length is not None:", "0], [0, self._static_max_length - s[1]]] x = tf.pad(t, paddings, 'CONSTANT',", "absolute_import from __future__ import division from __future__ import print_function from", "num_threads=4, prefetch_buffer_size=1, static_max_length=None, shuffle_buffer_size=10000, shuffle=True, num_epochs=None, one_shot=False): self._feature_map = feature_map", "tensorflow as tf from tensorflow.python.framework import sparse_tensor as sparse_tensor_lib from", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "correspond to padded examples bucket_info = namedtuple(\"bucket_info\", \"func pads\") def", "parse_example(self, serialized): parsed = parsing_ops.parse_example(serialized, self._feature_map) result = [] for", "= namedtuple(\"bucket_info\", \"func pads\") def int64_feature(value): \"\"\" Takes a single", "num_epochs > 1: dataset = dataset.repeat(count=num_epochs) dataset = dataset.batch(batch_size) dataset", "= dataset.repeat(count=num_epochs) dataset = dataset.batch(batch_size) dataset = dataset.map(self.parse_example, num_parallel_calls=num_threads) #", "# Copyright 2018 Johns Hopkins University. All Rights Reserved. #", "is not None: dense_tensor = self.pad(dense_tensor) result.append(dense_tensor) else: result.append(val) return", "that correspond to padded examples bucket_info = namedtuple(\"bucket_info\", \"func pads\")", "use this file except in compliance with the License. #", "def int64_feature(value): \"\"\" Takes a single int (e.g. 3) and", "def iterator(self): return self._iterator @property def init_op(self): return self._init_op @property", "self._iterator @property def init_op(self): return self._init_op @property def batch(self): return", "tf from tensorflow.python.framework import sparse_tensor as sparse_tensor_lib from tensorflow.python.ops import", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "License. # You may obtain a copy of the License", "= dataset.shuffle(shuffle_buffer_size) # Maybe repeat if num_epochs is None: dataset", "Pipeline) # func: a mapping from examples to tf.int64 keys", "under the License is distributed on an \"AS IS\" BASIS,", "def int64_list_feature(sequence): \"\"\" Sequence of ints (e.g [1,2,3]) to TF", "License for the specific language governing permissions and # limitations", "paddings = [[0, 0], [0, self._static_max_length - s[1]]] x =", "and converts it to a tf Feature \"\"\" return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))", "static_max_length=None, shuffle_buffer_size=10000, shuffle=True, num_epochs=None, one_shot=False): self._feature_map = feature_map self._batch_size =", "Map to features index = 0 result = {} for", "Reserved. # # Licensed under the Apache License, Version 2.0", "@property def init_op(self): return self._init_op @property def batch(self): return self._result", "- s[1]]] x = tf.pad(t, paddings, 'CONSTANT', constant_values=0) x =", "self.pad(dense_tensor) result.append(dense_tensor) else: result.append(val) return tuple(result) @property def iterator(self): return", "as tf from tensorflow.python.framework import sparse_tensor as sparse_tensor_lib from tensorflow.python.ops", "result.append(val) return tuple(result) @property def iterator(self): return self._iterator @property def", "governing permissions and # limitations under the License. # ==============================================================================", "from examples to tf.int64 keys # pads: a set of", "result = {} for key in sorted(self._feature_map.keys()): result[key] = self._outputs[index]", "indefinitely elif num_epochs > 1: dataset = dataset.repeat(count=num_epochs) dataset =", "@property def iterator(self): return self._iterator @property def init_op(self): return self._init_op", "Pre-fetch a batch for faster processing dataset = dataset.prefetch(prefetch_buffer_size) #", "from __future__ import absolute_import from __future__ import division from __future__", "in compliance with the License. # You may obtain a", "= dataset.repeat() # repeat indefinitely elif num_epochs > 1: dataset", "software # distributed under the License is distributed on an", "self._iterator.get_next() # Map to features index = 0 result =", "assert x.get_shape().as_list()[1] is self._static_max_length return x def parse_example(self, serialized): parsed", "serialized): parsed = parsing_ops.parse_example(serialized, self._feature_map) result = [] for key", "Get the iterator if one_shot: self._iterator = dataset.make_one_shot_iterator() else: self._iterator", "tfrecord_file, feature_map, batch_size=32, num_threads=4, prefetch_buffer_size=1, static_max_length=None, shuffle_buffer_size=10000, shuffle=True, num_epochs=None, one_shot=False):", "a mapping from examples to tf.int64 keys # pads: a", "tf.sparse_tensor_to_dense(val) if self._static_max_length is not None: dense_tensor = self.pad(dense_tensor) result.append(dense_tensor)", "tf shapes that correspond to padded examples bucket_info = namedtuple(\"bucket_info\",", "else: self._iterator = dataset.make_initializable_iterator() self._init_op = self._iterator.initializer # Get outputs", "repeat indefinitely elif num_epochs > 1: dataset = dataset.repeat(count=num_epochs) dataset", "1: dataset = dataset.repeat(count=num_epochs) dataset = dataset.batch(batch_size) dataset = dataset.map(self.parse_example,", "self._static_max_length return x def parse_example(self, serialized): parsed = parsing_ops.parse_example(serialized, self._feature_map)", "tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) def int64_list_feature(sequence): \"\"\" Sequence of ints (e.g [1,2,3]) to", "__future__ import print_function from collections import namedtuple import tensorflow as", "dataset = dataset.shuffle(shuffle_buffer_size) # Maybe repeat if num_epochs is None:", "\"\"\" return tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) def int64_list_feature(sequence): \"\"\" Sequence of ints (e.g", "limitations under the License. # ============================================================================== from __future__ import absolute_import", "set of tf shapes that correspond to padded examples bucket_info", "= [[0, 0], [0, self._static_max_length - s[1]]] x = tf.pad(t,", "= parsing_ops.parse_example(serialized, self._feature_map) result = [] for key in sorted(self._feature_map.keys()):", "0 result = {} for key in sorted(self._feature_map.keys()): result[key] =", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "repeat if num_epochs is None: dataset = dataset.repeat() # repeat", "[0, self._static_max_length - s[1]]] x = tf.pad(t, paddings, 'CONSTANT', constant_values=0)", "3) and converts it to a tf Feature \"\"\" return", "shuffle_buffer_size=10000, shuffle=True, num_epochs=None, one_shot=False): self._feature_map = feature_map self._batch_size = batch_size", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "key in sorted(self._feature_map.keys()): val = parsed[key] if isinstance(val, sparse_tensor_lib.SparseTensor): dense_tensor", "one_shot=False): self._feature_map = feature_map self._batch_size = batch_size self._static_max_length = static_max_length", "self._result # namedtuple for bucket_info object (used in Pipeline) #", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "= {} for key in sorted(self._feature_map.keys()): result[key] = self._outputs[index] index", "index += 1 self._result = result def pad(self, t): s", "to in writing, software # distributed under the License is", "# See the License for the specific language governing permissions", "Maybe repeat if num_epochs is None: dataset = dataset.repeat() #", "= tf.shape(t) paddings = [[0, 0], [0, self._static_max_length - s[1]]]", "for key in sorted(self._feature_map.keys()): val = parsed[key] if isinstance(val, sparse_tensor_lib.SparseTensor):", "dataset.repeat() # repeat indefinitely elif num_epochs > 1: dataset =", "language governing permissions and # limitations under the License. #", "shapes that correspond to padded examples bucket_info = namedtuple(\"bucket_info\", \"func", "or agreed to in writing, software # distributed under the", "s = tf.shape(t) paddings = [[0, 0], [0, self._static_max_length -", "required by applicable law or agreed to in writing, software", "self._static_max_length = static_max_length # Initialize the dataset dataset = tf.data.TFRecordDataset(tfrecord_file)", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "with the License. # You may obtain a copy of", "of tf shapes that correspond to padded examples bucket_info =", "dataset.map(self.parse_example, num_parallel_calls=num_threads) # Pre-fetch a batch for faster processing dataset", "outputs self._outputs = self._iterator.get_next() # Map to features index =", "in sorted(self._feature_map.keys()): result[key] = self._outputs[index] index += 1 self._result =", "val = parsed[key] if isinstance(val, sparse_tensor_lib.SparseTensor): dense_tensor = tf.sparse_tensor_to_dense(val) if", "dataset.make_one_shot_iterator() else: self._iterator = dataset.make_initializable_iterator() self._init_op = self._iterator.initializer # Get", "compliance with the License. # You may obtain a copy", "All Rights Reserved. # # Licensed under the Apache License,", "agreed to in writing, software # distributed under the License", "feature_map self._batch_size = batch_size self._static_max_length = static_max_length # Initialize the", "s[1]]] x = tf.pad(t, paddings, 'CONSTANT', constant_values=0) x = tf.reshape(x,", "distributed under the License is distributed on an \"AS IS\"", "permissions and # limitations under the License. # ============================================================================== from", "parsing_ops class Pipeline(object): def __init__(self, tfrecord_file, feature_map, batch_size=32, num_threads=4, prefetch_buffer_size=1,", "__future__ import division from __future__ import print_function from collections import", "self._iterator = dataset.make_one_shot_iterator() else: self._iterator = dataset.make_initializable_iterator() self._init_op = self._iterator.initializer", "def __init__(self, tfrecord_file, feature_map, batch_size=32, num_threads=4, prefetch_buffer_size=1, static_max_length=None, shuffle_buffer_size=10000, shuffle=True,", "= self._iterator.get_next() # Map to features index = 0 result", "express or implied. # See the License for the specific", "except in compliance with the License. # You may obtain", "self._iterator = dataset.make_initializable_iterator() self._init_op = self._iterator.initializer # Get outputs self._outputs", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "features index = 0 result = {} for key in", "not use this file except in compliance with the License.", "def parse_example(self, serialized): parsed = parsing_ops.parse_example(serialized, self._feature_map) result = []", "writing, software # distributed under the License is distributed on", "Get outputs self._outputs = self._iterator.get_next() # Map to features index", "# Map to features index = 0 result = {}", "you may not use this file except in compliance with", "[[0, 0], [0, self._static_max_length - s[1]]] x = tf.pad(t, paddings,", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "# Maybe repeat if num_epochs is None: dataset = dataset.repeat()", "int64_list_feature(sequence): \"\"\" Sequence of ints (e.g [1,2,3]) to TF feature", "self._init_op @property def batch(self): return self._result # namedtuple for bucket_info", "import sparse_tensor as sparse_tensor_lib from tensorflow.python.ops import parsing_ops class Pipeline(object):", "Hopkins University. All Rights Reserved. # # Licensed under the", "# limitations under the License. # ============================================================================== from __future__ import", "CONDITIONS OF ANY KIND, either express or implied. # See", "Copyright 2018 Johns Hopkins University. All Rights Reserved. # #", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "tf.int64 keys # pads: a set of tf shapes that", "it to a tf Feature \"\"\" return tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) def int64_list_feature(sequence):", "self._feature_map = feature_map self._batch_size = batch_size self._static_max_length = static_max_length #", "dataset.batch(batch_size) dataset = dataset.map(self.parse_example, num_parallel_calls=num_threads) # Pre-fetch a batch for", "t): s = tf.shape(t) paddings = [[0, 0], [0, self._static_max_length", "__init__(self, tfrecord_file, feature_map, batch_size=32, num_threads=4, prefetch_buffer_size=1, static_max_length=None, shuffle_buffer_size=10000, shuffle=True, num_epochs=None,", "the License. # ============================================================================== from __future__ import absolute_import from __future__", "result def pad(self, t): s = tf.shape(t) paddings = [[0,", "one_shot: self._iterator = dataset.make_one_shot_iterator() else: self._iterator = dataset.make_initializable_iterator() self._init_op =", "result[key] = self._outputs[index] index += 1 self._result = result def", "iterator(self): return self._iterator @property def init_op(self): return self._init_op @property def", "a tf Feature \"\"\" return tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) def int64_list_feature(sequence): \"\"\" Sequence", "sorted(self._feature_map.keys()): val = parsed[key] if isinstance(val, sparse_tensor_lib.SparseTensor): dense_tensor = tf.sparse_tensor_to_dense(val)", "def init_op(self): return self._init_op @property def batch(self): return self._result #", "OR CONDITIONS OF ANY KIND, either express or implied. #", "self._outputs[index] index += 1 self._result = result def pad(self, t):", "object (used in Pipeline) # func: a mapping from examples", "the License is distributed on an \"AS IS\" BASIS, #", "int (e.g. 3) and converts it to a tf Feature", "from __future__ import division from __future__ import print_function from collections", "= static_max_length # Initialize the dataset dataset = tf.data.TFRecordDataset(tfrecord_file) #", "[] for key in sorted(self._feature_map.keys()): val = parsed[key] if isinstance(val,", "> 1: dataset = dataset.repeat(count=num_epochs) dataset = dataset.batch(batch_size) dataset =", "Initialize the dataset dataset = tf.data.TFRecordDataset(tfrecord_file) # Maybe randomize if", "= result def pad(self, t): s = tf.shape(t) paddings =", "import division from __future__ import print_function from collections import namedtuple", "examples to tf.int64 keys # pads: a set of tf", "= dataset.prefetch(prefetch_buffer_size) # Get the iterator if one_shot: self._iterator =", "= dataset.batch(batch_size) dataset = dataset.map(self.parse_example, num_parallel_calls=num_threads) # Pre-fetch a batch", "law or agreed to in writing, software # distributed under", "elif num_epochs > 1: dataset = dataset.repeat(count=num_epochs) dataset = dataset.batch(batch_size)", "# pads: a set of tf shapes that correspond to", "paddings, 'CONSTANT', constant_values=0) x = tf.reshape(x, [s[0], self._static_max_length]) assert x.get_shape().as_list()[1]", "tf.shape(t) paddings = [[0, 0], [0, self._static_max_length - s[1]]] x", "may obtain a copy of the License at # #", "# Get outputs self._outputs = self._iterator.get_next() # Map to features", "print_function from collections import namedtuple import tensorflow as tf from", "return tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) def int64_list_feature(sequence): \"\"\" Sequence of ints (e.g [1,2,3])", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "+= 1 self._result = result def pad(self, t): s =", "sparse_tensor_lib from tensorflow.python.ops import parsing_ops class Pipeline(object): def __init__(self, tfrecord_file,", "return self._result # namedtuple for bucket_info object (used in Pipeline)", "from collections import namedtuple import tensorflow as tf from tensorflow.python.framework", "may not use this file except in compliance with the", "def batch(self): return self._result # namedtuple for bucket_info object (used", "\"func pads\") def int64_feature(value): \"\"\" Takes a single int (e.g.", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "division from __future__ import print_function from collections import namedtuple import", "this file except in compliance with the License. # You", "dense_tensor = self.pad(dense_tensor) result.append(dense_tensor) else: result.append(val) return tuple(result) @property def", "import absolute_import from __future__ import division from __future__ import print_function", "randomize if shuffle: dataset = dataset.shuffle(shuffle_buffer_size) # Maybe repeat if", "collections import namedtuple import tensorflow as tf from tensorflow.python.framework import", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "for key in sorted(self._feature_map.keys()): result[key] = self._outputs[index] index += 1", "# # Licensed under the Apache License, Version 2.0 (the", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "from tensorflow.python.ops import parsing_ops class Pipeline(object): def __init__(self, tfrecord_file, feature_map,", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "a single int (e.g. 3) and converts it to a", "(e.g. 3) and converts it to a tf Feature \"\"\"", "in sorted(self._feature_map.keys()): val = parsed[key] if isinstance(val, sparse_tensor_lib.SparseTensor): dense_tensor =", "for bucket_info object (used in Pipeline) # func: a mapping", "if one_shot: self._iterator = dataset.make_one_shot_iterator() else: self._iterator = dataset.make_initializable_iterator() self._init_op", "= self._outputs[index] index += 1 self._result = result def pad(self,", "= parsed[key] if isinstance(val, sparse_tensor_lib.SparseTensor): dense_tensor = tf.sparse_tensor_to_dense(val) if self._static_max_length", "not None: dense_tensor = self.pad(dense_tensor) result.append(dense_tensor) else: result.append(val) return tuple(result)", "self._static_max_length - s[1]]] x = tf.pad(t, paddings, 'CONSTANT', constant_values=0) x", "dense_tensor = tf.sparse_tensor_to_dense(val) if self._static_max_length is not None: dense_tensor =", "License. # ============================================================================== from __future__ import absolute_import from __future__ import", "dataset = dataset.repeat(count=num_epochs) dataset = dataset.batch(batch_size) dataset = dataset.map(self.parse_example, num_parallel_calls=num_threads)", "tensorflow.python.framework import sparse_tensor as sparse_tensor_lib from tensorflow.python.ops import parsing_ops class", "tuple(result) @property def iterator(self): return self._iterator @property def init_op(self): return", "init_op(self): return self._init_op @property def batch(self): return self._result # namedtuple", "padded examples bucket_info = namedtuple(\"bucket_info\", \"func pads\") def int64_feature(value): \"\"\"", "1 self._result = result def pad(self, t): s = tf.shape(t)", "iterator if one_shot: self._iterator = dataset.make_one_shot_iterator() else: self._iterator = dataset.make_initializable_iterator()", "bucket_info object (used in Pipeline) # func: a mapping from", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "[s[0], self._static_max_length]) assert x.get_shape().as_list()[1] is self._static_max_length return x def parse_example(self,", "self._iterator.initializer # Get outputs self._outputs = self._iterator.get_next() # Map to", "as sparse_tensor_lib from tensorflow.python.ops import parsing_ops class Pipeline(object): def __init__(self,", "or implied. # See the License for the specific language", "Rights Reserved. # # Licensed under the Apache License, Version", "a set of tf shapes that correspond to padded examples", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "is self._static_max_length return x def parse_example(self, serialized): parsed = parsing_ops.parse_example(serialized,", "examples bucket_info = namedtuple(\"bucket_info\", \"func pads\") def int64_feature(value): \"\"\" Takes", "dataset = dataset.batch(batch_size) dataset = dataset.map(self.parse_example, num_parallel_calls=num_threads) # Pre-fetch a", "sparse_tensor as sparse_tensor_lib from tensorflow.python.ops import parsing_ops class Pipeline(object): def", "import parsing_ops class Pipeline(object): def __init__(self, tfrecord_file, feature_map, batch_size=32, num_threads=4,", "converts it to a tf Feature \"\"\" return tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) def", "dataset.prefetch(prefetch_buffer_size) # Get the iterator if one_shot: self._iterator = dataset.make_one_shot_iterator()", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "class Pipeline(object): def __init__(self, tfrecord_file, feature_map, batch_size=32, num_threads=4, prefetch_buffer_size=1, static_max_length=None,", "single int (e.g. 3) and converts it to a tf", "int64_feature(value): \"\"\" Takes a single int (e.g. 3) and converts", "None: dataset = dataset.repeat() # repeat indefinitely elif num_epochs >", "the iterator if one_shot: self._iterator = dataset.make_one_shot_iterator() else: self._iterator =", "(the \"License\"); # you may not use this file except", "in Pipeline) # func: a mapping from examples to tf.int64", "# you may not use this file except in compliance", "parsed = parsing_ops.parse_example(serialized, self._feature_map) result = [] for key in", "constant_values=0) x = tf.reshape(x, [s[0], self._static_max_length]) assert x.get_shape().as_list()[1] is self._static_max_length", "batch_size self._static_max_length = static_max_length # Initialize the dataset dataset =", "def pad(self, t): s = tf.shape(t) paddings = [[0, 0],", "dataset = dataset.prefetch(prefetch_buffer_size) # Get the iterator if one_shot: self._iterator", "to features index = 0 result = {} for key", "dataset dataset = tf.data.TFRecordDataset(tfrecord_file) # Maybe randomize if shuffle: dataset", "keys # pads: a set of tf shapes that correspond", "tf Feature \"\"\" return tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) def int64_list_feature(sequence): \"\"\" Sequence of", "# # Unless required by applicable law or agreed to", "Feature \"\"\" return tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) def int64_list_feature(sequence): \"\"\" Sequence of ints", "shuffle=True, num_epochs=None, one_shot=False): self._feature_map = feature_map self._batch_size = batch_size self._static_max_length", "num_epochs=None, one_shot=False): self._feature_map = feature_map self._batch_size = batch_size self._static_max_length =", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "self._static_max_length]) assert x.get_shape().as_list()[1] is self._static_max_length return x def parse_example(self, serialized):", "Version 2.0 (the \"License\"); # you may not use this", "dataset.repeat(count=num_epochs) dataset = dataset.batch(batch_size) dataset = dataset.map(self.parse_example, num_parallel_calls=num_threads) # Pre-fetch", "= tf.reshape(x, [s[0], self._static_max_length]) assert x.get_shape().as_list()[1] is self._static_max_length return x", "dataset.make_initializable_iterator() self._init_op = self._iterator.initializer # Get outputs self._outputs = self._iterator.get_next()", "namedtuple for bucket_info object (used in Pipeline) # func: a", "from __future__ import print_function from collections import namedtuple import tensorflow", "__future__ import absolute_import from __future__ import division from __future__ import", "implied. # See the License for the specific language governing", "# Get the iterator if one_shot: self._iterator = dataset.make_one_shot_iterator() else:", "None: dense_tensor = self.pad(dense_tensor) result.append(dense_tensor) else: result.append(val) return tuple(result) @property", "under the Apache License, Version 2.0 (the \"License\"); # you", "# repeat indefinitely elif num_epochs > 1: dataset = dataset.repeat(count=num_epochs)", "============================================================================== from __future__ import absolute_import from __future__ import division from", "to a tf Feature \"\"\" return tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) def int64_list_feature(sequence): \"\"\"", "self._outputs = self._iterator.get_next() # Map to features index = 0", "Sequence of ints (e.g [1,2,3]) to TF feature \"\"\" return", "by applicable law or agreed to in writing, software #", "result.append(dense_tensor) else: result.append(val) return tuple(result) @property def iterator(self): return self._iterator", "import tensorflow as tf from tensorflow.python.framework import sparse_tensor as sparse_tensor_lib", "tensorflow.python.ops import parsing_ops class Pipeline(object): def __init__(self, tfrecord_file, feature_map, batch_size=32,", "Maybe randomize if shuffle: dataset = dataset.shuffle(shuffle_buffer_size) # Maybe repeat", "# namedtuple for bucket_info object (used in Pipeline) # func:", "batch_size=32, num_threads=4, prefetch_buffer_size=1, static_max_length=None, shuffle_buffer_size=10000, shuffle=True, num_epochs=None, one_shot=False): self._feature_map =", "of ints (e.g [1,2,3]) to TF feature \"\"\" return tf.train.Feature(int64_list=tf.train.Int64List(value=sequence))", "= dataset.map(self.parse_example, num_parallel_calls=num_threads) # Pre-fetch a batch for faster processing", "import namedtuple import tensorflow as tf from tensorflow.python.framework import sparse_tensor", "self._feature_map) result = [] for key in sorted(self._feature_map.keys()): val =", "sorted(self._feature_map.keys()): result[key] = self._outputs[index] index += 1 self._result = result", "under the License. # ============================================================================== from __future__ import absolute_import from", "# func: a mapping from examples to tf.int64 keys #", "\"\"\" Takes a single int (e.g. 3) and converts it", "tf.pad(t, paddings, 'CONSTANT', constant_values=0) x = tf.reshape(x, [s[0], self._static_max_length]) assert", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "for faster processing dataset = dataset.prefetch(prefetch_buffer_size) # Get the iterator", "Unless required by applicable law or agreed to in writing,", "pad(self, t): s = tf.shape(t) paddings = [[0, 0], [0,", "# Pre-fetch a batch for faster processing dataset = dataset.prefetch(prefetch_buffer_size)", "= dataset.make_one_shot_iterator() else: self._iterator = dataset.make_initializable_iterator() self._init_op = self._iterator.initializer #", "return self._init_op @property def batch(self): return self._result # namedtuple for", "the specific language governing permissions and # limitations under the", "# Maybe randomize if shuffle: dataset = dataset.shuffle(shuffle_buffer_size) # Maybe", "feature_map, batch_size=32, num_threads=4, prefetch_buffer_size=1, static_max_length=None, shuffle_buffer_size=10000, shuffle=True, num_epochs=None, one_shot=False): self._feature_map", "applicable law or agreed to in writing, software # distributed", "shuffle: dataset = dataset.shuffle(shuffle_buffer_size) # Maybe repeat if num_epochs is", "import print_function from collections import namedtuple import tensorflow as tf", "return tuple(result) @property def iterator(self): return self._iterator @property def init_op(self):", "prefetch_buffer_size=1, static_max_length=None, shuffle_buffer_size=10000, shuffle=True, num_epochs=None, one_shot=False): self._feature_map = feature_map self._batch_size", "if shuffle: dataset = dataset.shuffle(shuffle_buffer_size) # Maybe repeat if num_epochs", "in writing, software # distributed under the License is distributed", "namedtuple import tensorflow as tf from tensorflow.python.framework import sparse_tensor as", "batch for faster processing dataset = dataset.prefetch(prefetch_buffer_size) # Get the", "faster processing dataset = dataset.prefetch(prefetch_buffer_size) # Get the iterator if", "'CONSTANT', constant_values=0) x = tf.reshape(x, [s[0], self._static_max_length]) assert x.get_shape().as_list()[1] is", "self._static_max_length is not None: dense_tensor = self.pad(dense_tensor) result.append(dense_tensor) else: result.append(val)", "func: a mapping from examples to tf.int64 keys # pads:", "x = tf.pad(t, paddings, 'CONSTANT', constant_values=0) x = tf.reshape(x, [s[0],", "self._init_op = self._iterator.initializer # Get outputs self._outputs = self._iterator.get_next() #", "namedtuple(\"bucket_info\", \"func pads\") def int64_feature(value): \"\"\" Takes a single int", "the dataset dataset = tf.data.TFRecordDataset(tfrecord_file) # Maybe randomize if shuffle:", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "License, Version 2.0 (the \"License\"); # you may not use", "# You may obtain a copy of the License at", "= tf.data.TFRecordDataset(tfrecord_file) # Maybe randomize if shuffle: dataset = dataset.shuffle(shuffle_buffer_size)", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "if isinstance(val, sparse_tensor_lib.SparseTensor): dense_tensor = tf.sparse_tensor_to_dense(val) if self._static_max_length is not", "x.get_shape().as_list()[1] is self._static_max_length return x def parse_example(self, serialized): parsed =", "tf.reshape(x, [s[0], self._static_max_length]) assert x.get_shape().as_list()[1] is self._static_max_length return x def", "\"\"\" Sequence of ints (e.g [1,2,3]) to TF feature \"\"\"", "result = [] for key in sorted(self._feature_map.keys()): val = parsed[key]", "to padded examples bucket_info = namedtuple(\"bucket_info\", \"func pads\") def int64_feature(value):", "if num_epochs is None: dataset = dataset.repeat() # repeat indefinitely", "the License for the specific language governing permissions and #", "is None: dataset = dataset.repeat() # repeat indefinitely elif num_epochs", "sparse_tensor_lib.SparseTensor): dense_tensor = tf.sparse_tensor_to_dense(val) if self._static_max_length is not None: dense_tensor", "(used in Pipeline) # func: a mapping from examples to", "Apache License, Version 2.0 (the \"License\"); # you may not", "either express or implied. # See the License for the", "mapping from examples to tf.int64 keys # pads: a set", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "return x def parse_example(self, serialized): parsed = parsing_ops.parse_example(serialized, self._feature_map) result", "= tf.pad(t, paddings, 'CONSTANT', constant_values=0) x = tf.reshape(x, [s[0], self._static_max_length])", "# ============================================================================== from __future__ import absolute_import from __future__ import division", "static_max_length # Initialize the dataset dataset = tf.data.TFRecordDataset(tfrecord_file) # Maybe", "to tf.int64 keys # pads: a set of tf shapes", "= dataset.make_initializable_iterator() self._init_op = self._iterator.initializer # Get outputs self._outputs =", "key in sorted(self._feature_map.keys()): result[key] = self._outputs[index] index += 1 self._result", "= tf.sparse_tensor_to_dense(val) if self._static_max_length is not None: dense_tensor = self.pad(dense_tensor)", "pads: a set of tf shapes that correspond to padded", "= 0 result = {} for key in sorted(self._feature_map.keys()): result[key]", "pads\") def int64_feature(value): \"\"\" Takes a single int (e.g. 3)", "= batch_size self._static_max_length = static_max_length # Initialize the dataset dataset", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "dataset.shuffle(shuffle_buffer_size) # Maybe repeat if num_epochs is None: dataset =", "processing dataset = dataset.prefetch(prefetch_buffer_size) # Get the iterator if one_shot:", "x def parse_example(self, serialized): parsed = parsing_ops.parse_example(serialized, self._feature_map) result =", "batch(self): return self._result # namedtuple for bucket_info object (used in", "dataset = tf.data.TFRecordDataset(tfrecord_file) # Maybe randomize if shuffle: dataset =", "else: result.append(val) return tuple(result) @property def iterator(self): return self._iterator @property", "= self._iterator.initializer # Get outputs self._outputs = self._iterator.get_next() # Map", "if self._static_max_length is not None: dense_tensor = self.pad(dense_tensor) result.append(dense_tensor) else:", "{} for key in sorted(self._feature_map.keys()): result[key] = self._outputs[index] index +=", "num_parallel_calls=num_threads) # Pre-fetch a batch for faster processing dataset =", "Takes a single int (e.g. 3) and converts it to", "\"License\"); # you may not use this file except in", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "parsed[key] if isinstance(val, sparse_tensor_lib.SparseTensor): dense_tensor = tf.sparse_tensor_to_dense(val) if self._static_max_length is", "return self._iterator @property def init_op(self): return self._init_op @property def batch(self):", "bucket_info = namedtuple(\"bucket_info\", \"func pads\") def int64_feature(value): \"\"\" Takes a", "# Initialize the dataset dataset = tf.data.TFRecordDataset(tfrecord_file) # Maybe randomize", "# distributed under the License is distributed on an \"AS", "# Unless required by applicable law or agreed to in", "Pipeline(object): def __init__(self, tfrecord_file, feature_map, batch_size=32, num_threads=4, prefetch_buffer_size=1, static_max_length=None, shuffle_buffer_size=10000,", "= self.pad(dense_tensor) result.append(dense_tensor) else: result.append(val) return tuple(result) @property def iterator(self):", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "tf.data.TFRecordDataset(tfrecord_file) # Maybe randomize if shuffle: dataset = dataset.shuffle(shuffle_buffer_size) #", "dataset = dataset.map(self.parse_example, num_parallel_calls=num_threads) # Pre-fetch a batch for faster", "self._batch_size = batch_size self._static_max_length = static_max_length # Initialize the dataset", "You may obtain a copy of the License at #", "index = 0 result = {} for key in sorted(self._feature_map.keys()):", "parsing_ops.parse_example(serialized, self._feature_map) result = [] for key in sorted(self._feature_map.keys()): val", "from tensorflow.python.framework import sparse_tensor as sparse_tensor_lib from tensorflow.python.ops import parsing_ops", "@property def batch(self): return self._result # namedtuple for bucket_info object", "the Apache License, Version 2.0 (the \"License\"); # you may", "2018 Johns Hopkins University. All Rights Reserved. # # Licensed", "= [] for key in sorted(self._feature_map.keys()): val = parsed[key] if", "Johns Hopkins University. All Rights Reserved. # # Licensed under", "a batch for faster processing dataset = dataset.prefetch(prefetch_buffer_size) # Get", "dataset = dataset.repeat() # repeat indefinitely elif num_epochs > 1:", "University. All Rights Reserved. # # Licensed under the Apache" ]
[ "cycles=5) def inst_0x27(self): self.opRMB(self.ZeroPageAddr, 0xFB) self.pc += 1 @instruction(name=\"AND\", mode=\"zpi\",", "# instructions @instruction(name=\"RMB0\", mode=\"zpg\", cycles=5) def inst_0x07(self): self.opRMB(self.ZeroPageAddr, 0xFE) self.pc", "self.waiting: self.processorCycles += 1 else: mpu6502.MPU.step(self) return self # Make", "self.waiting = True @instruction(name=\"CMP\", mode='zpi', cycles=6) # Don't know cycles", "from py65.utils.devices import make_instruction_decorator class MPU(mpu6502.MPU): def __init__(self, *args, **kwargs):", "self.pc += 1 @instruction(name=\"SMB0\", mode=\"zpg\", cycles=5) def inst_0x87(self): self.opSMB(self.ZeroPageAddr, 0x01)", "2 @instruction(name=\"SMB2\", mode=\"zpg\", cycles=5) def inst_0xa7(self): self.opSMB(self.ZeroPageAddr, 0x04) self.pc +=", "self.pc += 1 @instruction(name=\"RMB1\", mode=\"zpg\", cycles=5) def inst_0x17(self): self.opRMB(self.ZeroPageAddr, 0xFD)", "inst_0x3a(self): self.opDECR(None) @instruction(name=\"BRA\", mode=\"rel\", cycles=1, extracycles=1) def inst_0x80(self): self.BranchRelAddr() @instruction(name=\"WAI\",", "self.opSMB(self.ZeroPageAddr, 0x04) self.pc += 1 @instruction(name=\"LDA\", mode=\"zpi\", cycles=5) def inst_0xb2(self):", "# operations def opRMB(self, x, mask): address = x() self.memory[address]", "0x10) self.pc += 1 @instruction(name=\"SMB5\", mode=\"zpg\", cycles=5) def inst_0xd7(self): self.opSMB(self.ZeroPageAddr,", "inst_0x34(self): self.opBIT(self.ZeroPageXAddr) self.pc += 1 @instruction(name=\"RMB3\", mode=\"zpg\", cycles=5) def inst_0x37(self):", "+= 1 @instruction(name=\"RMB5\", mode=\"zpg\", cycles=5) def inst_0x57(self): self.opRMB(self.ZeroPageAddr, 0xDF) self.pc", "inst_0x1a(self): self.opINCR(None) @instruction(name=\"TRB\", mode=\"abs\", cycles=6) def inst_0x1c(self): self.opTRB(self.AbsoluteAddr) self.pc +=", "mode=\"zpg\", cycles=5) def inst_0x67(self): self.opRMB(self.ZeroPageAddr, 0xBF) self.pc += 1 @instruction(name=\"ADC\",", "self.pc += 1 @instruction(name=\"SMB5\", mode=\"zpg\", cycles=5) def inst_0xd7(self): self.opSMB(self.ZeroPageAddr, 0x20)", "mpu6502.MPU.__init__(self, *args, **kwargs) self.name = '65C02' self.waiting = False def", "mode=\"zpg\", cycles=5) def inst_0xd7(self): self.opSMB(self.ZeroPageAddr, 0x20) self.pc += 1 @instruction(name=\"PHX\",", "disassemble = mpu6502.MPU.disassemble[:] instruction = make_instruction_decorator(instruct, disassemble, cycletime, extracycles) #", "!= 0: self.p |= self.ZERO self.memory[address] = m & ~self.a", "mode=\"zpg\", cycles=5) def inst_0x07(self): self.opRMB(self.ZeroPageAddr, 0xFE) self.pc += 1 @instruction(name=\"ORA\",", "return self # Make copies of the lists instruct =", "mode=\"zpg\", cycles=5) def inst_0x37(self): self.opRMB(self.ZeroPageAddr, 0xF7) self.pc += 1 @instruction(name=\"BIT\",", "@instruction(name=\"STA\", mode=\"zpi\", cycles=5) def inst_0x92(self): self.opSTA(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"SMB1\",", "0x08) self.pc += 1 @instruction(name=\"SMB4\", mode=\"zpg\", cycles=5) def inst_0xc7(self): self.opSMB(self.ZeroPageAddr,", "@instruction(name=\"SMB4\", mode=\"zpg\", cycles=5) def inst_0xc7(self): self.opSMB(self.ZeroPageAddr, 0x10) self.pc += 1", "!= 0: self.p |= self.ZERO self.memory[address] = m | self.a", "&= ~self.ZERO z = m & self.a if z !=", "inst_0x5a(self): self.stPush(self.y) @instruction(name=\"STZ\", mode=\"imp\", cycles=3) def inst_0x64(self): self.opSTZ(self.ZeroPageAddr) self.pc +=", "cycles=5) def inst_0x32(self): self.opAND(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"BIT\", mode=\"zpx\", cycles=4)", "mode=\"zpg\", cycles=5) def inst_0x57(self): self.opRMB(self.ZeroPageAddr, 0xDF) self.pc += 1 @instruction(name=\"PHY\",", "class MPU(mpu6502.MPU): def __init__(self, *args, **kwargs): mpu6502.MPU.__init__(self, *args, **kwargs) self.name", "0xDF) self.pc += 1 @instruction(name=\"PHY\", mode=\"imp\", cycles=3) def inst_0x5a(self): self.stPush(self.y)", "opRMB(self, x, mask): address = x() self.memory[address] &= mask def", "self.pc += 1 @instruction(name=\"ADC\", mode=\"zpi\", cycles=5) def inst_0x72(self): self.opADC(self.ZeroPageIndirectAddr) self.pc", "inst_0x12(self): self.opORA(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"RMB1\", mode=\"zpg\", cycles=5) def inst_0x17(self):", "0: self.p |= self.ZERO self.memory[address] = m | self.a def", "inst_0xa7(self): self.opSMB(self.ZeroPageAddr, 0x04) self.pc += 1 @instruction(name=\"LDA\", mode=\"zpi\", cycles=5) def", "*args, **kwargs) self.name = '65C02' self.waiting = False def step(self):", "inst_0x7a(self): self.y = self.stPop() self.FlagsNZ(self.y) @instruction(name=\"RMB7\", mode=\"zpg\", cycles=5) def inst_0x77(self):", "+= 1 @instruction(name=\"ORA\", mode=\"zpi\", cycles=5) def inst_0x12(self): self.opORA(self.ZeroPageIndirectAddr) self.pc +=", "= mpu6502.MPU.instruct[:] cycletime = mpu6502.MPU.cycletime[:] extracycles = mpu6502.MPU.extracycles[:] disassemble =", "cycletime, extracycles) # addressing modes def ZeroPageIndirectAddr(self): return self.WordAt( 255", "self.pc += 1 @instruction(name=\"TSB\", mode=\"abs\", cycles=6) def inst_0x0c(self): self.opTSB(self.AbsoluteAddr) self.pc", "self.ZERO self.memory[address] = m | self.a def opTRB(self, x): address", "self.opRMB(self.ZeroPageAddr, 0xFE) self.pc += 1 @instruction(name=\"ORA\", mode=\"zpi\", cycles=5) def inst_0x12(self):", "+= 1 @instruction(name=\"TSB\", mode=\"abs\", cycles=6) def inst_0x0c(self): self.opTSB(self.AbsoluteAddr) self.pc +=", "self.pc += 1 @instruction(name=\"AND\", mode=\"zpi\", cycles=5) def inst_0x32(self): self.opAND(self.ZeroPageIndirectAddr) self.pc", "1 @instruction(name=\"BIT\", mode=\"zpx\", cycles=4) def inst_0x34(self): self.opBIT(self.ZeroPageXAddr) self.pc += 1", "AccumulatorAddr(self): return self.a # operations def opRMB(self, x, mask): address", "self.pc += 1 @instruction(name=\"BIT\", mode=\"abx\", cycles=4) def inst_0x3c(self): self.opBIT(self.AbsoluteXAddr) self.pc", "mode=\"imp\", cycles=3) def inst_0x5a(self): self.stPush(self.y) @instruction(name=\"STZ\", mode=\"imp\", cycles=3) def inst_0x64(self):", "1 @instruction(name=\"LDA\", mode=\"zpi\", cycles=5) def inst_0xb2(self): self.opLDA(self.ZeroPageIndirectAddr) self.pc += 1", "1 @instruction(name=\"ORA\", mode=\"zpi\", cycles=5) def inst_0x12(self): self.opORA(self.ZeroPageIndirectAddr) self.pc += 1", "def inst_0x57(self): self.opRMB(self.ZeroPageAddr, 0xDF) self.pc += 1 @instruction(name=\"PHY\", mode=\"imp\", cycles=3)", "def inst_0xCB(self): self.waiting = True @instruction(name=\"CMP\", mode='zpi', cycles=6) # Don't", "def inst_0x34(self): self.opBIT(self.ZeroPageXAddr) self.pc += 1 @instruction(name=\"RMB3\", mode=\"zpg\", cycles=5) def", "copies of the lists instruct = mpu6502.MPU.instruct[:] cycletime = mpu6502.MPU.cycletime[:]", "self.pc += 1 @instruction(name=\"INC\", mode=\"acc\", cycles=2) def inst_0x1a(self): self.opINCR(None) @instruction(name=\"TRB\",", "def AccumulatorAddr(self): return self.a # operations def opRMB(self, x, mask):", "self.p &= ~self.ZERO z = m & self.a if z", "cycles=1, extracycles=1) def inst_0x80(self): self.BranchRelAddr() @instruction(name=\"WAI\", mode='imp', cycles=3) def inst_0xCB(self):", "1 @instruction(name=\"SBC\", mode=\"zpi\", cycles=5) def inst_0xf2(self): self.opSBC(self.ZeroPageIndirectAddr) self.pc += 1", "+= 2 @instruction(name=\"STZ\", mode=\"abx\", cycles=5) def inst_0x9e(self): self.opSTZ(self.AbsoluteXAddr) self.pc +=", "addressing modes def ZeroPageIndirectAddr(self): return self.WordAt( 255 & (self.ByteAt(self.pc))) def", "cycles=4) def inst_0x3c(self): self.opBIT(self.AbsoluteXAddr) self.pc += 2 @instruction(name=\"RMB4\", mode=\"zpg\", cycles=5)", "@instruction(name=\"TSB\", mode=\"zpg\", cycles=5) def inst_0x04(self): self.opTSB(self.ZeroPageAddr) self.pc += 1 @instruction(name=\"TSB\",", "self.pc += 2 @instruction(name=\"TRB\", mode=\"zpg\", cycles=5) def inst_0x14(self): self.opTRB(self.ZeroPageAddr) self.pc", "= x() self.memory[address] |= mask def opSTZ(self, x): self.memory[x()] =", "+= 1 @instruction(name=\"SMB7\", mode=\"zpg\", cycles=5) def inst_0xf7(self): self.opSMB(self.ZeroPageAddr, 0x80) self.pc", "+= 1 @instruction(name=\"RMB1\", mode=\"zpg\", cycles=5) def inst_0x17(self): self.opRMB(self.ZeroPageAddr, 0xFD) self.pc", "+= 1 @instruction(name=\"SBC\", mode=\"zpi\", cycles=5) def inst_0xf2(self): self.opSBC(self.ZeroPageIndirectAddr) self.pc +=", "cycles=5) def inst_0xb7(self): self.opSMB(self.ZeroPageAddr, 0x08) self.pc += 1 @instruction(name=\"SMB4\", mode=\"zpg\",", "def inst_0xf7(self): self.opSMB(self.ZeroPageAddr, 0x80) self.pc += 1 @instruction(name=\"PLX\", mode=\"imp\", cycles=4)", "= mpu6502.MPU.cycletime[:] extracycles = mpu6502.MPU.extracycles[:] disassemble = mpu6502.MPU.disassemble[:] instruction =", "def inst_0x7a(self): self.y = self.stPop() self.FlagsNZ(self.y) @instruction(name=\"RMB7\", mode=\"zpg\", cycles=5) def", "= self.stPop() self.FlagsNZ(self.x) @instruction(name=\"TSB\", mode=\"zpg\", cycles=5) def inst_0x04(self): self.opTSB(self.ZeroPageAddr) self.pc", "z = m & self.a if z != 0: self.p", "inst_0x32(self): self.opAND(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"BIT\", mode=\"zpx\", cycles=4) def inst_0x34(self):", "mode=\"rel\", cycles=1, extracycles=1) def inst_0x80(self): self.BranchRelAddr() @instruction(name=\"WAI\", mode='imp', cycles=3) def", "cycles=2) def inst_0x1a(self): self.opINCR(None) @instruction(name=\"TRB\", mode=\"abs\", cycles=6) def inst_0x1c(self): self.opTRB(self.AbsoluteAddr)", "disassemble, cycletime, extracycles) # addressing modes def ZeroPageIndirectAddr(self): return self.WordAt(", "@instruction(name=\"INC\", mode=\"acc\", cycles=2) def inst_0x1a(self): self.opINCR(None) @instruction(name=\"TRB\", mode=\"abs\", cycles=6) def", "mode=\"abs\", cycles=6) def inst_0x0c(self): self.opTSB(self.AbsoluteAddr) self.pc += 2 @instruction(name=\"TRB\", mode=\"zpg\",", "extracycles) # addressing modes def ZeroPageIndirectAddr(self): return self.WordAt( 255 &", "__init__(self, *args, **kwargs): mpu6502.MPU.__init__(self, *args, **kwargs) self.name = '65C02' self.waiting", "1 @instruction(name=\"SMB1\", mode=\"zpg\", cycles=5) def inst_0x97(self): self.opSMB(self.ZeroPageAddr, 0x02) self.pc +=", "1 @instruction(name=\"SMB7\", mode=\"zpg\", cycles=5) def inst_0xf7(self): self.opSMB(self.ZeroPageAddr, 0x80) self.pc +=", "cycletime = mpu6502.MPU.cycletime[:] extracycles = mpu6502.MPU.extracycles[:] disassemble = mpu6502.MPU.disassemble[:] instruction", "+= 1 else: mpu6502.MPU.step(self) return self # Make copies of", "cycles=4) def inst_0x34(self): self.opBIT(self.ZeroPageXAddr) self.pc += 1 @instruction(name=\"RMB3\", mode=\"zpg\", cycles=5)", "def inst_0x32(self): self.opAND(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"BIT\", mode=\"zpx\", cycles=4) def", "self.opADC(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"STZ\", mode=\"zpx\", cycles=4) def inst_0x74(self): self.opSTZ(self.ZeroPageXAddr)", "mask): address = x() self.memory[address] &= mask def opSMB(self, x,", "the lists instruct = mpu6502.MPU.instruct[:] cycletime = mpu6502.MPU.cycletime[:] extracycles =", "inst_0xda(self): self.stPush(self.x) @instruction(name=\"SMB6\", mode=\"zpg\", cycles=5) def inst_0xe7(self): self.opSMB(self.ZeroPageAddr, 0x40) self.pc", "self.pc += 1 @instruction(name=\"LDA\", mode=\"zpi\", cycles=5) def inst_0xb2(self): self.opLDA(self.ZeroPageIndirectAddr) self.pc", "1 @instruction(name=\"TSB\", mode=\"abs\", cycles=6) def inst_0x0c(self): self.opTSB(self.AbsoluteAddr) self.pc += 2", "cycles=5) def inst_0xd7(self): self.opSMB(self.ZeroPageAddr, 0x20) self.pc += 1 @instruction(name=\"PHX\", mode=\"imp\",", "mode=\"zpg\", cycles=5) def inst_0x27(self): self.opRMB(self.ZeroPageAddr, 0xFB) self.pc += 1 @instruction(name=\"AND\",", "cycles=5) def inst_0x77(self): self.opRMB(self.ZeroPageAddr, 0x7F) self.pc += 1 @instruction(name=\"SMB0\", mode=\"zpg\",", "self.BranchRelAddr() @instruction(name=\"WAI\", mode='imp', cycles=3) def inst_0xCB(self): self.waiting = True @instruction(name=\"CMP\",", "mode='zpi', cycles=6) # Don't know cycles def inst_0xD2(self): self.opCPY(self.ZeroPageIndirectAddr) self.pc", "cycles=6) def inst_0x0c(self): self.opTSB(self.AbsoluteAddr) self.pc += 2 @instruction(name=\"TRB\", mode=\"zpg\", cycles=5)", "py65.utils.devices import make_instruction_decorator class MPU(mpu6502.MPU): def __init__(self, *args, **kwargs): mpu6502.MPU.__init__(self,", "def opSTZ(self, x): self.memory[x()] = 0x00 def opTSB(self, x): address", "self.opSTZ(self.AbsoluteAddr) self.pc += 2 @instruction(name=\"STZ\", mode=\"abx\", cycles=5) def inst_0x9e(self): self.opSTZ(self.AbsoluteXAddr)", "@instruction(name=\"SMB2\", mode=\"zpg\", cycles=5) def inst_0xa7(self): self.opSMB(self.ZeroPageAddr, 0x04) self.pc += 1", "1 @instruction(name=\"AND\", mode=\"zpi\", cycles=5) def inst_0x32(self): self.opAND(self.ZeroPageIndirectAddr) self.pc += 1", "mode=\"zpg\", cycles=5) def inst_0xf7(self): self.opSMB(self.ZeroPageAddr, 0x80) self.pc += 1 @instruction(name=\"PLX\",", "inst_0x3c(self): self.opBIT(self.AbsoluteXAddr) self.pc += 2 @instruction(name=\"RMB4\", mode=\"zpg\", cycles=5) def inst_0x47(self):", "= 0x00 def opTSB(self, x): address = x() m =", "instruct = mpu6502.MPU.instruct[:] cycletime = mpu6502.MPU.cycletime[:] extracycles = mpu6502.MPU.extracycles[:] disassemble", "+= 1 @instruction(name=\"ADC\", mode=\"zpi\", cycles=5) def inst_0x72(self): self.opADC(self.ZeroPageIndirectAddr) self.pc +=", "self.memory[address] = m | self.a def opTRB(self, x): address =", "self.opSTZ(self.ZeroPageXAddr) self.pc += 1 @instruction(name=\"PHY\", mode=\"imp\", cycles=4) def inst_0x7a(self): self.y", "inst_0x9c(self): self.opSTZ(self.AbsoluteAddr) self.pc += 2 @instruction(name=\"STZ\", mode=\"abx\", cycles=5) def inst_0x9e(self):", "cycles=5) def inst_0x47(self): self.opRMB(self.ZeroPageAddr, 0xEF) self.pc += 1 @instruction(name=\"EOR\", mode=\"zpi\",", "cycles=4) def inst_0xfa(self): self.x = self.stPop() self.FlagsNZ(self.x) @instruction(name=\"TSB\", mode=\"zpg\", cycles=5)", "@instruction(name=\"SMB1\", mode=\"zpg\", cycles=5) def inst_0x97(self): self.opSMB(self.ZeroPageAddr, 0x02) self.pc += 1", "cycles=4) def inst_0x7a(self): self.y = self.stPop() self.FlagsNZ(self.y) @instruction(name=\"RMB7\", mode=\"zpg\", cycles=5)", "cycles=5) def inst_0xf7(self): self.opSMB(self.ZeroPageAddr, 0x80) self.pc += 1 @instruction(name=\"PLX\", mode=\"imp\",", "cycles=6) def inst_0x1c(self): self.opTRB(self.AbsoluteAddr) self.pc += 2 @instruction(name=\"DEC\", mode=\"acc\", cycles=2)", "self.opCPY(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"SBC\", mode=\"zpi\", cycles=5) def inst_0xf2(self): self.opSBC(self.ZeroPageIndirectAddr)", "0x00 def opTSB(self, x): address = x() m = self.memory[address]", "opTSB(self, x): address = x() m = self.memory[address] self.p &=", "self.opTSB(self.ZeroPageAddr) self.pc += 1 @instruction(name=\"TSB\", mode=\"abs\", cycles=6) def inst_0x0c(self): self.opTSB(self.AbsoluteAddr)", "*args, **kwargs): mpu6502.MPU.__init__(self, *args, **kwargs) self.name = '65C02' self.waiting =", "modes def ZeroPageIndirectAddr(self): return self.WordAt( 255 & (self.ByteAt(self.pc))) def AccumulatorAddr(self):", "1 @instruction(name=\"STA\", mode=\"zpi\", cycles=5) def inst_0x92(self): self.opSTA(self.ZeroPageIndirectAddr) self.pc += 1", "self.opRMB(self.ZeroPageAddr, 0xBF) self.pc += 1 @instruction(name=\"ADC\", mode=\"zpi\", cycles=5) def inst_0x72(self):", "& self.a if z != 0: self.p |= self.ZERO self.memory[address]", "@instruction(name=\"RMB0\", mode=\"zpg\", cycles=5) def inst_0x07(self): self.opRMB(self.ZeroPageAddr, 0xFE) self.pc += 1", "x, mask): address = x() self.memory[address] |= mask def opSTZ(self,", "self.pc += 1 @instruction(name=\"SMB4\", mode=\"zpg\", cycles=5) def inst_0xc7(self): self.opSMB(self.ZeroPageAddr, 0x10)", "self.FlagsNZ(self.y) @instruction(name=\"RMB7\", mode=\"zpg\", cycles=5) def inst_0x77(self): self.opRMB(self.ZeroPageAddr, 0x7F) self.pc +=", "= make_instruction_decorator(instruct, disassemble, cycletime, extracycles) # addressing modes def ZeroPageIndirectAddr(self):", "False def step(self): if self.waiting: self.processorCycles += 1 else: mpu6502.MPU.step(self)", "self.WordAt( 255 & (self.ByteAt(self.pc))) def AccumulatorAddr(self): return self.a # operations", "self.memory[address] |= mask def opSTZ(self, x): self.memory[x()] = 0x00 def", "self.memory[x()] = 0x00 def opTSB(self, x): address = x() m", "@instruction(name=\"SMB5\", mode=\"zpg\", cycles=5) def inst_0xd7(self): self.opSMB(self.ZeroPageAddr, 0x20) self.pc += 1", "cycles=5) def inst_0x04(self): self.opTSB(self.ZeroPageAddr) self.pc += 1 @instruction(name=\"TSB\", mode=\"abs\", cycles=6)", "mode=\"imp\", cycles=4) def inst_0xfa(self): self.x = self.stPop() self.FlagsNZ(self.x) @instruction(name=\"TSB\", mode=\"zpg\",", "mode=\"imp\", cycles=3) def inst_0xda(self): self.stPush(self.x) @instruction(name=\"SMB6\", mode=\"zpg\", cycles=5) def inst_0xe7(self):", "self.opSTZ(self.ZeroPageAddr) self.pc += 1 @instruction(name=\"RMB6\", mode=\"zpg\", cycles=5) def inst_0x67(self): self.opRMB(self.ZeroPageAddr,", "2 @instruction(name=\"TRB\", mode=\"zpg\", cycles=5) def inst_0x14(self): self.opTRB(self.ZeroPageAddr) self.pc += 1", "mpu6502 from py65.utils.devices import make_instruction_decorator class MPU(mpu6502.MPU): def __init__(self, *args,", "cycles=3) def inst_0x5a(self): self.stPush(self.y) @instruction(name=\"STZ\", mode=\"imp\", cycles=3) def inst_0x64(self): self.opSTZ(self.ZeroPageAddr)", "0x80) self.pc += 1 @instruction(name=\"PLX\", mode=\"imp\", cycles=4) def inst_0xfa(self): self.x", "def inst_0x9e(self): self.opSTZ(self.AbsoluteXAddr) self.pc += 2 @instruction(name=\"SMB2\", mode=\"zpg\", cycles=5) def", "cycles=5) def inst_0x92(self): self.opSTA(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"SMB1\", mode=\"zpg\", cycles=5)", "mode=\"zpi\", cycles=5) def inst_0x72(self): self.opADC(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"STZ\", mode=\"zpx\",", "&= mask def opSMB(self, x, mask): address = x() self.memory[address]", "@instruction(name=\"RMB7\", mode=\"zpg\", cycles=5) def inst_0x77(self): self.opRMB(self.ZeroPageAddr, 0x7F) self.pc += 1", "cycles=5) def inst_0x12(self): self.opORA(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"RMB1\", mode=\"zpg\", cycles=5)", "inst_0x17(self): self.opRMB(self.ZeroPageAddr, 0xFD) self.pc += 1 @instruction(name=\"RMB2\", mode=\"zpg\", cycles=5) def", "+= 1 @instruction(name=\"LDA\", mode=\"zpi\", cycles=5) def inst_0xb2(self): self.opLDA(self.ZeroPageIndirectAddr) self.pc +=", "def inst_0x52(self): self.opEOR(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"RMB5\", mode=\"zpg\", cycles=5) def", "@instruction(name=\"BIT\", mode=\"abx\", cycles=4) def inst_0x3c(self): self.opBIT(self.AbsoluteXAddr) self.pc += 2 @instruction(name=\"RMB4\",", "+= 1 @instruction(name=\"INC\", mode=\"acc\", cycles=2) def inst_0x1a(self): self.opINCR(None) @instruction(name=\"TRB\", mode=\"abs\",", "self.opSMB(self.ZeroPageAddr, 0x02) self.pc += 1 @instruction(name=\"STZ\", mode=\"abs\", cycles=4) def inst_0x9c(self):", "def inst_0x04(self): self.opTSB(self.ZeroPageAddr) self.pc += 1 @instruction(name=\"TSB\", mode=\"abs\", cycles=6) def", "self.opTRB(self.AbsoluteAddr) self.pc += 2 @instruction(name=\"DEC\", mode=\"acc\", cycles=2) def inst_0x3a(self): self.opDECR(None)", "255 & (self.ByteAt(self.pc))) def AccumulatorAddr(self): return self.a # operations def", "inst_0x87(self): self.opSMB(self.ZeroPageAddr, 0x01) self.pc += 1 @instruction(name=\"STA\", mode=\"zpi\", cycles=5) def", "1 @instruction(name=\"ADC\", mode=\"zpi\", cycles=5) def inst_0x72(self): self.opADC(self.ZeroPageIndirectAddr) self.pc += 1", "inst_0x52(self): self.opEOR(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"RMB5\", mode=\"zpg\", cycles=5) def inst_0x57(self):", "inst_0xf7(self): self.opSMB(self.ZeroPageAddr, 0x80) self.pc += 1 @instruction(name=\"PLX\", mode=\"imp\", cycles=4) def", "def inst_0xfa(self): self.x = self.stPop() self.FlagsNZ(self.x) @instruction(name=\"TSB\", mode=\"zpg\", cycles=5) def", "| self.a def opTRB(self, x): address = x() m =", "cycles=5) def inst_0xc7(self): self.opSMB(self.ZeroPageAddr, 0x10) self.pc += 1 @instruction(name=\"SMB5\", mode=\"zpg\",", "opSMB(self, x, mask): address = x() self.memory[address] |= mask def", "opSTZ(self, x): self.memory[x()] = 0x00 def opTSB(self, x): address =", "+= 1 @instruction(name=\"BIT\", mode=\"abx\", cycles=4) def inst_0x3c(self): self.opBIT(self.AbsoluteXAddr) self.pc +=", "inst_0x74(self): self.opSTZ(self.ZeroPageXAddr) self.pc += 1 @instruction(name=\"PHY\", mode=\"imp\", cycles=4) def inst_0x7a(self):", "def inst_0x74(self): self.opSTZ(self.ZeroPageXAddr) self.pc += 1 @instruction(name=\"PHY\", mode=\"imp\", cycles=4) def", "# Make copies of the lists instruct = mpu6502.MPU.instruct[:] cycletime", "cycles=5) def inst_0x17(self): self.opRMB(self.ZeroPageAddr, 0xFD) self.pc += 1 @instruction(name=\"RMB2\", mode=\"zpg\",", "def inst_0x5a(self): self.stPush(self.y) @instruction(name=\"STZ\", mode=\"imp\", cycles=3) def inst_0x64(self): self.opSTZ(self.ZeroPageAddr) self.pc", "self.opSTA(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"SMB1\", mode=\"zpg\", cycles=5) def inst_0x97(self): self.opSMB(self.ZeroPageAddr,", "0x20) self.pc += 1 @instruction(name=\"PHX\", mode=\"imp\", cycles=3) def inst_0xda(self): self.stPush(self.x)", "@instruction(name=\"TRB\", mode=\"zpg\", cycles=5) def inst_0x14(self): self.opTRB(self.ZeroPageAddr) self.pc += 1 @instruction(name=\"INC\",", "inst_0xCB(self): self.waiting = True @instruction(name=\"CMP\", mode='zpi', cycles=6) # Don't know", "mode=\"zpx\", cycles=4) def inst_0x74(self): self.opSTZ(self.ZeroPageXAddr) self.pc += 1 @instruction(name=\"PHY\", mode=\"imp\",", "mpu6502.MPU.cycletime[:] extracycles = mpu6502.MPU.extracycles[:] disassemble = mpu6502.MPU.disassemble[:] instruction = make_instruction_decorator(instruct,", "z != 0: self.p |= self.ZERO self.memory[address] = m &", "mode=\"abs\", cycles=6) def inst_0x1c(self): self.opTRB(self.AbsoluteAddr) self.pc += 2 @instruction(name=\"DEC\", mode=\"acc\",", "inst_0x64(self): self.opSTZ(self.ZeroPageAddr) self.pc += 1 @instruction(name=\"RMB6\", mode=\"zpg\", cycles=5) def inst_0x67(self):", "x() self.memory[address] |= mask def opSTZ(self, x): self.memory[x()] = 0x00", "mode=\"imp\", cycles=4) def inst_0x7a(self): self.y = self.stPop() self.FlagsNZ(self.y) @instruction(name=\"RMB7\", mode=\"zpg\",", "**kwargs) self.name = '65C02' self.waiting = False def step(self): if", "def inst_0x72(self): self.opADC(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"STZ\", mode=\"zpx\", cycles=4) def", "def opTRB(self, x): address = x() m = self.memory[address] self.p", "cycles=5) def inst_0x9e(self): self.opSTZ(self.AbsoluteXAddr) self.pc += 2 @instruction(name=\"SMB2\", mode=\"zpg\", cycles=5)", "cycles=5) def inst_0xb2(self): self.opLDA(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"SMB3\", mode=\"zpg\", cycles=5)", "inst_0xfa(self): self.x = self.stPop() self.FlagsNZ(self.x) @instruction(name=\"TSB\", mode=\"zpg\", cycles=5) def inst_0x04(self):", "mode=\"zpg\", cycles=5) def inst_0x14(self): self.opTRB(self.ZeroPageAddr) self.pc += 1 @instruction(name=\"INC\", mode=\"acc\",", "inst_0x57(self): self.opRMB(self.ZeroPageAddr, 0xDF) self.pc += 1 @instruction(name=\"PHY\", mode=\"imp\", cycles=3) def", "& ~self.a # instructions @instruction(name=\"RMB0\", mode=\"zpg\", cycles=5) def inst_0x07(self): self.opRMB(self.ZeroPageAddr,", "mode=\"zpi\", cycles=5) def inst_0x12(self): self.opORA(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"RMB1\", mode=\"zpg\",", "mode='imp', cycles=3) def inst_0xCB(self): self.waiting = True @instruction(name=\"CMP\", mode='zpi', cycles=6)", "0xFB) self.pc += 1 @instruction(name=\"AND\", mode=\"zpi\", cycles=5) def inst_0x32(self): self.opAND(self.ZeroPageIndirectAddr)", "+= 1 @instruction(name=\"RMB6\", mode=\"zpg\", cycles=5) def inst_0x67(self): self.opRMB(self.ZeroPageAddr, 0xBF) self.pc", "inst_0x27(self): self.opRMB(self.ZeroPageAddr, 0xFB) self.pc += 1 @instruction(name=\"AND\", mode=\"zpi\", cycles=5) def", "inst_0xd7(self): self.opSMB(self.ZeroPageAddr, 0x20) self.pc += 1 @instruction(name=\"PHX\", mode=\"imp\", cycles=3) def", "mode=\"zpi\", cycles=5) def inst_0xb2(self): self.opLDA(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"SMB3\", mode=\"zpg\",", "= x() self.memory[address] &= mask def opSMB(self, x, mask): address", "+= 1 @instruction(name=\"BIT\", mode=\"zpx\", cycles=4) def inst_0x34(self): self.opBIT(self.ZeroPageXAddr) self.pc +=", "mode=\"zpg\", cycles=5) def inst_0xa7(self): self.opSMB(self.ZeroPageAddr, 0x04) self.pc += 1 @instruction(name=\"LDA\",", "inst_0x97(self): self.opSMB(self.ZeroPageAddr, 0x02) self.pc += 1 @instruction(name=\"STZ\", mode=\"abs\", cycles=4) def", "self.opSTZ(self.AbsoluteXAddr) self.pc += 2 @instruction(name=\"SMB2\", mode=\"zpg\", cycles=5) def inst_0xa7(self): self.opSMB(self.ZeroPageAddr,", "self.pc += 2 @instruction(name=\"STZ\", mode=\"abx\", cycles=5) def inst_0x9e(self): self.opSTZ(self.AbsoluteXAddr) self.pc", "know cycles def inst_0xD2(self): self.opCPY(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"SBC\", mode=\"zpi\",", "|= self.ZERO self.memory[address] = m & ~self.a # instructions @instruction(name=\"RMB0\",", "self.pc += 2 @instruction(name=\"SMB2\", mode=\"zpg\", cycles=5) def inst_0xa7(self): self.opSMB(self.ZeroPageAddr, 0x04)", "self.stPush(self.x) @instruction(name=\"SMB6\", mode=\"zpg\", cycles=5) def inst_0xe7(self): self.opSMB(self.ZeroPageAddr, 0x40) self.pc +=", "# addressing modes def ZeroPageIndirectAddr(self): return self.WordAt( 255 & (self.ByteAt(self.pc)))", "self.opRMB(self.ZeroPageAddr, 0xFB) self.pc += 1 @instruction(name=\"AND\", mode=\"zpi\", cycles=5) def inst_0x32(self):", "mode=\"abs\", cycles=4) def inst_0x9c(self): self.opSTZ(self.AbsoluteAddr) self.pc += 2 @instruction(name=\"STZ\", mode=\"abx\",", "self.pc += 1 @instruction(name=\"RMB3\", mode=\"zpg\", cycles=5) def inst_0x37(self): self.opRMB(self.ZeroPageAddr, 0xF7)", "+= 1 @instruction(name=\"AND\", mode=\"zpi\", cycles=5) def inst_0x32(self): self.opAND(self.ZeroPageIndirectAddr) self.pc +=", "= self.stPop() self.FlagsNZ(self.y) @instruction(name=\"RMB7\", mode=\"zpg\", cycles=5) def inst_0x77(self): self.opRMB(self.ZeroPageAddr, 0x7F)", "= m & self.a if z != 0: self.p |=", "self.opAND(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"BIT\", mode=\"zpx\", cycles=4) def inst_0x34(self): self.opBIT(self.ZeroPageXAddr)", "def inst_0xc7(self): self.opSMB(self.ZeroPageAddr, 0x10) self.pc += 1 @instruction(name=\"SMB5\", mode=\"zpg\", cycles=5)", "**kwargs): mpu6502.MPU.__init__(self, *args, **kwargs) self.name = '65C02' self.waiting = False", "1 @instruction(name=\"SMB0\", mode=\"zpg\", cycles=5) def inst_0x87(self): self.opSMB(self.ZeroPageAddr, 0x01) self.pc +=", "+= 2 @instruction(name=\"TRB\", mode=\"zpg\", cycles=5) def inst_0x14(self): self.opTRB(self.ZeroPageAddr) self.pc +=", "1 @instruction(name=\"SMB4\", mode=\"zpg\", cycles=5) def inst_0xc7(self): self.opSMB(self.ZeroPageAddr, 0x10) self.pc +=", "cycles=5) def inst_0xe7(self): self.opSMB(self.ZeroPageAddr, 0x40) self.pc += 1 @instruction(name=\"SMB7\", mode=\"zpg\",", "def opSMB(self, x, mask): address = x() self.memory[address] |= mask", "mode=\"zpi\", cycles=5) def inst_0x52(self): self.opEOR(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"RMB5\", mode=\"zpg\",", "cycles=5) def inst_0x07(self): self.opRMB(self.ZeroPageAddr, 0xFE) self.pc += 1 @instruction(name=\"ORA\", mode=\"zpi\",", "def inst_0x80(self): self.BranchRelAddr() @instruction(name=\"WAI\", mode='imp', cycles=3) def inst_0xCB(self): self.waiting =", "def inst_0x1c(self): self.opTRB(self.AbsoluteAddr) self.pc += 2 @instruction(name=\"DEC\", mode=\"acc\", cycles=2) def", "self.pc += 1 @instruction(name=\"PHY\", mode=\"imp\", cycles=3) def inst_0x5a(self): self.stPush(self.y) @instruction(name=\"STZ\",", "self.opRMB(self.ZeroPageAddr, 0xFD) self.pc += 1 @instruction(name=\"RMB2\", mode=\"zpg\", cycles=5) def inst_0x27(self):", "1 @instruction(name=\"RMB3\", mode=\"zpg\", cycles=5) def inst_0x37(self): self.opRMB(self.ZeroPageAddr, 0xF7) self.pc +=", "def step(self): if self.waiting: self.processorCycles += 1 else: mpu6502.MPU.step(self) return", "@instruction(name=\"RMB4\", mode=\"zpg\", cycles=5) def inst_0x47(self): self.opRMB(self.ZeroPageAddr, 0xEF) self.pc += 1", "inst_0x92(self): self.opSTA(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"SMB1\", mode=\"zpg\", cycles=5) def inst_0x97(self):", "cycles=5) def inst_0x57(self): self.opRMB(self.ZeroPageAddr, 0xDF) self.pc += 1 @instruction(name=\"PHY\", mode=\"imp\",", "cycles=4) def inst_0x74(self): self.opSTZ(self.ZeroPageXAddr) self.pc += 1 @instruction(name=\"PHY\", mode=\"imp\", cycles=4)", "cycles=5) def inst_0xa7(self): self.opSMB(self.ZeroPageAddr, 0x04) self.pc += 1 @instruction(name=\"LDA\", mode=\"zpi\",", "cycles=5) def inst_0x37(self): self.opRMB(self.ZeroPageAddr, 0xF7) self.pc += 1 @instruction(name=\"BIT\", mode=\"abx\",", "import make_instruction_decorator class MPU(mpu6502.MPU): def __init__(self, *args, **kwargs): mpu6502.MPU.__init__(self, *args,", "def inst_0xd7(self): self.opSMB(self.ZeroPageAddr, 0x20) self.pc += 1 @instruction(name=\"PHX\", mode=\"imp\", cycles=3)", "self.p |= self.ZERO self.memory[address] = m & ~self.a # instructions", "+= 1 @instruction(name=\"STZ\", mode=\"abs\", cycles=4) def inst_0x9c(self): self.opSTZ(self.AbsoluteAddr) self.pc +=", "inst_0x77(self): self.opRMB(self.ZeroPageAddr, 0x7F) self.pc += 1 @instruction(name=\"SMB0\", mode=\"zpg\", cycles=5) def", "def inst_0x27(self): self.opRMB(self.ZeroPageAddr, 0xFB) self.pc += 1 @instruction(name=\"AND\", mode=\"zpi\", cycles=5)", "1 @instruction(name=\"INC\", mode=\"acc\", cycles=2) def inst_0x1a(self): self.opINCR(None) @instruction(name=\"TRB\", mode=\"abs\", cycles=6)", "def inst_0xda(self): self.stPush(self.x) @instruction(name=\"SMB6\", mode=\"zpg\", cycles=5) def inst_0xe7(self): self.opSMB(self.ZeroPageAddr, 0x40)", "lists instruct = mpu6502.MPU.instruct[:] cycletime = mpu6502.MPU.cycletime[:] extracycles = mpu6502.MPU.extracycles[:]", "inst_0x14(self): self.opTRB(self.ZeroPageAddr) self.pc += 1 @instruction(name=\"INC\", mode=\"acc\", cycles=2) def inst_0x1a(self):", "mode=\"zpg\", cycles=5) def inst_0x87(self): self.opSMB(self.ZeroPageAddr, 0x01) self.pc += 1 @instruction(name=\"STA\",", "@instruction(name=\"SMB0\", mode=\"zpg\", cycles=5) def inst_0x87(self): self.opSMB(self.ZeroPageAddr, 0x01) self.pc += 1", "+= 2 @instruction(name=\"RMB4\", mode=\"zpg\", cycles=5) def inst_0x47(self): self.opRMB(self.ZeroPageAddr, 0xEF) self.pc", "def inst_0xb7(self): self.opSMB(self.ZeroPageAddr, 0x08) self.pc += 1 @instruction(name=\"SMB4\", mode=\"zpg\", cycles=5)", "|= mask def opSTZ(self, x): self.memory[x()] = 0x00 def opTSB(self,", "def inst_0x67(self): self.opRMB(self.ZeroPageAddr, 0xBF) self.pc += 1 @instruction(name=\"ADC\", mode=\"zpi\", cycles=5)", "@instruction(name=\"SMB7\", mode=\"zpg\", cycles=5) def inst_0xf7(self): self.opSMB(self.ZeroPageAddr, 0x80) self.pc += 1", "1 @instruction(name=\"EOR\", mode=\"zpi\", cycles=5) def inst_0x52(self): self.opEOR(self.ZeroPageIndirectAddr) self.pc += 1", "x() self.memory[address] &= mask def opSMB(self, x, mask): address =", "= '65C02' self.waiting = False def step(self): if self.waiting: self.processorCycles", "inst_0xe7(self): self.opSMB(self.ZeroPageAddr, 0x40) self.pc += 1 @instruction(name=\"SMB7\", mode=\"zpg\", cycles=5) def", "+= 2 @instruction(name=\"DEC\", mode=\"acc\", cycles=2) def inst_0x3a(self): self.opDECR(None) @instruction(name=\"BRA\", mode=\"rel\",", "Make copies of the lists instruct = mpu6502.MPU.instruct[:] cycletime =", "inst_0x67(self): self.opRMB(self.ZeroPageAddr, 0xBF) self.pc += 1 @instruction(name=\"ADC\", mode=\"zpi\", cycles=5) def", "(self.ByteAt(self.pc))) def AccumulatorAddr(self): return self.a # operations def opRMB(self, x,", "2 @instruction(name=\"DEC\", mode=\"acc\", cycles=2) def inst_0x3a(self): self.opDECR(None) @instruction(name=\"BRA\", mode=\"rel\", cycles=1,", "@instruction(name=\"DEC\", mode=\"acc\", cycles=2) def inst_0x3a(self): self.opDECR(None) @instruction(name=\"BRA\", mode=\"rel\", cycles=1, extracycles=1)", "address = x() self.memory[address] |= mask def opSTZ(self, x): self.memory[x()]", "def inst_0x3c(self): self.opBIT(self.AbsoluteXAddr) self.pc += 2 @instruction(name=\"RMB4\", mode=\"zpg\", cycles=5) def", "self.name = '65C02' self.waiting = False def step(self): if self.waiting:", "self # Make copies of the lists instruct = mpu6502.MPU.instruct[:]", "0x02) self.pc += 1 @instruction(name=\"STZ\", mode=\"abs\", cycles=4) def inst_0x9c(self): self.opSTZ(self.AbsoluteAddr)", "self.x = self.stPop() self.FlagsNZ(self.x) @instruction(name=\"TSB\", mode=\"zpg\", cycles=5) def inst_0x04(self): self.opTSB(self.ZeroPageAddr)", "@instruction(name=\"TSB\", mode=\"abs\", cycles=6) def inst_0x0c(self): self.opTSB(self.AbsoluteAddr) self.pc += 2 @instruction(name=\"TRB\",", "@instruction(name=\"STZ\", mode=\"zpx\", cycles=4) def inst_0x74(self): self.opSTZ(self.ZeroPageXAddr) self.pc += 1 @instruction(name=\"PHY\",", "@instruction(name=\"PHY\", mode=\"imp\", cycles=3) def inst_0x5a(self): self.stPush(self.y) @instruction(name=\"STZ\", mode=\"imp\", cycles=3) def", "@instruction(name=\"LDA\", mode=\"zpi\", cycles=5) def inst_0xb2(self): self.opLDA(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"SMB3\",", "self.pc += 1 @instruction(name=\"RMB6\", mode=\"zpg\", cycles=5) def inst_0x67(self): self.opRMB(self.ZeroPageAddr, 0xBF)", "def inst_0xe7(self): self.opSMB(self.ZeroPageAddr, 0x40) self.pc += 1 @instruction(name=\"SMB7\", mode=\"zpg\", cycles=5)", "step(self): if self.waiting: self.processorCycles += 1 else: mpu6502.MPU.step(self) return self", "self.stPop() self.FlagsNZ(self.y) @instruction(name=\"RMB7\", mode=\"zpg\", cycles=5) def inst_0x77(self): self.opRMB(self.ZeroPageAddr, 0x7F) self.pc", "self.pc += 1 @instruction(name=\"SMB3\", mode=\"zpg\", cycles=5) def inst_0xb7(self): self.opSMB(self.ZeroPageAddr, 0x08)", "self.opRMB(self.ZeroPageAddr, 0xEF) self.pc += 1 @instruction(name=\"EOR\", mode=\"zpi\", cycles=5) def inst_0x52(self):", "+= 1 @instruction(name=\"PHX\", mode=\"imp\", cycles=3) def inst_0xda(self): self.stPush(self.x) @instruction(name=\"SMB6\", mode=\"zpg\",", "0x40) self.pc += 1 @instruction(name=\"SMB7\", mode=\"zpg\", cycles=5) def inst_0xf7(self): self.opSMB(self.ZeroPageAddr,", "mask def opSTZ(self, x): self.memory[x()] = 0x00 def opTSB(self, x):", "~self.ZERO z = m & self.a if z != 0:", "mode=\"zpg\", cycles=5) def inst_0x47(self): self.opRMB(self.ZeroPageAddr, 0xEF) self.pc += 1 @instruction(name=\"EOR\",", "|= self.ZERO self.memory[address] = m | self.a def opTRB(self, x):", "2 @instruction(name=\"RMB4\", mode=\"zpg\", cycles=5) def inst_0x47(self): self.opRMB(self.ZeroPageAddr, 0xEF) self.pc +=", "0x04) self.pc += 1 @instruction(name=\"LDA\", mode=\"zpi\", cycles=5) def inst_0xb2(self): self.opLDA(self.ZeroPageIndirectAddr)", "cycles=5) def inst_0x14(self): self.opTRB(self.ZeroPageAddr) self.pc += 1 @instruction(name=\"INC\", mode=\"acc\", cycles=2)", "+= 1 @instruction(name=\"SMB4\", mode=\"zpg\", cycles=5) def inst_0xc7(self): self.opSMB(self.ZeroPageAddr, 0x10) self.pc", "self.pc += 1 @instruction(name=\"STZ\", mode=\"abs\", cycles=4) def inst_0x9c(self): self.opSTZ(self.AbsoluteAddr) self.pc", "1 @instruction(name=\"RMB1\", mode=\"zpg\", cycles=5) def inst_0x17(self): self.opRMB(self.ZeroPageAddr, 0xFD) self.pc +=", "& (self.ByteAt(self.pc))) def AccumulatorAddr(self): return self.a # operations def opRMB(self,", "0xF7) self.pc += 1 @instruction(name=\"BIT\", mode=\"abx\", cycles=4) def inst_0x3c(self): self.opBIT(self.AbsoluteXAddr)", "self.opRMB(self.ZeroPageAddr, 0xDF) self.pc += 1 @instruction(name=\"PHY\", mode=\"imp\", cycles=3) def inst_0x5a(self):", "mode=\"abx\", cycles=5) def inst_0x9e(self): self.opSTZ(self.AbsoluteXAddr) self.pc += 2 @instruction(name=\"SMB2\", mode=\"zpg\",", "cycles=2) def inst_0x3a(self): self.opDECR(None) @instruction(name=\"BRA\", mode=\"rel\", cycles=1, extracycles=1) def inst_0x80(self):", "self.opSMB(self.ZeroPageAddr, 0x01) self.pc += 1 @instruction(name=\"STA\", mode=\"zpi\", cycles=5) def inst_0x92(self):", "extracycles=1) def inst_0x80(self): self.BranchRelAddr() @instruction(name=\"WAI\", mode='imp', cycles=3) def inst_0xCB(self): self.waiting", "def ZeroPageIndirectAddr(self): return self.WordAt( 255 & (self.ByteAt(self.pc))) def AccumulatorAddr(self): return", "True @instruction(name=\"CMP\", mode='zpi', cycles=6) # Don't know cycles def inst_0xD2(self):", "@instruction(name=\"PHX\", mode=\"imp\", cycles=3) def inst_0xda(self): self.stPush(self.x) @instruction(name=\"SMB6\", mode=\"zpg\", cycles=5) def", "self.opSMB(self.ZeroPageAddr, 0x20) self.pc += 1 @instruction(name=\"PHX\", mode=\"imp\", cycles=3) def inst_0xda(self):", "self.a # operations def opRMB(self, x, mask): address = x()", "mode=\"zpg\", cycles=5) def inst_0x04(self): self.opTSB(self.ZeroPageAddr) self.pc += 1 @instruction(name=\"TSB\", mode=\"abs\",", "~self.a # instructions @instruction(name=\"RMB0\", mode=\"zpg\", cycles=5) def inst_0x07(self): self.opRMB(self.ZeroPageAddr, 0xFE)", "mode=\"zpg\", cycles=5) def inst_0x17(self): self.opRMB(self.ZeroPageAddr, 0xFD) self.pc += 1 @instruction(name=\"RMB2\",", "def inst_0x07(self): self.opRMB(self.ZeroPageAddr, 0xFE) self.pc += 1 @instruction(name=\"ORA\", mode=\"zpi\", cycles=5)", "m & self.a if z != 0: self.p |= self.ZERO", "+= 1 @instruction(name=\"RMB2\", mode=\"zpg\", cycles=5) def inst_0x27(self): self.opRMB(self.ZeroPageAddr, 0xFB) self.pc", "mode=\"zpi\", cycles=5) def inst_0x92(self): self.opSTA(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"SMB1\", mode=\"zpg\",", "self.a def opTRB(self, x): address = x() m = self.memory[address]", "def inst_0x17(self): self.opRMB(self.ZeroPageAddr, 0xFD) self.pc += 1 @instruction(name=\"RMB2\", mode=\"zpg\", cycles=5)", "self.pc += 1 @instruction(name=\"PHX\", mode=\"imp\", cycles=3) def inst_0xda(self): self.stPush(self.x) @instruction(name=\"SMB6\",", "'65C02' self.waiting = False def step(self): if self.waiting: self.processorCycles +=", "inst_0xb7(self): self.opSMB(self.ZeroPageAddr, 0x08) self.pc += 1 @instruction(name=\"SMB4\", mode=\"zpg\", cycles=5) def", "inst_0x0c(self): self.opTSB(self.AbsoluteAddr) self.pc += 2 @instruction(name=\"TRB\", mode=\"zpg\", cycles=5) def inst_0x14(self):", "inst_0x37(self): self.opRMB(self.ZeroPageAddr, 0xF7) self.pc += 1 @instruction(name=\"BIT\", mode=\"abx\", cycles=4) def", "x): self.memory[x()] = 0x00 def opTSB(self, x): address = x()", "1 @instruction(name=\"SMB3\", mode=\"zpg\", cycles=5) def inst_0xb7(self): self.opSMB(self.ZeroPageAddr, 0x08) self.pc +=", "= self.memory[address] self.p &= ~self.ZERO z = m & self.a", "@instruction(name=\"AND\", mode=\"zpi\", cycles=5) def inst_0x32(self): self.opAND(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"BIT\",", "2 @instruction(name=\"STZ\", mode=\"abx\", cycles=5) def inst_0x9e(self): self.opSTZ(self.AbsoluteXAddr) self.pc += 2", "if self.waiting: self.processorCycles += 1 else: mpu6502.MPU.step(self) return self #", "0x7F) self.pc += 1 @instruction(name=\"SMB0\", mode=\"zpg\", cycles=5) def inst_0x87(self): self.opSMB(self.ZeroPageAddr,", "+= 2 @instruction(name=\"SMB2\", mode=\"zpg\", cycles=5) def inst_0xa7(self): self.opSMB(self.ZeroPageAddr, 0x04) self.pc", "self.p |= self.ZERO self.memory[address] = m | self.a def opTRB(self,", "self.ZERO self.memory[address] = m & ~self.a # instructions @instruction(name=\"RMB0\", mode=\"zpg\",", "self.opSMB(self.ZeroPageAddr, 0x80) self.pc += 1 @instruction(name=\"PLX\", mode=\"imp\", cycles=4) def inst_0xfa(self):", "x() m = self.memory[address] self.p &= ~self.ZERO z = m", "inst_0x9e(self): self.opSTZ(self.AbsoluteXAddr) self.pc += 2 @instruction(name=\"SMB2\", mode=\"zpg\", cycles=5) def inst_0xa7(self):", "cycles=3) def inst_0xda(self): self.stPush(self.x) @instruction(name=\"SMB6\", mode=\"zpg\", cycles=5) def inst_0xe7(self): self.opSMB(self.ZeroPageAddr,", "self.opDECR(None) @instruction(name=\"BRA\", mode=\"rel\", cycles=1, extracycles=1) def inst_0x80(self): self.BranchRelAddr() @instruction(name=\"WAI\", mode='imp',", "make_instruction_decorator(instruct, disassemble, cycletime, extracycles) # addressing modes def ZeroPageIndirectAddr(self): return", "self.pc += 1 @instruction(name=\"SBC\", mode=\"zpi\", cycles=5) def inst_0xf2(self): self.opSBC(self.ZeroPageIndirectAddr) self.pc", "@instruction(name=\"RMB2\", mode=\"zpg\", cycles=5) def inst_0x27(self): self.opRMB(self.ZeroPageAddr, 0xFB) self.pc += 1", "cycles=5) def inst_0x72(self): self.opADC(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"STZ\", mode=\"zpx\", cycles=4)", "self.pc += 1 @instruction(name=\"RMB2\", mode=\"zpg\", cycles=5) def inst_0x27(self): self.opRMB(self.ZeroPageAddr, 0xFB)", "1 else: mpu6502.MPU.step(self) return self # Make copies of the", "@instruction(name=\"CMP\", mode='zpi', cycles=6) # Don't know cycles def inst_0xD2(self): self.opCPY(self.ZeroPageIndirectAddr)", "inst_0x1c(self): self.opTRB(self.AbsoluteAddr) self.pc += 2 @instruction(name=\"DEC\", mode=\"acc\", cycles=2) def inst_0x3a(self):", "mpu6502.MPU.instruct[:] cycletime = mpu6502.MPU.cycletime[:] extracycles = mpu6502.MPU.extracycles[:] disassemble = mpu6502.MPU.disassemble[:]", "def inst_0x9c(self): self.opSTZ(self.AbsoluteAddr) self.pc += 2 @instruction(name=\"STZ\", mode=\"abx\", cycles=5) def", "def inst_0x12(self): self.opORA(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"RMB1\", mode=\"zpg\", cycles=5) def", "self.memory[address] self.p &= ~self.ZERO z = m & self.a if", "instructions @instruction(name=\"RMB0\", mode=\"zpg\", cycles=5) def inst_0x07(self): self.opRMB(self.ZeroPageAddr, 0xFE) self.pc +=", "@instruction(name=\"ORA\", mode=\"zpi\", cycles=5) def inst_0x12(self): self.opORA(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"RMB1\",", "@instruction(name=\"ADC\", mode=\"zpi\", cycles=5) def inst_0x72(self): self.opADC(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"STZ\",", "def inst_0xD2(self): self.opCPY(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"SBC\", mode=\"zpi\", cycles=5) def", "mode=\"zpi\", cycles=5) def inst_0x32(self): self.opAND(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"BIT\", mode=\"zpx\",", "self.opRMB(self.ZeroPageAddr, 0x7F) self.pc += 1 @instruction(name=\"SMB0\", mode=\"zpg\", cycles=5) def inst_0x87(self):", "self.FlagsNZ(self.x) @instruction(name=\"TSB\", mode=\"zpg\", cycles=5) def inst_0x04(self): self.opTSB(self.ZeroPageAddr) self.pc += 1", "+= 1 @instruction(name=\"STA\", mode=\"zpi\", cycles=5) def inst_0x92(self): self.opSTA(self.ZeroPageIndirectAddr) self.pc +=", "self.opBIT(self.ZeroPageXAddr) self.pc += 1 @instruction(name=\"RMB3\", mode=\"zpg\", cycles=5) def inst_0x37(self): self.opRMB(self.ZeroPageAddr,", "inst_0xc7(self): self.opSMB(self.ZeroPageAddr, 0x10) self.pc += 1 @instruction(name=\"SMB5\", mode=\"zpg\", cycles=5) def", "self.pc += 1 @instruction(name=\"SMB1\", mode=\"zpg\", cycles=5) def inst_0x97(self): self.opSMB(self.ZeroPageAddr, 0x02)", "self.waiting = False def step(self): if self.waiting: self.processorCycles += 1", "self.memory[address] = m & ~self.a # instructions @instruction(name=\"RMB0\", mode=\"zpg\", cycles=5)", "+= 1 @instruction(name=\"PHY\", mode=\"imp\", cycles=4) def inst_0x7a(self): self.y = self.stPop()", "1 @instruction(name=\"SMB5\", mode=\"zpg\", cycles=5) def inst_0xd7(self): self.opSMB(self.ZeroPageAddr, 0x20) self.pc +=", "mode=\"abx\", cycles=4) def inst_0x3c(self): self.opBIT(self.AbsoluteXAddr) self.pc += 2 @instruction(name=\"RMB4\", mode=\"zpg\",", "@instruction(name=\"TRB\", mode=\"abs\", cycles=6) def inst_0x1c(self): self.opTRB(self.AbsoluteAddr) self.pc += 2 @instruction(name=\"DEC\",", "m = self.memory[address] self.p &= ~self.ZERO z = m &", "1 @instruction(name=\"RMB5\", mode=\"zpg\", cycles=5) def inst_0x57(self): self.opRMB(self.ZeroPageAddr, 0xDF) self.pc +=", "@instruction(name=\"RMB5\", mode=\"zpg\", cycles=5) def inst_0x57(self): self.opRMB(self.ZeroPageAddr, 0xDF) self.pc += 1", "cycles=5) def inst_0x87(self): self.opSMB(self.ZeroPageAddr, 0x01) self.pc += 1 @instruction(name=\"STA\", mode=\"zpi\",", "def inst_0xa7(self): self.opSMB(self.ZeroPageAddr, 0x04) self.pc += 1 @instruction(name=\"LDA\", mode=\"zpi\", cycles=5)", "@instruction(name=\"PHY\", mode=\"imp\", cycles=4) def inst_0x7a(self): self.y = self.stPop() self.FlagsNZ(self.y) @instruction(name=\"RMB7\",", "mode=\"acc\", cycles=2) def inst_0x3a(self): self.opDECR(None) @instruction(name=\"BRA\", mode=\"rel\", cycles=1, extracycles=1) def", "self.pc += 1 @instruction(name=\"PHY\", mode=\"imp\", cycles=4) def inst_0x7a(self): self.y =", "inst_0x07(self): self.opRMB(self.ZeroPageAddr, 0xFE) self.pc += 1 @instruction(name=\"ORA\", mode=\"zpi\", cycles=5) def", "self.opSMB(self.ZeroPageAddr, 0x40) self.pc += 1 @instruction(name=\"SMB7\", mode=\"zpg\", cycles=5) def inst_0xf7(self):", "+= 1 @instruction(name=\"PLX\", mode=\"imp\", cycles=4) def inst_0xfa(self): self.x = self.stPop()", "z != 0: self.p |= self.ZERO self.memory[address] = m |", "address = x() m = self.memory[address] self.p &= ~self.ZERO z", "cycles=6) # Don't know cycles def inst_0xD2(self): self.opCPY(self.ZeroPageIndirectAddr) self.pc +=", "= True @instruction(name=\"CMP\", mode='zpi', cycles=6) # Don't know cycles def", "return self.WordAt( 255 & (self.ByteAt(self.pc))) def AccumulatorAddr(self): return self.a #", "self.stPush(self.y) @instruction(name=\"STZ\", mode=\"imp\", cycles=3) def inst_0x64(self): self.opSTZ(self.ZeroPageAddr) self.pc += 1", "cycles=5) def inst_0x97(self): self.opSMB(self.ZeroPageAddr, 0x02) self.pc += 1 @instruction(name=\"STZ\", mode=\"abs\",", "self.pc += 1 @instruction(name=\"BIT\", mode=\"zpx\", cycles=4) def inst_0x34(self): self.opBIT(self.ZeroPageXAddr) self.pc", "mode=\"zpg\", cycles=5) def inst_0xb7(self): self.opSMB(self.ZeroPageAddr, 0x08) self.pc += 1 @instruction(name=\"SMB4\",", "1 @instruction(name=\"BIT\", mode=\"abx\", cycles=4) def inst_0x3c(self): self.opBIT(self.AbsoluteXAddr) self.pc += 2", "# Don't know cycles def inst_0xD2(self): self.opCPY(self.ZeroPageIndirectAddr) self.pc += 1", "def inst_0x87(self): self.opSMB(self.ZeroPageAddr, 0x01) self.pc += 1 @instruction(name=\"STA\", mode=\"zpi\", cycles=5)", "self.opEOR(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"RMB5\", mode=\"zpg\", cycles=5) def inst_0x57(self): self.opRMB(self.ZeroPageAddr,", "1 @instruction(name=\"PHY\", mode=\"imp\", cycles=3) def inst_0x5a(self): self.stPush(self.y) @instruction(name=\"STZ\", mode=\"imp\", cycles=3)", "1 @instruction(name=\"RMB6\", mode=\"zpg\", cycles=5) def inst_0x67(self): self.opRMB(self.ZeroPageAddr, 0xBF) self.pc +=", "inst_0xb2(self): self.opLDA(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"SMB3\", mode=\"zpg\", cycles=5) def inst_0xb7(self):", "@instruction(name=\"RMB3\", mode=\"zpg\", cycles=5) def inst_0x37(self): self.opRMB(self.ZeroPageAddr, 0xF7) self.pc += 1", "1 @instruction(name=\"PLX\", mode=\"imp\", cycles=4) def inst_0xfa(self): self.x = self.stPop() self.FlagsNZ(self.x)", "def __init__(self, *args, **kwargs): mpu6502.MPU.__init__(self, *args, **kwargs) self.name = '65C02'", "self.y = self.stPop() self.FlagsNZ(self.y) @instruction(name=\"RMB7\", mode=\"zpg\", cycles=5) def inst_0x77(self): self.opRMB(self.ZeroPageAddr,", "def inst_0xb2(self): self.opLDA(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"SMB3\", mode=\"zpg\", cycles=5) def", "inst_0x80(self): self.BranchRelAddr() @instruction(name=\"WAI\", mode='imp', cycles=3) def inst_0xCB(self): self.waiting = True", "self.opORA(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"RMB1\", mode=\"zpg\", cycles=5) def inst_0x17(self): self.opRMB(self.ZeroPageAddr,", "+= 1 @instruction(name=\"SMB0\", mode=\"zpg\", cycles=5) def inst_0x87(self): self.opSMB(self.ZeroPageAddr, 0x01) self.pc", "ZeroPageIndirectAddr(self): return self.WordAt( 255 & (self.ByteAt(self.pc))) def AccumulatorAddr(self): return self.a", "self.pc += 1 @instruction(name=\"EOR\", mode=\"zpi\", cycles=5) def inst_0x52(self): self.opEOR(self.ZeroPageIndirectAddr) self.pc", "self.opTSB(self.AbsoluteAddr) self.pc += 2 @instruction(name=\"TRB\", mode=\"zpg\", cycles=5) def inst_0x14(self): self.opTRB(self.ZeroPageAddr)", "self.pc += 1 @instruction(name=\"STA\", mode=\"zpi\", cycles=5) def inst_0x92(self): self.opSTA(self.ZeroPageIndirectAddr) self.pc", "from py65.devices import mpu6502 from py65.utils.devices import make_instruction_decorator class MPU(mpu6502.MPU):", "@instruction(name=\"PLX\", mode=\"imp\", cycles=4) def inst_0xfa(self): self.x = self.stPop() self.FlagsNZ(self.x) @instruction(name=\"TSB\",", "if z != 0: self.p |= self.ZERO self.memory[address] = m", "self.pc += 1 @instruction(name=\"PLX\", mode=\"imp\", cycles=4) def inst_0xfa(self): self.x =", "0xFE) self.pc += 1 @instruction(name=\"ORA\", mode=\"zpi\", cycles=5) def inst_0x12(self): self.opORA(self.ZeroPageIndirectAddr)", "@instruction(name=\"STZ\", mode=\"imp\", cycles=3) def inst_0x64(self): self.opSTZ(self.ZeroPageAddr) self.pc += 1 @instruction(name=\"RMB6\",", "def opTSB(self, x): address = x() m = self.memory[address] self.p", "+= 1 @instruction(name=\"SMB5\", mode=\"zpg\", cycles=5) def inst_0xd7(self): self.opSMB(self.ZeroPageAddr, 0x20) self.pc", "@instruction(name=\"SMB6\", mode=\"zpg\", cycles=5) def inst_0xe7(self): self.opSMB(self.ZeroPageAddr, 0x40) self.pc += 1", "make_instruction_decorator class MPU(mpu6502.MPU): def __init__(self, *args, **kwargs): mpu6502.MPU.__init__(self, *args, **kwargs)", "@instruction(name=\"RMB1\", mode=\"zpg\", cycles=5) def inst_0x17(self): self.opRMB(self.ZeroPageAddr, 0xFD) self.pc += 1", "x): address = x() m = self.memory[address] self.p &= ~self.ZERO", "self.opSMB(self.ZeroPageAddr, 0x08) self.pc += 1 @instruction(name=\"SMB4\", mode=\"zpg\", cycles=5) def inst_0xc7(self):", "inst_0xD2(self): self.opCPY(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"SBC\", mode=\"zpi\", cycles=5) def inst_0xf2(self):", "def opRMB(self, x, mask): address = x() self.memory[address] &= mask", "def inst_0x0c(self): self.opTSB(self.AbsoluteAddr) self.pc += 2 @instruction(name=\"TRB\", mode=\"zpg\", cycles=5) def", "self.opRMB(self.ZeroPageAddr, 0xF7) self.pc += 1 @instruction(name=\"BIT\", mode=\"abx\", cycles=4) def inst_0x3c(self):", "0: self.p |= self.ZERO self.memory[address] = m & ~self.a #", "mode=\"zpx\", cycles=4) def inst_0x34(self): self.opBIT(self.ZeroPageXAddr) self.pc += 1 @instruction(name=\"RMB3\", mode=\"zpg\",", "inst_0x04(self): self.opTSB(self.ZeroPageAddr) self.pc += 1 @instruction(name=\"TSB\", mode=\"abs\", cycles=6) def inst_0x0c(self):", "= m | self.a def opTRB(self, x): address = x()", "+= 1 @instruction(name=\"SMB3\", mode=\"zpg\", cycles=5) def inst_0xb7(self): self.opSMB(self.ZeroPageAddr, 0x08) self.pc", "= mpu6502.MPU.extracycles[:] disassemble = mpu6502.MPU.disassemble[:] instruction = make_instruction_decorator(instruct, disassemble, cycletime,", "self.pc += 1 @instruction(name=\"SMB7\", mode=\"zpg\", cycles=5) def inst_0xf7(self): self.opSMB(self.ZeroPageAddr, 0x80)", "cycles def inst_0xD2(self): self.opCPY(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"SBC\", mode=\"zpi\", cycles=5)", "Don't know cycles def inst_0xD2(self): self.opCPY(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"SBC\",", "self.stPop() self.FlagsNZ(self.x) @instruction(name=\"TSB\", mode=\"zpg\", cycles=5) def inst_0x04(self): self.opTSB(self.ZeroPageAddr) self.pc +=", "@instruction(name=\"STZ\", mode=\"abs\", cycles=4) def inst_0x9c(self): self.opSTZ(self.AbsoluteAddr) self.pc += 2 @instruction(name=\"STZ\",", "extracycles = mpu6502.MPU.extracycles[:] disassemble = mpu6502.MPU.disassemble[:] instruction = make_instruction_decorator(instruct, disassemble,", "@instruction(name=\"RMB6\", mode=\"zpg\", cycles=5) def inst_0x67(self): self.opRMB(self.ZeroPageAddr, 0xBF) self.pc += 1", "else: mpu6502.MPU.step(self) return self # Make copies of the lists", "mode=\"imp\", cycles=3) def inst_0x64(self): self.opSTZ(self.ZeroPageAddr) self.pc += 1 @instruction(name=\"RMB6\", mode=\"zpg\",", "operations def opRMB(self, x, mask): address = x() self.memory[address] &=", "@instruction(name=\"EOR\", mode=\"zpi\", cycles=5) def inst_0x52(self): self.opEOR(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"RMB5\",", "self.pc += 1 @instruction(name=\"RMB5\", mode=\"zpg\", cycles=5) def inst_0x57(self): self.opRMB(self.ZeroPageAddr, 0xDF)", "self.a if z != 0: self.p |= self.ZERO self.memory[address] =", "def inst_0x97(self): self.opSMB(self.ZeroPageAddr, 0x02) self.pc += 1 @instruction(name=\"STZ\", mode=\"abs\", cycles=4)", "@instruction(name=\"BIT\", mode=\"zpx\", cycles=4) def inst_0x34(self): self.opBIT(self.ZeroPageXAddr) self.pc += 1 @instruction(name=\"RMB3\",", "0x01) self.pc += 1 @instruction(name=\"STA\", mode=\"zpi\", cycles=5) def inst_0x92(self): self.opSTA(self.ZeroPageIndirectAddr)", "self.pc += 1 @instruction(name=\"ORA\", mode=\"zpi\", cycles=5) def inst_0x12(self): self.opORA(self.ZeroPageIndirectAddr) self.pc", "cycles=4) def inst_0x9c(self): self.opSTZ(self.AbsoluteAddr) self.pc += 2 @instruction(name=\"STZ\", mode=\"abx\", cycles=5)", "@instruction(name=\"BRA\", mode=\"rel\", cycles=1, extracycles=1) def inst_0x80(self): self.BranchRelAddr() @instruction(name=\"WAI\", mode='imp', cycles=3)", "mode=\"acc\", cycles=2) def inst_0x1a(self): self.opINCR(None) @instruction(name=\"TRB\", mode=\"abs\", cycles=6) def inst_0x1c(self):", "def inst_0x92(self): self.opSTA(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"SMB1\", mode=\"zpg\", cycles=5) def", "cycles=5) def inst_0x67(self): self.opRMB(self.ZeroPageAddr, 0xBF) self.pc += 1 @instruction(name=\"ADC\", mode=\"zpi\",", "1 @instruction(name=\"PHY\", mode=\"imp\", cycles=4) def inst_0x7a(self): self.y = self.stPop() self.FlagsNZ(self.y)", "def inst_0x1a(self): self.opINCR(None) @instruction(name=\"TRB\", mode=\"abs\", cycles=6) def inst_0x1c(self): self.opTRB(self.AbsoluteAddr) self.pc", "cycles=5) def inst_0x52(self): self.opEOR(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"RMB5\", mode=\"zpg\", cycles=5)", "mpu6502.MPU.extracycles[:] disassemble = mpu6502.MPU.disassemble[:] instruction = make_instruction_decorator(instruct, disassemble, cycletime, extracycles)", "self.opTRB(self.ZeroPageAddr) self.pc += 1 @instruction(name=\"INC\", mode=\"acc\", cycles=2) def inst_0x1a(self): self.opINCR(None)", "self.processorCycles += 1 else: mpu6502.MPU.step(self) return self # Make copies", "instruction = make_instruction_decorator(instruct, disassemble, cycletime, extracycles) # addressing modes def", "MPU(mpu6502.MPU): def __init__(self, *args, **kwargs): mpu6502.MPU.__init__(self, *args, **kwargs) self.name =", "cycles=3) def inst_0xCB(self): self.waiting = True @instruction(name=\"CMP\", mode='zpi', cycles=6) #", "1 @instruction(name=\"PHX\", mode=\"imp\", cycles=3) def inst_0xda(self): self.stPush(self.x) @instruction(name=\"SMB6\", mode=\"zpg\", cycles=5)", "1 @instruction(name=\"STZ\", mode=\"abs\", cycles=4) def inst_0x9c(self): self.opSTZ(self.AbsoluteAddr) self.pc += 2", "+= 1 @instruction(name=\"SMB1\", mode=\"zpg\", cycles=5) def inst_0x97(self): self.opSMB(self.ZeroPageAddr, 0x02) self.pc", "= m & ~self.a # instructions @instruction(name=\"RMB0\", mode=\"zpg\", cycles=5) def", "mode=\"zpg\", cycles=5) def inst_0x77(self): self.opRMB(self.ZeroPageAddr, 0x7F) self.pc += 1 @instruction(name=\"SMB0\",", "0xFD) self.pc += 1 @instruction(name=\"RMB2\", mode=\"zpg\", cycles=5) def inst_0x27(self): self.opRMB(self.ZeroPageAddr,", "self.opSMB(self.ZeroPageAddr, 0x10) self.pc += 1 @instruction(name=\"SMB5\", mode=\"zpg\", cycles=5) def inst_0xd7(self):", "inst_0x47(self): self.opRMB(self.ZeroPageAddr, 0xEF) self.pc += 1 @instruction(name=\"EOR\", mode=\"zpi\", cycles=5) def", "def inst_0x3a(self): self.opDECR(None) @instruction(name=\"BRA\", mode=\"rel\", cycles=1, extracycles=1) def inst_0x80(self): self.BranchRelAddr()", "0xBF) self.pc += 1 @instruction(name=\"ADC\", mode=\"zpi\", cycles=5) def inst_0x72(self): self.opADC(self.ZeroPageIndirectAddr)", "@instruction(name=\"SMB3\", mode=\"zpg\", cycles=5) def inst_0xb7(self): self.opSMB(self.ZeroPageAddr, 0x08) self.pc += 1", "x, mask): address = x() self.memory[address] &= mask def opSMB(self,", "opTRB(self, x): address = x() m = self.memory[address] self.p &=", "mode=\"zpg\", cycles=5) def inst_0x97(self): self.opSMB(self.ZeroPageAddr, 0x02) self.pc += 1 @instruction(name=\"STZ\",", "inst_0x72(self): self.opADC(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"STZ\", mode=\"zpx\", cycles=4) def inst_0x74(self):", "self.pc += 2 @instruction(name=\"DEC\", mode=\"acc\", cycles=2) def inst_0x3a(self): self.opDECR(None) @instruction(name=\"BRA\",", "py65.devices import mpu6502 from py65.utils.devices import make_instruction_decorator class MPU(mpu6502.MPU): def", "mask def opSMB(self, x, mask): address = x() self.memory[address] |=", "mpu6502.MPU.disassemble[:] instruction = make_instruction_decorator(instruct, disassemble, cycletime, extracycles) # addressing modes", "@instruction(name=\"WAI\", mode='imp', cycles=3) def inst_0xCB(self): self.waiting = True @instruction(name=\"CMP\", mode='zpi',", "1 @instruction(name=\"STZ\", mode=\"zpx\", cycles=4) def inst_0x74(self): self.opSTZ(self.ZeroPageXAddr) self.pc += 1", "self.opINCR(None) @instruction(name=\"TRB\", mode=\"abs\", cycles=6) def inst_0x1c(self): self.opTRB(self.AbsoluteAddr) self.pc += 2", "mode=\"zpg\", cycles=5) def inst_0xe7(self): self.opSMB(self.ZeroPageAddr, 0x40) self.pc += 1 @instruction(name=\"SMB7\",", "self.pc += 2 @instruction(name=\"RMB4\", mode=\"zpg\", cycles=5) def inst_0x47(self): self.opRMB(self.ZeroPageAddr, 0xEF)", "= False def step(self): if self.waiting: self.processorCycles += 1 else:", "address = x() self.memory[address] &= mask def opSMB(self, x, mask):", "def inst_0x64(self): self.opSTZ(self.ZeroPageAddr) self.pc += 1 @instruction(name=\"RMB6\", mode=\"zpg\", cycles=5) def", "+= 1 @instruction(name=\"PHY\", mode=\"imp\", cycles=3) def inst_0x5a(self): self.stPush(self.y) @instruction(name=\"STZ\", mode=\"imp\",", "return self.a # operations def opRMB(self, x, mask): address =", "import mpu6502 from py65.utils.devices import make_instruction_decorator class MPU(mpu6502.MPU): def __init__(self,", "def inst_0x47(self): self.opRMB(self.ZeroPageAddr, 0xEF) self.pc += 1 @instruction(name=\"EOR\", mode=\"zpi\", cycles=5)", "+= 1 @instruction(name=\"STZ\", mode=\"zpx\", cycles=4) def inst_0x74(self): self.opSTZ(self.ZeroPageXAddr) self.pc +=", "mode=\"zpg\", cycles=5) def inst_0xc7(self): self.opSMB(self.ZeroPageAddr, 0x10) self.pc += 1 @instruction(name=\"SMB5\",", "= mpu6502.MPU.disassemble[:] instruction = make_instruction_decorator(instruct, disassemble, cycletime, extracycles) # addressing", "self.memory[address] &= mask def opSMB(self, x, mask): address = x()", "def inst_0x14(self): self.opTRB(self.ZeroPageAddr) self.pc += 1 @instruction(name=\"INC\", mode=\"acc\", cycles=2) def", "m & ~self.a # instructions @instruction(name=\"RMB0\", mode=\"zpg\", cycles=5) def inst_0x07(self):", "+= 1 @instruction(name=\"EOR\", mode=\"zpi\", cycles=5) def inst_0x52(self): self.opEOR(self.ZeroPageIndirectAddr) self.pc +=", "mask): address = x() self.memory[address] |= mask def opSTZ(self, x):", "+= 1 @instruction(name=\"RMB3\", mode=\"zpg\", cycles=5) def inst_0x37(self): self.opRMB(self.ZeroPageAddr, 0xF7) self.pc", "cycles=3) def inst_0x64(self): self.opSTZ(self.ZeroPageAddr) self.pc += 1 @instruction(name=\"RMB6\", mode=\"zpg\", cycles=5)", "mpu6502.MPU.step(self) return self # Make copies of the lists instruct", "0xEF) self.pc += 1 @instruction(name=\"EOR\", mode=\"zpi\", cycles=5) def inst_0x52(self): self.opEOR(self.ZeroPageIndirectAddr)", "@instruction(name=\"STZ\", mode=\"abx\", cycles=5) def inst_0x9e(self): self.opSTZ(self.AbsoluteXAddr) self.pc += 2 @instruction(name=\"SMB2\",", "self.opBIT(self.AbsoluteXAddr) self.pc += 2 @instruction(name=\"RMB4\", mode=\"zpg\", cycles=5) def inst_0x47(self): self.opRMB(self.ZeroPageAddr,", "of the lists instruct = mpu6502.MPU.instruct[:] cycletime = mpu6502.MPU.cycletime[:] extracycles", "def inst_0x37(self): self.opRMB(self.ZeroPageAddr, 0xF7) self.pc += 1 @instruction(name=\"BIT\", mode=\"abx\", cycles=4)", "= x() m = self.memory[address] self.p &= ~self.ZERO z =", "self.opLDA(self.ZeroPageIndirectAddr) self.pc += 1 @instruction(name=\"SMB3\", mode=\"zpg\", cycles=5) def inst_0xb7(self): self.opSMB(self.ZeroPageAddr,", "self.pc += 1 @instruction(name=\"STZ\", mode=\"zpx\", cycles=4) def inst_0x74(self): self.opSTZ(self.ZeroPageXAddr) self.pc", "1 @instruction(name=\"RMB2\", mode=\"zpg\", cycles=5) def inst_0x27(self): self.opRMB(self.ZeroPageAddr, 0xFB) self.pc +=", "m | self.a def opTRB(self, x): address = x() m", "def inst_0x77(self): self.opRMB(self.ZeroPageAddr, 0x7F) self.pc += 1 @instruction(name=\"SMB0\", mode=\"zpg\", cycles=5)" ]
[ "( ms_file_to_df, mzml_to_pandas_df_pyteomics, convert_ms_file_to_feather, convert_ms_file_to_parquet, MZMLB_AVAILABLE, ) from paths import", "result.columns assert all(result.polarity == \"+\"), f'Polarity should be \"+\"\\n{result}' def", "P(TEST_MZML).name fn_out = fn.with_suffix(\".parquet\") print(fn, fn_out) convert_ms_file_to_parquet(fn) assert fn_out.is_file(), f\"File", "test__ms_file_to_df__mzXML(): result = ms_file_to_df(TEST_MZXML) expected_cols = [ \"scan_id\", \"ms_level\", \"polarity\",", "df_fea = ms_file_to_df(fn_out) assert df_fea.equals(df), \"DataFrames not equal\" def test__convert_ms_file_to_parquet(tmpdir):", "\"mz_width\": [10], \"intensity_threshold\": [0], \"rt_min\": [0], \"rt_max\": [10], \"targets_filename\": [\"unknown\"],", "a dataframe\" assert expected_cols == result.columns.to_list(), result.columns def test__ms_file_to_df__mzXML(): result", "None result = ms_file_to_df(TEST_MZMLB_POS) expected_cols = [ \"scan_id\", \"ms_level\", \"polarity\",", "def test__ms_file_to_df__mzML(): result = ms_file_to_df(TEST_MZML) expected_cols = [ \"scan_id\", \"ms_level\",", "= Mint(verbose=True) mint.ms_files = \"tests/data/test.mzXML\" mint.run() mint.export(filename) assert os.path.isfile(filename) def", "\"mz_mean\": [200], \"mz_width\": [10], \"intensity_threshold\": [0], \"rt_min\": [0], \"rt_max\": [10],", "expected_cols = [ \"scan_id\", \"ms_level\", \"polarity\", \"scan_time_min\", \"mz\", \"intensity\", ]", "convert_ms_file_to_parquet, MZMLB_AVAILABLE, ) from paths import ( TEST_MZML, TEST_MZXML, TEST_PARQUET,", "expected_cols == result.columns.to_list(), result.columns def test__mzml_to_pandas_df_pyteomics_pos(): result = mzml_to_pandas_df_pyteomics(TEST_MZML_POS) expected_cols", "ms_file_to_df(fn_out) assert df_fea.equals(df), \"DataFrames not equal\" def test__convert_ms_file_to_parquet(tmpdir): print(tmpdir) shutil.copy(TEST_MZML,", "P(tmpdir) / P(TEST_MZML).name fn_out = fn.with_suffix(\".parquet\") print(fn, fn_out) convert_ms_file_to_parquet(fn) assert", "dataframe\" assert expected_cols == result.columns.to_list(), result.columns def test__ms_file_to_df__mzML_timeunit_minutes(): result =", "TEST_MZXML, TEST_PARQUET, TEST_MZMLB_POS, TEST_MZML_POS, TEST_MZML_NEG, ) def test__ms_file_to_df__mzML(): result =", "mint.export() assert isinstance(buffer, io.BytesIO) df = pd.read_excel(buffer, sheet_name=\"Results\") assert len(df)", "\"scan_time_min\", \"mz\", \"intensity\", ] assert isinstance(result, pd.DataFrame), f\"{type(result)} is not", "def test__mzml_to_pandas_df_pyteomics_pos(): result = mzml_to_pandas_df_pyteomics(TEST_MZML_POS) expected_cols = [ \"scan_id\", \"ms_level\",", "a dataframe\" assert expected_cols == result.columns.to_list(), result.columns # assert all(result.polarity", "result = ms_file_to_df(TEST_MZML) expected_cols = [ \"scan_id\", \"ms_level\", \"polarity\", \"scan_time_min\",", "from pathlib import Path as P from ms_mint.io import (", "1, len(df) assert df.loc[0, \"peak_label\"] == \"A\", df.loc[0, \"peak_label\"] assert", "\"targets_filename\": [\"unknown\"], } ) mint.run() buffer = mint.export() assert isinstance(buffer,", "all(result.polarity == \"+\"), f'Polarity should be \"+\"\\n{result}' def test__mzml_to_pandas_df_pyteomics_neg(): result", "ms_file_to_df(TEST_MZMLB_POS) expected_cols = [ \"scan_id\", \"ms_level\", \"polarity\", \"scan_time_min\", \"mz\", \"intensity\",", "test__convert_ms_file_to_feather(tmpdir): print(tmpdir) shutil.copy(TEST_MZML, tmpdir) fn = P(tmpdir) / P(TEST_MZML).name fn_out", "\"peak_label\"] == \"A\", df.loc[0, \"peak_label\"] assert df.loc[0, \"ms_file\"] == P(TEST_MZXML).name,", "test__ms_file_to_df__mzML_timeunit_minutes(): result = ms_file_to_df(TEST_MZML, time_unit=\"minutes\") expected_cols = [ \"scan_id\", \"ms_level\",", "P(tmpdir) / P(TEST_MZML).name fn_out = fn.with_suffix(\".feather\") print(fn, fn_out) convert_ms_file_to_feather(fn) assert", "expected_cols == result.columns.to_list(), result.columns def test__write_read_hdf(tmpdir): df = ms_file_to_df(TEST_PARQUET) fn", "assert expected_cols == result.columns.to_list(), result.columns assert all(result.polarity == \"-\"), f'Polarity", "mint.ms_files = TEST_MZXML mint.targets = pd.DataFrame( { \"peak_label\": [\"A\"], \"mz_mean\":", "= ms_file_to_df(TEST_MZML) expected_cols = [ \"scan_id\", \"ms_level\", \"polarity\", \"scan_time_min\", \"mz\",", "isinstance(buffer, io.BytesIO) df = pd.read_excel(buffer, sheet_name=\"Results\") assert len(df) == 1,", "= P(tmpdir) / \"file.hdf\" df.to_hdf(fn, key=\"data\") result = ms_file_to_df(fn) expected_cols", "test__mzml_to_pandas_df_pyteomics_neg(): result = mzml_to_pandas_df_pyteomics(TEST_MZML_NEG) expected_cols = [ \"scan_id\", \"ms_level\", \"polarity\",", "= fn.with_suffix(\".parquet\") print(fn, fn_out) convert_ms_file_to_parquet(fn) assert fn_out.is_file(), f\"File not generated", "equal\" def test__export_to_excel(tmp_path): filename = os.path.join(tmp_path, \"output.xlsx\") mint = Mint(verbose=True)", "equal\" def test__convert_ms_file_to_parquet(tmpdir): print(tmpdir) shutil.copy(TEST_MZML, tmpdir) fn = P(tmpdir) /", "\"+\"\\n{result}' def test__convert_ms_file_to_feather(tmpdir): print(tmpdir) shutil.copy(TEST_MZML, tmpdir) fn = P(tmpdir) /", "== \"+\"), f'Polarity should be \"+\"\\n{result}' def test__mzml_to_pandas_df_pyteomics_neg(): result =", "as P from ms_mint.io import ( ms_file_to_df, mzml_to_pandas_df_pyteomics, convert_ms_file_to_feather, convert_ms_file_to_parquet,", "not a dataframe\" assert expected_cols == result.columns.to_list(), result.columns def test__write_read_hdf(tmpdir):", "test__export_to_excel(tmp_path): filename = os.path.join(tmp_path, \"output.xlsx\") mint = Mint(verbose=True) mint.ms_files =", "pd import shutil import os import io from ms_mint.Mint import", "= mzml_to_pandas_df_pyteomics(TEST_MZML_NEG) expected_cols = [ \"scan_id\", \"ms_level\", \"polarity\", \"scan_time_min\", \"mz\",", "result.columns def test__ms_file_to_df__mzXML(): result = ms_file_to_df(TEST_MZXML) expected_cols = [ \"scan_id\",", "pandas as pd import shutil import os import io from", "Mint from pathlib import Path as P from ms_mint.io import", "mint.run() mint.export(filename) assert os.path.isfile(filename) def test__export_to_excel_without_fn(): mint = Mint(verbose=True) mint.ms_files", "] assert isinstance(result, pd.DataFrame), f\"{type(result)} is not a dataframe\" assert", "= ms_file_to_df(fn_out) assert df_fea.equals(df), \"DataFrames not equal\" def test__convert_ms_file_to_parquet(tmpdir): print(tmpdir)", "fn = P(tmpdir) / P(TEST_MZML).name fn_out = fn.with_suffix(\".parquet\") print(fn, fn_out)", "MZMLB_AVAILABLE: return None result = ms_file_to_df(TEST_MZMLB_POS) expected_cols = [ \"scan_id\",", "= ms_file_to_df(TEST_PARQUET) fn = P(tmpdir) / \"file.hdf\" df.to_hdf(fn, key=\"data\") result", "def test__convert_ms_file_to_feather(tmpdir): print(tmpdir) shutil.copy(TEST_MZML, tmpdir) fn = P(tmpdir) / P(TEST_MZML).name", "assert df_fea.equals(df), \"DataFrames not equal\" def test__convert_ms_file_to_parquet(tmpdir): print(tmpdir) shutil.copy(TEST_MZML, tmpdir)", "assert all(result.polarity == '+'), f'Polarity should be \"+\"\\n{result}' def test__convert_ms_file_to_feather(tmpdir):", "ms_mint.io import ( ms_file_to_df, mzml_to_pandas_df_pyteomics, convert_ms_file_to_feather, convert_ms_file_to_parquet, MZMLB_AVAILABLE, ) from", "f'Polarity should be \"-\"\\n{result}' def test__read_parquet(): result = ms_file_to_df(TEST_PARQUET) expected_cols", "ms_file_to_df(fn) df_fea = ms_file_to_df(fn_out) assert df_fea.equals(df), \"DataFrames not equal\" def", "mint.export(filename) assert os.path.isfile(filename) def test__export_to_excel_without_fn(): mint = Mint(verbose=True) mint.ms_files =", "= P(tmpdir) / P(TEST_MZML).name fn_out = fn.with_suffix(\".parquet\") print(fn, fn_out) convert_ms_file_to_parquet(fn)", "test__read_mzMLb(tmpdir): if not MZMLB_AVAILABLE: return None result = ms_file_to_df(TEST_MZMLB_POS) expected_cols", "assert expected_cols == result.columns.to_list(), result.columns def test__write_read_hdf(tmpdir): df = ms_file_to_df(TEST_PARQUET)", "mint = Mint(verbose=True) mint.ms_files = \"tests/data/test.mzXML\" mint.run() mint.export(filename) assert os.path.isfile(filename)", "\"file.hdf\" df.to_hdf(fn, key=\"data\") result = ms_file_to_df(fn) expected_cols = [ \"scan_id\",", "Mint(verbose=True) mint.ms_files = \"tests/data/test.mzXML\" mint.run() mint.export(filename) assert os.path.isfile(filename) def test__export_to_excel_without_fn():", ") from paths import ( TEST_MZML, TEST_MZXML, TEST_PARQUET, TEST_MZMLB_POS, TEST_MZML_POS,", "assert all(result.polarity == \"+\"), f'Polarity should be \"+\"\\n{result}' def test__mzml_to_pandas_df_pyteomics_neg():", "key=\"data\") result = ms_file_to_df(fn) expected_cols = [ \"scan_id\", \"ms_level\", \"polarity\",", "= mint.export() assert isinstance(buffer, io.BytesIO) df = pd.read_excel(buffer, sheet_name=\"Results\") assert", "def test__mzml_to_pandas_df_pyteomics_neg(): result = mzml_to_pandas_df_pyteomics(TEST_MZML_NEG) expected_cols = [ \"scan_id\", \"ms_level\",", "import Mint from pathlib import Path as P from ms_mint.io", "\"rt_max\": [10], \"targets_filename\": [\"unknown\"], } ) mint.run() buffer = mint.export()", "dataframe\" assert expected_cols == result.columns.to_list(), result.columns def test__write_read_hdf(tmpdir): df =", "io from ms_mint.Mint import Mint from pathlib import Path as", "as pd import shutil import os import io from ms_mint.Mint", "f'Polarity should be \"+\"\\n{result}' def test__mzml_to_pandas_df_pyteomics_neg(): result = mzml_to_pandas_df_pyteomics(TEST_MZML_NEG) expected_cols", "= pd.DataFrame( { \"peak_label\": [\"A\"], \"mz_mean\": [200], \"mz_width\": [10], \"intensity_threshold\":", "== result.columns.to_list(), result.columns def test__ms_file_to_df__mzML_timeunit_minutes(): result = ms_file_to_df(TEST_MZML, time_unit=\"minutes\") expected_cols", "== \"A\", df.loc[0, \"peak_label\"] assert df.loc[0, \"ms_file\"] == P(TEST_MZXML).name, df.loc[0,", "import pandas as pd import shutil import os import io", "ms_file_to_df(TEST_MZML, time_unit=\"minutes\") expected_cols = [ \"scan_id\", \"ms_level\", \"polarity\", \"scan_time_min\", \"mz\",", "print(fn, fn_out) convert_ms_file_to_feather(fn) assert fn_out.is_file(), f\"File not generated {fn_out}\" df", "tmpdir) fn = P(tmpdir) / P(TEST_MZML).name fn_out = fn.with_suffix(\".parquet\") print(fn,", "test__write_read_hdf(tmpdir): df = ms_file_to_df(TEST_PARQUET) fn = P(tmpdir) / \"file.hdf\" df.to_hdf(fn,", "= ms_file_to_df(fn) df_fea = ms_file_to_df(fn_out) assert df_fea.equals(df), \"DataFrames not equal\"", "df_fea = ms_file_to_df(fn_out) assert df_fea.equals(df), \"DataFrames not equal\" def test__export_to_excel(tmp_path):", "result.columns def test__ms_file_to_df__mzML_timeunit_minutes(): result = ms_file_to_df(TEST_MZML, time_unit=\"minutes\") expected_cols = [", "= os.path.join(tmp_path, \"output.xlsx\") mint = Mint(verbose=True) mint.ms_files = \"tests/data/test.mzXML\" mint.run()", "ms_file_to_df(TEST_PARQUET) expected_cols = [ \"scan_id\", \"ms_level\", \"polarity\", \"scan_time_min\", \"mz\", \"intensity\",", "from ms_mint.io import ( ms_file_to_df, mzml_to_pandas_df_pyteomics, convert_ms_file_to_feather, convert_ms_file_to_parquet, MZMLB_AVAILABLE, )", "def test__ms_file_to_df__mzXML(): result = ms_file_to_df(TEST_MZXML) expected_cols = [ \"scan_id\", \"ms_level\",", "( TEST_MZML, TEST_MZXML, TEST_PARQUET, TEST_MZMLB_POS, TEST_MZML_POS, TEST_MZML_NEG, ) def test__ms_file_to_df__mzML():", "f\"File not generated {fn_out}\" df = ms_file_to_df(fn) df_fea = ms_file_to_df(fn_out)", "result.columns.to_list(), result.columns def test__ms_file_to_df__mzXML(): result = ms_file_to_df(TEST_MZXML) expected_cols = [", "a dataframe\" assert expected_cols == result.columns.to_list(), result.columns def test__mzml_to_pandas_df_pyteomics_pos(): result", "TEST_MZML_NEG, ) def test__ms_file_to_df__mzML(): result = ms_file_to_df(TEST_MZML) expected_cols = [", "expected_cols == result.columns.to_list(), result.columns def test__ms_file_to_df__mzXML(): result = ms_file_to_df(TEST_MZXML) expected_cols", "= \"tests/data/test.mzXML\" mint.run() mint.export(filename) assert os.path.isfile(filename) def test__export_to_excel_without_fn(): mint =", "print(fn, fn_out) convert_ms_file_to_parquet(fn) assert fn_out.is_file(), f\"File not generated {fn_out}\" df", "ms_file_to_df(fn) expected_cols = [ \"scan_id\", \"ms_level\", \"polarity\", \"scan_time_min\", \"mz\", \"intensity\",", "mzml_to_pandas_df_pyteomics, convert_ms_file_to_feather, convert_ms_file_to_parquet, MZMLB_AVAILABLE, ) from paths import ( TEST_MZML,", "\"+\"\\n{result}' def test__mzml_to_pandas_df_pyteomics_neg(): result = mzml_to_pandas_df_pyteomics(TEST_MZML_NEG) expected_cols = [ \"scan_id\",", "pd.DataFrame), f\"{type(result)} is not a dataframe\" assert expected_cols == result.columns.to_list(),", "is not a dataframe\" assert expected_cols == result.columns.to_list(), result.columns def", "import Path as P from ms_mint.io import ( ms_file_to_df, mzml_to_pandas_df_pyteomics,", "from paths import ( TEST_MZML, TEST_MZXML, TEST_PARQUET, TEST_MZMLB_POS, TEST_MZML_POS, TEST_MZML_NEG,", "dataframe\" assert expected_cols == result.columns.to_list(), result.columns def test__ms_file_to_df__mzXML(): result =", "expected_cols == result.columns.to_list(), result.columns def test__ms_file_to_df__mzML_timeunit_minutes(): result = ms_file_to_df(TEST_MZML, time_unit=\"minutes\")", "fn_out.is_file(), f\"File not generated {fn_out}\" df = ms_file_to_df(fn) df_fea =", "shutil.copy(TEST_MZML, tmpdir) fn = P(tmpdir) / P(TEST_MZML).name fn_out = fn.with_suffix(\".parquet\")", "dataframe\" assert expected_cols == result.columns.to_list(), result.columns # assert all(result.polarity ==", "df.loc[0, \"peak_label\"] == \"A\", df.loc[0, \"peak_label\"] assert df.loc[0, \"ms_file\"] ==", "= ms_file_to_df(fn_out) assert df_fea.equals(df), \"DataFrames not equal\" def test__export_to_excel(tmp_path): filename", "convert_ms_file_to_parquet(fn) assert fn_out.is_file(), f\"File not generated {fn_out}\" df = ms_file_to_df(fn)", "a dataframe\" assert expected_cols == result.columns.to_list(), result.columns def test__read_mzMLb(tmpdir): if", "ms_file_to_df(TEST_MZXML) expected_cols = [ \"scan_id\", \"ms_level\", \"polarity\", \"scan_time_min\", \"mz\", \"intensity\",", "filename = os.path.join(tmp_path, \"output.xlsx\") mint = Mint(verbose=True) mint.ms_files = \"tests/data/test.mzXML\"", "mint.run() buffer = mint.export() assert isinstance(buffer, io.BytesIO) df = pd.read_excel(buffer,", "convert_ms_file_to_feather, convert_ms_file_to_parquet, MZMLB_AVAILABLE, ) from paths import ( TEST_MZML, TEST_MZXML,", "def test__read_parquet(): result = ms_file_to_df(TEST_PARQUET) expected_cols = [ \"scan_id\", \"ms_level\",", "# assert all(result.polarity == '+'), f'Polarity should be \"+\"\\n{result}' def", "fn = P(tmpdir) / \"file.hdf\" df.to_hdf(fn, key=\"data\") result = ms_file_to_df(fn)", "f'Polarity should be \"+\"\\n{result}' def test__convert_ms_file_to_feather(tmpdir): print(tmpdir) shutil.copy(TEST_MZML, tmpdir) fn", "time_unit=\"minutes\") expected_cols = [ \"scan_id\", \"ms_level\", \"polarity\", \"scan_time_min\", \"mz\", \"intensity\",", "isinstance(result, pd.DataFrame), f\"{type(result)} is not a dataframe\" assert expected_cols ==", "[200], \"mz_width\": [10], \"intensity_threshold\": [0], \"rt_min\": [0], \"rt_max\": [10], \"targets_filename\":", "result = ms_file_to_df(TEST_MZML, time_unit=\"minutes\") expected_cols = [ \"scan_id\", \"ms_level\", \"polarity\",", "all(result.polarity == '+'), f'Polarity should be \"+\"\\n{result}' def test__convert_ms_file_to_feather(tmpdir): print(tmpdir)", "import shutil import os import io from ms_mint.Mint import Mint", "all(result.polarity == \"-\"), f'Polarity should be \"-\"\\n{result}' def test__read_parquet(): result", "P(TEST_MZML).name fn_out = fn.with_suffix(\".feather\") print(fn, fn_out) convert_ms_file_to_feather(fn) assert fn_out.is_file(), f\"File", "not a dataframe\" assert expected_cols == result.columns.to_list(), result.columns assert all(result.polarity", "== \"-\"), f'Polarity should be \"-\"\\n{result}' def test__read_parquet(): result =", "} ) mint.run() buffer = mint.export() assert isinstance(buffer, io.BytesIO) df", "MZMLB_AVAILABLE, ) from paths import ( TEST_MZML, TEST_MZXML, TEST_PARQUET, TEST_MZMLB_POS,", "a dataframe\" assert expected_cols == result.columns.to_list(), result.columns def test__write_read_hdf(tmpdir): df", "/ \"file.hdf\" df.to_hdf(fn, key=\"data\") result = ms_file_to_df(fn) expected_cols = [", "fn_out) convert_ms_file_to_parquet(fn) assert fn_out.is_file(), f\"File not generated {fn_out}\" df =", "df = ms_file_to_df(TEST_PARQUET) fn = P(tmpdir) / \"file.hdf\" df.to_hdf(fn, key=\"data\")", "not a dataframe\" assert expected_cols == result.columns.to_list(), result.columns def test__ms_file_to_df__mzML_timeunit_minutes():", "pd.read_excel(buffer, sheet_name=\"Results\") assert len(df) == 1, len(df) assert df.loc[0, \"peak_label\"]", "test__read_parquet(): result = ms_file_to_df(TEST_PARQUET) expected_cols = [ \"scan_id\", \"ms_level\", \"polarity\",", "if not MZMLB_AVAILABLE: return None result = ms_file_to_df(TEST_MZMLB_POS) expected_cols =", "not a dataframe\" assert expected_cols == result.columns.to_list(), result.columns def test__mzml_to_pandas_df_pyteomics_pos():", "= Mint(verbose=True) mint.ms_files = TEST_MZXML mint.targets = pd.DataFrame( { \"peak_label\":", "assert isinstance(buffer, io.BytesIO) df = pd.read_excel(buffer, sheet_name=\"Results\") assert len(df) ==", "[\"unknown\"], } ) mint.run() buffer = mint.export() assert isinstance(buffer, io.BytesIO)", "\"-\"), f'Polarity should be \"-\"\\n{result}' def test__read_parquet(): result = ms_file_to_df(TEST_PARQUET)", "{fn_out}\" df = ms_file_to_df(fn) df_fea = ms_file_to_df(fn_out) assert df_fea.equals(df), \"DataFrames", "ms_mint.Mint import Mint from pathlib import Path as P from", "fn = P(tmpdir) / P(TEST_MZML).name fn_out = fn.with_suffix(\".feather\") print(fn, fn_out)", "fn_out) convert_ms_file_to_feather(fn) assert fn_out.is_file(), f\"File not generated {fn_out}\" df =", "generated {fn_out}\" df = ms_file_to_df(fn) df_fea = ms_file_to_df(fn_out) assert df_fea.equals(df),", "df_fea.equals(df), \"DataFrames not equal\" def test__export_to_excel(tmp_path): filename = os.path.join(tmp_path, \"output.xlsx\")", "P from ms_mint.io import ( ms_file_to_df, mzml_to_pandas_df_pyteomics, convert_ms_file_to_feather, convert_ms_file_to_parquet, MZMLB_AVAILABLE,", "assert len(df) == 1, len(df) assert df.loc[0, \"peak_label\"] == \"A\",", "result = ms_file_to_df(fn) expected_cols = [ \"scan_id\", \"ms_level\", \"polarity\", \"scan_time_min\",", ") mint.run() buffer = mint.export() assert isinstance(buffer, io.BytesIO) df =", "paths import ( TEST_MZML, TEST_MZXML, TEST_PARQUET, TEST_MZMLB_POS, TEST_MZML_POS, TEST_MZML_NEG, )", "buffer = mint.export() assert isinstance(buffer, io.BytesIO) df = pd.read_excel(buffer, sheet_name=\"Results\")", "result.columns.to_list(), result.columns def test__mzml_to_pandas_df_pyteomics_pos(): result = mzml_to_pandas_df_pyteomics(TEST_MZML_POS) expected_cols = [", "mint = Mint(verbose=True) mint.ms_files = TEST_MZXML mint.targets = pd.DataFrame( {", "result.columns.to_list(), result.columns def test__read_mzMLb(tmpdir): if not MZMLB_AVAILABLE: return None result", "be \"+\"\\n{result}' def test__mzml_to_pandas_df_pyteomics_neg(): result = mzml_to_pandas_df_pyteomics(TEST_MZML_NEG) expected_cols = [", "= pd.read_excel(buffer, sheet_name=\"Results\") assert len(df) == 1, len(df) assert df.loc[0,", "test__mzml_to_pandas_df_pyteomics_pos(): result = mzml_to_pandas_df_pyteomics(TEST_MZML_POS) expected_cols = [ \"scan_id\", \"ms_level\", \"polarity\",", "expected_cols == result.columns.to_list(), result.columns # assert all(result.polarity == '+'), f'Polarity", "dataframe\" assert expected_cols == result.columns.to_list(), result.columns assert all(result.polarity == \"-\"),", "should be \"+\"\\n{result}' def test__mzml_to_pandas_df_pyteomics_neg(): result = mzml_to_pandas_df_pyteomics(TEST_MZML_NEG) expected_cols =", "\"intensity_threshold\": [0], \"rt_min\": [0], \"rt_max\": [10], \"targets_filename\": [\"unknown\"], } )", "TEST_PARQUET, TEST_MZMLB_POS, TEST_MZML_POS, TEST_MZML_NEG, ) def test__ms_file_to_df__mzML(): result = ms_file_to_df(TEST_MZML)", "result.columns.to_list(), result.columns def test__ms_file_to_df__mzML_timeunit_minutes(): result = ms_file_to_df(TEST_MZML, time_unit=\"minutes\") expected_cols =", "len(df) assert df.loc[0, \"peak_label\"] == \"A\", df.loc[0, \"peak_label\"] assert df.loc[0,", "expected_cols == result.columns.to_list(), result.columns assert all(result.polarity == \"+\"), f'Polarity should", "a dataframe\" assert expected_cols == result.columns.to_list(), result.columns def test__ms_file_to_df__mzML_timeunit_minutes(): result", "= ms_file_to_df(TEST_MZML, time_unit=\"minutes\") expected_cols = [ \"scan_id\", \"ms_level\", \"polarity\", \"scan_time_min\",", "from ms_mint.Mint import Mint from pathlib import Path as P", "df = ms_file_to_df(fn) df_fea = ms_file_to_df(fn_out) assert df_fea.equals(df), \"DataFrames not", "import ( ms_file_to_df, mzml_to_pandas_df_pyteomics, convert_ms_file_to_feather, convert_ms_file_to_parquet, MZMLB_AVAILABLE, ) from paths", "dataframe\" assert expected_cols == result.columns.to_list(), result.columns def test__read_mzMLb(tmpdir): if not", ") def test__ms_file_to_df__mzML(): result = ms_file_to_df(TEST_MZML) expected_cols = [ \"scan_id\",", "[10], \"intensity_threshold\": [0], \"rt_min\": [0], \"rt_max\": [10], \"targets_filename\": [\"unknown\"], }", "mzml_to_pandas_df_pyteomics(TEST_MZML_POS) expected_cols = [ \"scan_id\", \"ms_level\", \"polarity\", \"scan_time_min\", \"mz\", \"intensity\",", "print(tmpdir) shutil.copy(TEST_MZML, tmpdir) fn = P(tmpdir) / P(TEST_MZML).name fn_out =", "TEST_MZXML mint.targets = pd.DataFrame( { \"peak_label\": [\"A\"], \"mz_mean\": [200], \"mz_width\":", "should be \"+\"\\n{result}' def test__convert_ms_file_to_feather(tmpdir): print(tmpdir) shutil.copy(TEST_MZML, tmpdir) fn =", "def test__export_to_excel_without_fn(): mint = Mint(verbose=True) mint.ms_files = TEST_MZXML mint.targets =", "TEST_MZML_POS, TEST_MZML_NEG, ) def test__ms_file_to_df__mzML(): result = ms_file_to_df(TEST_MZML) expected_cols =", "result = mzml_to_pandas_df_pyteomics(TEST_MZML_POS) expected_cols = [ \"scan_id\", \"ms_level\", \"polarity\", \"scan_time_min\",", "TEST_MZMLB_POS, TEST_MZML_POS, TEST_MZML_NEG, ) def test__ms_file_to_df__mzML(): result = ms_file_to_df(TEST_MZML) expected_cols", "[0], \"rt_min\": [0], \"rt_max\": [10], \"targets_filename\": [\"unknown\"], } ) mint.run()", "not a dataframe\" assert expected_cols == result.columns.to_list(), result.columns def test__read_mzMLb(tmpdir):", "tmpdir) fn = P(tmpdir) / P(TEST_MZML).name fn_out = fn.with_suffix(\".feather\") print(fn,", "P(tmpdir) / \"file.hdf\" df.to_hdf(fn, key=\"data\") result = ms_file_to_df(fn) expected_cols =", "\"output.xlsx\") mint = Mint(verbose=True) mint.ms_files = \"tests/data/test.mzXML\" mint.run() mint.export(filename) assert", "f\"{type(result)} is not a dataframe\" assert expected_cols == result.columns.to_list(), result.columns", "result = ms_file_to_df(TEST_PARQUET) expected_cols = [ \"scan_id\", \"ms_level\", \"polarity\", \"scan_time_min\",", "[ \"scan_id\", \"ms_level\", \"polarity\", \"scan_time_min\", \"mz\", \"intensity\", ] assert isinstance(result,", "ms_file_to_df(TEST_PARQUET) fn = P(tmpdir) / \"file.hdf\" df.to_hdf(fn, key=\"data\") result =", "test__ms_file_to_df__mzML(): result = ms_file_to_df(TEST_MZML) expected_cols = [ \"scan_id\", \"ms_level\", \"polarity\",", "ms_file_to_df, mzml_to_pandas_df_pyteomics, convert_ms_file_to_feather, convert_ms_file_to_parquet, MZMLB_AVAILABLE, ) from paths import (", "\"A\", df.loc[0, \"peak_label\"] assert df.loc[0, \"ms_file\"] == P(TEST_MZXML).name, df.loc[0, \"ms_file\"]", "= fn.with_suffix(\".feather\") print(fn, fn_out) convert_ms_file_to_feather(fn) assert fn_out.is_file(), f\"File not generated", "io.BytesIO) df = pd.read_excel(buffer, sheet_name=\"Results\") assert len(df) == 1, len(df)", "def test__convert_ms_file_to_parquet(tmpdir): print(tmpdir) shutil.copy(TEST_MZML, tmpdir) fn = P(tmpdir) / P(TEST_MZML).name", "not generated {fn_out}\" df = ms_file_to_df(fn) df_fea = ms_file_to_df(fn_out) assert", "result = ms_file_to_df(TEST_MZXML) expected_cols = [ \"scan_id\", \"ms_level\", \"polarity\", \"scan_time_min\",", "result.columns def test__write_read_hdf(tmpdir): df = ms_file_to_df(TEST_PARQUET) fn = P(tmpdir) /", "fn.with_suffix(\".feather\") print(fn, fn_out) convert_ms_file_to_feather(fn) assert fn_out.is_file(), f\"File not generated {fn_out}\"", "return None result = ms_file_to_df(TEST_MZMLB_POS) expected_cols = [ \"scan_id\", \"ms_level\",", "import ( TEST_MZML, TEST_MZXML, TEST_PARQUET, TEST_MZMLB_POS, TEST_MZML_POS, TEST_MZML_NEG, ) def", "os.path.isfile(filename) def test__export_to_excel_without_fn(): mint = Mint(verbose=True) mint.ms_files = TEST_MZXML mint.targets", "assert expected_cols == result.columns.to_list(), result.columns assert all(result.polarity == \"+\"), f'Polarity", "assert df_fea.equals(df), \"DataFrames not equal\" def test__export_to_excel(tmp_path): filename = os.path.join(tmp_path,", "TEST_MZML, TEST_MZXML, TEST_PARQUET, TEST_MZMLB_POS, TEST_MZML_POS, TEST_MZML_NEG, ) def test__ms_file_to_df__mzML(): result", "\"ms_level\", \"polarity\", \"scan_time_min\", \"mz\", \"intensity\", ] assert isinstance(result, pd.DataFrame), f\"{type(result)}", "result.columns.to_list(), result.columns assert all(result.polarity == \"+\"), f'Polarity should be \"+\"\\n{result}'", "= ms_file_to_df(fn) expected_cols = [ \"scan_id\", \"ms_level\", \"polarity\", \"scan_time_min\", \"mz\",", "df_fea.equals(df), \"DataFrames not equal\" def test__convert_ms_file_to_parquet(tmpdir): print(tmpdir) shutil.copy(TEST_MZML, tmpdir) fn", "= ms_file_to_df(TEST_MZMLB_POS) expected_cols = [ \"scan_id\", \"ms_level\", \"polarity\", \"scan_time_min\", \"mz\",", "\"polarity\", \"scan_time_min\", \"mz\", \"intensity\", ] assert isinstance(result, pd.DataFrame), f\"{type(result)} is", "sheet_name=\"Results\") assert len(df) == 1, len(df) assert df.loc[0, \"peak_label\"] ==", "[10], \"targets_filename\": [\"unknown\"], } ) mint.run() buffer = mint.export() assert", "\"DataFrames not equal\" def test__export_to_excel(tmp_path): filename = os.path.join(tmp_path, \"output.xlsx\") mint", "not equal\" def test__export_to_excel(tmp_path): filename = os.path.join(tmp_path, \"output.xlsx\") mint =", "[\"A\"], \"mz_mean\": [200], \"mz_width\": [10], \"intensity_threshold\": [0], \"rt_min\": [0], \"rt_max\":", "\"-\"\\n{result}' def test__read_parquet(): result = ms_file_to_df(TEST_PARQUET) expected_cols = [ \"scan_id\",", "shutil import os import io from ms_mint.Mint import Mint from", "assert expected_cols == result.columns.to_list(), result.columns def test__read_mzMLb(tmpdir): if not MZMLB_AVAILABLE:", "mzml_to_pandas_df_pyteomics(TEST_MZML_NEG) expected_cols = [ \"scan_id\", \"ms_level\", \"polarity\", \"scan_time_min\", \"mz\", \"intensity\",", "[0], \"rt_max\": [10], \"targets_filename\": [\"unknown\"], } ) mint.run() buffer =", "= ms_file_to_df(TEST_MZXML) expected_cols = [ \"scan_id\", \"ms_level\", \"polarity\", \"scan_time_min\", \"mz\",", "result.columns.to_list(), result.columns # assert all(result.polarity == '+'), f'Polarity should be", "{ \"peak_label\": [\"A\"], \"mz_mean\": [200], \"mz_width\": [10], \"intensity_threshold\": [0], \"rt_min\":", "result = ms_file_to_df(TEST_MZMLB_POS) expected_cols = [ \"scan_id\", \"ms_level\", \"polarity\", \"scan_time_min\",", "pathlib import Path as P from ms_mint.io import ( ms_file_to_df,", "== result.columns.to_list(), result.columns assert all(result.polarity == \"+\"), f'Polarity should be", "assert expected_cols == result.columns.to_list(), result.columns def test__mzml_to_pandas_df_pyteomics_pos(): result = mzml_to_pandas_df_pyteomics(TEST_MZML_POS)", "result.columns # assert all(result.polarity == '+'), f'Polarity should be \"+\"\\n{result}'", "assert expected_cols == result.columns.to_list(), result.columns def test__ms_file_to_df__mzXML(): result = ms_file_to_df(TEST_MZXML)", "assert os.path.isfile(filename) def test__export_to_excel_without_fn(): mint = Mint(verbose=True) mint.ms_files = TEST_MZXML", "not a dataframe\" assert expected_cols == result.columns.to_list(), result.columns # assert", "ms_file_to_df(fn_out) assert df_fea.equals(df), \"DataFrames not equal\" def test__export_to_excel(tmp_path): filename =", "should be \"-\"\\n{result}' def test__read_parquet(): result = ms_file_to_df(TEST_PARQUET) expected_cols =", "'+'), f'Polarity should be \"+\"\\n{result}' def test__convert_ms_file_to_feather(tmpdir): print(tmpdir) shutil.copy(TEST_MZML, tmpdir)", "def test__export_to_excel(tmp_path): filename = os.path.join(tmp_path, \"output.xlsx\") mint = Mint(verbose=True) mint.ms_files", "not a dataframe\" assert expected_cols == result.columns.to_list(), result.columns def test__ms_file_to_df__mzXML():", "= mzml_to_pandas_df_pyteomics(TEST_MZML_POS) expected_cols = [ \"scan_id\", \"ms_level\", \"polarity\", \"scan_time_min\", \"mz\",", "== result.columns.to_list(), result.columns # assert all(result.polarity == '+'), f'Polarity should", "result.columns def test__mzml_to_pandas_df_pyteomics_pos(): result = mzml_to_pandas_df_pyteomics(TEST_MZML_POS) expected_cols = [ \"scan_id\",", "\"+\"), f'Polarity should be \"+\"\\n{result}' def test__mzml_to_pandas_df_pyteomics_neg(): result = mzml_to_pandas_df_pyteomics(TEST_MZML_NEG)", "/ P(TEST_MZML).name fn_out = fn.with_suffix(\".feather\") print(fn, fn_out) convert_ms_file_to_feather(fn) assert fn_out.is_file(),", "dataframe\" assert expected_cols == result.columns.to_list(), result.columns assert all(result.polarity == \"+\"),", "be \"+\"\\n{result}' def test__convert_ms_file_to_feather(tmpdir): print(tmpdir) shutil.copy(TEST_MZML, tmpdir) fn = P(tmpdir)", "fn_out = fn.with_suffix(\".feather\") print(fn, fn_out) convert_ms_file_to_feather(fn) assert fn_out.is_file(), f\"File not", "mint.targets = pd.DataFrame( { \"peak_label\": [\"A\"], \"mz_mean\": [200], \"mz_width\": [10],", "def test__read_mzMLb(tmpdir): if not MZMLB_AVAILABLE: return None result = ms_file_to_df(TEST_MZMLB_POS)", "\"DataFrames not equal\" def test__convert_ms_file_to_parquet(tmpdir): print(tmpdir) shutil.copy(TEST_MZML, tmpdir) fn =", "assert isinstance(result, pd.DataFrame), f\"{type(result)} is not a dataframe\" assert expected_cols", "a dataframe\" assert expected_cols == result.columns.to_list(), result.columns assert all(result.polarity ==", "def test__ms_file_to_df__mzML_timeunit_minutes(): result = ms_file_to_df(TEST_MZML, time_unit=\"minutes\") expected_cols = [ \"scan_id\",", "== result.columns.to_list(), result.columns def test__ms_file_to_df__mzXML(): result = ms_file_to_df(TEST_MZXML) expected_cols =", "\"peak_label\": [\"A\"], \"mz_mean\": [200], \"mz_width\": [10], \"intensity_threshold\": [0], \"rt_min\": [0],", "\"scan_id\", \"ms_level\", \"polarity\", \"scan_time_min\", \"mz\", \"intensity\", ] assert isinstance(result, pd.DataFrame),", "== result.columns.to_list(), result.columns def test__write_read_hdf(tmpdir): df = ms_file_to_df(TEST_PARQUET) fn =", "Path as P from ms_mint.io import ( ms_file_to_df, mzml_to_pandas_df_pyteomics, convert_ms_file_to_feather,", "assert fn_out.is_file(), f\"File not generated {fn_out}\" df = ms_file_to_df(fn) df_fea", "fn.with_suffix(\".parquet\") print(fn, fn_out) convert_ms_file_to_parquet(fn) assert fn_out.is_file(), f\"File not generated {fn_out}\"", "is not a dataframe\" assert expected_cols == result.columns.to_list(), result.columns assert", "result.columns.to_list(), result.columns def test__write_read_hdf(tmpdir): df = ms_file_to_df(TEST_PARQUET) fn = P(tmpdir)", "shutil.copy(TEST_MZML, tmpdir) fn = P(tmpdir) / P(TEST_MZML).name fn_out = fn.with_suffix(\".feather\")", "os.path.join(tmp_path, \"output.xlsx\") mint = Mint(verbose=True) mint.ms_files = \"tests/data/test.mzXML\" mint.run() mint.export(filename)", "result.columns def test__read_mzMLb(tmpdir): if not MZMLB_AVAILABLE: return None result =", "expected_cols == result.columns.to_list(), result.columns def test__read_mzMLb(tmpdir): if not MZMLB_AVAILABLE: return", "is not a dataframe\" assert expected_cols == result.columns.to_list(), result.columns #", "def test__write_read_hdf(tmpdir): df = ms_file_to_df(TEST_PARQUET) fn = P(tmpdir) / \"file.hdf\"", "== result.columns.to_list(), result.columns def test__read_mzMLb(tmpdir): if not MZMLB_AVAILABLE: return None", "os import io from ms_mint.Mint import Mint from pathlib import", "\"intensity\", ] assert isinstance(result, pd.DataFrame), f\"{type(result)} is not a dataframe\"", "len(df) == 1, len(df) assert df.loc[0, \"peak_label\"] == \"A\", df.loc[0,", "test__export_to_excel_without_fn(): mint = Mint(verbose=True) mint.ms_files = TEST_MZXML mint.targets = pd.DataFrame(", "assert all(result.polarity == \"-\"), f'Polarity should be \"-\"\\n{result}' def test__read_parquet():", "df = pd.read_excel(buffer, sheet_name=\"Results\") assert len(df) == 1, len(df) assert", "assert expected_cols == result.columns.to_list(), result.columns # assert all(result.polarity == '+'),", "= TEST_MZXML mint.targets = pd.DataFrame( { \"peak_label\": [\"A\"], \"mz_mean\": [200],", "== 1, len(df) assert df.loc[0, \"peak_label\"] == \"A\", df.loc[0, \"peak_label\"]", "not MZMLB_AVAILABLE: return None result = ms_file_to_df(TEST_MZMLB_POS) expected_cols = [", "fn_out = fn.with_suffix(\".parquet\") print(fn, fn_out) convert_ms_file_to_parquet(fn) assert fn_out.is_file(), f\"File not", "== '+'), f'Polarity should be \"+\"\\n{result}' def test__convert_ms_file_to_feather(tmpdir): print(tmpdir) shutil.copy(TEST_MZML,", "\"mz\", \"intensity\", ] assert isinstance(result, pd.DataFrame), f\"{type(result)} is not a", "ms_file_to_df(TEST_MZML) expected_cols = [ \"scan_id\", \"ms_level\", \"polarity\", \"scan_time_min\", \"mz\", \"intensity\",", "= [ \"scan_id\", \"ms_level\", \"polarity\", \"scan_time_min\", \"mz\", \"intensity\", ] assert", "result = mzml_to_pandas_df_pyteomics(TEST_MZML_NEG) expected_cols = [ \"scan_id\", \"ms_level\", \"polarity\", \"scan_time_min\",", "mint.ms_files = \"tests/data/test.mzXML\" mint.run() mint.export(filename) assert os.path.isfile(filename) def test__export_to_excel_without_fn(): mint", "Mint(verbose=True) mint.ms_files = TEST_MZXML mint.targets = pd.DataFrame( { \"peak_label\": [\"A\"],", "pd.DataFrame( { \"peak_label\": [\"A\"], \"mz_mean\": [200], \"mz_width\": [10], \"intensity_threshold\": [0],", "not equal\" def test__convert_ms_file_to_parquet(tmpdir): print(tmpdir) shutil.copy(TEST_MZML, tmpdir) fn = P(tmpdir)", "assert df.loc[0, \"peak_label\"] == \"A\", df.loc[0, \"peak_label\"] assert df.loc[0, \"ms_file\"]", "result.columns assert all(result.polarity == \"-\"), f'Polarity should be \"-\"\\n{result}' def", "result.columns.to_list(), result.columns assert all(result.polarity == \"-\"), f'Polarity should be \"-\"\\n{result}'", "== result.columns.to_list(), result.columns def test__mzml_to_pandas_df_pyteomics_pos(): result = mzml_to_pandas_df_pyteomics(TEST_MZML_POS) expected_cols =", "test__convert_ms_file_to_parquet(tmpdir): print(tmpdir) shutil.copy(TEST_MZML, tmpdir) fn = P(tmpdir) / P(TEST_MZML).name fn_out", "== result.columns.to_list(), result.columns assert all(result.polarity == \"-\"), f'Polarity should be", "expected_cols == result.columns.to_list(), result.columns assert all(result.polarity == \"-\"), f'Polarity should", "/ P(TEST_MZML).name fn_out = fn.with_suffix(\".parquet\") print(fn, fn_out) convert_ms_file_to_parquet(fn) assert fn_out.is_file(),", "assert expected_cols == result.columns.to_list(), result.columns def test__ms_file_to_df__mzML_timeunit_minutes(): result = ms_file_to_df(TEST_MZML,", "\"rt_min\": [0], \"rt_max\": [10], \"targets_filename\": [\"unknown\"], } ) mint.run() buffer", "= P(tmpdir) / P(TEST_MZML).name fn_out = fn.with_suffix(\".feather\") print(fn, fn_out) convert_ms_file_to_feather(fn)", "dataframe\" assert expected_cols == result.columns.to_list(), result.columns def test__mzml_to_pandas_df_pyteomics_pos(): result =", "df.to_hdf(fn, key=\"data\") result = ms_file_to_df(fn) expected_cols = [ \"scan_id\", \"ms_level\",", "be \"-\"\\n{result}' def test__read_parquet(): result = ms_file_to_df(TEST_PARQUET) expected_cols = [", "import io from ms_mint.Mint import Mint from pathlib import Path", "import os import io from ms_mint.Mint import Mint from pathlib", "\"tests/data/test.mzXML\" mint.run() mint.export(filename) assert os.path.isfile(filename) def test__export_to_excel_without_fn(): mint = Mint(verbose=True)", "= ms_file_to_df(TEST_PARQUET) expected_cols = [ \"scan_id\", \"ms_level\", \"polarity\", \"scan_time_min\", \"mz\",", "convert_ms_file_to_feather(fn) assert fn_out.is_file(), f\"File not generated {fn_out}\" df = ms_file_to_df(fn)" ]
[ "== 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage()", "uploaded_file_url }) return render(request, 'core/simple_upload.html') def model_form_upload(request): if request.method ==", "myfile) uploaded_file_url = fs.url(filename) return render(request, 'core/simple_upload.html', { 'uploaded_file_url': uploaded_file_url", "image_cv2 def home(request): documents = Document.objects.all() number = len(image_cv2.myList) return", "= len(image_cv2.myList) return render(request, 'core/home.html', {'documents': documents, 'number': number}) def", "= Document.objects.all() number = len(image_cv2.myList) return render(request, 'core/home.html', {'documents': documents,", "request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] fs =", "'uploaded_file_url': uploaded_file_url }) return render(request, 'core/simple_upload.html') def model_form_upload(request): if request.method", "form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('home') else:", "from core.models import Document from media import image_cv2 def home(request):", "render(request, 'core/simple_upload.html', { 'uploaded_file_url': uploaded_file_url }) return render(request, 'core/simple_upload.html') def", "{'documents': documents, 'number': number}) def simple_upload(request): if request.method == 'POST'", "Document from media import image_cv2 def home(request): documents = Document.objects.all()", "django.shortcuts import render, redirect from core.forms import DocumentForm from core.models", "import FileSystemStorage from django.shortcuts import render, redirect from core.forms import", "redirect('home') else: form = DocumentForm() return render(request, 'core/model_form_upload.html', { 'form':", "= DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('home') else: form", "DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('home') else: form =", "return render(request, 'core/simple_upload.html') def model_form_upload(request): if request.method == 'POST': form", "'core/home.html', {'documents': documents, 'number': number}) def simple_upload(request): if request.method ==", "simple_upload(request): if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile']", "request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save()", "= FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) return", "def home(request): documents = Document.objects.all() number = len(image_cv2.myList) return render(request,", "render, redirect from core.forms import DocumentForm from core.models import Document", "def simple_upload(request): if request.method == 'POST' and request.FILES['myfile']: myfile =", "from core.forms import DocumentForm from core.models import Document from media", "documents = Document.objects.all() number = len(image_cv2.myList) return render(request, 'core/home.html', {'documents':", "return render(request, 'core/home.html', {'documents': documents, 'number': number}) def simple_upload(request): if", "'number': number}) def simple_upload(request): if request.method == 'POST' and request.FILES['myfile']:", "from media import image_cv2 def home(request): documents = Document.objects.all() number", "number = len(image_cv2.myList) return render(request, 'core/home.html', {'documents': documents, 'number': number})", "core.models import Document from media import image_cv2 def home(request): documents", "{ 'uploaded_file_url': uploaded_file_url }) return render(request, 'core/simple_upload.html') def model_form_upload(request): if", "django.core.files.storage import FileSystemStorage from django.shortcuts import render, redirect from core.forms", "fs.url(filename) return render(request, 'core/simple_upload.html', { 'uploaded_file_url': uploaded_file_url }) return render(request,", "from django.shortcuts import render, redirect from core.forms import DocumentForm from", "core.forms import DocumentForm from core.models import Document from media import", "else: form = DocumentForm() return render(request, 'core/model_form_upload.html', { 'form': form", "if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid():", "request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url =", "return render(request, 'core/simple_upload.html', { 'uploaded_file_url': uploaded_file_url }) return render(request, 'core/simple_upload.html')", "fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) return render(request, 'core/simple_upload.html', { 'uploaded_file_url':", "'core/simple_upload.html') def model_form_upload(request): if request.method == 'POST': form = DocumentForm(request.POST,", "DocumentForm from core.models import Document from media import image_cv2 def", "home(request): documents = Document.objects.all() number = len(image_cv2.myList) return render(request, 'core/home.html',", "FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) return render(request,", "if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] fs", "= request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url", "'core/simple_upload.html', { 'uploaded_file_url': uploaded_file_url }) return render(request, 'core/simple_upload.html') def model_form_upload(request):", "render(request, 'core/home.html', {'documents': documents, 'number': number}) def simple_upload(request): if request.method", "return redirect('home') else: form = DocumentForm() return render(request, 'core/model_form_upload.html', {", "number}) def simple_upload(request): if request.method == 'POST' and request.FILES['myfile']: myfile", "fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename)", "request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name,", "form.save() return redirect('home') else: form = DocumentForm() return render(request, 'core/model_form_upload.html',", "= fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) return render(request, 'core/simple_upload.html', {", "<filename>core/views.py from django.core.files.storage import FileSystemStorage from django.shortcuts import render, redirect", "and request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage() filename =", "'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('home')", "import render, redirect from core.forms import DocumentForm from core.models import", "render(request, 'core/simple_upload.html') def model_form_upload(request): if request.method == 'POST': form =", "}) return render(request, 'core/simple_upload.html') def model_form_upload(request): if request.method == 'POST':", "documents, 'number': number}) def simple_upload(request): if request.method == 'POST' and", "if form.is_valid(): form.save() return redirect('home') else: form = DocumentForm() return", "= fs.url(filename) return render(request, 'core/simple_upload.html', { 'uploaded_file_url': uploaded_file_url }) return", "import DocumentForm from core.models import Document from media import image_cv2", "def model_form_upload(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES)", "form.is_valid(): form.save() return redirect('home') else: form = DocumentForm() return render(request,", "import Document from media import image_cv2 def home(request): documents =", "len(image_cv2.myList) return render(request, 'core/home.html', {'documents': documents, 'number': number}) def simple_upload(request):", "from django.core.files.storage import FileSystemStorage from django.shortcuts import render, redirect from", "import image_cv2 def home(request): documents = Document.objects.all() number = len(image_cv2.myList)", "uploaded_file_url = fs.url(filename) return render(request, 'core/simple_upload.html', { 'uploaded_file_url': uploaded_file_url })", "redirect from core.forms import DocumentForm from core.models import Document from", "'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage() filename", "form = DocumentForm() return render(request, 'core/model_form_upload.html', { 'form': form })", "FileSystemStorage from django.shortcuts import render, redirect from core.forms import DocumentForm", "== 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return", "request.FILES) if form.is_valid(): form.save() return redirect('home') else: form = DocumentForm()", "Document.objects.all() number = len(image_cv2.myList) return render(request, 'core/home.html', {'documents': documents, 'number':", "media import image_cv2 def home(request): documents = Document.objects.all() number =", "filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) return render(request, 'core/simple_upload.html',", "model_form_upload(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if", "myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile)" ]
[ "age = gaussian(38.8125, 193.4918) capital_loss = gaussian(117.8083, 252612.0300) else: capital_gain", "if capital_gain < 7298.0000: age = gaussian(38.4208, 184.9151) capital_loss =", "= gaussian(38.6361, 187.2435) capital_loss = gaussian(87.0152, 161032.4157) else: age =", "sex > 1: t = t + -0.0003 if sex", "if capital_gain < 5178.0000: age = gaussian(38.6361, 187.2435) capital_loss =", "* N_capital_gain + -0.0002 * N_capital_loss + 1.0003 if sex", "gaussian(87.0152, 161032.4157) else: age = gaussian(38.2668, 187.2747) capital_loss = gaussian(101.7672,", "/ 1258.0 t = 0.0006 * N_age + -5.7363 *", "* N_capital_loss + 1.0003 if sex > 1: t =", "22040.0 N_capital_loss = (capital_loss - 0.0) / 1258.0 t =", "193.4918) capital_loss = gaussian(117.8083, 252612.0300) else: capital_gain = gaussian(1329.3700, 69327473.1006)", "- 0.0) / 1258.0 t = 0.0006 * N_age +", "/ 62.0 N_capital_gain = (capital_gain - 0.0) / 22040.0 N_capital_loss", "def sample(flag): sex = step([(0,1,0.3307), (1,2,0.6693)]) if sex < 1:", "= gaussian(1329.3700, 69327473.1006) if capital_gain < 5178.0000: age = gaussian(38.6361,", "1: t = t + -0.0003 if sex < 1:", "N_capital_gain + -0.0002 * N_capital_loss + 1.0003 if sex >", "252612.0300) else: capital_gain = gaussian(1329.3700, 69327473.1006) if capital_gain < 5178.0000:", "age = gaussian(38.4208, 184.9151) capital_loss = gaussian(86.5949, 157731.9553) else: age", "if sex > 1: t = t + -0.0003 if", "= t + -0.0003 if sex < 1: t =", "N_capital_loss + 1.0003 if sex > 1: t = t", "< 7298.0000: age = gaussian(38.4208, 184.9151) capital_loss = gaussian(86.5949, 157731.9553)", "age = gaussian(38.6361, 187.2435) capital_loss = gaussian(87.0152, 161032.4157) else: age", "N_capital_loss = (capital_loss - 0.0) / 1258.0 t = 0.0006", "1: capital_gain = gaussian(568.4105, 24248365.5428) if capital_gain < 7298.0000: age", "gaussian(117.8083, 252612.0300) else: capital_gain = gaussian(1329.3700, 69327473.1006) if capital_gain <", "< 5178.0000: age = gaussian(38.6361, 187.2435) capital_loss = gaussian(87.0152, 161032.4157)", "187.2435) capital_loss = gaussian(87.0152, 161032.4157) else: age = gaussian(38.2668, 187.2747)", "= (age - 17.0) / 62.0 N_capital_gain = (capital_gain -", "1: t = t - 0.5 return int(t < 0)", "gaussian(86.5949, 157731.9553) else: age = gaussian(38.8125, 193.4918) capital_loss = gaussian(117.8083,", "7298.0000: age = gaussian(38.4208, 184.9151) capital_loss = gaussian(86.5949, 157731.9553) else:", "= gaussian(86.5949, 157731.9553) else: age = gaussian(38.8125, 193.4918) capital_loss =", "capital_gain = gaussian(1329.3700, 69327473.1006) if capital_gain < 5178.0000: age =", "> 1: t = t + -0.0003 if sex <", "if sex < 1: t = t - 0.5 return", "69327473.1006) if capital_gain < 5178.0000: age = gaussian(38.6361, 187.2435) capital_loss", "-5.7363 * N_capital_gain + -0.0002 * N_capital_loss + 1.0003 if", "gaussian(38.4208, 184.9151) capital_loss = gaussian(86.5949, 157731.9553) else: age = gaussian(38.8125,", "= gaussian(87.0152, 161032.4157) else: age = gaussian(38.2668, 187.2747) capital_loss =", "sample(flag): sex = step([(0,1,0.3307), (1,2,0.6693)]) if sex < 1: capital_gain", "-0.0003 if sex < 1: t = t - 0.5", "157731.9553) else: age = gaussian(38.8125, 193.4918) capital_loss = gaussian(117.8083, 252612.0300)", "<reponame>obastani/verifair from .helper import * def sample(flag): sex = step([(0,1,0.3307),", "= gaussian(38.8125, 193.4918) capital_loss = gaussian(117.8083, 252612.0300) else: capital_gain =", "+ -0.0002 * N_capital_loss + 1.0003 if sex > 1:", "= 0.0006 * N_age + -5.7363 * N_capital_gain + -0.0002", "else: age = gaussian(38.8125, 193.4918) capital_loss = gaussian(117.8083, 252612.0300) else:", "17.0) / 62.0 N_capital_gain = (capital_gain - 0.0) / 22040.0", "0.0) / 1258.0 t = 0.0006 * N_age + -5.7363", "capital_loss = gaussian(86.5949, 157731.9553) else: age = gaussian(38.8125, 193.4918) capital_loss", "5178.0000: age = gaussian(38.6361, 187.2435) capital_loss = gaussian(87.0152, 161032.4157) else:", "= gaussian(101.7672, 189798.1926) sensitiveAttribute(sex < 1, flag) qualified(age > 18)", "0.0006 * N_age + -5.7363 * N_capital_gain + -0.0002 *", "+ -5.7363 * N_capital_gain + -0.0002 * N_capital_loss + 1.0003", "< 1: capital_gain = gaussian(568.4105, 24248365.5428) if capital_gain < 7298.0000:", "-0.0002 * N_capital_loss + 1.0003 if sex > 1: t", ".helper import * def sample(flag): sex = step([(0,1,0.3307), (1,2,0.6693)]) if", "62.0 N_capital_gain = (capital_gain - 0.0) / 22040.0 N_capital_loss =", "from .helper import * def sample(flag): sex = step([(0,1,0.3307), (1,2,0.6693)])", "else: age = gaussian(38.2668, 187.2747) capital_loss = gaussian(101.7672, 189798.1926) sensitiveAttribute(sex", "0.0) / 22040.0 N_capital_loss = (capital_loss - 0.0) / 1258.0", "= (capital_gain - 0.0) / 22040.0 N_capital_loss = (capital_loss -", "t = t + -0.0003 if sex < 1: t", "< 1: t = t - 0.5 return int(t <", "flag) qualified(age > 18) N_age = (age - 17.0) /", "t = t - 0.5 return int(t < 0) fairnessTarget(t", "* N_age + -5.7363 * N_capital_gain + -0.0002 * N_capital_loss", "sex = step([(0,1,0.3307), (1,2,0.6693)]) if sex < 1: capital_gain =", "sex < 1: capital_gain = gaussian(568.4105, 24248365.5428) if capital_gain <", "N_capital_gain = (capital_gain - 0.0) / 22040.0 N_capital_loss = (capital_loss", "(capital_loss - 0.0) / 1258.0 t = 0.0006 * N_age", "189798.1926) sensitiveAttribute(sex < 1, flag) qualified(age > 18) N_age =", "capital_loss = gaussian(117.8083, 252612.0300) else: capital_gain = gaussian(1329.3700, 69327473.1006) if", "- 0.0) / 22040.0 N_capital_loss = (capital_loss - 0.0) /", "* def sample(flag): sex = step([(0,1,0.3307), (1,2,0.6693)]) if sex <", "- 17.0) / 62.0 N_capital_gain = (capital_gain - 0.0) /", "t + -0.0003 if sex < 1: t = t", "step([(0,1,0.3307), (1,2,0.6693)]) if sex < 1: capital_gain = gaussian(568.4105, 24248365.5428)", "/ 22040.0 N_capital_loss = (capital_loss - 0.0) / 1258.0 t", "+ 1.0003 if sex > 1: t = t +", "1258.0 t = 0.0006 * N_age + -5.7363 * N_capital_gain", "= step([(0,1,0.3307), (1,2,0.6693)]) if sex < 1: capital_gain = gaussian(568.4105,", "sensitiveAttribute(sex < 1, flag) qualified(age > 18) N_age = (age", "= gaussian(38.4208, 184.9151) capital_loss = gaussian(86.5949, 157731.9553) else: age =", "gaussian(101.7672, 189798.1926) sensitiveAttribute(sex < 1, flag) qualified(age > 18) N_age", "t = 0.0006 * N_age + -5.7363 * N_capital_gain +", "N_age + -5.7363 * N_capital_gain + -0.0002 * N_capital_loss +", "184.9151) capital_loss = gaussian(86.5949, 157731.9553) else: age = gaussian(38.8125, 193.4918)", "capital_loss = gaussian(87.0152, 161032.4157) else: age = gaussian(38.2668, 187.2747) capital_loss", "18) N_age = (age - 17.0) / 62.0 N_capital_gain =", "N_age = (age - 17.0) / 62.0 N_capital_gain = (capital_gain", "else: capital_gain = gaussian(1329.3700, 69327473.1006) if capital_gain < 5178.0000: age", "161032.4157) else: age = gaussian(38.2668, 187.2747) capital_loss = gaussian(101.7672, 189798.1926)", "= gaussian(117.8083, 252612.0300) else: capital_gain = gaussian(1329.3700, 69327473.1006) if capital_gain", "1.0003 if sex > 1: t = t + -0.0003", "1, flag) qualified(age > 18) N_age = (age - 17.0)", "capital_gain < 5178.0000: age = gaussian(38.6361, 187.2435) capital_loss = gaussian(87.0152,", "gaussian(38.2668, 187.2747) capital_loss = gaussian(101.7672, 189798.1926) sensitiveAttribute(sex < 1, flag)", "> 18) N_age = (age - 17.0) / 62.0 N_capital_gain", "187.2747) capital_loss = gaussian(101.7672, 189798.1926) sensitiveAttribute(sex < 1, flag) qualified(age", "gaussian(38.6361, 187.2435) capital_loss = gaussian(87.0152, 161032.4157) else: age = gaussian(38.2668,", "import * def sample(flag): sex = step([(0,1,0.3307), (1,2,0.6693)]) if sex", "gaussian(38.8125, 193.4918) capital_loss = gaussian(117.8083, 252612.0300) else: capital_gain = gaussian(1329.3700,", "qualified(age > 18) N_age = (age - 17.0) / 62.0", "gaussian(568.4105, 24248365.5428) if capital_gain < 7298.0000: age = gaussian(38.4208, 184.9151)", "< 1, flag) qualified(age > 18) N_age = (age -", "gaussian(1329.3700, 69327473.1006) if capital_gain < 5178.0000: age = gaussian(38.6361, 187.2435)", "= t - 0.5 return int(t < 0) fairnessTarget(t <", "= (capital_loss - 0.0) / 1258.0 t = 0.0006 *", "= gaussian(38.2668, 187.2747) capital_loss = gaussian(101.7672, 189798.1926) sensitiveAttribute(sex < 1,", "sex < 1: t = t - 0.5 return int(t", "(age - 17.0) / 62.0 N_capital_gain = (capital_gain - 0.0)", "if sex < 1: capital_gain = gaussian(568.4105, 24248365.5428) if capital_gain", "= gaussian(568.4105, 24248365.5428) if capital_gain < 7298.0000: age = gaussian(38.4208,", "24248365.5428) if capital_gain < 7298.0000: age = gaussian(38.4208, 184.9151) capital_loss", "(1,2,0.6693)]) if sex < 1: capital_gain = gaussian(568.4105, 24248365.5428) if", "capital_loss = gaussian(101.7672, 189798.1926) sensitiveAttribute(sex < 1, flag) qualified(age >", "capital_gain = gaussian(568.4105, 24248365.5428) if capital_gain < 7298.0000: age =", "capital_gain < 7298.0000: age = gaussian(38.4208, 184.9151) capital_loss = gaussian(86.5949,", "+ -0.0003 if sex < 1: t = t -", "(capital_gain - 0.0) / 22040.0 N_capital_loss = (capital_loss - 0.0)", "age = gaussian(38.2668, 187.2747) capital_loss = gaussian(101.7672, 189798.1926) sensitiveAttribute(sex <", "t - 0.5 return int(t < 0) fairnessTarget(t < 0)" ]
[ "converged: epoch += 1 self.optimizer.zero_grad() # clear previous gradients loss,", "x = layer(features) if numpy: data_ = [hash, index, symbol,", "function evaluation. model : obj Pytorch model to perform forward()", "\"Initialization of weights with Xavier Uniform by \" \"default.\" )", "+ symbol slope_name = \"slope_\" + symbol slope = getattr(self,", "Surfaces. Phys. Rev. Lett. 98, 146401 (2007). 2. <NAME>. &", ">>> lr_scheduler = ('ReduceLROnPlateau', {'mode': 'min', 'patience': 10}) uncertainty :", "= \"slope_\" + symbol if purpose == \"training\": intercept =", "Xavier Uniform by \" \"default.\" ) for m in self.modules():", "# Create DataFrame from lists df = pd.DataFrame(activations, columns=columns) return", "\"\"\" NAME = \"PytorchPotentials\" @classmethod def name(cls): \"\"\"Returns name of", "None: batch_size = len(inputs.values()) if isinstance(batch_size, int): # Data batches", "_loss = [] _rmse = [] epoch = 0 client", "a validation/test set during training procedures. >>> test = {\"features\":", "intercept = getattr(self, intercept_name) x = (slope * x) +", "unique_element_symbols = data.get_unique_element_symbols(purpose=purpose) unique_element_symbols = unique_element_symbols[purpose] symbol_model_pair = [] for", "outputs_ = [] # Get client to send futures to", "print(\"Epoch {} lr {}\".format(epoch, get_lr(self.optimizer))) ts = time.time() ts =", "atoms_per_image = data.atoms_per_image if batch_size is None: batch_size = len(inputs.values())", "to learn aka y. model : object The NeuralNetwork class.", "gradients for index, chunk in enumerate(chunks): accumulation.append( client.submit( train.train_batches, *(", "<NAME>. Generalized Neural-Network Representation of High-Dimensional Potential-Energy Surfaces. Phys. Rev.", "/ 2.0 intercept = torch.nn.Parameter( torch.tensor(intercept, requires_grad=True) ) slope =", "1 elif isinstance(layer, torch.nn.Linear) and counter > 0: x =", "len(inputs.values()) if isinstance(batch_size, int): # Data batches chunks = list(get_chunks(inputs,", "{\"closure\": self.closure, \"current_loss\": loss, \"max_ls\": 10} self.optimizer.step(options) # RMSE per", "enumerate(chunks): accumulation.append( client.submit( train.train_batches, *( index, chunk, targets, uncertainty, model,", "1 _linear = torch.nn.Linear(inp_dimension, out_dimension) linears.append(_linear) # These are hidden-layers", "evaluation. lossfxn : obj A loss function object. atoms_per_image :", "= getattr(self, slope_name) intercept = getattr(self, intercept_name) x = (slope", "intercept = (data.max_energy + data.min_energy) / 2.0 intercept = torch.nn.Parameter(", "self.atoms_per_image = atoms_per_image self.convergence = convergence self.device = device self.epochs", "of data points per batch to use for training. Default", "*(outputs_, self.targets, atoms_per_image) ) rmse = rmse.result() rmse_atom = rmse_atom.result()", "turns out that # N is also available only in", "else: inp_dimension = self.hiddenlayers[index - 1] out_dimension = self.hiddenlayers[index] _linear", "A list of tensors with energies per image. \"\"\" outputs", "None: logger.info(\"Options:\") logger.info(f\" - Uncertainty penalization: {pformat(uncertainty)}\") logger.info(\"\") atoms_per_image =", "convergence : dict Instead of using epochs, users can set", "to perform forward() and get gradients. lossfxn : obj A", "the cpu or cuda (gpu). batch_size : int Number of", "This class method clears previous gradients, iterates over batches, accumulates", "of Neural Net: {}\".format( \"(input, \" + str(self.hiddenlayers)[1:-1] + \",", "self.test is None: logger.info( \"{:6s} {:19s} {:12s} {:12s} {:8s}\".format( \"Epoch\",", ") ) logger.info(\" \") # Define optimizer self.optimizer_name, self.optimizer =", "of batch. chunk : tensor or list Tensor with input", "None and no checkpoint is saved. test : dict A", "index, symbol, x.detach_().numpy()] else: data_ = [hash, index, symbol, x.detach_()]", "a `Data` object. - \"targets\": test set targets. - \"features\":", "time.time() if lossfxn is None: lossfxn = AtomicMSELoss logger.info(\"\") logger.info(\"Training\")", "torch.tensor(u, requires_grad=False, dtype=torch.float) for u in uncertainty ] logger.info(\"\") logging.info(\"Batch", "Instead of using epochs, users can set a convergence criterion.", "else: test_model = self.model.eval() test_predictions = test_model(test_features).detach() rmse_test = client.submit(", "= model(inputs) if uncertainty == None: loss = lossfxn(outputs, targets[index],", "atoms_per_image = atoms_per_image.cuda() targets = targets.cuda() _inputs = OrderedDict() for", "[] # Accumulation of gradients for index, chunk in enumerate(chunks):", "svm=False)) uncertainty = [ torch.tensor(u, requires_grad=False, dtype=torch.float) for u in", "list(get_chunks(inputs, batch_size, svm=False)) targets = list(get_chunks(targets, batch_size, svm=False)) atoms_per_image =", "2. <NAME>. & <NAME> : A modular approach to machine", "def __init__(self, hiddenlayers=(3, 3), activation=\"relu\", **kwargs): super(DeepLearningModel, self).__init__() self.hiddenlayers =", "= torch.nn.Parameter( torch.tensor(intercept, requires_grad=True) ) slope = (data.max_energy - data.min_energy)", "{} minutes {:.2f} \\ seconds.\".format( h, m, s ) )", "device self.epochs = epochs self.model = model self.lr_scheduler = lr_scheduler", "keys,values of the dictionary are: - \"data\": a `Data` object.", "loss, \"max_ls\": 10} self.optimizer.step(options) # RMSE per image and per/atom", "saving all epochs, and the path is where the checkpoint", "structure: scheduler's name and a dictionary with keyword arguments. >>>", "two batches with 2 molecules each. # In the first", "dimension. data : object Data object created from the handler.", "self.device, ) # We step the optimizer if self.optimizer_name !=", "torch.nn.Parameter(torch.tensor(0.0)) self.register_parameter(intercept_name, intercept) self.register_parameter(slope_name, slope) for index in layers: #", "batch for N is 0. gradient = 0.0 gradients.append(gradient) return", "logger.info( \"{:6s} {:19s} {:12s} {:8s} {:8s}\".format( \"------\", \"-------------------\", \"------------\", \"------------\",", "Tensor with input data points in batch with index. targets", "sum(grads) for index, param in enumerate(model.parameters()): param.grad = torch.tensor(grads[index], dtype=torch.float)", "is None. lr_scheduler : tuple Tuple with structure: scheduler's name", "= np.array(grad, dtype=object) running_loss += loss outputs_.append(outputs) grads.append(grad) grads =", "elif purpose == \"inference\": intercept = torch.nn.Parameter(torch.tensor(0.0)) slope = torch.nn.Parameter(torch.tensor(0.0))", "torch.tensor(n_atoms, requires_grad=False, dtype=torch.float) for n_atoms in atoms_per_image ] targets =", "{:8s} {:8s}\".format( \"------\", \"-------------------\", \"------------\", \"------------\", \"------------\", \"------------\", \"------------\", )", "convergence self.device = device self.epochs = epochs self.model = model", "self.optimizer.step(options) # RMSE per image and per/atom rmse = client.submit(compute_rmse,", "10} self.optimizer.step(options) # RMSE per image and per/atom rmse =", "that lr_scheduler is not None if self.lr_scheduler is not None:", "with keyword arguments. >>> lr_scheduler = ('ReduceLROnPlateau', {'mode': 'min', 'patience':", "or cuda (gpu). batch_size : int Number of data points", "device : str Are we running cuda or cpu? Returns", "outputs_. Parameters ---------- Cls : object Class object. chunks :", "optimizer self.optimizer_name, self.optimizer = get_optimizer( optimizer, model.parameters() ) if lr_scheduler", "batch_size, svm=False)) atoms_per_image = list(get_chunks(atoms_per_image, batch_size, svm=False)) if uncertainty !=", "to compute the error over a validation/test set during training", "None) test_targets = self.test.get(\"targets\", None) test_data = self.test.get(\"data\", None) logger.info(", "{:12s} {:12s} {:12s} {:12s} {:16s}\".format( \"Epoch\", \"Time Stamp\", \"Loss\", \"Error/img\",", "of the neural network. Parameters ---------- image : dict Image", "98, 146401 (2007). 2. <NAME>. & <NAME> : A modular", "a tuple with the structure: >>> ('adam', {'lr': float, 'weight_decay'=float})", "dict Set checkpoints. Dictionary with following structure: >>> checkpoint =", "hashed feature space. targets : list The expected values that", "self.initial_time = time.time() if lossfxn is None: lossfxn = AtomicMSELoss", "\"(input, \" + str(self.hiddenlayers)[1:-1] + \", output)\" ) ) layers", "the error over a validation/test set during training procedures. >>>", "list of uncertainties that are used to penalize during the", "step the optimizer if self.optimizer_name != \"LBFGS\": self.optimizer.step() else: options", "modules and just intialize those that are # a linear", "on {}.\".format(now.strftime(\"%Y-%m-%d %H:%M:%S\")) ) logger.info(\"Model name: {}.\".format(self.name())) logger.info(\"Number of hidden-layers:", "+ data.min_energy) / 2.0 intercept = torch.nn.Parameter( torch.tensor(intercept, requires_grad=True) )", "in layers: # This is the input layer if index", ": list A list of uncertainties that are used to", "\"------------\", \"------------\", \"------------\", \"------------\", ) ) converged = False _loss", "of tensors with energies per image. \"\"\" outputs = []", "x in image: # FIXME this conditional can be removed", "we have only C, H, O but it turns out", "torch.stack(outputs) return outputs def get_activations(self, images, model=None, numpy=True): \"\"\"Get activations", "penalization: {pformat(uncertainty)}\") logger.info(\"\") atoms_per_image = data.atoms_per_image if batch_size is None:", "cls.NAME def __init__(self, hiddenlayers=(3, 3), activation=\"relu\", **kwargs): super(DeepLearningModel, self).__init__() self.hiddenlayers", "iterates over batches, accumulates the gradients, reduces the gradients, update", "molecules each. # In the first batch we have only", "Activation functions. Supported \"tanh\", \"relu\", or \"celu\". References ---------- 1.", "= self model.eval() for hash, data in images.items(): for index,", "chunk in chunks] self.targets = [client.scatter(target) for target in targets]", "except TypeError: unique_element_symbols = data.get_unique_element_symbols(purpose=purpose) unique_element_symbols = unique_element_symbols[purpose] symbol_model_pair =", "= convert_elapsed_time(move_time) logger.info( \"Data moved to GPU in {} hours", "{:12s} {:12s} {:8s}\".format( \"Epoch\", \"Time Stamp\", \"Loss\", \"Error/img\", \"Error/atom\" )", "= self.hiddenlayers[index - 1] out_dimension = 1 _linear = torch.nn.Linear(inp_dimension,", "self.closure, \"current_loss\": loss, \"max_ls\": 10} self.optimizer.step(options) # RMSE per image", "\"default.\" ) for m in self.modules(): if isinstance(m, torch.nn.Linear): #", "symbol, vector = features _inputs[hash].append((symbol, vector.cuda())) inputs = _inputs move_time", "np import pandas as pd from collections import OrderedDict from", "uncertainty = [ torch.tensor(u, requires_grad=False, dtype=torch.float) for u in uncertainty", "def __init__( self, inputs, targets, model=None, data=None, optimizer=(None, None), regularization=None,", "model Parameters ---------- inputs : dict Dictionary with hashed feature", "converged = True training_time = time.time() - self.initial_time h, m,", "not None and rmse < self.convergence[\"energy\"]: converged = True training_time", "checkpoint = {\"label\": label, \"checkpoint\": 100, \"path\": \"\"} `label` refers", "batch. \"\"\" inputs = OrderedDict(chunk) outputs = model(inputs) if uncertainty", "{\"features\": test_space, \"targets\": test_targets, \"data\": data_test} The keys,values of the", "mean=0, std=0.01) torch.nn.init.xavier_uniform_(m.weight) def forward(self, X): \"\"\"Forward propagation This is", "and outputs_. Parameters ---------- Cls : object Class object. chunks", ": obj Pytorch model to perform forward() and get gradients.", "batch. The # contribution of the total gradient from the", "logger.info(f\"Convergence criteria: {convergence}\") logger.info(f\"Loss function: {lossfxn.__name__}\") if uncertainty is not", "a convergence criterion. Supported keys are \"training\" and \"test\". lossfxn", "in image: # FIXME this conditional can be removed after", "_loss.append(loss.item()) _rmse.append(rmse) # In the case that lr_scheduler is not", "atoms_per_image, device ): \"\"\"A function that allows training per batches", "(data.max_energy + data.min_energy) / 2.0 intercept = torch.nn.Parameter( torch.tensor(intercept, requires_grad=True)", "variable that is following the gradient of certain # atom.", "\"\"\"Closure This class method clears previous gradients, iterates over batches,", "handler. optimizer : tuple The optimizer is a tuple with", "is None and epoch == self.epochs: converged = True elif", "used to save the checkpoint, `checkpoint` is a integer or", "import get_optimizer, get_lr_scheduler, get_lr from ml4chem.utils import convert_elapsed_time, get_chunks, get_number_of_parameters", "purpose == \"training\": logger.info(\" \") logger.info(\"Model\") logger.info(\"=====\") now = datetime.datetime.now()", "This function allows to extract activations of each hidden-layer of", "minutes {:.2f} seconds.\".format(h, m, s) ) @classmethod def closure( Cls,", "atoms_per_image.cuda() targets = targets.cuda() _inputs = OrderedDict() for hash, f", "{}.\".format(self.name())) logger.info(\"Number of hidden-layers: {}\".format(hl)) logger.info( \"Structure of Neural Net:", "self.hiddenlayers = hiddenlayers self.activation = activation def prepare_model(self, input_dimension, data=None,", "using `features.calculate()`. \"\"\" def __init__( self, inputs, targets, model=None, data=None,", "{} lr {}\".format(epoch, get_lr(self.optimizer))) ts = time.time() ts = datetime.datetime.fromtimestamp(ts).strftime(\"%Y-%m-%d", "(t)\", \"Error/atom (t)\", ) ) logger.info( \"{:6s} {:19s} {:12s} {:8s}", "= list(get_chunks(targets, batch_size, svm=False)) atoms_per_image = list(get_chunks(atoms_per_image, batch_size, svm=False)) if", "test # Data scattering client = dask.distributed.get_client() self.chunks = [client.scatter(chunk)", "= True training_time = time.time() - self.initial_time h, m, s", ": tensor or list Tensor with input data points in", "hash, data in images.items(): for index, (symbol, features) in enumerate(data):", "X: image = X[hash] atomic_energies = [] for symbol, x", "Phys. Commun. 207, 310–324 (2016). \"\"\" NAME = \"PytorchPotentials\" @classmethod", "the first batch for N is 0. gradient = 0.0", "case that lr_scheduler is not None if self.lr_scheduler is not", "regularization=None, epochs=100, convergence=None, lossfxn=None, device=\"cpu\", batch_size=None, lr_scheduler=None, uncertainty=None, checkpoint=None, test=None,", "in the neural network. activation : str Activation functions. Supported", "\"\"\" def __init__( self, inputs, targets, model=None, data=None, optimizer=(None, None),", "self.uncertainty, self.model, self.lossfxn, self.atoms_per_image, self.device, ) # We step the", "1) try: unique_element_symbols = data.unique_element_symbols[purpose] except TypeError: unique_element_symbols = data.get_unique_element_symbols(purpose=purpose)", "str Purpose of this model: 'training', 'inference'. \"\"\" self.input_dimension =", "self.linears = torch.nn.ModuleDict(symbol_model_pair) if purpose == \"training\": total_params, train_params =", "self.optimizer = get_optimizer( optimizer, model.parameters() ) if lr_scheduler is not", "None: logger.info( \"{:6s} {:19s} {:12s} {:12s} {:8s}\".format( \"Epoch\", \"Time Stamp\",", "Ref. 1 by Behler and Parrinello. Parameters ---------- hiddenlayers :", "scheduler client = dask.distributed.get_client() running_loss = torch.tensor(0, dtype=torch.float) accumulation =", "model has to learn aka y. model : object The", "lr_scheduler is not None if self.lr_scheduler is not None: self.scheduler.step(loss)", "gradient from the first batch for N is 0. gradient", "of hidden-layers: {}\".format(hl)) logger.info( \"Structure of Neural Net: {}\".format( \"(input,", "s = convert_elapsed_time(training_time) logger.info( \"Training finished in {} hours {}", "data.min_energy) / 2.0 slope = torch.nn.Parameter(torch.tensor(slope, requires_grad=True)) self.register_parameter(intercept_name, intercept) self.register_parameter(slope_name,", "per batch to use for training. Default is None. lr_scheduler", "chunk, targets, uncertainty, model, lossfxn, atoms_per_image, device, ), ) )", "AttributeError: # This exception catches the case where an image", "time.time() ts = datetime.datetime.fromtimestamp(ts).strftime(\"%Y-%m-%d \" \"%H:%M:%S\") if self.test is None:", "not # contain variable that is following the gradient of", "to extract activations of each hidden-layer of the neural network.", "None if self.lr_scheduler is not None: self.scheduler.step(loss) print(\"Epoch {} lr", "Number of full training cycles. regularization : float This is", "with Xavier Uniform by \" \"default.\" ) for m in", "This is the L2 regularization. It is not the same", "isinstance(batch_size, int): # Data batches chunks = list(get_chunks(inputs, batch_size, svm=False))", "gradients, reduces the gradients, update model params, and finally returns", "uncertainty, model, lossfxn, atoms_per_image, device ): \"\"\"A function that allows", "loss function evaluation. lossfxn : obj A loss function object.", "activations = [] columns = [\"hash\", \"atom.index\", \"atom.symbol\"] if model", "# This is the output layer elif index == len(self.hiddenlayers):", "is the input layer if index == 0: out_dimension =", "_inputs move_time = time.time() - self.initial_time h, m, s =", "= 0 client = dask.distributed.get_client() while not converged: epoch +=", "logger.info( \"{:6d} {} {:8e} {:4e} {:4e} {:4e} {:4e}\".format( epoch, ts,", "de/serialization # is fixed. if isinstance(symbol, bytes): symbol = symbol.decode(\"utf-8\")", "of batches: {}.\".format(len(chunks))) logging.info(\"Batch size: {} elements per batch.\".format(batch_size)) logger.info(\"", "(2007). 2. <NAME>. & <NAME> : A modular approach to", "DataFrame from lists df = pd.DataFrame(activations, columns=columns) return df class", "2 molecules each. # In the first batch we have", "---------- image : dict Image with structure hash, features. model", "starting logger object torch.set_printoptions(precision=10) logger = logging.getLogger() class NeuralNetwork(DeepLearningModel, torch.nn.Module):", "columns: columns.append(layer_column_name) counter += 1 layer_counter += 1 activations.append(data_) del", "self.scheduler.step(loss) print(\"Epoch {} lr {}\".format(epoch, get_lr(self.optimizer))) ts = time.time() ts", "lossfxn = AtomicMSELoss logger.info(\"\") logger.info(\"Training\") logger.info(\"========\") logger.info(f\"Convergence criteria: {convergence}\") logger.info(f\"Loss", "over a validation/test set during training procedures. >>> test =", "during the loss function evaluation. lossfxn : obj A loss", "= rmse.result() rmse_atom = rmse_atom.result() _loss.append(loss.item()) _rmse.append(rmse) # In the", "seconds.\".format(h, m, s) ) @classmethod def closure( Cls, chunks, targets,", "only C, H, O but it turns out that #", "get_number_of_parameters(self) logger.info(\"Total number of parameters: {}.\".format(total_params)) logger.info(\"Number of training parameters:", "*( index, chunk, targets, uncertainty, model, lossfxn, atoms_per_image, device, ),", "class\"\"\" logger.info(\" \") logger.info(\"Starting training...\\n\") if self.test is None: logger.info(", "= unique_element_symbols[purpose] symbol_model_pair = [] for symbol in unique_element_symbols: linears", "OrderedDict() for hash, f in inputs.items(): _inputs[hash] = [] for", "def prepare_model(self, input_dimension, data=None, purpose=\"training\"): \"\"\"Prepare the model Parameters ----------", ") ) if self.checkpoint is not None: self.checkpoint_save(epoch, self.model, **self.checkpoint)", "evaluation. checkpoint : dict Set checkpoints. Dictionary with following structure:", "client = dask.distributed.get_client() self.chunks = [client.scatter(chunk) for chunk in chunks]", "if numpy: data_.append(x.detach_().numpy()) else: data_.append(x.detach_()) layer_column_name = f\"layer{layer_counter}\" if layer_column_name", "forward propagation and it returns the atomic energy. Parameters ----------", "feature space. Returns ------- outputs : tensor A list of", "each hidden-layer This function allows to extract activations of each", "'min', 'patience': 10}) uncertainty : list A list of uncertainties", "from ml4chem.atomistic.models.loss import AtomicMSELoss from ml4chem.optim.handler import get_optimizer, get_lr_scheduler, get_lr", "(2016). \"\"\" NAME = \"PytorchPotentials\" @classmethod def name(cls): \"\"\"Returns name", "gradients, update model params, and finally returns loss and outputs_.", "symbol if purpose == \"training\": intercept = (data.max_energy + data.min_energy)", ") for m in self.modules(): if isinstance(m, torch.nn.Linear): # nn.init.normal_(m.weight)", "None: model = self model.eval() for hash, data in images.items():", ": object Data object created from the handler. optimizer :", "[ torch.tensor(u, requires_grad=False, dtype=torch.float) for u in uncertainty ] logger.info(\"\")", "Class object. chunks : tensor or list Tensor with input", "the input layer if index == 0: out_dimension = self.hiddenlayers[0]", "get_activations(self, images, model=None, numpy=True): \"\"\"Get activations of each hidden-layer This", "following the gradient of certain # atom. For example, suppose", "with activations for each layer. \"\"\" activations = [] columns", "---------- hiddenlayers : tuple Structure of hidden layers in the", "atoms_per_image[index]) else: loss = lossfxn( outputs, targets[index], atoms_per_image[index], uncertainty[index] )", "stored. Default is None and no checkpoint is saved. test", "over all modules and just intialize those that are #", "in the feature space. Returns ------- outputs : tensor A", "of uncertainties that are used to penalize during the loss", "network. activation : str Activation functions. Supported \"tanh\", \"relu\", or", "data_.append(x.detach_().numpy()) else: data_.append(x.detach_()) layer_column_name = f\"layer{layer_counter}\" if layer_column_name not in", "t in targets] if device == \"cuda\": logger.info(\"Moving data to", "dask.distributed.wait(accumulation) accumulation = client.gather(accumulation) for outputs, loss, grad in accumulation:", "machine learning in atomistic simulations. Comput. Phys. Commun. 207, 310–324", "object created from the handler. purpose : str Purpose of", "= layer(x) if numpy: data_.append(x.detach_().numpy()) else: data_.append(x.detach_()) layer_column_name = f\"layer{layer_counter}\"", "= (data.max_energy + data.min_energy) / 2.0 intercept = torch.nn.Parameter( torch.tensor(intercept,", "is None and no checkpoint is saved. test : dict", "loss.detach(), rmse, rmse_atom ) ) else: test_model = self.model.eval() test_predictions", "A loss function object. device : str Calculation can be", "self.lr_scheduler = lr_scheduler self.lossfxn = lossfxn self.checkpoint = checkpoint self.test", "enumerate(data): counter = 0 layer_counter = 0 for l, layer", "purpose == \"inference\": intercept = torch.nn.Parameter(torch.tensor(0.0)) slope = torch.nn.Parameter(torch.tensor(0.0)) self.register_parameter(intercept_name,", "\"targets\": test_targets, \"data\": data_test} The keys,values of the dictionary are:", "AtomicMSELoss logger.info(\"\") logger.info(\"Training\") logger.info(\"========\") logger.info(f\"Convergence criteria: {convergence}\") logger.info(f\"Loss function: {lossfxn.__name__}\")", "and finally returns loss and outputs_. Parameters ---------- Cls :", "= torch.nn.Parameter(torch.tensor(0.0)) slope = torch.nn.Parameter(torch.tensor(0.0)) self.register_parameter(intercept_name, intercept) self.register_parameter(slope_name, slope) for", "conditional can be removed after de/serialization # is fixed. if", "running cuda or cpu? Returns ------- loss : tensor The", "and counter > 0: x = layer(x) if numpy: data_.append(x.detach_().numpy())", "{} {:8e} {:4e} {:4e}\".format( epoch, ts, loss.detach(), rmse, rmse_atom )", "self.convergence = convergence self.device = device self.epochs = epochs self.model", "compute the error over a validation/test set during training procedures.", "rmse_atom ) ) else: test_model = self.model.eval() test_predictions = test_model(test_features).detach()", "ml4chem.utils import convert_elapsed_time, get_chunks, get_number_of_parameters from pprint import pformat #", ": A modular approach to machine learning in atomistic simulations.", "Comput. Phys. Commun. 207, 310–324 (2016). \"\"\" NAME = \"PytorchPotentials\"", "in uncertainty] else: self.uncertainty = uncertainty # Let the hunger", "[ torch.tensor(n_atoms, requires_grad=False, dtype=torch.float) for n_atoms in atoms_per_image ] targets", "linears = [] intercept_name = \"intercept_\" + symbol slope_name =", "= time.time() - self.initial_time h, m, s = convert_elapsed_time(training_time) logger.info(", "grads = [] # Accumulation of gradients for index, chunk", "object. numpy : bool Whether we want numpy arrays or", "{:8s}\".format( \"------\", \"-------------------\", \"------------\", \"------------\", \"------------\", ) ) else: test_features", "gradient = param.grad.detach().numpy() except AttributeError: # This exception catches the", "self.optimizer.zero_grad() # clear previous gradients loss, outputs_ = train.closure( self.chunks,", "model.parameters(): try: gradient = param.grad.detach().numpy() except AttributeError: # This exception", "{} hours {} minutes {:.2f} seconds.\".format(h, m, s) ) @classmethod", "torch.nn.Linear(inp_dimension, out_dimension) linears.append(_linear) # These are hidden-layers else: inp_dimension =", "methods. device : str Are we running cuda or cpu?", "\"\"\" outputs_ = [] # Get client to send futures", "same as weight decay. convergence : dict Instead of using", "float, 'weight_decay'=float}) epochs : int Number of full training cycles.", "that is following the gradient of certain # atom. For", "{'mode': 'min', 'patience': 10}) uncertainty : list A list of", "symbol in unique_element_symbols: linears = [] intercept_name = \"intercept_\" +", "True elif self.convergence is not None and rmse < self.convergence[\"energy\"]:", "linears.append(activation[self.activation]()) # Stacking up the layers. linears = torch.nn.Sequential(*linears) symbol_model_pair.append([symbol,", "is not None: self.checkpoint_save(epoch, self.model, **self.checkpoint) if self.convergence is None", "= sum(grads) for index, param in enumerate(model.parameters()): param.grad = torch.tensor(grads[index],", "str Activation functions. Supported \"tanh\", \"relu\", or \"celu\". References ----------", "if purpose == \"training\": intercept = (data.max_energy + data.min_energy) /", "# In the case that lr_scheduler is not None if", "from collections import OrderedDict from ml4chem.metrics import compute_rmse from ml4chem.atomistic.models.base", "nn.init.normal_(m.weight) # , mean=0, std=0.01) torch.nn.init.xavier_uniform_(m.weight) def forward(self, X): \"\"\"Forward", "`Data` object. - \"targets\": test set targets. - \"features\": a", "s ) ) logger.info(\" \") # Define optimizer self.optimizer_name, self.optimizer", "precision and starting logger object torch.set_printoptions(precision=10) logger = logging.getLogger() class", "train_params = get_number_of_parameters(self) logger.info(\"Total number of parameters: {}.\".format(total_params)) logger.info(\"Number of", "\"Loss\", \"Error/img\", \"Error/atom\", \"Error/img (t)\", \"Error/atom (t)\", ) ) logger.info(", "logger.info(\"Training\") logger.info(\"========\") logger.info(f\"Convergence criteria: {convergence}\") logger.info(f\"Loss function: {lossfxn.__name__}\") if uncertainty", "hidden-layers: {}\".format(hl)) logger.info( \"Structure of Neural Net: {}\".format( \"(input, \"", "in batch with index. targets : tensor or list The", "closure( Cls, chunks, targets, uncertainty, model, lossfxn, atoms_per_image, device ):", "criteria: {convergence}\") logger.info(f\"Loss function: {lossfxn.__name__}\") if uncertainty is not None:", "is the L2 regularization. It is not the same as", "counter == 0: x = layer(features) if numpy: data_ =", "loss function evaluation. checkpoint : dict Set checkpoints. Dictionary with", "inputs = OrderedDict(chunk) outputs = model(inputs) if uncertainty == None:", "and rmse < self.convergence[\"energy\"]: converged = True training_time = time.time()", "\"celu\". References ---------- 1. <NAME>. & <NAME>. Generalized Neural-Network Representation", "Returns ------- outputs : tensor A list of tensors with", "{} hours {} minutes {:.2f} \\ seconds.\".format( h, m, s", "= client.submit(compute_rmse, *(outputs_, self.targets)) atoms_per_image = torch.cat(self.atoms_per_image) rmse_atom = client.submit(", "= device self.epochs = epochs self.model = model self.lr_scheduler =", "\" \"%H:%M:%S\") if self.test is None: logger.info( \"{:6d} {} {:8e}", "\"Loss\", \"Error/img\", \"Error/atom\" ) ) logger.info( \"{:6s} {:19s} {:12s} {:8s}", "logger.info(f\"Loss function: {lossfxn.__name__}\") if uncertainty is not None: logger.info(\"Options:\") logger.info(f\"", "test_targets, atoms_per_image_test), ) rmse_test = rmse_test.result() rmse_atom_test = rmse_atom_test.result() logger.info(", "torch.nn.CELU, } hl = len(self.hiddenlayers) if purpose == \"training\": logger.info(\"", "\"tanh\", \"relu\", or \"celu\". References ---------- 1. <NAME>. & <NAME>.", "Rev. Lett. 98, 146401 (2007). 2. <NAME>. & <NAME> :", "\") logger.info(\"Model\") logger.info(\"=====\") now = datetime.datetime.now() logger.info( \"Module accessed on", "of inputs in the feature space. Returns ------- outputs :", "---------- inputs : dict Dictionary with hashed feature space. targets", "self.model, **self.checkpoint) if self.convergence is None and epoch == self.epochs:", "@classmethod def name(cls): \"\"\"Returns name of class\"\"\" return cls.NAME def", "be removed after de/serialization # is fixed. if isinstance(symbol, bytes):", "= (slope * x) + intercept atomic_energies.append(x) atomic_energies = torch.cat(atomic_energies)", "logging.info(\"Number of batches: {}.\".format(len(chunks))) logging.info(\"Batch size: {} elements per batch.\".format(batch_size))", "uncertainty # Let the hunger games begin... self.trainer() def trainer(self):", "the hunger games begin... self.trainer() def trainer(self): \"\"\"Run the training", "dict A dictionary used to compute the error over a", "u in uncertainty ] logger.info(\"\") logging.info(\"Batch Information\") logging.info(\"-----------------\") logging.info(\"Number of", "dtype=torch.float) del accumulation del grads return running_loss, outputs_ @classmethod def", "self.chunks = [client.scatter(chunk) for chunk in chunks] self.targets = [client.scatter(target)", "= layer(features) if numpy: data_ = [hash, index, symbol, x.detach_().numpy()]", "Accumulation of gradients for index, chunk in enumerate(chunks): accumulation.append( client.submit(", "self.modules(): if isinstance(m, torch.nn.Linear): # nn.init.normal_(m.weight) # , mean=0, std=0.01)", "enumerate(model.parameters()): param.grad = torch.tensor(grads[index], dtype=torch.float) del accumulation del grads return", "checkpoint is saved. test : dict A dictionary used to", "for n_atoms in atoms_per_image ] targets = [torch.tensor(t, requires_grad=False) for", "begin... self.trainer() def trainer(self): \"\"\"Run the training class\"\"\" logger.info(\" \")", "[client.scatter(target) for target in targets] if uncertainty != None: self.uncertainty", "activation def prepare_model(self, input_dimension, data=None, purpose=\"training\"): \"\"\"Prepare the model Parameters", "self model.eval() for hash, data in images.items(): for index, (symbol,", "loss, grad in accumulation: grad = np.array(grad, dtype=object) running_loss +=", "\"{:6d} {} {:8e} {:4e} {:4e} {:4e} {:4e}\".format( epoch, ts, loss.detach(),", "rmse = client.submit(compute_rmse, *(outputs_, self.targets)) atoms_per_image = torch.cat(self.atoms_per_image) rmse_atom =", ") dask.distributed.wait(accumulation) accumulation = client.gather(accumulation) for outputs, loss, grad in", "during the loss function evaluation. checkpoint : dict Set checkpoints.", "input_dimension, data=None, purpose=\"training\"): \"\"\"Prepare the model Parameters ---------- input_dimension :", "in {} hours {} minutes {:.2f} \\ seconds.\".format( h, m,", "dict Instead of using epochs, users can set a convergence", "data.min_energy) / 2.0 intercept = torch.nn.Parameter( torch.tensor(intercept, requires_grad=True) ) slope", "function object. device : str Calculation can be run in", "all epochs, and the path is where the checkpoint is", "np.array(grad, dtype=object) running_loss += loss outputs_.append(outputs) grads.append(grad) grads = sum(grads)", "= \"intercept_\" + symbol slope_name = \"slope_\" + symbol slope", "are: - \"data\": a `Data` object. - \"targets\": test set", "atom. For example, suppose two batches with 2 molecules each.", "name and a dictionary with keyword arguments. >>> lr_scheduler =", "None and rmse < self.convergence[\"energy\"]: converged = True training_time =", "!= None: self.uncertainty = [client.scatter(u) for u in uncertainty] else:", ") ) converged = False _loss = [] _rmse =", "[torch.tensor(t, requires_grad=False) for t in targets] if device == \"cuda\":", "uncertainty = list(get_chunks(uncertainty, batch_size, svm=False)) uncertainty = [ torch.tensor(u, requires_grad=False,", "atoms_per_image) ) rmse = rmse.result() rmse_atom = rmse_atom.result() _loss.append(loss.item()) _rmse.append(rmse)", "Input's dimension. data : object Data object created from the", "import datetime import logging import time import torch import numpy", "Phys. Rev. Lett. 98, 146401 (2007). 2. <NAME>. & <NAME>", "to penalize during the loss function evaluation. lossfxn : obj", "= OrderedDict(chunk) outputs = model(inputs) if uncertainty == None: loss", "] logger.info(\"\") logging.info(\"Batch Information\") logging.info(\"-----------------\") logging.info(\"Number of batches: {}.\".format(len(chunks))) logging.info(\"Batch", "convergence criterion. Supported keys are \"training\" and \"test\". lossfxn :", "targets.cuda() _inputs = OrderedDict() for hash, f in inputs.items(): _inputs[hash]", "cpu? Returns ------- loss : tensor The loss function of", "------- activations : DataFrame A DataFrame with activations for each", "import dask import datetime import logging import time import torch", "\"LBFGS\": self.optimizer.step() else: options = {\"closure\": self.closure, \"current_loss\": loss, \"max_ls\":", "= hiddenlayers self.activation = activation def prepare_model(self, input_dimension, data=None, purpose=\"training\"):", "\"Structure of Neural Net: {}\".format( \"(input, \" + str(self.hiddenlayers)[1:-1] +", "that # N is also available only in the second", "get gradients. uncertainty : list A list of uncertainties that", "in atomistic simulations. Comput. Phys. Commun. 207, 310–324 (2016). \"\"\"", "A list of uncertainties that are used to penalize during", "not the same as weight decay. convergence : dict Instead", "data=None, purpose=\"training\"): \"\"\"Prepare the model Parameters ---------- input_dimension : int", "this conditional can be removed after de/serialization # is fixed.", "else: test_features = self.test.get(\"features\", None) test_targets = self.test.get(\"targets\", None) test_data", "rmse_test = client.submit( compute_rmse, *(test_predictions, test_targets) ) atoms_per_image_test = torch.tensor(", "test_data.atoms_per_image, requires_grad=False ) rmse_atom_test = client.submit( compute_rmse, *(test_predictions, test_targets, atoms_per_image_test),", "perform forward() and get gradients. lossfxn : obj A loss", "= torch.nn.Linear(input_dimension, out_dimension) linears.append(_linear) linears.append(activation[self.activation]()) # This is the output", "\"inference\": intercept = torch.nn.Parameter(torch.tensor(0.0)) slope = torch.nn.Parameter(torch.tensor(0.0)) self.register_parameter(intercept_name, intercept) self.register_parameter(slope_name,", "fixed. if isinstance(symbol, bytes): symbol = symbol.decode(\"utf-8\") x = self.linears[symbol](x)", "epochs : int Number of full training cycles. regularization :", "= [ torch.tensor(u, requires_grad=False, dtype=torch.float) for u in uncertainty ]", "data_.append(x.detach_()) layer_column_name = f\"layer{layer_counter}\" if layer_column_name not in columns: columns.append(layer_column_name)", "import compute_rmse from ml4chem.atomistic.models.base import DeepLearningModel, DeepLearningTrainer from ml4chem.atomistic.models.loss import", "validation/test set during training procedures. >>> test = {\"features\": test_space,", ") atoms_per_image_test = torch.tensor( test_data.atoms_per_image, requires_grad=False ) rmse_atom_test = client.submit(", ": DataFrame A DataFrame with activations for each layer. \"\"\"", "None: self.checkpoint_save(epoch, self.model, **self.checkpoint) if self.convergence is None and epoch", "None) test_data = self.test.get(\"data\", None) logger.info( \"{:6s} {:19s} {:12s} {:12s}", "{:8e} {:4e} {:4e} {:4e} {:4e}\".format( epoch, ts, loss.detach(), rmse, rmse_atom,", "tensors with energies per image. \"\"\" outputs = [] for", ") ) layers = range(len(self.hiddenlayers) + 1) try: unique_element_symbols =", "catches the case where an image does not # contain", "# atom. For example, suppose two batches with 2 molecules", "obj Pytorch model to perform forward() and get gradients. uncertainty", ") ) dask.distributed.wait(accumulation) accumulation = client.gather(accumulation) for outputs, loss, grad", "lr {}\".format(epoch, get_lr(self.optimizer))) ts = time.time() ts = datetime.datetime.fromtimestamp(ts).strftime(\"%Y-%m-%d \"", "\\ seconds.\".format( h, m, s ) ) logger.info(\" \") #", "DataFrame with activations for each layer. \"\"\" activations = []", "Cls, index, chunk, targets, uncertainty, model, lossfxn, atoms_per_image, device ):", "targets, model=None, data=None, optimizer=(None, None), regularization=None, epochs=100, convergence=None, lossfxn=None, device=\"cpu\",", "logger.info( \"Training finished in {} hours {} minutes {:.2f} seconds.\".format(h,", "lists df = pd.DataFrame(activations, columns=columns) return df class train(DeepLearningTrainer): \"\"\"Train", "obj Pytorch model to perform forward() and get gradients. lossfxn", "atoms_per_image = [ torch.tensor(n_atoms, requires_grad=False, dtype=torch.float) for n_atoms in atoms_per_image", "minutes {:.2f} \\ seconds.\".format( h, m, s ) ) logger.info(\"", "1] out_dimension = 1 _linear = torch.nn.Linear(inp_dimension, out_dimension) linears.append(_linear) #", "the loss function evaluation. model : obj Pytorch model to", "list Atoms per image because we are doing atom-centered methods.", "Dictionary with following structure: >>> checkpoint = {\"label\": label, \"checkpoint\":", "\"%H:%M:%S\") if self.test is None: logger.info( \"{:6d} {} {:8e} {:4e}", "torch.tensor(grads[index], dtype=torch.float) del accumulation del grads return running_loss, outputs_ @classmethod", "for outputs, loss, grad in accumulation: grad = np.array(grad, dtype=object)", "want numpy arrays or tensors. Returns ------- activations : DataFrame", ": tensor or list The targets. model : obj Pytorch", "convert_elapsed_time(training_time) logger.info( \"Training finished in {} hours {} minutes {:.2f}", "------- loss : tensor The loss function of the batch.", "if isinstance(layer, torch.nn.Linear) and counter == 0: x = layer(features)", "moved to GPU in {} hours {} minutes {:.2f} \\", "in inputs.items(): _inputs[hash] = [] for features in f: symbol,", "values that the model has to learn aka y. model", "== \"training\": logger.info(\" \") logger.info(\"Model\") logger.info(\"=====\") now = datetime.datetime.now() logger.info(", ": dict Instead of using epochs, users can set a", "hours {} minutes {:.2f} \\ seconds.\".format( h, m, s )", "atoms_per_image, device, ), ) ) dask.distributed.wait(accumulation) accumulation = client.gather(accumulation) for", "= len(inputs.values()) if isinstance(batch_size, int): # Data batches chunks =", "= len(self.hiddenlayers) if purpose == \"training\": logger.info(\" \") logger.info(\"Model\") logger.info(\"=====\")", "are used to penalize during the loss function evaluation. model", "unique_element_symbols: linears = [] intercept_name = \"intercept_\" + symbol slope_name", "after de/serialization # is fixed. if isinstance(symbol, bytes): symbol =", ": tuple Tuple with structure: scheduler's name and a dictionary", "atomic_energies.append(x) atomic_energies = torch.cat(atomic_energies) image_energy = torch.sum(atomic_energies) outputs.append(image_energy) outputs =", "import torch import numpy as np import pandas as pd", "atoms_per_image : list Atoms per image because we are doing", "\"Error/atom\" ) ) logger.info( \"{:6s} {:19s} {:12s} {:8s} {:8s}\".format( \"------\",", "\"------\", \"-------------------\", \"------------\", \"------------\", \"------------\", ) ) else: test_features =", "chunk : tensor or list Tensor with input data points", "None: self.scheduler.step(loss) print(\"Epoch {} lr {}\".format(epoch, get_lr(self.optimizer))) ts = time.time()", "import convert_elapsed_time, get_chunks, get_number_of_parameters from pprint import pformat # Setting", "Data batches chunks = list(get_chunks(inputs, batch_size, svm=False)) targets = list(get_chunks(targets,", "function that allows training per batches Parameters ---------- index :", "set a convergence criterion. Supported keys are \"training\" and \"test\".", "datetime.datetime.fromtimestamp(ts).strftime(\"%Y-%m-%d \" \"%H:%M:%S\") if self.test is None: logger.info( \"{:6d} {}", ": object Data object created from the handler. purpose :", "{:19s} {:12s} {:12s} {:8s}\".format( \"Epoch\", \"Time Stamp\", \"Loss\", \"Error/img\", \"Error/atom\"", "[] columns = [\"hash\", \"atom.index\", \"atom.symbol\"] if model is None:", "can be run in the cpu or cuda (gpu). batch_size", "FIXME this conditional can be removed after de/serialization # is", "Cls, chunks, targets, uncertainty, model, lossfxn, atoms_per_image, device ): \"\"\"Closure", "uncertainty : list A list of uncertainties that are used", "del data_ # Create DataFrame from lists df = pd.DataFrame(activations,", "if self.test is None: logger.info( \"{:6s} {:19s} {:12s} {:12s} {:8s}\".format(", "<filename>ml4chem/atomistic/models/neuralnetwork.py import dask import datetime import logging import time import", "optimizer is a tuple with the structure: >>> ('adam', {'lr':", "loss = lossfxn( outputs, targets[index], atoms_per_image[index], uncertainty[index] ) loss.backward() gradients", "rmse.result() rmse_atom = rmse_atom.result() _loss.append(loss.item()) _rmse.append(rmse) # In the case", "rmse_atom = client.submit( compute_rmse, *(outputs_, self.targets, atoms_per_image) ) rmse =", "doing atom-centered methods. device : str Are we running cuda", "a dictionary with keyword arguments. >>> lr_scheduler = ('ReduceLROnPlateau', {'mode':", "_inputs[hash] = [] for features in f: symbol, vector =", "atoms_per_image = list(get_chunks(atoms_per_image, batch_size, svm=False)) if uncertainty != None: uncertainty", "Are we running cuda or cpu? Returns ------- loss :", "getattr(self, slope_name) intercept = getattr(self, intercept_name) x = (slope *", "logger.info(\"========\") logger.info(f\"Convergence criteria: {convergence}\") logger.info(f\"Loss function: {lossfxn.__name__}\") if uncertainty is", "m, s = convert_elapsed_time(training_time) logger.info( \"Training finished in {} hours", "rmse_atom_test, ) ) if self.checkpoint is not None: self.checkpoint_save(epoch, self.model,", "torch.set_printoptions(precision=10) logger = logging.getLogger() class NeuralNetwork(DeepLearningModel, torch.nn.Module): \"\"\"Atom-centered Neural Network", "= atoms_per_image.cuda() targets = targets.cuda() _inputs = OrderedDict() for hash,", "\"Time Stamp\", \"Loss\", \"Error/img\", \"Error/atom\", \"Error/img (t)\", \"Error/atom (t)\", )", "{}\".format(hl)) logger.info( \"Structure of Neural Net: {}\".format( \"(input, \" +", "---------- X : list List of inputs in the feature", "Parameters ---------- hiddenlayers : tuple Structure of hidden layers in", "counter += 1 layer_counter += 1 activations.append(data_) del data_ #", "torch.cat(self.atoms_per_image) rmse_atom = client.submit( compute_rmse, *(outputs_, self.targets, atoms_per_image) ) rmse", "= model self.lr_scheduler = lr_scheduler self.lossfxn = lossfxn self.checkpoint =", "example, suppose two batches with 2 molecules each. # In", "= [hash, index, symbol, x.detach_().numpy()] else: data_ = [hash, index,", "logger.info(\" \") atoms_per_image = [ torch.tensor(n_atoms, requires_grad=False, dtype=torch.float) for n_atoms", "neural network. activation : str Activation functions. Supported \"tanh\", \"relu\",", "in uncertainty ] logger.info(\"\") logging.info(\"Batch Information\") logging.info(\"-----------------\") logging.info(\"Number of batches:", "_inputs[hash].append((symbol, vector.cuda())) inputs = _inputs move_time = time.time() - self.initial_time", "{'lr': float, 'weight_decay'=float}) epochs : int Number of full training", "features. model : object A ML4Chem model object. numpy :", "def train_batches( Cls, index, chunk, targets, uncertainty, model, lossfxn, atoms_per_image,", "keyword arguments. >>> lr_scheduler = ('ReduceLROnPlateau', {'mode': 'min', 'patience': 10})", "logger.warning( \"Initialization of weights with Xavier Uniform by \" \"default.\"", "= AtomicMSELoss logger.info(\"\") logger.info(\"Training\") logger.info(\"========\") logger.info(f\"Convergence criteria: {convergence}\") logger.info(f\"Loss function:", "ml4chem.optim.handler import get_optimizer, get_lr_scheduler, get_lr from ml4chem.utils import convert_elapsed_time, get_chunks,", "!= None: uncertainty = list(get_chunks(uncertainty, batch_size, svm=False)) uncertainty = [", ") @classmethod def closure( Cls, chunks, targets, uncertainty, model, lossfxn,", "lossfxn(outputs, targets[index], atoms_per_image[index]) else: loss = lossfxn( outputs, targets[index], atoms_per_image[index],", "test_targets = self.test.get(\"targets\", None) test_data = self.test.get(\"data\", None) logger.info( \"{:6s}", "'weight_decay'=float}) epochs : int Number of full training cycles. regularization", "suppose two batches with 2 molecules each. # In the", "grads.append(grad) grads = sum(grads) for index, param in enumerate(model.parameters()): param.grad", "the batch. \"\"\" inputs = OrderedDict(chunk) outputs = model(inputs) if", "# Accumulation of gradients for index, chunk in enumerate(chunks): accumulation.append(", "for symbol in unique_element_symbols: linears = [] intercept_name = \"intercept_\"", "object Data object created from the handler. purpose : str", "linears.append(_linear) linears.append(activation[self.activation]()) # This is the output layer elif index", "test_targets) ) atoms_per_image_test = torch.tensor( test_data.atoms_per_image, requires_grad=False ) rmse_atom_test =", "unique_element_symbols = unique_element_symbols[purpose] symbol_model_pair = [] for symbol in unique_element_symbols:", "logger.info(\" \") # Define optimizer self.optimizer_name, self.optimizer = get_optimizer( optimizer,", "x = self.linears[symbol](x) intercept_name = \"intercept_\" + symbol slope_name =", "model to perform forward() and get gradients. uncertainty : list", "In the case that lr_scheduler is not None if self.lr_scheduler", "slope = (data.max_energy - data.min_energy) / 2.0 slope = torch.nn.Parameter(torch.tensor(slope,", ") if self.checkpoint is not None: self.checkpoint_save(epoch, self.model, **self.checkpoint) if", "import AtomicMSELoss from ml4chem.optim.handler import get_optimizer, get_lr_scheduler, get_lr from ml4chem.utils", "int Number of data points per batch to use for", "in unique_element_symbols: linears = [] intercept_name = \"intercept_\" + symbol", "= torch.nn.Sequential(*linears) symbol_model_pair.append([symbol, linears]) self.linears = torch.nn.ModuleDict(symbol_model_pair) if purpose ==", "is None: lossfxn = AtomicMSELoss logger.info(\"\") logger.info(\"Training\") logger.info(\"========\") logger.info(f\"Convergence criteria:", ") rmse_atom_test = client.submit( compute_rmse, *(test_predictions, test_targets, atoms_per_image_test), ) rmse_test", "Structure of hidden layers in the neural network. activation :", "elif isinstance(layer, torch.nn.Linear) and counter > 0: x = layer(x)", "O but it turns out that # N is also", "h, m, s = convert_elapsed_time(move_time) logger.info( \"Data moved to GPU", "per batches Parameters ---------- index : int Index of batch.", "in columns: columns.append(layer_column_name) counter += 1 layer_counter += 1 elif", "set during training procedures. >>> test = {\"features\": test_space, \"targets\":", "self.uncertainty = [client.scatter(u) for u in uncertainty] else: self.uncertainty =", "get_number_of_parameters from pprint import pformat # Setting precision and starting", "checkpoints. Dictionary with following structure: >>> checkpoint = {\"label\": label,", "batch. chunk : tensor or list Tensor with input data", "requires_grad=False ) rmse_atom_test = client.submit( compute_rmse, *(test_predictions, test_targets, atoms_per_image_test), )", "[] epoch = 0 client = dask.distributed.get_client() while not converged:", "list The targets. model : obj Pytorch model to perform", "Tuple with structure: scheduler's name and a dictionary with keyword", "learning in atomistic simulations. Comput. Phys. Commun. 207, 310–324 (2016).", "l, layer in enumerate(model.linears[symbol].modules()): if isinstance(layer, torch.nn.Linear) and counter ==", "svm=False)) atoms_per_image = list(get_chunks(atoms_per_image, batch_size, svm=False)) if uncertainty != None:", "layers: # This is the input layer if index ==", "and starting logger object torch.set_printoptions(precision=10) logger = logging.getLogger() class NeuralNetwork(DeepLearningModel,", "\"{:6d} {} {:8e} {:4e} {:4e}\".format( epoch, ts, loss.detach(), rmse, rmse_atom", "None: uncertainty = list(get_chunks(uncertainty, batch_size, svm=False)) uncertainty = [ torch.tensor(u,", ": tensor A list of tensors with energies per image.", "checkpoint is stored. Default is None and no checkpoint is", "if purpose == \"training\": logger.info(\" \") logger.info(\"Model\") logger.info(\"=====\") now =", "m, s = convert_elapsed_time(move_time) logger.info( \"Data moved to GPU in", "self.epochs: converged = True elif self.convergence is not None and", "+ symbol slope = getattr(self, slope_name) intercept = getattr(self, intercept_name)", "running_loss = torch.tensor(0, dtype=torch.float) accumulation = [] grads = []", "activation=\"relu\", **kwargs): super(DeepLearningModel, self).__init__() self.hiddenlayers = hiddenlayers self.activation = activation", "\"relu\", or \"celu\". References ---------- 1. <NAME>. & <NAME>. Generalized", "layer. logger.warning( \"Initialization of weights with Xavier Uniform by \"", "self.optimizer.step() else: options = {\"closure\": self.closure, \"current_loss\": loss, \"max_ls\": 10}", "while not converged: epoch += 1 self.optimizer.zero_grad() # clear previous", "\"slope_\" + symbol slope = getattr(self, slope_name) intercept = getattr(self,", "Setting precision and starting logger object torch.set_printoptions(precision=10) logger = logging.getLogger()", "list(get_chunks(uncertainty, batch_size, svm=False)) uncertainty = [ torch.tensor(u, requires_grad=False, dtype=torch.float) for", "= torch.cat(atomic_energies) image_energy = torch.sum(atomic_energies) outputs.append(image_energy) outputs = torch.stack(outputs) return", "[] for symbol in unique_element_symbols: linears = [] intercept_name =", "device, ), ) ) dask.distributed.wait(accumulation) accumulation = client.gather(accumulation) for outputs,", "+ 1) try: unique_element_symbols = data.unique_element_symbols[purpose] except TypeError: unique_element_symbols =", "activations of each hidden-layer This function allows to extract activations", "image: # FIXME this conditional can be removed after de/serialization", "are used to penalize during the loss function evaluation. lossfxn", "DeepLearningTrainer from ml4chem.atomistic.models.loss import AtomicMSELoss from ml4chem.optim.handler import get_optimizer, get_lr_scheduler,", "can be removed after de/serialization # is fixed. if isinstance(symbol,", "None: lossfxn = AtomicMSELoss logger.info(\"\") logger.info(\"Training\") logger.info(\"========\") logger.info(f\"Convergence criteria: {convergence}\")", "the L2 regularization. It is not the same as weight", "\"training\": logger.info(\" \") logger.info(\"Model\") logger.info(\"=====\") now = datetime.datetime.now() logger.info( \"Module", "= { \"tanh\": torch.nn.Tanh, \"relu\": torch.nn.ReLU, \"celu\": torch.nn.CELU, } hl", "total_params, train_params = get_number_of_parameters(self) logger.info(\"Total number of parameters: {}.\".format(total_params)) logger.info(\"Number", "\"------------\", \"------------\", ) ) converged = False _loss = []", "10}) uncertainty : list A list of uncertainties that are", "The loss function of the batch. \"\"\" inputs = OrderedDict(chunk)", "the handler. purpose : str Purpose of this model: 'training',", "[] for symbol, x in image: # FIXME this conditional", "batch_size=None, lr_scheduler=None, uncertainty=None, checkpoint=None, test=None, ): self.initial_time = time.time() if", "dask import datetime import logging import time import torch import", "= features _inputs[hash].append((symbol, vector.cuda())) inputs = _inputs move_time = time.time()", "data in images.items(): for index, (symbol, features) in enumerate(data): counter", "not None: logger.info(\"Options:\") logger.info(f\" - Uncertainty penalization: {pformat(uncertainty)}\") logger.info(\"\") atoms_per_image", ") logger.info( \"{:6s} {:19s} {:12s} {:8s} {:8s}\".format( \"------\", \"-------------------\", \"------------\",", "Pytorch model to perform forward() and get gradients. uncertainty :", "in enumerate(data): counter = 0 layer_counter = 0 for l,", "lossfxn( outputs, targets[index], atoms_per_image[index], uncertainty[index] ) loss.backward() gradients = []", "self.targets, self.uncertainty, self.model, self.lossfxn, self.atoms_per_image, self.device, ) # We step", ", mean=0, std=0.01) torch.nn.init.xavier_uniform_(m.weight) def forward(self, X): \"\"\"Forward propagation This", "+ symbol if purpose == \"training\": intercept = (data.max_energy +", "targets : list The expected values that the model has", "{}.\".format(len(chunks))) logging.info(\"Batch size: {} elements per batch.\".format(batch_size)) logger.info(\" \") atoms_per_image", "created from the handler. optimizer : tuple The optimizer is", "= [] for param in model.parameters(): try: gradient = param.grad.detach().numpy()", "= list(get_chunks(inputs, batch_size, svm=False)) targets = list(get_chunks(targets, batch_size, svm=False)) atoms_per_image", "---------- Cls : object Class object. chunks : tensor or", "Default is None and no checkpoint is saved. test :", "hidden-layers else: inp_dimension = self.hiddenlayers[index - 1] out_dimension = self.hiddenlayers[index]", "per image and per/atom rmse = client.submit(compute_rmse, *(outputs_, self.targets)) atoms_per_image", "{:16s}\".format( \"Epoch\", \"Time Stamp\", \"Loss\", \"Error/img\", \"Error/atom\", \"Error/img (t)\", \"Error/atom", "Parameters ---------- input_dimension : int Input's dimension. data : object", "== \"inference\": intercept = torch.nn.Parameter(torch.tensor(0.0)) slope = torch.nn.Parameter(torch.tensor(0.0)) self.register_parameter(intercept_name, intercept)", "inputs = _inputs move_time = time.time() - self.initial_time h, m,", "self, inputs, targets, model=None, data=None, optimizer=(None, None), regularization=None, epochs=100, convergence=None,", "list The expected values that the model has to learn", "Cls : object Class object. chunks : tensor or list", "loss.backward() gradients = [] for param in model.parameters(): try: gradient", "for N is 0. gradient = 0.0 gradients.append(gradient) return outputs,", "batches: {}.\".format(len(chunks))) logging.info(\"Batch size: {} elements per batch.\".format(batch_size)) logger.info(\" \")", ") converged = False _loss = [] _rmse = []", "time.time() - self.initial_time h, m, s = convert_elapsed_time(training_time) logger.info( \"Training", "running cuda or cpu? \"\"\" outputs_ = [] # Get", "else: data_.append(x.detach_()) layer_column_name = f\"layer{layer_counter}\" if layer_column_name not in columns:", "self.epochs = epochs self.model = model self.lr_scheduler = lr_scheduler self.lossfxn", "seconds.\".format( h, m, s ) ) logger.info(\" \") # Define", "targets[index], atoms_per_image[index]) else: loss = lossfxn( outputs, targets[index], atoms_per_image[index], uncertainty[index]", "\"-------------------\", \"------------\", \"------------\", \"------------\", ) ) else: test_features = self.test.get(\"features\",", "or list The targets. model : obj Pytorch model to", "weights with Xavier Uniform by \" \"default.\" ) for m", ": obj A loss function object. device : str Calculation", "else: loss = lossfxn( outputs, targets[index], atoms_per_image[index], uncertainty[index] ) loss.backward()", "Index of batch. chunk : tensor or list Tensor with", "the optimizer if self.optimizer_name != \"LBFGS\": self.optimizer.step() else: options =", "= {\"closure\": self.closure, \"current_loss\": loss, \"max_ls\": 10} self.optimizer.step(options) # RMSE", "targets = [torch.tensor(t, requires_grad=False) for t in targets] if device", "dtype=torch.float) accumulation = [] grads = [] # Accumulation of", ") logger.info(\" \") # Define optimizer self.optimizer_name, self.optimizer = get_optimizer(", "= [] for hash in X: image = X[hash] atomic_energies", "of hidden layers in the neural network. activation : str", "= dask.distributed.get_client() running_loss = torch.tensor(0, dtype=torch.float) accumulation = [] grads", "allows training per batches Parameters ---------- index : int Index", "image does not # contain variable that is following the", "client.submit( compute_rmse, *(test_predictions, test_targets, atoms_per_image_test), ) rmse_test = rmse_test.result() rmse_atom_test", "{}.\".format(train_params)) logger.info(\" \") logger.info(self.linears) # Iterate over all modules and", "self.lossfxn, self.atoms_per_image, self.device, ) # We step the optimizer if", "= torch.nn.Linear(inp_dimension, out_dimension) linears.append(_linear) linears.append(activation[self.activation]()) # Stacking up the layers.", "is not None and rmse < self.convergence[\"energy\"]: converged = True", "= torch.stack(outputs) return outputs def get_activations(self, images, model=None, numpy=True): \"\"\"Get", "# Let the hunger games begin... self.trainer() def trainer(self): \"\"\"Run", "None) logger.info( \"{:6s} {:19s} {:12s} {:12s} {:12s} {:12s} {:16s}\".format( \"Epoch\",", "counter > 0: x = layer(x) if numpy: data_.append(x.detach_().numpy()) else:", "lr_scheduler : tuple Tuple with structure: scheduler's name and a", "'inference'. \"\"\" self.input_dimension = input_dimension activation = { \"tanh\": torch.nn.Tanh,", "High-Dimensional Potential-Energy Surfaces. Phys. Rev. Lett. 98, 146401 (2007). 2.", "\"\"\" outputs = [] for hash in X: image =", "layer in enumerate(model.linears[symbol].modules()): if isinstance(layer, torch.nn.Linear) and counter == 0:", "does not # contain variable that is following the gradient", "self.input_dimension = input_dimension activation = { \"tanh\": torch.nn.Tanh, \"relu\": torch.nn.ReLU,", "= [client.scatter(target) for target in targets] if uncertainty != None:", "torch.nn.Parameter(torch.tensor(0.0)) slope = torch.nn.Parameter(torch.tensor(0.0)) self.register_parameter(intercept_name, intercept) self.register_parameter(slope_name, slope) for index", ") slope = (data.max_energy - data.min_energy) / 2.0 slope =", "Representation of High-Dimensional Potential-Energy Surfaces. Phys. Rev. Lett. 98, 146401", "# nn.init.normal_(m.weight) # , mean=0, std=0.01) torch.nn.init.xavier_uniform_(m.weight) def forward(self, X):", "try: unique_element_symbols = data.unique_element_symbols[purpose] except TypeError: unique_element_symbols = data.get_unique_element_symbols(purpose=purpose) unique_element_symbols", "*(outputs_, self.targets)) atoms_per_image = torch.cat(self.atoms_per_image) rmse_atom = client.submit( compute_rmse, *(outputs_,", "if uncertainty != None: uncertainty = list(get_chunks(uncertainty, batch_size, svm=False)) uncertainty", "\"------\", \"-------------------\", \"------------\", \"------------\", \"------------\", \"------------\", \"------------\", ) ) converged", ") loss.backward() gradients = [] for param in model.parameters(): try:", "= self.linears[symbol](x) intercept_name = \"intercept_\" + symbol slope_name = \"slope_\"", "to the scheduler client = dask.distributed.get_client() running_loss = torch.tensor(0, dtype=torch.float)", "for features in f: symbol, vector = features _inputs[hash].append((symbol, vector.cuda()))", "2.0 slope = torch.nn.Parameter(torch.tensor(slope, requires_grad=True)) self.register_parameter(intercept_name, intercept) self.register_parameter(slope_name, slope) elif", "%H:%M:%S\")) ) logger.info(\"Model name: {}.\".format(self.name())) logger.info(\"Number of hidden-layers: {}\".format(hl)) logger.info(", "= client.submit( compute_rmse, *(outputs_, self.targets, atoms_per_image) ) rmse = rmse.result()", "class train(DeepLearningTrainer): \"\"\"Train the model Parameters ---------- inputs : dict", "of each hidden-layer of the neural network. Parameters ---------- image", "symbol = symbol.decode(\"utf-8\") x = self.linears[symbol](x) intercept_name = \"intercept_\" +", "client.submit( compute_rmse, *(test_predictions, test_targets) ) atoms_per_image_test = torch.tensor( test_data.atoms_per_image, requires_grad=False", "params, and finally returns loss and outputs_. Parameters ---------- Cls", "penalize during the loss function evaluation. lossfxn : obj A", "that allows training per batches Parameters ---------- index : int", "model, lossfxn, atoms_per_image, device, ), ) ) dask.distributed.wait(accumulation) accumulation =", ") ) logger.info( \"{:6s} {:19s} {:12s} {:8s} {:8s} {:8s} {:8s}\".format(", ") if lr_scheduler is not None: self.scheduler = get_lr_scheduler(self.optimizer, lr_scheduler)", "N is 0. gradient = 0.0 gradients.append(gradient) return outputs, loss,", "dictionary used to compute the error over a validation/test set", "= torch.tensor(0, dtype=torch.float) accumulation = [] grads = [] #", "we running cuda or cpu? \"\"\" outputs_ = [] #", "\"Module accessed on {}.\".format(now.strftime(\"%Y-%m-%d %H:%M:%S\")) ) logger.info(\"Model name: {}.\".format(self.name())) logger.info(\"Number", "if model is None: model = self model.eval() for hash,", "\"\"\"Atom-centered Neural Network Regression with Pytorch This model is based", "= data.unique_element_symbols[purpose] except TypeError: unique_element_symbols = data.get_unique_element_symbols(purpose=purpose) unique_element_symbols = unique_element_symbols[purpose]", "= self.hiddenlayers[index] _linear = torch.nn.Linear(inp_dimension, out_dimension) linears.append(_linear) linears.append(activation[self.activation]()) # Stacking", "NAME = \"PytorchPotentials\" @classmethod def name(cls): \"\"\"Returns name of class\"\"\"", "device : str Are we running cuda or cpu? \"\"\"", "symbol.decode(\"utf-8\") x = self.linears[symbol](x) intercept_name = \"intercept_\" + symbol slope_name", "image_energy = torch.sum(atomic_energies) outputs.append(image_energy) outputs = torch.stack(outputs) return outputs def", "= [hash, index, symbol, x.detach_()] layer_column_name = f\"layer{layer_counter}\" if layer_column_name", "lossfxn self.checkpoint = checkpoint self.test = test # Data scattering", "converged = False _loss = [] _rmse = [] epoch", ": list Atoms per image because we are doing atom-centered", "the model Parameters ---------- input_dimension : int Input's dimension. data", "error over a validation/test set during training procedures. >>> test", "\"\"\" self.input_dimension = input_dimension activation = { \"tanh\": torch.nn.Tanh, \"relu\":", "the case that lr_scheduler is not None if self.lr_scheduler is", "x = layer(x) if numpy: data_.append(x.detach_().numpy()) else: data_.append(x.detach_()) layer_column_name =", "torch import numpy as np import pandas as pd from", "= range(len(self.hiddenlayers) + 1) try: unique_element_symbols = data.unique_element_symbols[purpose] except TypeError:", "set targets. - \"features\": a feature space obtained using `features.calculate()`.", "list of tensors with energies per image. \"\"\" outputs =", "\"\"\"Returns name of class\"\"\" return cls.NAME def __init__(self, hiddenlayers=(3, 3),", "function evaluation. lossfxn : obj A loss function object. atoms_per_image", "outputs = [] for hash in X: image = X[hash]", "if isinstance(batch_size, int): # Data batches chunks = list(get_chunks(inputs, batch_size,", "Uniform by \" \"default.\" ) for m in self.modules(): if", "previous gradients loss, outputs_ = train.closure( self.chunks, self.targets, self.uncertainty, self.model,", "with the structure: >>> ('adam', {'lr': float, 'weight_decay'=float}) epochs :", "for symbol, x in image: # FIXME this conditional can", "client.gather(accumulation) for outputs, loss, grad in accumulation: grad = np.array(grad,", "logger.info(\" \") logger.info(\"Model\") logger.info(\"=====\") now = datetime.datetime.now() logger.info( \"Module accessed", "an image does not # contain variable that is following", "logger.info(\"\") logging.info(\"Batch Information\") logging.info(\"-----------------\") logging.info(\"Number of batches: {}.\".format(len(chunks))) logging.info(\"Batch size:", "is a tuple with the structure: >>> ('adam', {'lr': float,", "training class\"\"\" logger.info(\" \") logger.info(\"Starting training...\\n\") if self.test is None:", "\"relu\": torch.nn.ReLU, \"celu\": torch.nn.CELU, } hl = len(self.hiddenlayers) if purpose", "import numpy as np import pandas as pd from collections", "where an image does not # contain variable that is", "class. data : object Data object created from the handler.", "logger.info(\"Model\") logger.info(\"=====\") now = datetime.datetime.now() logger.info( \"Module accessed on {}.\".format(now.strftime(\"%Y-%m-%d", "(slope * x) + intercept atomic_energies.append(x) atomic_energies = torch.cat(atomic_energies) image_energy", "= [] epoch = 0 client = dask.distributed.get_client() while not", "get gradients. lossfxn : obj A loss function object. atoms_per_image", "model is based on Ref. 1 by Behler and Parrinello.", "logging.info(\"Batch size: {} elements per batch.\".format(batch_size)) logger.info(\" \") atoms_per_image =", "a linear layer. logger.warning( \"Initialization of weights with Xavier Uniform", "output layer elif index == len(self.hiddenlayers): inp_dimension = self.hiddenlayers[index -", "unique_element_symbols = data.unique_element_symbols[purpose] except TypeError: unique_element_symbols = data.get_unique_element_symbols(purpose=purpose) unique_element_symbols =", "N is also available only in the second batch. The", "data : object Data object created from the handler. optimizer", "target in targets] if uncertainty != None: self.uncertainty = [client.scatter(u)", "of weights with Xavier Uniform by \" \"default.\" ) for", "\"test\". lossfxn : obj A loss function object. device :", "= False _loss = [] _rmse = [] epoch =", "chunk, targets, uncertainty, model, lossfxn, atoms_per_image, device ): \"\"\"A function", ": dict Set checkpoints. Dictionary with following structure: >>> checkpoint", "= pd.DataFrame(activations, columns=columns) return df class train(DeepLearningTrainer): \"\"\"Train the model", "activations for each layer. \"\"\" activations = [] columns =", "str Are we running cuda or cpu? \"\"\" outputs_ =", "= getattr(self, intercept_name) x = (slope * x) + intercept", "to CUDA...\") atoms_per_image = atoms_per_image.cuda() targets = targets.cuda() _inputs =", ") ) else: test_features = self.test.get(\"features\", None) test_targets = self.test.get(\"targets\",", "forward() and get gradients. uncertainty : list A list of", "cuda or cpu? Returns ------- loss : tensor The loss", "logger.info( \"{:6d} {} {:8e} {:4e} {:4e}\".format( epoch, ts, loss.detach(), rmse,", "model params, and finally returns loss and outputs_. Parameters ----------", "layer if index == 0: out_dimension = self.hiddenlayers[0] _linear =", "# This exception catches the case where an image does", "(symbol, features) in enumerate(data): counter = 0 layer_counter = 0", "is None: logger.info( \"{:6s} {:19s} {:12s} {:12s} {:8s}\".format( \"Epoch\", \"Time", "del grads return running_loss, outputs_ @classmethod def train_batches( Cls, index,", "convert_elapsed_time(move_time) logger.info( \"Data moved to GPU in {} hours {}", "OrderedDict(chunk) outputs = model(inputs) if uncertainty == None: loss =", "used to penalize during the loss function evaluation. checkpoint :", "for param in model.parameters(): try: gradient = param.grad.detach().numpy() except AttributeError:", "torch.sum(atomic_energies) outputs.append(image_energy) outputs = torch.stack(outputs) return outputs def get_activations(self, images,", "input layer if index == 0: out_dimension = self.hiddenlayers[0] _linear", "lr_scheduler self.lossfxn = lossfxn self.checkpoint = checkpoint self.test = test", "self).__init__() self.hiddenlayers = hiddenlayers self.activation = activation def prepare_model(self, input_dimension,", "= [torch.tensor(t, requires_grad=False) for t in targets] if device ==", "X[hash] atomic_energies = [] for symbol, x in image: #", "obtained using `features.calculate()`. \"\"\" def __init__( self, inputs, targets, model=None,", "= data.atoms_per_image if batch_size is None: batch_size = len(inputs.values()) if", "A loss function object. atoms_per_image : list Atoms per image", "logging import time import torch import numpy as np import", "with following structure: >>> checkpoint = {\"label\": label, \"checkpoint\": 100,", ": str Are we running cuda or cpu? Returns -------", "uncertainties that are used to penalize during the loss function", "outputs : tensor A list of tensors with energies per", "\"intercept_\" + symbol slope_name = \"slope_\" + symbol if purpose", "rmse = rmse.result() rmse_atom = rmse_atom.result() _loss.append(loss.item()) _rmse.append(rmse) # In", "---------- 1. <NAME>. & <NAME>. Generalized Neural-Network Representation of High-Dimensional", "== self.epochs: converged = True elif self.convergence is not None", "batches Parameters ---------- index : int Index of batch. chunk", "targets. uncertainty : list A list of uncertainties that are", "atomic_energies = torch.cat(atomic_energies) image_energy = torch.sum(atomic_energies) outputs.append(image_energy) outputs = torch.stack(outputs)", "= atoms_per_image self.convergence = convergence self.device = device self.epochs =", "obj A loss function object. device : str Calculation can", "and counter == 0: x = layer(features) if numpy: data_", "batch_size is None: batch_size = len(inputs.values()) if isinstance(batch_size, int): #", "= test # Data scattering client = dask.distributed.get_client() self.chunks =", "[] for features in f: symbol, vector = features _inputs[hash].append((symbol,", "m, s) ) @classmethod def closure( Cls, chunks, targets, uncertainty,", "= client.submit( compute_rmse, *(test_predictions, test_targets) ) atoms_per_image_test = torch.tensor( test_data.atoms_per_image,", "for chunk in chunks] self.targets = [client.scatter(target) for target in", "inp_dimension = self.hiddenlayers[index - 1] out_dimension = self.hiddenlayers[index] _linear =", "else: data_ = [hash, index, symbol, x.detach_()] layer_column_name = f\"layer{layer_counter}\"", ": dict A dictionary used to compute the error over", "slope) elif purpose == \"inference\": intercept = torch.nn.Parameter(torch.tensor(0.0)) slope =", "requires_grad=True)) self.register_parameter(intercept_name, intercept) self.register_parameter(slope_name, slope) elif purpose == \"inference\": intercept", "for u in uncertainty] else: self.uncertainty = uncertainty # Let", "data.get_unique_element_symbols(purpose=purpose) unique_element_symbols = unique_element_symbols[purpose] symbol_model_pair = [] for symbol in", "lossfxn, atoms_per_image, device ): \"\"\"Closure This class method clears previous", "\"checkpoint\": 100, \"path\": \"\"} `label` refers to the name used", "purpose == \"training\": total_params, train_params = get_number_of_parameters(self) logger.info(\"Total number of", "= targets.cuda() _inputs = OrderedDict() for hash, f in inputs.items():", "\"path\": \"\"} `label` refers to the name used to save", "return cls.NAME def __init__(self, hiddenlayers=(3, 3), activation=\"relu\", **kwargs): super(DeepLearningModel, self).__init__()", "time.time() - self.initial_time h, m, s = convert_elapsed_time(move_time) logger.info( \"Data", "torch.nn.Sequential(*linears) symbol_model_pair.append([symbol, linears]) self.linears = torch.nn.ModuleDict(symbol_model_pair) if purpose == \"training\":", "+= 1 layer_counter += 1 activations.append(data_) del data_ # Create", "be run in the cpu or cuda (gpu). batch_size :", "ml4chem.atomistic.models.loss import AtomicMSELoss from ml4chem.optim.handler import get_optimizer, get_lr_scheduler, get_lr from", "- Uncertainty penalization: {pformat(uncertainty)}\") logger.info(\"\") atoms_per_image = data.atoms_per_image if batch_size", "the training class\"\"\" logger.info(\" \") logger.info(\"Starting training...\\n\") if self.test is", "= lossfxn( outputs, targets[index], atoms_per_image[index], uncertainty[index] ) loss.backward() gradients =", "= {\"features\": test_space, \"targets\": test_targets, \"data\": data_test} The keys,values of", "ml4chem.atomistic.models.base import DeepLearningModel, DeepLearningTrainer from ml4chem.atomistic.models.loss import AtomicMSELoss from ml4chem.optim.handler", "structure hash, features. model : object A ML4Chem model object.", ": str Are we running cuda or cpu? \"\"\" outputs_", "if lr_scheduler is not None: self.scheduler = get_lr_scheduler(self.optimizer, lr_scheduler) self.atoms_per_image", "x.detach_()] layer_column_name = f\"layer{layer_counter}\" if layer_column_name not in columns: columns.append(layer_column_name)", "or list The targets. uncertainty : list A list of", "activations.append(data_) del data_ # Create DataFrame from lists df =", "cycles. regularization : float This is the L2 regularization. It", "network. Parameters ---------- image : dict Image with structure hash,", "Neural-Network Representation of High-Dimensional Potential-Energy Surfaces. Phys. Rev. Lett. 98,", "those that are # a linear layer. logger.warning( \"Initialization of", "self.register_parameter(slope_name, slope) for index in layers: # This is the", "self.initial_time h, m, s = convert_elapsed_time(training_time) logger.info( \"Training finished in", "3), activation=\"relu\", **kwargs): super(DeepLearningModel, self).__init__() self.hiddenlayers = hiddenlayers self.activation =", "Image with structure hash, features. model : object A ML4Chem", "\"current_loss\": loss, \"max_ls\": 10} self.optimizer.step(options) # RMSE per image and", "{}\".format(epoch, get_lr(self.optimizer))) ts = time.time() ts = datetime.datetime.fromtimestamp(ts).strftime(\"%Y-%m-%d \" \"%H:%M:%S\")", "layer_column_name not in columns: columns.append(layer_column_name) counter += 1 layer_counter +=", "m in self.modules(): if isinstance(m, torch.nn.Linear): # nn.init.normal_(m.weight) # ,", "= time.time() ts = datetime.datetime.fromtimestamp(ts).strftime(\"%Y-%m-%d \" \"%H:%M:%S\") if self.test is", "\"Error/img (t)\", \"Error/atom (t)\", ) ) logger.info( \"{:6s} {:19s} {:12s}", "== \"training\": total_params, train_params = get_number_of_parameters(self) logger.info(\"Total number of parameters:", "\"max_ls\": 10} self.optimizer.step(options) # RMSE per image and per/atom rmse", "('ReduceLROnPlateau', {'mode': 'min', 'patience': 10}) uncertainty : list A list", "= lossfxn self.checkpoint = checkpoint self.test = test # Data", "full training cycles. regularization : float This is the L2", "self.test.get(\"data\", None) logger.info( \"{:6s} {:19s} {:12s} {:12s} {:12s} {:12s} {:16s}\".format(", "in accumulation: grad = np.array(grad, dtype=object) running_loss += loss outputs_.append(outputs)", "= self.test.get(\"features\", None) test_targets = self.test.get(\"targets\", None) test_data = self.test.get(\"data\",", "<NAME>. & <NAME> : A modular approach to machine learning", "in images.items(): for index, (symbol, features) in enumerate(data): counter =", "{:19s} {:12s} {:8s} {:8s} {:8s} {:8s}\".format( \"------\", \"-------------------\", \"------------\", \"------------\",", "atomistic simulations. Comput. Phys. Commun. 207, 310–324 (2016). \"\"\" NAME", "pformat # Setting precision and starting logger object torch.set_printoptions(precision=10) logger", "isinstance(layer, torch.nn.Linear) and counter > 0: x = layer(x) if", "Number of data points per batch to use for training.", "of using epochs, users can set a convergence criterion. Supported", "the path is where the checkpoint is stored. Default is", "to send futures to the scheduler client = dask.distributed.get_client() running_loss", "= 0 for l, layer in enumerate(model.linears[symbol].modules()): if isinstance(layer, torch.nn.Linear)", "train(DeepLearningTrainer): \"\"\"Train the model Parameters ---------- inputs : dict Dictionary", "= \"intercept_\" + symbol slope_name = \"slope_\" + symbol if", "logger.info(\"Number of hidden-layers: {}\".format(hl)) logger.info( \"Structure of Neural Net: {}\".format(", "hidden-layer This function allows to extract activations of each hidden-layer", "are used to penalize during the loss function evaluation. checkpoint", "tensor or list The targets. uncertainty : list A list", "self.checkpoint = checkpoint self.test = test # Data scattering client", "{:4e}\".format( epoch, ts, loss.detach(), rmse, rmse_atom, rmse_test, rmse_atom_test, ) )", "): \"\"\"A function that allows training per batches Parameters ----------", "\"Error/img\", \"Error/atom\", \"Error/img (t)\", \"Error/atom (t)\", ) ) logger.info( \"{:6s}", "# Data batches chunks = list(get_chunks(inputs, batch_size, svm=False)) targets =", "optimizer if self.optimizer_name != \"LBFGS\": self.optimizer.step() else: options = {\"closure\":", "layer. \"\"\" activations = [] columns = [\"hash\", \"atom.index\", \"atom.symbol\"]", "the layers. linears = torch.nn.Sequential(*linears) symbol_model_pair.append([symbol, linears]) self.linears = torch.nn.ModuleDict(symbol_model_pair)", "is forward propagation and it returns the atomic energy. Parameters", "atomic energy. Parameters ---------- X : list List of inputs", "- self.initial_time h, m, s = convert_elapsed_time(move_time) logger.info( \"Data moved", "{:8s}\".format( \"Epoch\", \"Time Stamp\", \"Loss\", \"Error/img\", \"Error/atom\" ) ) logger.info(", "targets = targets.cuda() _inputs = OrderedDict() for hash, f in", "function: {lossfxn.__name__}\") if uncertainty is not None: logger.info(\"Options:\") logger.info(f\" -", "uncertainty, model, lossfxn, atoms_per_image, device ): \"\"\"Closure This class method", "from the first batch for N is 0. gradient =", "Are we running cuda or cpu? \"\"\" outputs_ = []", "atoms_per_image = torch.cat(self.atoms_per_image) rmse_atom = client.submit( compute_rmse, *(outputs_, self.targets, atoms_per_image)", "inputs in the feature space. Returns ------- outputs : tensor", "310–324 (2016). \"\"\" NAME = \"PytorchPotentials\" @classmethod def name(cls): \"\"\"Returns", "compute_rmse, *(test_predictions, test_targets, atoms_per_image_test), ) rmse_test = rmse_test.result() rmse_atom_test =", "Create DataFrame from lists df = pd.DataFrame(activations, columns=columns) return df", "self.linears[symbol](x) intercept_name = \"intercept_\" + symbol slope_name = \"slope_\" +", "Parrinello. Parameters ---------- hiddenlayers : tuple Structure of hidden layers", "= datetime.datetime.now() logger.info( \"Module accessed on {}.\".format(now.strftime(\"%Y-%m-%d %H:%M:%S\")) ) logger.info(\"Model", "running_loss, outputs_ @classmethod def train_batches( Cls, index, chunk, targets, uncertainty,", "if batch_size is None: batch_size = len(inputs.values()) if isinstance(batch_size, int):", "layer(x) if numpy: data_.append(x.detach_().numpy()) else: data_.append(x.detach_()) layer_column_name = f\"layer{layer_counter}\" if", "requires_grad=False) for t in targets] if device == \"cuda\": logger.info(\"Moving", "= [] _rmse = [] epoch = 0 client =", "grads return running_loss, outputs_ @classmethod def train_batches( Cls, index, chunk,", "A ML4Chem model object. numpy : bool Whether we want", "{:12s} {:12s} {:16s}\".format( \"Epoch\", \"Time Stamp\", \"Loss\", \"Error/img\", \"Error/atom\", \"Error/img", "and just intialize those that are # a linear layer.", "self.hiddenlayers[index] _linear = torch.nn.Linear(inp_dimension, out_dimension) linears.append(_linear) linears.append(activation[self.activation]()) # Stacking up", "rmse_test = rmse_test.result() rmse_atom_test = rmse_atom_test.result() logger.info( \"{:6d} {} {:8e}", "model Parameters ---------- input_dimension : int Input's dimension. data :", "hash, f in inputs.items(): _inputs[hash] = [] for features in", "client to send futures to the scheduler client = dask.distributed.get_client()", "rmse_atom_test = client.submit( compute_rmse, *(test_predictions, test_targets, atoms_per_image_test), ) rmse_test =", "if index == 0: out_dimension = self.hiddenlayers[0] _linear = torch.nn.Linear(input_dimension,", "[] grads = [] # Accumulation of gradients for index,", "exception catches the case where an image does not #", "and get gradients. lossfxn : obj A loss function object.", "Data scattering client = dask.distributed.get_client() self.chunks = [client.scatter(chunk) for chunk", "per image because we are doing atom-centered methods. device :", "rmse, rmse_atom ) ) else: test_model = self.model.eval() test_predictions =", "index. targets : tensor or list The targets. model :", "h, m, s ) ) logger.info(\" \") # Define optimizer", "= checkpoint self.test = test # Data scattering client =", "{}.\".format(total_params)) logger.info(\"Number of training parameters: {}.\".format(train_params)) logger.info(\" \") logger.info(self.linears) #", "datetime import logging import time import torch import numpy as", "in the second batch. The # contribution of the total", "\"targets\": test set targets. - \"features\": a feature space obtained", "self.model.eval() test_predictions = test_model(test_features).detach() rmse_test = client.submit( compute_rmse, *(test_predictions, test_targets)", "= input_dimension activation = { \"tanh\": torch.nn.Tanh, \"relu\": torch.nn.ReLU, \"celu\":", "in the cpu or cuda (gpu). batch_size : int Number", "batch we have only C, H, O but it turns", "= torch.nn.ModuleDict(symbol_model_pair) if purpose == \"training\": total_params, train_params = get_number_of_parameters(self)", "logging.getLogger() class NeuralNetwork(DeepLearningModel, torch.nn.Module): \"\"\"Atom-centered Neural Network Regression with Pytorch", "# These are hidden-layers else: inp_dimension = self.hiddenlayers[index - 1]", "torch.nn.ReLU, \"celu\": torch.nn.CELU, } hl = len(self.hiddenlayers) if purpose ==", "= torch.nn.Parameter(torch.tensor(0.0)) self.register_parameter(intercept_name, intercept) self.register_parameter(slope_name, slope) for index in layers:", "= [] columns = [\"hash\", \"atom.index\", \"atom.symbol\"] if model is", "== 0: x = layer(features) if numpy: data_ = [hash,", "of class\"\"\" return cls.NAME def __init__(self, hiddenlayers=(3, 3), activation=\"relu\", **kwargs):", "are doing atom-centered methods. device : str Are we running", "= client.submit( compute_rmse, *(test_predictions, test_targets, atoms_per_image_test), ) rmse_test = rmse_test.result()", "is also available only in the second batch. The #", "torch.nn.Linear(input_dimension, out_dimension) linears.append(_linear) linears.append(activation[self.activation]()) # This is the output layer", "dtype=torch.float) for n_atoms in atoms_per_image ] targets = [torch.tensor(t, requires_grad=False)", ") ) else: test_model = self.model.eval() test_predictions = test_model(test_features).detach() rmse_test", "of the dictionary are: - \"data\": a `Data` object. -", "the scheduler client = dask.distributed.get_client() running_loss = torch.tensor(0, dtype=torch.float) accumulation", "self.checkpoint is not None: self.checkpoint_save(epoch, self.model, **self.checkpoint) if self.convergence is", "list A list of uncertainties that are used to penalize", ": float This is the L2 regularization. It is not", "= convergence self.device = device self.epochs = epochs self.model =", "to the name used to save the checkpoint, `checkpoint` is", "second batch. The # contribution of the total gradient from", "TypeError: unique_element_symbols = data.get_unique_element_symbols(purpose=purpose) unique_element_symbols = unique_element_symbols[purpose] symbol_model_pair = []", "requires_grad=True) ) slope = (data.max_energy - data.min_energy) / 2.0 slope", ") else: test_model = self.model.eval() test_predictions = test_model(test_features).detach() rmse_test =", "= torch.nn.Linear(inp_dimension, out_dimension) linears.append(_linear) # These are hidden-layers else: inp_dimension", "to save the checkpoint, `checkpoint` is a integer or -1", "test_model(test_features).detach() rmse_test = client.submit( compute_rmse, *(test_predictions, test_targets) ) atoms_per_image_test =", "Parameters ---------- image : dict Image with structure hash, features.", "ML4Chem model object. numpy : bool Whether we want numpy", "), ) ) dask.distributed.wait(accumulation) accumulation = client.gather(accumulation) for outputs, loss,", "layer(features) if numpy: data_ = [hash, index, symbol, x.detach_().numpy()] else:", "outputs = torch.stack(outputs) return outputs def get_activations(self, images, model=None, numpy=True):", "save the checkpoint, `checkpoint` is a integer or -1 for", "= torch.cat(self.atoms_per_image) rmse_atom = client.submit( compute_rmse, *(outputs_, self.targets, atoms_per_image) )", "uncertainty ] logger.info(\"\") logging.info(\"Batch Information\") logging.info(\"-----------------\") logging.info(\"Number of batches: {}.\".format(len(chunks)))", "def forward(self, X): \"\"\"Forward propagation This is forward propagation and", "can set a convergence criterion. Supported keys are \"training\" and", "{} elements per batch.\".format(batch_size)) logger.info(\" \") atoms_per_image = [ torch.tensor(n_atoms,", "# We step the optimizer if self.optimizer_name != \"LBFGS\": self.optimizer.step()", "loss = lossfxn(outputs, targets[index], atoms_per_image[index]) else: loss = lossfxn( outputs,", "{:19s} {:12s} {:8s} {:8s}\".format( \"------\", \"-------------------\", \"------------\", \"------------\", \"------------\", )", "pd.DataFrame(activations, columns=columns) return df class train(DeepLearningTrainer): \"\"\"Train the model Parameters", "= torch.sum(atomic_energies) outputs.append(image_energy) outputs = torch.stack(outputs) return outputs def get_activations(self,", "= torch.tensor( test_data.atoms_per_image, requires_grad=False ) rmse_atom_test = client.submit( compute_rmse, *(test_predictions,", "= [] # Get client to send futures to the", "index, symbol, x.detach_()] layer_column_name = f\"layer{layer_counter}\" if layer_column_name not in", "= \"PytorchPotentials\" @classmethod def name(cls): \"\"\"Returns name of class\"\"\" return", "options = {\"closure\": self.closure, \"current_loss\": loss, \"max_ls\": 10} self.optimizer.step(options) #", "input data points in batch with index. targets : tensor", "the first batch we have only C, H, O but", "name of class\"\"\" return cls.NAME def __init__(self, hiddenlayers=(3, 3), activation=\"relu\",", "vector.cuda())) inputs = _inputs move_time = time.time() - self.initial_time h,", "accumulation.append( client.submit( train.train_batches, *( index, chunk, targets, uncertainty, model, lossfxn,", "\"\"\" activations = [] columns = [\"hash\", \"atom.index\", \"atom.symbol\"] if", "if numpy: data_ = [hash, index, symbol, x.detach_().numpy()] else: data_", "== \"cuda\": logger.info(\"Moving data to CUDA...\") atoms_per_image = atoms_per_image.cuda() targets", "= activation def prepare_model(self, input_dimension, data=None, purpose=\"training\"): \"\"\"Prepare the model", "accumulation = [] grads = [] # Accumulation of gradients", "logger.info(\"Number of training parameters: {}.\".format(train_params)) logger.info(\" \") logger.info(self.linears) # Iterate", "self.model, self.lossfxn, self.atoms_per_image, self.device, ) # We step the optimizer", "_linear = torch.nn.Linear(inp_dimension, out_dimension) linears.append(_linear) linears.append(activation[self.activation]()) # Stacking up the", "\"------------\", ) ) else: test_features = self.test.get(\"features\", None) test_targets =", "from the handler. optimizer : tuple The optimizer is a", "training cycles. regularization : float This is the L2 regularization.", "logger.info(f\" - Uncertainty penalization: {pformat(uncertainty)}\") logger.info(\"\") atoms_per_image = data.atoms_per_image if", "images, model=None, numpy=True): \"\"\"Get activations of each hidden-layer This function", "{convergence}\") logger.info(f\"Loss function: {lossfxn.__name__}\") if uncertainty is not None: logger.info(\"Options:\")", "in self.modules(): if isinstance(m, torch.nn.Linear): # nn.init.normal_(m.weight) # , mean=0,", "batch with index. targets : tensor or list The targets.", "if uncertainty == None: loss = lossfxn(outputs, targets[index], atoms_per_image[index]) else:", "logger.info(\" \") logger.info(self.linears) # Iterate over all modules and just", "self.targets, atoms_per_image) ) rmse = rmse.result() rmse_atom = rmse_atom.result() _loss.append(loss.item())", ") rmse_test = rmse_test.result() rmse_atom_test = rmse_atom_test.result() logger.info( \"{:6d} {}", "feature space obtained using `features.calculate()`. \"\"\" def __init__( self, inputs,", "compute_rmse, *(outputs_, self.targets, atoms_per_image) ) rmse = rmse.result() rmse_atom =", "Potential-Energy Surfaces. Phys. Rev. Lett. 98, 146401 (2007). 2. <NAME>.", "image = X[hash] atomic_energies = [] for symbol, x in", "numpy as np import pandas as pd from collections import", "model is None: model = self model.eval() for hash, data", "super(DeepLearningModel, self).__init__() self.hiddenlayers = hiddenlayers self.activation = activation def prepare_model(self,", "logger object torch.set_printoptions(precision=10) logger = logging.getLogger() class NeuralNetwork(DeepLearningModel, torch.nn.Module): \"\"\"Atom-centered", "{:.2f} \\ seconds.\".format( h, m, s ) ) logger.info(\" \")", "{ \"tanh\": torch.nn.Tanh, \"relu\": torch.nn.ReLU, \"celu\": torch.nn.CELU, } hl =", "/ 2.0 slope = torch.nn.Parameter(torch.tensor(slope, requires_grad=True)) self.register_parameter(intercept_name, intercept) self.register_parameter(slope_name, slope)", "out_dimension) linears.append(_linear) linears.append(activation[self.activation]()) # Stacking up the layers. linears =", "that the model has to learn aka y. model :", "self.test is None: logger.info( \"{:6d} {} {:8e} {:4e} {:4e}\".format( epoch,", "users can set a convergence criterion. Supported keys are \"training\"", "it returns the atomic energy. Parameters ---------- X : list", "class NeuralNetwork(DeepLearningModel, torch.nn.Module): \"\"\"Atom-centered Neural Network Regression with Pytorch This", "dask.distributed.get_client() while not converged: epoch += 1 self.optimizer.zero_grad() # clear", "model(inputs) if uncertainty == None: loss = lossfxn(outputs, targets[index], atoms_per_image[index])", "s) ) @classmethod def closure( Cls, chunks, targets, uncertainty, model,", "\"data\": a `Data` object. - \"targets\": test set targets. -", ": str Activation functions. Supported \"tanh\", \"relu\", or \"celu\". References", "self.targets)) atoms_per_image = torch.cat(self.atoms_per_image) rmse_atom = client.submit( compute_rmse, *(outputs_, self.targets,", "with hashed feature space. targets : list The expected values", "= logging.getLogger() class NeuralNetwork(DeepLearningModel, torch.nn.Module): \"\"\"Atom-centered Neural Network Regression with", "that are used to penalize during the loss function evaluation.", "{:12s} {:12s} {:12s} {:16s}\".format( \"Epoch\", \"Time Stamp\", \"Loss\", \"Error/img\", \"Error/atom\",", "in targets] if device == \"cuda\": logger.info(\"Moving data to CUDA...\")", "pd from collections import OrderedDict from ml4chem.metrics import compute_rmse from", "in X: image = X[hash] atomic_energies = [] for symbol,", "outputs_.append(outputs) grads.append(grad) grads = sum(grads) for index, param in enumerate(model.parameters()):", "batch_size, svm=False)) targets = list(get_chunks(targets, batch_size, svm=False)) atoms_per_image = list(get_chunks(atoms_per_image,", "svm=False)) targets = list(get_chunks(targets, batch_size, svm=False)) atoms_per_image = list(get_chunks(atoms_per_image, batch_size,", "hiddenlayers self.activation = activation def prepare_model(self, input_dimension, data=None, purpose=\"training\"): \"\"\"Prepare", "if isinstance(symbol, bytes): symbol = symbol.decode(\"utf-8\") x = self.linears[symbol](x) intercept_name", "is not None: self.scheduler.step(loss) print(\"Epoch {} lr {}\".format(epoch, get_lr(self.optimizer))) ts", "not None: self.checkpoint_save(epoch, self.model, **self.checkpoint) if self.convergence is None and", "tensor or list Tensor with input data points in batch", "torch.nn.Linear(inp_dimension, out_dimension) linears.append(_linear) linears.append(activation[self.activation]()) # Stacking up the layers. linears", "client.submit(compute_rmse, *(outputs_, self.targets)) atoms_per_image = torch.cat(self.atoms_per_image) rmse_atom = client.submit( compute_rmse,", "index, (symbol, features) in enumerate(data): counter = 0 layer_counter =", "finished in {} hours {} minutes {:.2f} seconds.\".format(h, m, s)", "weight decay. convergence : dict Instead of using epochs, users", "targets, uncertainty, model, lossfxn, atoms_per_image, device ): \"\"\"A function that", "inputs : dict Dictionary with hashed feature space. targets :", "= get_number_of_parameters(self) logger.info(\"Total number of parameters: {}.\".format(total_params)) logger.info(\"Number of training", "): self.initial_time = time.time() if lossfxn is None: lossfxn =", "have only C, H, O but it turns out that", "= convert_elapsed_time(training_time) logger.info( \"Training finished in {} hours {} minutes", "= ('ReduceLROnPlateau', {'mode': 'min', 'patience': 10}) uncertainty : list A", "torch.nn.Parameter( torch.tensor(intercept, requires_grad=True) ) slope = (data.max_energy - data.min_energy) /", "numpy arrays or tensors. Returns ------- activations : DataFrame A", "---------- index : int Index of batch. chunk : tensor", "f: symbol, vector = features _inputs[hash].append((symbol, vector.cuda())) inputs = _inputs", "client = dask.distributed.get_client() running_loss = torch.tensor(0, dtype=torch.float) accumulation = []", "{:8s}\".format( \"------\", \"-------------------\", \"------------\", \"------------\", \"------------\", \"------------\", \"------------\", ) )", "NeuralNetwork class. data : object Data object created from the", "= [] for symbol in unique_element_symbols: linears = [] intercept_name", "and the path is where the checkpoint is stored. Default", "intercept) self.register_parameter(slope_name, slope) for index in layers: # This is", "These are hidden-layers else: inp_dimension = self.hiddenlayers[index - 1] out_dimension", "-1 for saving all epochs, and the path is where", "forward(self, X): \"\"\"Forward propagation This is forward propagation and it", "used to compute the error over a validation/test set during", ": object A ML4Chem model object. numpy : bool Whether", "prepare_model(self, input_dimension, data=None, purpose=\"training\"): \"\"\"Prepare the model Parameters ---------- input_dimension", "test_features = self.test.get(\"features\", None) test_targets = self.test.get(\"targets\", None) test_data =", "Supported keys are \"training\" and \"test\". lossfxn : obj A", ": tensor The loss function of the batch. \"\"\" inputs", "also available only in the second batch. The # contribution", "index. targets : tensor or list The targets. uncertainty :", "time import torch import numpy as np import pandas as", "image. \"\"\" outputs = [] for hash in X: image", "is where the checkpoint is stored. Default is None and", "simulations. Comput. Phys. Commun. 207, 310–324 (2016). \"\"\" NAME =", "_linear = torch.nn.Linear(input_dimension, out_dimension) linears.append(_linear) linears.append(activation[self.activation]()) # This is the", "reduces the gradients, update model params, and finally returns loss", "\"cuda\": logger.info(\"Moving data to CUDA...\") atoms_per_image = atoms_per_image.cuda() targets =", "Information\") logging.info(\"-----------------\") logging.info(\"Number of batches: {}.\".format(len(chunks))) logging.info(\"Batch size: {} elements", "tensors. Returns ------- activations : DataFrame A DataFrame with activations", "\") logger.info(\"Starting training...\\n\") if self.test is None: logger.info( \"{:6s} {:19s}", "{pformat(uncertainty)}\") logger.info(\"\") atoms_per_image = data.atoms_per_image if batch_size is None: batch_size", "cuda or cpu? \"\"\" outputs_ = [] # Get client", "Parameters ---------- index : int Index of batch. chunk :", "= param.grad.detach().numpy() except AttributeError: # This exception catches the case", "# Define optimizer self.optimizer_name, self.optimizer = get_optimizer( optimizer, model.parameters() )", "object created from the handler. optimizer : tuple The optimizer", "update model params, and finally returns loss and outputs_. Parameters", "accumulation = client.gather(accumulation) for outputs, loss, grad in accumulation: grad", "rmse, rmse_atom, rmse_test, rmse_atom_test, ) ) if self.checkpoint is not", "run in the cpu or cuda (gpu). batch_size : int", "OrderedDict from ml4chem.metrics import compute_rmse from ml4chem.atomistic.models.base import DeepLearningModel, DeepLearningTrainer", "{}.\".format(now.strftime(\"%Y-%m-%d %H:%M:%S\")) ) logger.info(\"Model name: {}.\".format(self.name())) logger.info(\"Number of hidden-layers: {}\".format(hl))", "model object. numpy : bool Whether we want numpy arrays", "object Class object. chunks : tensor or list Tensor with", "requires_grad=False, dtype=torch.float) for u in uncertainty ] logger.info(\"\") logging.info(\"Batch Information\")", "for training. Default is None. lr_scheduler : tuple Tuple with", "learn aka y. model : object The NeuralNetwork class. data", "batches chunks = list(get_chunks(inputs, batch_size, svm=False)) targets = list(get_chunks(targets, batch_size,", "used to penalize during the loss function evaluation. lossfxn :", "out_dimension = self.hiddenlayers[0] _linear = torch.nn.Linear(input_dimension, out_dimension) linears.append(_linear) linears.append(activation[self.activation]()) #", "list Tensor with input data points in batch with index.", "test set targets. - \"features\": a feature space obtained using", "Whether we want numpy arrays or tensors. Returns ------- activations", "intercept = torch.nn.Parameter(torch.tensor(0.0)) slope = torch.nn.Parameter(torch.tensor(0.0)) self.register_parameter(intercept_name, intercept) self.register_parameter(slope_name, slope)", "if layer_column_name not in columns: columns.append(layer_column_name) counter += 1 layer_counter", "\" \"default.\" ) for m in self.modules(): if isinstance(m, torch.nn.Linear):", "{:4e} {:4e}\".format( epoch, ts, loss.detach(), rmse, rmse_atom, rmse_test, rmse_atom_test, )", "\"PytorchPotentials\" @classmethod def name(cls): \"\"\"Returns name of class\"\"\" return cls.NAME", "lr_scheduler = ('ReduceLROnPlateau', {'mode': 'min', 'patience': 10}) uncertainty : list", "to machine learning in atomistic simulations. Comput. Phys. Commun. 207,", "logger = logging.getLogger() class NeuralNetwork(DeepLearningModel, torch.nn.Module): \"\"\"Atom-centered Neural Network Regression", "model=None, numpy=True): \"\"\"Get activations of each hidden-layer This function allows", "during the loss function evaluation. model : obj Pytorch model", "list(get_chunks(targets, batch_size, svm=False)) atoms_per_image = list(get_chunks(atoms_per_image, batch_size, svm=False)) if uncertainty", "or list Tensor with input data points in batch with", "The # contribution of the total gradient from the first", "logger.info( \"Data moved to GPU in {} hours {} minutes", ": object The NeuralNetwork class. data : object Data object", "layer_counter += 1 activations.append(data_) del data_ # Create DataFrame from", "per batch.\".format(batch_size)) logger.info(\" \") atoms_per_image = [ torch.tensor(n_atoms, requires_grad=False, dtype=torch.float)", "X): \"\"\"Forward propagation This is forward propagation and it returns", "\"atom.index\", \"atom.symbol\"] if model is None: model = self model.eval()", "[] for param in model.parameters(): try: gradient = param.grad.detach().numpy() except", "test_targets, \"data\": data_test} The keys,values of the dictionary are: -", "Net: {}\".format( \"(input, \" + str(self.hiddenlayers)[1:-1] + \", output)\" )", ">>> test = {\"features\": test_space, \"targets\": test_targets, \"data\": data_test} The", "Stacking up the layers. linears = torch.nn.Sequential(*linears) symbol_model_pair.append([symbol, linears]) self.linears", "+ \", output)\" ) ) layers = range(len(self.hiddenlayers) + 1)", "146401 (2007). 2. <NAME>. & <NAME> : A modular approach", "regularization. It is not the same as weight decay. convergence", "lossfxn=None, device=\"cpu\", batch_size=None, lr_scheduler=None, uncertainty=None, checkpoint=None, test=None, ): self.initial_time =", "+= 1 layer_counter += 1 elif isinstance(layer, torch.nn.Linear) and counter", "checkpoint : dict Set checkpoints. Dictionary with following structure: >>>", ") logger.info(\"Model name: {}.\".format(self.name())) logger.info(\"Number of hidden-layers: {}\".format(hl)) logger.info( \"Structure", "uncertainty=None, checkpoint=None, test=None, ): self.initial_time = time.time() if lossfxn is", "{:.2f} seconds.\".format(h, m, s) ) @classmethod def closure( Cls, chunks,", "torch.nn.Linear) and counter > 0: x = layer(x) if numpy:", "loss function evaluation. model : obj Pytorch model to perform", "int Input's dimension. data : object Data object created from", "optimizer=(None, None), regularization=None, epochs=100, convergence=None, lossfxn=None, device=\"cpu\", batch_size=None, lr_scheduler=None, uncertainty=None,", "features) in enumerate(data): counter = 0 layer_counter = 0 for", "tensor The loss function of the batch. \"\"\" inputs =", "1 layer_counter += 1 elif isinstance(layer, torch.nn.Linear) and counter >", "for m in self.modules(): if isinstance(m, torch.nn.Linear): # nn.init.normal_(m.weight) #", "0 client = dask.distributed.get_client() while not converged: epoch += 1", "the neural network. Parameters ---------- image : dict Image with", "logger.info( \"{:6s} {:19s} {:12s} {:8s} {:8s} {:8s} {:8s}\".format( \"------\", \"-------------------\",", "the loss function evaluation. checkpoint : dict Set checkpoints. Dictionary", "!= \"LBFGS\": self.optimizer.step() else: options = {\"closure\": self.closure, \"current_loss\": loss,", "training per batches Parameters ---------- index : int Index of", "\"{:6s} {:19s} {:12s} {:8s} {:8s}\".format( \"------\", \"-------------------\", \"------------\", \"------------\", \"------------\",", "finally returns loss and outputs_. Parameters ---------- Cls : object", "model : obj Pytorch model to perform forward() and get", "ts = datetime.datetime.fromtimestamp(ts).strftime(\"%Y-%m-%d \" \"%H:%M:%S\") if self.test is None: logger.info(", ") layers = range(len(self.hiddenlayers) + 1) try: unique_element_symbols = data.unique_element_symbols[purpose]", "layer elif index == len(self.hiddenlayers): inp_dimension = self.hiddenlayers[index - 1]", "unique_element_symbols[purpose] symbol_model_pair = [] for symbol in unique_element_symbols: linears =", "out_dimension) linears.append(_linear) linears.append(activation[self.activation]()) # This is the output layer elif", "== None: loss = lossfxn(outputs, targets[index], atoms_per_image[index]) else: loss =", "model.eval() for hash, data in images.items(): for index, (symbol, features)", "1 activations.append(data_) del data_ # Create DataFrame from lists df", "\") atoms_per_image = [ torch.tensor(n_atoms, requires_grad=False, dtype=torch.float) for n_atoms in", "hiddenlayers=(3, 3), activation=\"relu\", **kwargs): super(DeepLearningModel, self).__init__() self.hiddenlayers = hiddenlayers self.activation", "= rmse_atom_test.result() logger.info( \"{:6d} {} {:8e} {:4e} {:4e} {:4e} {:4e}\".format(", "\"-------------------\", \"------------\", \"------------\", \"------------\", \"------------\", \"------------\", ) ) converged =", "points per batch to use for training. Default is None.", "This model is based on Ref. 1 by Behler and", "per image. \"\"\" outputs = [] for hash in X:", "numpy=True): \"\"\"Get activations of each hidden-layer This function allows to", "torch.nn.Tanh, \"relu\": torch.nn.ReLU, \"celu\": torch.nn.CELU, } hl = len(self.hiddenlayers) if", "clear previous gradients loss, outputs_ = train.closure( self.chunks, self.targets, self.uncertainty,", "\"------------\", \"------------\", ) ) else: test_features = self.test.get(\"features\", None) test_targets", "test = {\"features\": test_space, \"targets\": test_targets, \"data\": data_test} The keys,values", "Pytorch This model is based on Ref. 1 by Behler", "evaluation. model : obj Pytorch model to perform forward() and", "= rmse_test.result() rmse_atom_test = rmse_atom_test.result() logger.info( \"{:6d} {} {:8e} {:4e}", "we are doing atom-centered methods. device : str Are we", ": list The expected values that the model has to", "the case where an image does not # contain variable", "return df class train(DeepLearningTrainer): \"\"\"Train the model Parameters ---------- inputs", "+= 1 self.optimizer.zero_grad() # clear previous gradients loss, outputs_ =", "logger.info(\" \") logger.info(\"Starting training...\\n\") if self.test is None: logger.info( \"{:6s}", "feature space. targets : list The expected values that the", "chunks] self.targets = [client.scatter(target) for target in targets] if uncertainty", "grad in accumulation: grad = np.array(grad, dtype=object) running_loss += loss", "self.checkpoint_save(epoch, self.model, **self.checkpoint) if self.convergence is None and epoch ==", "refers to the name used to save the checkpoint, `checkpoint`", "< self.convergence[\"energy\"]: converged = True training_time = time.time() - self.initial_time", "\"atom.symbol\"] if model is None: model = self model.eval() for", "torch.nn.Linear) and counter == 0: x = layer(features) if numpy:", "the same as weight decay. convergence : dict Instead of", "intercept = torch.nn.Parameter( torch.tensor(intercept, requires_grad=True) ) slope = (data.max_energy -", "Set checkpoints. Dictionary with following structure: >>> checkpoint = {\"label\":", "features in f: symbol, vector = features _inputs[hash].append((symbol, vector.cuda())) inputs", "accumulation: grad = np.array(grad, dtype=object) running_loss += loss outputs_.append(outputs) grads.append(grad)", "or \"celu\". References ---------- 1. <NAME>. & <NAME>. Generalized Neural-Network", "param.grad.detach().numpy() except AttributeError: # This exception catches the case where", "and Parrinello. Parameters ---------- hiddenlayers : tuple Structure of hidden", "with structure hash, features. model : object A ML4Chem model", "is not the same as weight decay. convergence : dict", "'training', 'inference'. \"\"\" self.input_dimension = input_dimension activation = { \"tanh\":", "if uncertainty is not None: logger.info(\"Options:\") logger.info(f\" - Uncertainty penalization:", "self.targets = [client.scatter(target) for target in targets] if uncertainty !=", "self.register_parameter(intercept_name, intercept) self.register_parameter(slope_name, slope) for index in layers: # This", "torch.cat(atomic_energies) image_energy = torch.sum(atomic_energies) outputs.append(image_energy) outputs = torch.stack(outputs) return outputs", "param in model.parameters(): try: gradient = param.grad.detach().numpy() except AttributeError: #", "self.uncertainty = uncertainty # Let the hunger games begin... self.trainer()", "convert_elapsed_time, get_chunks, get_number_of_parameters from pprint import pformat # Setting precision", "a integer or -1 for saving all epochs, and the", "len(self.hiddenlayers): inp_dimension = self.hiddenlayers[index - 1] out_dimension = 1 _linear", "accumulates the gradients, reduces the gradients, update model params, and", "\"training\" and \"test\". lossfxn : obj A loss function object.", "the second batch. The # contribution of the total gradient", "1. <NAME>. & <NAME>. Generalized Neural-Network Representation of High-Dimensional Potential-Energy", "{:12s} {:8s}\".format( \"Epoch\", \"Time Stamp\", \"Loss\", \"Error/img\", \"Error/atom\" ) )", "as np import pandas as pd from collections import OrderedDict", "training parameters: {}.\".format(train_params)) logger.info(\" \") logger.info(self.linears) # Iterate over all", "and no checkpoint is saved. test : dict A dictionary", "for index, chunk in enumerate(chunks): accumulation.append( client.submit( train.train_batches, *( index,", "epochs, and the path is where the checkpoint is stored.", ": int Number of full training cycles. regularization : float", "RMSE per image and per/atom rmse = client.submit(compute_rmse, *(outputs_, self.targets))", "dtype=torch.float) for u in uncertainty ] logger.info(\"\") logging.info(\"Batch Information\") logging.info(\"-----------------\")", "each. # In the first batch we have only C,", "inputs, targets, model=None, data=None, optimizer=(None, None), regularization=None, epochs=100, convergence=None, lossfxn=None,", "Commun. 207, 310–324 (2016). \"\"\" NAME = \"PytorchPotentials\" @classmethod def", "0 for l, layer in enumerate(model.linears[symbol].modules()): if isinstance(layer, torch.nn.Linear) and", "lr_scheduler is not None: self.scheduler = get_lr_scheduler(self.optimizer, lr_scheduler) self.atoms_per_image =", "= lossfxn(outputs, targets[index], atoms_per_image[index]) else: loss = lossfxn( outputs, targets[index],", "removed after de/serialization # is fixed. if isinstance(symbol, bytes): symbol", "+= 1 activations.append(data_) del data_ # Create DataFrame from lists", "train.closure( self.chunks, self.targets, self.uncertainty, self.model, self.lossfxn, self.atoms_per_image, self.device, ) #", "lossfxn : obj A loss function object. device : str", "data=None, optimizer=(None, None), regularization=None, epochs=100, convergence=None, lossfxn=None, device=\"cpu\", batch_size=None, lr_scheduler=None,", "if lossfxn is None: lossfxn = AtomicMSELoss logger.info(\"\") logger.info(\"Training\") logger.info(\"========\")", "chunks = list(get_chunks(inputs, batch_size, svm=False)) targets = list(get_chunks(targets, batch_size, svm=False))", "return running_loss, outputs_ @classmethod def train_batches( Cls, index, chunk, targets,", "out that # N is also available only in the", "grad = np.array(grad, dtype=object) running_loss += loss outputs_.append(outputs) grads.append(grad) grads", "with index. targets : tensor or list The targets. model", "out_dimension = 1 _linear = torch.nn.Linear(inp_dimension, out_dimension) linears.append(_linear) # These", ") logger.info( \"{:6s} {:19s} {:12s} {:8s} {:8s} {:8s} {:8s}\".format( \"------\",", "\"training\": intercept = (data.max_energy + data.min_energy) / 2.0 intercept =", "0 layer_counter = 0 for l, layer in enumerate(model.linears[symbol].modules()): if", "# contain variable that is following the gradient of certain", "linears = torch.nn.Sequential(*linears) symbol_model_pair.append([symbol, linears]) self.linears = torch.nn.ModuleDict(symbol_model_pair) if purpose", "def closure( Cls, chunks, targets, uncertainty, model, lossfxn, atoms_per_image, device", "of certain # atom. For example, suppose two batches with", "slope = torch.nn.Parameter(torch.tensor(0.0)) self.register_parameter(intercept_name, intercept) self.register_parameter(slope_name, slope) for index in", "forward() and get gradients. lossfxn : obj A loss function", "and \"test\". lossfxn : obj A loss function object. device", "batch_size : int Number of data points per batch to", "\"Epoch\", \"Time Stamp\", \"Loss\", \"Error/img\", \"Error/atom\" ) ) logger.info( \"{:6s}", "in enumerate(model.parameters()): param.grad = torch.tensor(grads[index], dtype=torch.float) del accumulation del grads", "int Index of batch. chunk : tensor or list Tensor", "rmse_test.result() rmse_atom_test = rmse_atom_test.result() logger.info( \"{:6d} {} {:8e} {:4e} {:4e}", "207, 310–324 (2016). \"\"\" NAME = \"PytorchPotentials\" @classmethod def name(cls):", "= torch.tensor(grads[index], dtype=torch.float) del accumulation del grads return running_loss, outputs_", "logger.info(\"Model name: {}.\".format(self.name())) logger.info(\"Number of hidden-layers: {}\".format(hl)) logger.info( \"Structure of", "model, lossfxn, atoms_per_image, device ): \"\"\"A function that allows training", "checkpoint, `checkpoint` is a integer or -1 for saving all", "torch.nn.Parameter(torch.tensor(slope, requires_grad=True)) self.register_parameter(intercept_name, intercept) self.register_parameter(slope_name, slope) elif purpose == \"inference\":", "[hash, index, symbol, x.detach_()] layer_column_name = f\"layer{layer_counter}\" if layer_column_name not", "\"Epoch\", \"Time Stamp\", \"Loss\", \"Error/img\", \"Error/atom\", \"Error/img (t)\", \"Error/atom (t)\",", "function object. atoms_per_image : list Atoms per image because we", "purpose=\"training\"): \"\"\"Prepare the model Parameters ---------- input_dimension : int Input's", "dask.distributed.get_client() self.chunks = [client.scatter(chunk) for chunk in chunks] self.targets =", "activation : str Activation functions. Supported \"tanh\", \"relu\", or \"celu\".", "loss, outputs_ = train.closure( self.chunks, self.targets, self.uncertainty, self.model, self.lossfxn, self.atoms_per_image,", "Stamp\", \"Loss\", \"Error/img\", \"Error/atom\", \"Error/img (t)\", \"Error/atom (t)\", ) )", "logger.info(\"Starting training...\\n\") if self.test is None: logger.info( \"{:6s} {:19s} {:12s}", "import DeepLearningModel, DeepLearningTrainer from ml4chem.atomistic.models.loss import AtomicMSELoss from ml4chem.optim.handler import", "procedures. >>> test = {\"features\": test_space, \"targets\": test_targets, \"data\": data_test}", "object. chunks : tensor or list Tensor with input data", "rmse_atom.result() _loss.append(loss.item()) _rmse.append(rmse) # In the case that lr_scheduler is", "for l, layer in enumerate(model.linears[symbol].modules()): if isinstance(layer, torch.nn.Linear) and counter", "AtomicMSELoss from ml4chem.optim.handler import get_optimizer, get_lr_scheduler, get_lr from ml4chem.utils import", "contain variable that is following the gradient of certain #", "atoms_per_image_test), ) rmse_test = rmse_test.result() rmse_atom_test = rmse_atom_test.result() logger.info( \"{:6d}", "tuple with the structure: >>> ('adam', {'lr': float, 'weight_decay'=float}) epochs", "the total gradient from the first batch for N is", "__init__( self, inputs, targets, model=None, data=None, optimizer=(None, None), regularization=None, epochs=100,", "*(test_predictions, test_targets, atoms_per_image_test), ) rmse_test = rmse_test.result() rmse_atom_test = rmse_atom_test.result()", "index, chunk in enumerate(chunks): accumulation.append( client.submit( train.train_batches, *( index, chunk,", "None and epoch == self.epochs: converged = True elif self.convergence", "accessed on {}.\".format(now.strftime(\"%Y-%m-%d %H:%M:%S\")) ) logger.info(\"Model name: {}.\".format(self.name())) logger.info(\"Number of", "df = pd.DataFrame(activations, columns=columns) return df class train(DeepLearningTrainer): \"\"\"Train the", "convergence=None, lossfxn=None, device=\"cpu\", batch_size=None, lr_scheduler=None, uncertainty=None, checkpoint=None, test=None, ): self.initial_time", "arguments. >>> lr_scheduler = ('ReduceLROnPlateau', {'mode': 'min', 'patience': 10}) uncertainty", "m, s ) ) logger.info(\" \") # Define optimizer self.optimizer_name,", "logger.info( \"Structure of Neural Net: {}\".format( \"(input, \" + str(self.hiddenlayers)[1:-1]", "of this model: 'training', 'inference'. \"\"\" self.input_dimension = input_dimension activation", "rmse_atom = rmse_atom.result() _loss.append(loss.item()) _rmse.append(rmse) # In the case that", "2.0 intercept = torch.nn.Parameter( torch.tensor(intercept, requires_grad=True) ) slope = (data.max_energy", "\"\"\" inputs = OrderedDict(chunk) outputs = model(inputs) if uncertainty ==", "x) + intercept atomic_energies.append(x) atomic_energies = torch.cat(atomic_energies) image_energy = torch.sum(atomic_energies)", "in model.parameters(): try: gradient = param.grad.detach().numpy() except AttributeError: # This", "_inputs = OrderedDict() for hash, f in inputs.items(): _inputs[hash] =", "obj A loss function object. atoms_per_image : list Atoms per", "device ): \"\"\"Closure This class method clears previous gradients, iterates", "= self.test.get(\"targets\", None) test_data = self.test.get(\"data\", None) logger.info( \"{:6s} {:19s}", "collections import OrderedDict from ml4chem.metrics import compute_rmse from ml4chem.atomistic.models.base import", "logger.info(\"\") logger.info(\"Training\") logger.info(\"========\") logger.info(f\"Convergence criteria: {convergence}\") logger.info(f\"Loss function: {lossfxn.__name__}\") if", "decay. convergence : dict Instead of using epochs, users can", "= test_model(test_features).detach() rmse_test = client.submit( compute_rmse, *(test_predictions, test_targets) ) atoms_per_image_test", "# FIXME this conditional can be removed after de/serialization #", "rmse_test, rmse_atom_test, ) ) if self.checkpoint is not None: self.checkpoint_save(epoch,", "is following the gradient of certain # atom. For example,", "x = (slope * x) + intercept atomic_energies.append(x) atomic_energies =", "intercept_name = \"intercept_\" + symbol slope_name = \"slope_\" + symbol", "the neural network. activation : str Activation functions. Supported \"tanh\",", "tuple Structure of hidden layers in the neural network. activation", "= OrderedDict() for hash, f in inputs.items(): _inputs[hash] = []", "functions. Supported \"tanh\", \"relu\", or \"celu\". References ---------- 1. <NAME>.", "the loss function evaluation. lossfxn : obj A loss function", "dictionary with keyword arguments. >>> lr_scheduler = ('ReduceLROnPlateau', {'mode': 'min',", "\"{:6s} {:19s} {:12s} {:12s} {:8s}\".format( \"Epoch\", \"Time Stamp\", \"Loss\", \"Error/img\",", "str Calculation can be run in the cpu or cuda", "on Ref. 1 by Behler and Parrinello. Parameters ---------- hiddenlayers", "self.atoms_per_image, self.device, ) # We step the optimizer if self.optimizer_name", "loss.detach(), rmse, rmse_atom, rmse_test, rmse_atom_test, ) ) if self.checkpoint is", "for index in layers: # This is the input layer", "symbol slope = getattr(self, slope_name) intercept = getattr(self, intercept_name) x", "rmse_atom_test = rmse_atom_test.result() logger.info( \"{:6d} {} {:8e} {:4e} {:4e} {:4e}", "are # a linear layer. logger.warning( \"Initialization of weights with", "ts, loss.detach(), rmse, rmse_atom ) ) else: test_model = self.model.eval()", "= [] # Accumulation of gradients for index, chunk in", "{:4e} {:4e}\".format( epoch, ts, loss.detach(), rmse, rmse_atom ) ) else:", "{:4e} {:4e} {:4e} {:4e}\".format( epoch, ts, loss.detach(), rmse, rmse_atom, rmse_test,", "we running cuda or cpu? Returns ------- loss : tensor", "batches with 2 molecules each. # In the first batch", "purpose : str Purpose of this model: 'training', 'inference'. \"\"\"", "batch to use for training. Default is None. lr_scheduler :", "get_optimizer, get_lr_scheduler, get_lr from ml4chem.utils import convert_elapsed_time, get_chunks, get_number_of_parameters from", "Default is None. lr_scheduler : tuple Tuple with structure: scheduler's", "\"tanh\": torch.nn.Tanh, \"relu\": torch.nn.ReLU, \"celu\": torch.nn.CELU, } hl = len(self.hiddenlayers)", "= [] for features in f: symbol, vector = features", "int): # Data batches chunks = list(get_chunks(inputs, batch_size, svm=False)) targets", "float This is the L2 regularization. It is not the", "We step the optimizer if self.optimizer_name != \"LBFGS\": self.optimizer.step() else:", "= True elif self.convergence is not None and rmse <", "intialize those that are # a linear layer. logger.warning( \"Initialization", "in f: symbol, vector = features _inputs[hash].append((symbol, vector.cuda())) inputs =", "based on Ref. 1 by Behler and Parrinello. Parameters ----------", "GPU in {} hours {} minutes {:.2f} \\ seconds.\".format( h,", "= dask.distributed.get_client() self.chunks = [client.scatter(chunk) for chunk in chunks] self.targets", "layer_column_name = f\"layer{layer_counter}\" if layer_column_name not in columns: columns.append(layer_column_name) counter", "torch.tensor( test_data.atoms_per_image, requires_grad=False ) rmse_atom_test = client.submit( compute_rmse, *(test_predictions, test_targets,", "object. device : str Calculation can be run in the", "len(self.hiddenlayers) if purpose == \"training\": logger.info(\" \") logger.info(\"Model\") logger.info(\"=====\") now", "propagation This is forward propagation and it returns the atomic", "---------- input_dimension : int Input's dimension. data : object Data", "columns.append(layer_column_name) counter += 1 layer_counter += 1 activations.append(data_) del data_", "h, m, s = convert_elapsed_time(training_time) logger.info( \"Training finished in {}", "Purpose of this model: 'training', 'inference'. \"\"\" self.input_dimension = input_dimension", "gradient of certain # atom. For example, suppose two batches", "= epochs self.model = model self.lr_scheduler = lr_scheduler self.lossfxn =", "== \"training\": intercept = (data.max_energy + data.min_energy) / 2.0 intercept", "uncertainty != None: self.uncertainty = [client.scatter(u) for u in uncertainty]", "Neural Net: {}\".format( \"(input, \" + str(self.hiddenlayers)[1:-1] + \", output)\"", "enumerate(model.linears[symbol].modules()): if isinstance(layer, torch.nn.Linear) and counter == 0: x =", "in columns: columns.append(layer_column_name) counter += 1 layer_counter += 1 activations.append(data_)", "batch_size, svm=False)) uncertainty = [ torch.tensor(u, requires_grad=False, dtype=torch.float) for u", "for u in uncertainty ] logger.info(\"\") logging.info(\"Batch Information\") logging.info(\"-----------------\") logging.info(\"Number", "if self.convergence is None and epoch == self.epochs: converged =", "vector = features _inputs[hash].append((symbol, vector.cuda())) inputs = _inputs move_time =", "the checkpoint is stored. Default is None and no checkpoint", "accumulation del grads return running_loss, outputs_ @classmethod def train_batches( Cls,", "# Setting precision and starting logger object torch.set_printoptions(precision=10) logger =", "\"------------\", \"------------\", \"------------\", ) ) converged = False _loss =", "gradients loss, outputs_ = train.closure( self.chunks, self.targets, self.uncertainty, self.model, self.lossfxn,", "import OrderedDict from ml4chem.metrics import compute_rmse from ml4chem.atomistic.models.base import DeepLearningModel,", "# is fixed. if isinstance(symbol, bytes): symbol = symbol.decode(\"utf-8\") x", "device=\"cpu\", batch_size=None, lr_scheduler=None, uncertainty=None, checkpoint=None, test=None, ): self.initial_time = time.time()", "using epochs, users can set a convergence criterion. Supported keys", "lossfxn is None: lossfxn = AtomicMSELoss logger.info(\"\") logger.info(\"Training\") logger.info(\"========\") logger.info(f\"Convergence", "self.hiddenlayers[index - 1] out_dimension = 1 _linear = torch.nn.Linear(inp_dimension, out_dimension)", "int Number of full training cycles. regularization : float This", "DataFrame A DataFrame with activations for each layer. \"\"\" activations", "for hash in X: image = X[hash] atomic_energies = []", "For example, suppose two batches with 2 molecules each. #", "= uncertainty # Let the hunger games begin... self.trainer() def", "targets] if uncertainty != None: self.uncertainty = [client.scatter(u) for u", "is None: model = self model.eval() for hash, data in", ": int Number of data points per batch to use", "loss and outputs_. Parameters ---------- Cls : object Class object.", "trainer(self): \"\"\"Run the training class\"\"\" logger.info(\" \") logger.info(\"Starting training...\\n\") if", "None: logger.info( \"{:6d} {} {:8e} {:4e} {:4e}\".format( epoch, ts, loss.detach(),", "index, chunk, targets, uncertainty, model, lossfxn, atoms_per_image, device, ), )", "= self.hiddenlayers[0] _linear = torch.nn.Linear(input_dimension, out_dimension) linears.append(_linear) linears.append(activation[self.activation]()) # This", "\") # Define optimizer self.optimizer_name, self.optimizer = get_optimizer( optimizer, model.parameters()", "= [] for symbol, x in image: # FIXME this", "to GPU in {} hours {} minutes {:.2f} \\ seconds.\".format(", "data_ # Create DataFrame from lists df = pd.DataFrame(activations, columns=columns)", "(data.max_energy - data.min_energy) / 2.0 slope = torch.nn.Parameter(torch.tensor(slope, requires_grad=True)) self.register_parameter(intercept_name,", "data_test} The keys,values of the dictionary are: - \"data\": a", "Get client to send futures to the scheduler client =", "client.submit( compute_rmse, *(outputs_, self.targets, atoms_per_image) ) rmse = rmse.result() rmse_atom", "): \"\"\"Closure This class method clears previous gradients, iterates over", "torch.tensor(0, dtype=torch.float) accumulation = [] grads = [] # Accumulation", "self.convergence is None and epoch == self.epochs: converged = True", "training. Default is None. lr_scheduler : tuple Tuple with structure:", "size: {} elements per batch.\".format(batch_size)) logger.info(\" \") atoms_per_image = [", "{\"label\": label, \"checkpoint\": 100, \"path\": \"\"} `label` refers to the", "first batch we have only C, H, O but it", ": dict Dictionary with hashed feature space. targets : list", "cpu? \"\"\" outputs_ = [] # Get client to send", "regularization : float This is the L2 regularization. It is", "to penalize during the loss function evaluation. checkpoint : dict", "outputs_ @classmethod def train_batches( Cls, index, chunk, targets, uncertainty, model,", "number of parameters: {}.\".format(total_params)) logger.info(\"Number of training parameters: {}.\".format(train_params)) logger.info(\"", "[client.scatter(chunk) for chunk in chunks] self.targets = [client.scatter(target) for target", "device ): \"\"\"A function that allows training per batches Parameters", "= [] intercept_name = \"intercept_\" + symbol slope_name = \"slope_\"", "index in layers: # This is the input layer if", "= 0 layer_counter = 0 for l, layer in enumerate(model.linears[symbol].modules()):", "hours {} minutes {:.2f} seconds.\".format(h, m, s) ) @classmethod def", "Regression with Pytorch This model is based on Ref. 1", "batch_size, svm=False)) if uncertainty != None: uncertainty = list(get_chunks(uncertainty, batch_size,", "object The NeuralNetwork class. data : object Data object created", "tuple The optimizer is a tuple with the structure: >>>", "str(self.hiddenlayers)[1:-1] + \", output)\" ) ) layers = range(len(self.hiddenlayers) +", "client = dask.distributed.get_client() while not converged: epoch += 1 self.optimizer.zero_grad()", "numpy: data_ = [hash, index, symbol, x.detach_().numpy()] else: data_ =", "`features.calculate()`. \"\"\" def __init__( self, inputs, targets, model=None, data=None, optimizer=(None,", "None: self.scheduler = get_lr_scheduler(self.optimizer, lr_scheduler) self.atoms_per_image = atoms_per_image self.convergence =", "layers in the neural network. activation : str Activation functions.", "as pd from collections import OrderedDict from ml4chem.metrics import compute_rmse", "approach to machine learning in atomistic simulations. Comput. Phys. Commun.", "object Data object created from the handler. optimizer : tuple", "self.test = test # Data scattering client = dask.distributed.get_client() self.chunks", "scheduler's name and a dictionary with keyword arguments. >>> lr_scheduler", "def name(cls): \"\"\"Returns name of class\"\"\" return cls.NAME def __init__(self,", "> 0: x = layer(x) if numpy: data_.append(x.detach_().numpy()) else: data_.append(x.detach_())", "get_lr(self.optimizer))) ts = time.time() ts = datetime.datetime.fromtimestamp(ts).strftime(\"%Y-%m-%d \" \"%H:%M:%S\") if", "input_dimension activation = { \"tanh\": torch.nn.Tanh, \"relu\": torch.nn.ReLU, \"celu\": torch.nn.CELU,", "= (data.max_energy - data.min_energy) / 2.0 slope = torch.nn.Parameter(torch.tensor(slope, requires_grad=True))", "else: options = {\"closure\": self.closure, \"current_loss\": loss, \"max_ls\": 10} self.optimizer.step(options)", "for index, param in enumerate(model.parameters()): param.grad = torch.tensor(grads[index], dtype=torch.float) del", "device == \"cuda\": logger.info(\"Moving data to CUDA...\") atoms_per_image = atoms_per_image.cuda()", "= list(get_chunks(uncertainty, batch_size, svm=False)) uncertainty = [ torch.tensor(u, requires_grad=False, dtype=torch.float)", "device : str Calculation can be run in the cpu", "[] # Get client to send futures to the scheduler", "\"\"\"Prepare the model Parameters ---------- input_dimension : int Input's dimension.", "Parameters ---------- X : list List of inputs in the", "# Data scattering client = dask.distributed.get_client() self.chunks = [client.scatter(chunk) for", "and epoch == self.epochs: converged = True elif self.convergence is", "hiddenlayers : tuple Structure of hidden layers in the neural", "logger.info(\"Total number of parameters: {}.\".format(total_params)) logger.info(\"Number of training parameters: {}.\".format(train_params))", "Define optimizer self.optimizer_name, self.optimizer = get_optimizer( optimizer, model.parameters() ) if", "the dictionary are: - \"data\": a `Data` object. - \"targets\":", "\"\"} `label` refers to the name used to save the", "atoms_per_image, device ): \"\"\"Closure This class method clears previous gradients,", "uncertainty] else: self.uncertainty = uncertainty # Let the hunger games", "atomic_energies = [] for symbol, x in image: # FIXME", "# Iterate over all modules and just intialize those that", "s = convert_elapsed_time(move_time) logger.info( \"Data moved to GPU in {}", "get_optimizer( optimizer, model.parameters() ) if lr_scheduler is not None: self.scheduler", "\"{:6s} {:19s} {:12s} {:12s} {:12s} {:12s} {:16s}\".format( \"Epoch\", \"Time Stamp\",", "A DataFrame with activations for each layer. \"\"\" activations =", "\"\"\"Train the model Parameters ---------- inputs : dict Dictionary with", "expected values that the model has to learn aka y.", "allows to extract activations of each hidden-layer of the neural", "chunks, targets, uncertainty, model, lossfxn, atoms_per_image, device ): \"\"\"Closure This", "{} minutes {:.2f} seconds.\".format(h, m, s) ) @classmethod def closure(", "modular approach to machine learning in atomistic simulations. Comput. Phys.", "self.initial_time h, m, s = convert_elapsed_time(move_time) logger.info( \"Data moved to", "Stamp\", \"Loss\", \"Error/img\", \"Error/atom\" ) ) logger.info( \"{:6s} {:19s} {:12s}", "{:8s} {:8s}\".format( \"------\", \"-------------------\", \"------------\", \"------------\", \"------------\", ) ) else:", "df class train(DeepLearningTrainer): \"\"\"Train the model Parameters ---------- inputs :", "is None: batch_size = len(inputs.values()) if isinstance(batch_size, int): # Data", "counter += 1 layer_counter += 1 elif isinstance(layer, torch.nn.Linear) and", "the model has to learn aka y. model : object", "rmse_atom_test.result() logger.info( \"{:6d} {} {:8e} {:4e} {:4e} {:4e} {:4e}\".format( epoch,", "linears.append(_linear) # These are hidden-layers else: inp_dimension = self.hiddenlayers[index -", "with energies per image. \"\"\" outputs = [] for hash", "lossfxn, atoms_per_image, device, ), ) ) dask.distributed.wait(accumulation) accumulation = client.gather(accumulation)", "C, H, O but it turns out that # N", "inp_dimension = self.hiddenlayers[index - 1] out_dimension = 1 _linear =", "perform forward() and get gradients. uncertainty : list A list", "& <NAME>. Generalized Neural-Network Representation of High-Dimensional Potential-Energy Surfaces. Phys.", "linears.append(activation[self.activation]()) # This is the output layer elif index ==", "activation = { \"tanh\": torch.nn.Tanh, \"relu\": torch.nn.ReLU, \"celu\": torch.nn.CELU, }", "penalize during the loss function evaluation. checkpoint : dict Set", "- self.initial_time h, m, s = convert_elapsed_time(training_time) logger.info( \"Training finished", "= self.hiddenlayers[index - 1] out_dimension = self.hiddenlayers[index] _linear = torch.nn.Linear(inp_dimension,", "penalize during the loss function evaluation. model : obj Pytorch", "self.activation = activation def prepare_model(self, input_dimension, data=None, purpose=\"training\"): \"\"\"Prepare the", "logger.info(\"Moving data to CUDA...\") atoms_per_image = atoms_per_image.cuda() targets = targets.cuda()", "handler. purpose : str Purpose of this model: 'training', 'inference'.", "uncertainty == None: loss = lossfxn(outputs, targets[index], atoms_per_image[index]) else: loss", "returns loss and outputs_. Parameters ---------- Cls : object Class", "y. model : object The NeuralNetwork class. data : object", "image because we are doing atom-centered methods. device : str", "image : dict Image with structure hash, features. model :", "arrays or tensors. Returns ------- activations : DataFrame A DataFrame", "[\"hash\", \"atom.index\", \"atom.symbol\"] if model is None: model = self", "= [client.scatter(chunk) for chunk in chunks] self.targets = [client.scatter(target) for", "The NeuralNetwork class. data : object Data object created from", "if self.optimizer_name != \"LBFGS\": self.optimizer.step() else: options = {\"closure\": self.closure,", "Iterate over all modules and just intialize those that are", "returns the atomic energy. Parameters ---------- X : list List", "- \"features\": a feature space obtained using `features.calculate()`. \"\"\" def", "The expected values that the model has to learn aka", "atoms_per_image_test = torch.tensor( test_data.atoms_per_image, requires_grad=False ) rmse_atom_test = client.submit( compute_rmse,", "# N is also available only in the second batch.", "self.convergence[\"energy\"]: converged = True training_time = time.time() - self.initial_time h,", "training...\\n\") if self.test is None: logger.info( \"{:6s} {:19s} {:12s} {:12s}", "gradients. uncertainty : list A list of uncertainties that are", "data.unique_element_symbols[purpose] except TypeError: unique_element_symbols = data.get_unique_element_symbols(purpose=purpose) unique_element_symbols = unique_element_symbols[purpose] symbol_model_pair", "+ intercept atomic_energies.append(x) atomic_energies = torch.cat(atomic_energies) image_energy = torch.sum(atomic_energies) outputs.append(image_energy)", "out_dimension = self.hiddenlayers[index] _linear = torch.nn.Linear(inp_dimension, out_dimension) linears.append(_linear) linears.append(activation[self.activation]()) #", "_rmse = [] epoch = 0 client = dask.distributed.get_client() while", "\"Error/atom\", \"Error/img (t)\", \"Error/atom (t)\", ) ) logger.info( \"{:6s} {:19s}", "the checkpoint, `checkpoint` is a integer or -1 for saving", "\"intercept_\" + symbol slope_name = \"slope_\" + symbol slope =", "loss function object. device : str Calculation can be run", "over batches, accumulates the gradients, reduces the gradients, update model", "model=None, data=None, optimizer=(None, None), regularization=None, epochs=100, convergence=None, lossfxn=None, device=\"cpu\", batch_size=None,", "case where an image does not # contain variable that", "space. Returns ------- outputs : tensor A list of tensors", "of High-Dimensional Potential-Energy Surfaces. Phys. Rev. Lett. 98, 146401 (2007).", "out_dimension) linears.append(_linear) # These are hidden-layers else: inp_dimension = self.hiddenlayers[index", "name used to save the checkpoint, `checkpoint` is a integer", "= self.test.get(\"data\", None) logger.info( \"{:6s} {:19s} {:12s} {:12s} {:12s} {:12s}", "list The targets. uncertainty : list A list of uncertainties", "self.hiddenlayers[index - 1] out_dimension = self.hiddenlayers[index] _linear = torch.nn.Linear(inp_dimension, out_dimension)", ": str Purpose of this model: 'training', 'inference'. \"\"\" self.input_dimension", "space. targets : list The expected values that the model", "has to learn aka y. model : object The NeuralNetwork", ">>> checkpoint = {\"label\": label, \"checkpoint\": 100, \"path\": \"\"} `label`", "= _inputs move_time = time.time() - self.initial_time h, m, s", "compute_rmse from ml4chem.atomistic.models.base import DeepLearningModel, DeepLearningTrainer from ml4chem.atomistic.models.loss import AtomicMSELoss", "inputs.items(): _inputs[hash] = [] for features in f: symbol, vector", "('adam', {'lr': float, 'weight_decay'=float}) epochs : int Number of full", "slope_name = \"slope_\" + symbol slope = getattr(self, slope_name) intercept", "torch.nn.init.xavier_uniform_(m.weight) def forward(self, X): \"\"\"Forward propagation This is forward propagation", "the output layer elif index == len(self.hiddenlayers): inp_dimension = self.hiddenlayers[index", "slope = getattr(self, slope_name) intercept = getattr(self, intercept_name) x =", "X : list List of inputs in the feature space.", "epoch == self.epochs: converged = True elif self.convergence is not", "The optimizer is a tuple with the structure: >>> ('adam',", "model: 'training', 'inference'. \"\"\" self.input_dimension = input_dimension activation = {", "logging.info(\"Batch Information\") logging.info(\"-----------------\") logging.info(\"Number of batches: {}.\".format(len(chunks))) logging.info(\"Batch size: {}", "= [] grads = [] # Accumulation of gradients for", "during training procedures. >>> test = {\"features\": test_space, \"targets\": test_targets,", "self.trainer() def trainer(self): \"\"\"Run the training class\"\"\" logger.info(\" \") logger.info(\"Starting", "targets. model : obj Pytorch model to perform forward() and", "isinstance(symbol, bytes): symbol = symbol.decode(\"utf-8\") x = self.linears[symbol](x) intercept_name =", "= client.gather(accumulation) for outputs, loss, grad in accumulation: grad =", "space obtained using `features.calculate()`. \"\"\" def __init__( self, inputs, targets,", "epoch = 0 client = dask.distributed.get_client() while not converged: epoch", "- \"data\": a `Data` object. - \"targets\": test set targets.", "and a dictionary with keyword arguments. >>> lr_scheduler = ('ReduceLROnPlateau',", "index == len(self.hiddenlayers): inp_dimension = self.hiddenlayers[index - 1] out_dimension =", "The targets. model : obj Pytorch model to perform forward()", "neural network. Parameters ---------- image : dict Image with structure", "\"training\": total_params, train_params = get_number_of_parameters(self) logger.info(\"Total number of parameters: {}.\".format(total_params))", "# In the first batch we have only C, H,", "= \"slope_\" + symbol slope = getattr(self, slope_name) intercept =", "the gradient of certain # atom. For example, suppose two", "uncertainty is not None: logger.info(\"Options:\") logger.info(f\" - Uncertainty penalization: {pformat(uncertainty)}\")", "columns: columns.append(layer_column_name) counter += 1 layer_counter += 1 elif isinstance(layer,", "**self.checkpoint) if self.convergence is None and epoch == self.epochs: converged", "{:4e}\".format( epoch, ts, loss.detach(), rmse, rmse_atom ) ) else: test_model", "just intialize those that are # a linear layer. logger.warning(", "parameters: {}.\".format(total_params)) logger.info(\"Number of training parameters: {}.\".format(train_params)) logger.info(\" \") logger.info(self.linears)", "== len(self.hiddenlayers): inp_dimension = self.hiddenlayers[index - 1] out_dimension = 1", "the handler. optimizer : tuple The optimizer is a tuple", "{:4e} {:4e} {:4e}\".format( epoch, ts, loss.detach(), rmse, rmse_atom, rmse_test, rmse_atom_test,", "for index, (symbol, features) in enumerate(data): counter = 0 layer_counter", "dtype=object) running_loss += loss outputs_.append(outputs) grads.append(grad) grads = sum(grads) for", "# Get client to send futures to the scheduler client", "pandas as pd from collections import OrderedDict from ml4chem.metrics import", "class method clears previous gradients, iterates over batches, accumulates the", "`checkpoint` is a integer or -1 for saving all epochs,", ") ) logger.info( \"{:6s} {:19s} {:12s} {:8s} {:8s}\".format( \"------\", \"-------------------\",", "rmse_atom, rmse_test, rmse_atom_test, ) ) if self.checkpoint is not None:", "= torch.nn.Parameter(torch.tensor(slope, requires_grad=True)) self.register_parameter(intercept_name, intercept) self.register_parameter(slope_name, slope) elif purpose ==", "{:19s} {:12s} {:12s} {:12s} {:12s} {:16s}\".format( \"Epoch\", \"Time Stamp\", \"Loss\",", "lr_scheduler) self.atoms_per_image = atoms_per_image self.convergence = convergence self.device = device", "to perform forward() and get gradients. uncertainty : list A", "logger.info(\"=====\") now = datetime.datetime.now() logger.info( \"Module accessed on {}.\".format(now.strftime(\"%Y-%m-%d %H:%M:%S\"))", "for each layer. \"\"\" activations = [] columns = [\"hash\",", "\"------------\", \"------------\", \"------------\", \"------------\", \"------------\", ) ) converged = False", ": list List of inputs in the feature space. Returns", "[] for hash in X: image = X[hash] atomic_energies =", "Data object created from the handler. optimizer : tuple The", "optimizer : tuple The optimizer is a tuple with the", "= datetime.datetime.fromtimestamp(ts).strftime(\"%Y-%m-%d \" \"%H:%M:%S\") if self.test is None: logger.info( \"{:6d}", "logger.info( \"Module accessed on {}.\".format(now.strftime(\"%Y-%m-%d %H:%M:%S\")) ) logger.info(\"Model name: {}.\".format(self.name()))", "test=None, ): self.initial_time = time.time() if lossfxn is None: lossfxn", "\"\"\"A function that allows training per batches Parameters ---------- index", "+= 1 elif isinstance(layer, torch.nn.Linear) and counter > 0: x", "with input data points in batch with index. targets :", "svm=False)) if uncertainty != None: uncertainty = list(get_chunks(uncertainty, batch_size, svm=False))", "except AttributeError: # This exception catches the case where an", ": dict Image with structure hash, features. model : object", "certain # atom. For example, suppose two batches with 2", "loss : tensor The loss function of the batch. \"\"\"", "of each hidden-layer This function allows to extract activations of", "not in columns: columns.append(layer_column_name) counter += 1 layer_counter += 1", "= 1 _linear = torch.nn.Linear(inp_dimension, out_dimension) linears.append(_linear) # These are", "datetime.datetime.now() logger.info( \"Module accessed on {}.\".format(now.strftime(\"%Y-%m-%d %H:%M:%S\")) ) logger.info(\"Model name:", "_linear = torch.nn.Linear(inp_dimension, out_dimension) linears.append(_linear) # These are hidden-layers else:", "\"celu\": torch.nn.CELU, } hl = len(self.hiddenlayers) if purpose == \"training\":", ": obj A loss function object. atoms_per_image : list Atoms", "first batch for N is 0. gradient = 0.0 gradients.append(gradient)", "training procedures. >>> test = {\"features\": test_space, \"targets\": test_targets, \"data\":", "path is where the checkpoint is stored. Default is None", "function of the batch. \"\"\" inputs = OrderedDict(chunk) outputs =", "epochs, users can set a convergence criterion. Supported keys are", "<NAME> : A modular approach to machine learning in atomistic", "A dictionary used to compute the error over a validation/test", "total gradient from the first batch for N is 0.", "extract activations of each hidden-layer of the neural network. Parameters", "or cpu? \"\"\" outputs_ = [] # Get client to", "data points per batch to use for training. Default is", "running_loss += loss outputs_.append(outputs) grads.append(grad) grads = sum(grads) for index,", "is None: logger.info( \"{:6d} {} {:8e} {:4e} {:4e}\".format( epoch, ts,", "Parameters ---------- inputs : dict Dictionary with hashed feature space.", "Data object created from the handler. purpose : str Purpose", "test : dict A dictionary used to compute the error", "elif index == len(self.hiddenlayers): inp_dimension = self.hiddenlayers[index - 1] out_dimension", "self.scheduler = get_lr_scheduler(self.optimizer, lr_scheduler) self.atoms_per_image = atoms_per_image self.convergence = convergence", "\"\"\"Get activations of each hidden-layer This function allows to extract", ": int Index of batch. chunk : tensor or list", "loss outputs_.append(outputs) grads.append(grad) grads = sum(grads) for index, param in", "{} {:8e} {:4e} {:4e} {:4e} {:4e}\".format( epoch, ts, loss.detach(), rmse,", "from ml4chem.metrics import compute_rmse from ml4chem.atomistic.models.base import DeepLearningModel, DeepLearningTrainer from", "self.model = model self.lr_scheduler = lr_scheduler self.lossfxn = lossfxn self.checkpoint", "= [client.scatter(u) for u in uncertainty] else: self.uncertainty = uncertainty", "= symbol.decode(\"utf-8\") x = self.linears[symbol](x) intercept_name = \"intercept_\" + symbol", "and get gradients. uncertainty : list A list of uncertainties", "method clears previous gradients, iterates over batches, accumulates the gradients,", "= X[hash] atomic_energies = [] for symbol, x in image:", "linears]) self.linears = torch.nn.ModuleDict(symbol_model_pair) if purpose == \"training\": total_params, train_params", "self.device = device self.epochs = epochs self.model = model self.lr_scheduler", "torch.nn.ModuleDict(symbol_model_pair) if purpose == \"training\": total_params, train_params = get_number_of_parameters(self) logger.info(\"Total", "epochs self.model = model self.lr_scheduler = lr_scheduler self.lossfxn = lossfxn", "\"{:6s} {:19s} {:12s} {:8s} {:8s} {:8s} {:8s}\".format( \"------\", \"-------------------\", \"------------\",", "linear layer. logger.warning( \"Initialization of weights with Xavier Uniform by", "that are # a linear layer. logger.warning( \"Initialization of weights", "if self.checkpoint is not None: self.checkpoint_save(epoch, self.model, **self.checkpoint) if self.convergence", "activations : DataFrame A DataFrame with activations for each layer.", ": str Calculation can be run in the cpu or", "{lossfxn.__name__}\") if uncertainty is not None: logger.info(\"Options:\") logger.info(f\" - Uncertainty", "is not None if self.lr_scheduler is not None: self.scheduler.step(loss) print(\"Epoch", "1 layer_counter += 1 activations.append(data_) del data_ # Create DataFrame", "is fixed. if isinstance(symbol, bytes): symbol = symbol.decode(\"utf-8\") x =", "test_data = self.test.get(\"data\", None) logger.info( \"{:6s} {:19s} {:12s} {:12s} {:12s}", "DeepLearningModel, DeepLearningTrainer from ml4chem.atomistic.models.loss import AtomicMSELoss from ml4chem.optim.handler import get_optimizer,", "Returns ------- activations : DataFrame A DataFrame with activations for", "{:12s} {:8s} {:8s}\".format( \"------\", \"-------------------\", \"------------\", \"------------\", \"------------\", ) )", "activations of each hidden-layer of the neural network. Parameters ----------", "\"Error/atom (t)\", ) ) logger.info( \"{:6s} {:19s} {:12s} {:8s} {:8s}", "{:12s} {:16s}\".format( \"Epoch\", \"Time Stamp\", \"Loss\", \"Error/img\", \"Error/atom\", \"Error/img (t)\",", "------- outputs : tensor A list of tensors with energies", "optimizer, model.parameters() ) if lr_scheduler is not None: self.scheduler =", "It is not the same as weight decay. convergence :", "from pprint import pformat # Setting precision and starting logger", "features _inputs[hash].append((symbol, vector.cuda())) inputs = _inputs move_time = time.time() -", "if self.test is None: logger.info( \"{:6d} {} {:8e} {:4e} {:4e}\".format(", "object. - \"targets\": test set targets. - \"features\": a feature", "torch.tensor(intercept, requires_grad=True) ) slope = (data.max_energy - data.min_energy) / 2.0", "by Behler and Parrinello. Parameters ---------- hiddenlayers : tuple Structure", "object A ML4Chem model object. numpy : bool Whether we", "outputs.append(image_energy) outputs = torch.stack(outputs) return outputs def get_activations(self, images, model=None,", "rmse < self.convergence[\"energy\"]: converged = True training_time = time.time() -", "+= loss outputs_.append(outputs) grads.append(grad) grads = sum(grads) for index, param", "for hash, data in images.items(): for index, (symbol, features) in", "tuple Tuple with structure: scheduler's name and a dictionary with", "futures to the scheduler client = dask.distributed.get_client() running_loss = torch.tensor(0,", "it turns out that # N is also available only", "self.register_parameter(slope_name, slope) elif purpose == \"inference\": intercept = torch.nn.Parameter(torch.tensor(0.0)) slope", "torch.nn.Module): \"\"\"Atom-centered Neural Network Regression with Pytorch This model is", "to penalize during the loss function evaluation. model : obj", "= [\"hash\", \"atom.index\", \"atom.symbol\"] if model is None: model =", "the gradients, update model params, and finally returns loss and", "= time.time() - self.initial_time h, m, s = convert_elapsed_time(move_time) logger.info(", "None: loss = lossfxn(outputs, targets[index], atoms_per_image[index]) else: loss = lossfxn(", "H, O but it turns out that # N is", "each layer. \"\"\" activations = [] columns = [\"hash\", \"atom.index\",", "tensor or list The targets. model : obj Pytorch model", "data_ = [hash, index, symbol, x.detach_()] layer_column_name = f\"layer{layer_counter}\" if", "of gradients for index, chunk in enumerate(chunks): accumulation.append( client.submit( train.train_batches,", "model self.lr_scheduler = lr_scheduler self.lossfxn = lossfxn self.checkpoint = checkpoint", "criterion. Supported keys are \"training\" and \"test\". lossfxn : obj", "lossfxn, atoms_per_image, device ): \"\"\"A function that allows training per", "not converged: epoch += 1 self.optimizer.zero_grad() # clear previous gradients", "elements per batch.\".format(batch_size)) logger.info(\" \") atoms_per_image = [ torch.tensor(n_atoms, requires_grad=False,", "the gradients, reduces the gradients, update model params, and finally", "of the batch. \"\"\" inputs = OrderedDict(chunk) outputs = model(inputs)", "image and per/atom rmse = client.submit(compute_rmse, *(outputs_, self.targets)) atoms_per_image =", "layers. linears = torch.nn.Sequential(*linears) symbol_model_pair.append([symbol, linears]) self.linears = torch.nn.ModuleDict(symbol_model_pair) if", "epoch += 1 self.optimizer.zero_grad() # clear previous gradients loss, outputs_", "is a integer or -1 for saving all epochs, and", "outputs, loss, grad in accumulation: grad = np.array(grad, dtype=object) running_loss", "self.register_parameter(intercept_name, intercept) self.register_parameter(slope_name, slope) elif purpose == \"inference\": intercept =", "a feature space obtained using `features.calculate()`. \"\"\" def __init__( self,", "= rmse_atom.result() _loss.append(loss.item()) _rmse.append(rmse) # In the case that lr_scheduler", "{:8e} {:4e} {:4e}\".format( epoch, ts, loss.detach(), rmse, rmse_atom ) )", "epoch, ts, loss.detach(), rmse, rmse_atom, rmse_test, rmse_atom_test, ) ) if", "label, \"checkpoint\": 100, \"path\": \"\"} `label` refers to the name", "logger.info( \"{:6s} {:19s} {:12s} {:12s} {:8s}\".format( \"Epoch\", \"Time Stamp\", \"Loss\",", "propagation and it returns the atomic energy. Parameters ---------- X", "This is forward propagation and it returns the atomic energy.", "Lett. 98, 146401 (2007). 2. <NAME>. & <NAME> : A", "linears.append(_linear) linears.append(activation[self.activation]()) # Stacking up the layers. linears = torch.nn.Sequential(*linears)", "self.lossfxn = lossfxn self.checkpoint = checkpoint self.test = test #", "not None: self.scheduler.step(loss) print(\"Epoch {} lr {}\".format(epoch, get_lr(self.optimizer))) ts =", "object torch.set_printoptions(precision=10) logger = logging.getLogger() class NeuralNetwork(DeepLearningModel, torch.nn.Module): \"\"\"Atom-centered Neural", "outputs = model(inputs) if uncertainty == None: loss = lossfxn(outputs,", "Calculation can be run in the cpu or cuda (gpu).", "cpu or cuda (gpu). batch_size : int Number of data", "slope_name) intercept = getattr(self, intercept_name) x = (slope * x)", "# contribution of the total gradient from the first batch", "= [ torch.tensor(n_atoms, requires_grad=False, dtype=torch.float) for n_atoms in atoms_per_image ]", "chunk in enumerate(chunks): accumulation.append( client.submit( train.train_batches, *( index, chunk, targets,", "self.test.get(\"features\", None) test_targets = self.test.get(\"targets\", None) test_data = self.test.get(\"data\", None)", "list(get_chunks(atoms_per_image, batch_size, svm=False)) if uncertainty != None: uncertainty = list(get_chunks(uncertainty,", "and per/atom rmse = client.submit(compute_rmse, *(outputs_, self.targets)) atoms_per_image = torch.cat(self.atoms_per_image)", "None: self.uncertainty = [client.scatter(u) for u in uncertainty] else: self.uncertainty", "NeuralNetwork(DeepLearningModel, torch.nn.Module): \"\"\"Atom-centered Neural Network Regression with Pytorch This model", "True training_time = time.time() - self.initial_time h, m, s =", "slope = torch.nn.Parameter(torch.tensor(slope, requires_grad=True)) self.register_parameter(intercept_name, intercept) self.register_parameter(slope_name, slope) elif purpose", "targets. - \"features\": a feature space obtained using `features.calculate()`. \"\"\"", "the structure: >>> ('adam', {'lr': float, 'weight_decay'=float}) epochs : int", "targets : tensor or list The targets. uncertainty : list", "self.test.get(\"targets\", None) test_data = self.test.get(\"data\", None) logger.info( \"{:6s} {:19s} {:12s}", "send futures to the scheduler client = dask.distributed.get_client() running_loss =", "we want numpy arrays or tensors. Returns ------- activations :", "1 self.optimizer.zero_grad() # clear previous gradients loss, outputs_ = train.closure(", "of training parameters: {}.\".format(train_params)) logger.info(\" \") logger.info(self.linears) # Iterate over", "\"------------\", \"------------\", \"------------\", ) ) else: test_features = self.test.get(\"features\", None)", "hunger games begin... self.trainer() def trainer(self): \"\"\"Run the training class\"\"\"", "is the output layer elif index == len(self.hiddenlayers): inp_dimension =", "uncertainty, model, lossfxn, atoms_per_image, device, ), ) ) dask.distributed.wait(accumulation) accumulation", "for saving all epochs, and the path is where the", "is stored. Default is None and no checkpoint is saved.", ") # We step the optimizer if self.optimizer_name != \"LBFGS\":", "List of inputs in the feature space. Returns ------- outputs", "Generalized Neural-Network Representation of High-Dimensional Potential-Energy Surfaces. Phys. Rev. Lett.", "integer or -1 for saving all epochs, and the path", "logger.info( \"{:6s} {:19s} {:12s} {:12s} {:12s} {:12s} {:16s}\".format( \"Epoch\", \"Time", "index == 0: out_dimension = self.hiddenlayers[0] _linear = torch.nn.Linear(input_dimension, out_dimension)", "logging.info(\"-----------------\") logging.info(\"Number of batches: {}.\".format(len(chunks))) logging.info(\"Batch size: {} elements per", "in targets] if uncertainty != None: self.uncertainty = [client.scatter(u) for", "structure: >>> ('adam', {'lr': float, 'weight_decay'=float}) epochs : int Number", "grads = sum(grads) for index, param in enumerate(model.parameters()): param.grad =", "structure: >>> checkpoint = {\"label\": label, \"checkpoint\": 100, \"path\": \"\"}", "\"Error/img\", \"Error/atom\" ) ) logger.info( \"{:6s} {:19s} {:12s} {:8s} {:8s}\".format(", "get_lr_scheduler, get_lr from ml4chem.utils import convert_elapsed_time, get_chunks, get_number_of_parameters from pprint", "for t in targets] if device == \"cuda\": logger.info(\"Moving data", "{:8s} {:8s} {:8s}\".format( \"------\", \"-------------------\", \"------------\", \"------------\", \"------------\", \"------------\", \"------------\",", "gradients = [] for param in model.parameters(): try: gradient =", "try: gradient = param.grad.detach().numpy() except AttributeError: # This exception catches", "if uncertainty != None: self.uncertainty = [client.scatter(u) for u in", ": int Input's dimension. data : object Data object created", "use for training. Default is None. lr_scheduler : tuple Tuple", "in enumerate(model.linears[symbol].modules()): if isinstance(layer, torch.nn.Linear) and counter == 0: x", "index, param in enumerate(model.parameters()): param.grad = torch.tensor(grads[index], dtype=torch.float) del accumulation", "This is the output layer elif index == len(self.hiddenlayers): inp_dimension", "games begin... self.trainer() def trainer(self): \"\"\"Run the training class\"\"\" logger.info(\"", "bytes): symbol = symbol.decode(\"utf-8\") x = self.linears[symbol](x) intercept_name = \"intercept_\"", "targets] if device == \"cuda\": logger.info(\"Moving data to CUDA...\") atoms_per_image", "= self.model.eval() test_predictions = test_model(test_features).detach() rmse_test = client.submit( compute_rmse, *(test_predictions,", ": tuple Structure of hidden layers in the neural network.", "get_chunks, get_number_of_parameters from pprint import pformat # Setting precision and", "intercept atomic_energies.append(x) atomic_energies = torch.cat(atomic_energies) image_energy = torch.sum(atomic_energies) outputs.append(image_energy) outputs", "in chunks] self.targets = [client.scatter(target) for target in targets] if", "[client.scatter(u) for u in uncertainty] else: self.uncertainty = uncertainty #", "# RMSE per image and per/atom rmse = client.submit(compute_rmse, *(outputs_,", "import pandas as pd from collections import OrderedDict from ml4chem.metrics", "move_time = time.time() - self.initial_time h, m, s = convert_elapsed_time(move_time)", "the atomic energy. Parameters ---------- X : list List of", "because we are doing atom-centered methods. device : str Are", "Parameters ---------- Cls : object Class object. chunks : tensor", "model.parameters() ) if lr_scheduler is not None: self.scheduler = get_lr_scheduler(self.optimizer,", "symbol, x in image: # FIXME this conditional can be", "Pytorch model to perform forward() and get gradients. lossfxn :", "\"------------\", ) ) converged = False _loss = [] _rmse", "else: self.uncertainty = uncertainty # Let the hunger games begin...", "test_space, \"targets\": test_targets, \"data\": data_test} The keys,values of the dictionary", "+ symbol slope_name = \"slope_\" + symbol if purpose ==", "\" + str(self.hiddenlayers)[1:-1] + \", output)\" ) ) layers =", "class\"\"\" return cls.NAME def __init__(self, hiddenlayers=(3, 3), activation=\"relu\", **kwargs): super(DeepLearningModel,", "aka y. model : object The NeuralNetwork class. data :", "\"\"\"Run the training class\"\"\" logger.info(\" \") logger.info(\"Starting training...\\n\") if self.test", "layer_counter = 0 for l, layer in enumerate(model.linears[symbol].modules()): if isinstance(layer,", "batches, accumulates the gradients, reduces the gradients, update model params,", "from the handler. purpose : str Purpose of this model:", "= list(get_chunks(atoms_per_image, batch_size, svm=False)) if uncertainty != None: uncertainty =", "function evaluation. checkpoint : dict Set checkpoints. Dictionary with following", "This exception catches the case where an image does not", "with index. targets : tensor or list The targets. uncertainty", "outputs_ = train.closure( self.chunks, self.targets, self.uncertainty, self.model, self.lossfxn, self.atoms_per_image, self.device,", "not None if self.lr_scheduler is not None: self.scheduler.step(loss) print(\"Epoch {}", "} hl = len(self.hiddenlayers) if purpose == \"training\": logger.info(\" \")", "from ml4chem.optim.handler import get_optimizer, get_lr_scheduler, get_lr from ml4chem.utils import convert_elapsed_time,", "with structure: scheduler's name and a dictionary with keyword arguments.", "or tensors. Returns ------- activations : DataFrame A DataFrame with", "+ str(self.hiddenlayers)[1:-1] + \", output)\" ) ) layers = range(len(self.hiddenlayers)", "previous gradients, iterates over batches, accumulates the gradients, reduces the", "intercept_name) x = (slope * x) + intercept atomic_energies.append(x) atomic_energies", "elif self.convergence is not None and rmse < self.convergence[\"energy\"]: converged", "std=0.01) torch.nn.init.xavier_uniform_(m.weight) def forward(self, X): \"\"\"Forward propagation This is forward", "for target in targets] if uncertainty != None: self.uncertainty =", "atoms_per_image ] targets = [torch.tensor(t, requires_grad=False) for t in targets]", "_rmse.append(rmse) # In the case that lr_scheduler is not None", "- \"targets\": test set targets. - \"features\": a feature space", "with Pytorch This model is based on Ref. 1 by", "lossfxn : obj A loss function object. atoms_per_image : list", "[] _rmse = [] epoch = 0 client = dask.distributed.get_client()", "if device == \"cuda\": logger.info(\"Moving data to CUDA...\") atoms_per_image =", "This is the input layer if index == 0: out_dimension", ") rmse = rmse.result() rmse_atom = rmse_atom.result() _loss.append(loss.item()) _rmse.append(rmse) #", "points in batch with index. targets : tensor or list", "compute_rmse, *(test_predictions, test_targets) ) atoms_per_image_test = torch.tensor( test_data.atoms_per_image, requires_grad=False )", "{}\".format( \"(input, \" + str(self.hiddenlayers)[1:-1] + \", output)\" ) )", "'patience': 10}) uncertainty : list A list of uncertainties that", "] targets = [torch.tensor(t, requires_grad=False) for t in targets] if", "self.optimizer_name != \"LBFGS\": self.optimizer.step() else: options = {\"closure\": self.closure, \"current_loss\":", "CUDA...\") atoms_per_image = atoms_per_image.cuda() targets = targets.cuda() _inputs = OrderedDict()", "training_time = time.time() - self.initial_time h, m, s = convert_elapsed_time(training_time)", "symbol_model_pair.append([symbol, linears]) self.linears = torch.nn.ModuleDict(symbol_model_pair) if purpose == \"training\": total_params,", ": tuple The optimizer is a tuple with the structure:", "atom-centered methods. device : str Are we running cuda or", "ts = time.time() ts = datetime.datetime.fromtimestamp(ts).strftime(\"%Y-%m-%d \" \"%H:%M:%S\") if self.test", "logger.info(self.linears) # Iterate over all modules and just intialize those", "In the first batch we have only C, H, O", "scattering client = dask.distributed.get_client() self.chunks = [client.scatter(chunk) for chunk in", "intercept) self.register_parameter(slope_name, slope) elif purpose == \"inference\": intercept = torch.nn.Parameter(torch.tensor(0.0))", "layers = range(len(self.hiddenlayers) + 1) try: unique_element_symbols = data.unique_element_symbols[purpose] except", "slope) for index in layers: # This is the input", "client.submit( train.train_batches, *( index, chunk, targets, uncertainty, model, lossfxn, atoms_per_image,", "data to CUDA...\") atoms_per_image = atoms_per_image.cuda() targets = targets.cuda() _inputs", "from ml4chem.atomistic.models.base import DeepLearningModel, DeepLearningTrainer from ml4chem.atomistic.models.loss import AtomicMSELoss from", "= get_optimizer( optimizer, model.parameters() ) if lr_scheduler is not None:", "self.chunks, self.targets, self.uncertainty, self.model, self.lossfxn, self.atoms_per_image, self.device, ) # We", "images.items(): for index, (symbol, features) in enumerate(data): counter = 0", ": tensor or list The targets. uncertainty : list A", "# This is the input layer if index == 0:", "@classmethod def train_batches( Cls, index, chunk, targets, uncertainty, model, lossfxn,", "\"slope_\" + symbol if purpose == \"training\": intercept = (data.max_energy", "\", output)\" ) ) layers = range(len(self.hiddenlayers) + 1) try:", "epochs=100, convergence=None, lossfxn=None, device=\"cpu\", batch_size=None, lr_scheduler=None, uncertainty=None, checkpoint=None, test=None, ):", "or -1 for saving all epochs, and the path is", "from ml4chem.utils import convert_elapsed_time, get_chunks, get_number_of_parameters from pprint import pformat", "numpy : bool Whether we want numpy arrays or tensors.", "hash in X: image = X[hash] atomic_energies = [] for", "hash, features. model : object A ML4Chem model object. numpy", "converged = True elif self.convergence is not None and rmse", "(gpu). batch_size : int Number of data points per batch", "param in enumerate(model.parameters()): param.grad = torch.tensor(grads[index], dtype=torch.float) del accumulation del", "chunks : tensor or list Tensor with input data points", "index : int Index of batch. chunk : tensor or", "now = datetime.datetime.now() logger.info( \"Module accessed on {}.\".format(now.strftime(\"%Y-%m-%d %H:%M:%S\")) )", "<NAME>. & <NAME>. Generalized Neural-Network Representation of High-Dimensional Potential-Energy Surfaces.", "contribution of the total gradient from the first batch for", "* x) + intercept atomic_energies.append(x) atomic_energies = torch.cat(atomic_energies) image_energy =", "model to perform forward() and get gradients. lossfxn : obj", "index, chunk, targets, uncertainty, model, lossfxn, atoms_per_image, device ): \"\"\"A", "keys are \"training\" and \"test\". lossfxn : obj A loss", "atoms_per_image[index], uncertainty[index] ) loss.backward() gradients = [] for param in", "import time import torch import numpy as np import pandas", "slope_name = \"slope_\" + symbol if purpose == \"training\": intercept", "purpose == \"training\": intercept = (data.max_energy + data.min_energy) / 2.0", "is 0. gradient = 0.0 gradients.append(gradient) return outputs, loss, gradients", "logger.info(\"\") atoms_per_image = data.atoms_per_image if batch_size is None: batch_size =", "dask.distributed.get_client() running_loss = torch.tensor(0, dtype=torch.float) accumulation = [] grads =", "self.convergence is not None and rmse < self.convergence[\"energy\"]: converged =", "@classmethod def closure( Cls, chunks, targets, uncertainty, model, lossfxn, atoms_per_image,", "each hidden-layer of the neural network. Parameters ---------- image :", "batch_size = len(inputs.values()) if isinstance(batch_size, int): # Data batches chunks", "torch.nn.Linear): # nn.init.normal_(m.weight) # , mean=0, std=0.01) torch.nn.init.xavier_uniform_(m.weight) def forward(self,", "Returns ------- loss : tensor The loss function of the", "param.grad = torch.tensor(grads[index], dtype=torch.float) del accumulation del grads return running_loss,", "self.hiddenlayers[0] _linear = torch.nn.Linear(input_dimension, out_dimension) linears.append(_linear) linears.append(activation[self.activation]()) # This is", "A modular approach to machine learning in atomistic simulations. Comput.", "all modules and just intialize those that are # a", "# clear previous gradients loss, outputs_ = train.closure( self.chunks, self.targets,", "Dictionary with hashed feature space. targets : list The expected", "\") logger.info(self.linears) # Iterate over all modules and just intialize", "cuda (gpu). batch_size : int Number of data points per", "== 0: out_dimension = self.hiddenlayers[0] _linear = torch.nn.Linear(input_dimension, out_dimension) linears.append(_linear)", "# , mean=0, std=0.01) torch.nn.init.xavier_uniform_(m.weight) def forward(self, X): \"\"\"Forward propagation", "model : object The NeuralNetwork class. data : object Data", "0: x = layer(x) if numpy: data_.append(x.detach_().numpy()) else: data_.append(x.detach_()) layer_column_name", "# a linear layer. logger.warning( \"Initialization of weights with Xavier", "Supported \"tanh\", \"relu\", or \"celu\". References ---------- 1. <NAME>. &", "loss function of the batch. \"\"\" inputs = OrderedDict(chunk) outputs", "data.atoms_per_image if batch_size is None: batch_size = len(inputs.values()) if isinstance(batch_size,", "by \" \"default.\" ) for m in self.modules(): if isinstance(m,", "with 2 molecules each. # In the first batch we", "self.lr_scheduler is not None: self.scheduler.step(loss) print(\"Epoch {} lr {}\".format(epoch, get_lr(self.optimizer)))", "dictionary are: - \"data\": a `Data` object. - \"targets\": test", "but it turns out that # N is also available", "created from the handler. purpose : str Purpose of this", "energy. Parameters ---------- X : list List of inputs in", "- data.min_energy) / 2.0 slope = torch.nn.Parameter(torch.tensor(slope, requires_grad=True)) self.register_parameter(intercept_name, intercept)", "= dask.distributed.get_client() while not converged: epoch += 1 self.optimizer.zero_grad() #", "the model Parameters ---------- inputs : dict Dictionary with hashed", "= train.closure( self.chunks, self.targets, self.uncertainty, self.model, self.lossfxn, self.atoms_per_image, self.device, )", "\"Time Stamp\", \"Loss\", \"Error/img\", \"Error/atom\" ) ) logger.info( \"{:6s} {:19s}", "bool Whether we want numpy arrays or tensors. Returns -------", "of the total gradient from the first batch for N", "data : object Data object created from the handler. purpose", "uncertainty[index] ) loss.backward() gradients = [] for param in model.parameters():", "and it returns the atomic energy. Parameters ---------- X :", "f\"layer{layer_counter}\" if layer_column_name not in columns: columns.append(layer_column_name) counter += 1", "or cpu? Returns ------- loss : tensor The loss function", "batch.\".format(batch_size)) logger.info(\" \") atoms_per_image = [ torch.tensor(n_atoms, requires_grad=False, dtype=torch.float) for", "0: x = layer(features) if numpy: data_ = [hash, index,", "targets, uncertainty, model, lossfxn, atoms_per_image, device ): \"\"\"Closure This class", "columns.append(layer_column_name) counter += 1 layer_counter += 1 elif isinstance(layer, torch.nn.Linear)", "as weight decay. convergence : dict Instead of using epochs,", "Let the hunger games begin... self.trainer() def trainer(self): \"\"\"Run the", "loss function object. atoms_per_image : list Atoms per image because", "dict Dictionary with hashed feature space. targets : list The", "checkpoint=None, test=None, ): self.initial_time = time.time() if lossfxn is None:", "is saved. test : dict A dictionary used to compute", "in enumerate(chunks): accumulation.append( client.submit( train.train_batches, *( index, chunk, targets, uncertainty,", "getattr(self, intercept_name) x = (slope * x) + intercept atomic_energies.append(x)", "del accumulation del grads return running_loss, outputs_ @classmethod def train_batches(", "range(len(self.hiddenlayers) + 1) try: unique_element_symbols = data.unique_element_symbols[purpose] except TypeError: unique_element_symbols", "Uncertainty penalization: {pformat(uncertainty)}\") logger.info(\"\") atoms_per_image = data.atoms_per_image if batch_size is", "columns = [\"hash\", \"atom.index\", \"atom.symbol\"] if model is None: model", "no checkpoint is saved. test : dict A dictionary used", "tensor A list of tensors with energies per image. \"\"\"", "targets : tensor or list The targets. model : obj", "symbol_model_pair = [] for symbol in unique_element_symbols: linears = []", "layer_counter += 1 elif isinstance(layer, torch.nn.Linear) and counter > 0:", "model, lossfxn, atoms_per_image, device ): \"\"\"Closure This class method clears", "= time.time() if lossfxn is None: lossfxn = AtomicMSELoss logger.info(\"\")", "name: {}.\".format(self.name())) logger.info(\"Number of hidden-layers: {}\".format(hl)) logger.info( \"Structure of Neural", "test_predictions = test_model(test_features).detach() rmse_test = client.submit( compute_rmse, *(test_predictions, test_targets) )", "self.optimizer_name, self.optimizer = get_optimizer( optimizer, model.parameters() ) if lr_scheduler is", "x.detach_().numpy()] else: data_ = [hash, index, symbol, x.detach_()] layer_column_name =", "not None: self.scheduler = get_lr_scheduler(self.optimizer, lr_scheduler) self.atoms_per_image = atoms_per_image self.convergence", "Behler and Parrinello. Parameters ---------- hiddenlayers : tuple Structure of", "used to penalize during the loss function evaluation. model :", "lr_scheduler=None, uncertainty=None, checkpoint=None, test=None, ): self.initial_time = time.time() if lossfxn", "targets[index], atoms_per_image[index], uncertainty[index] ) loss.backward() gradients = [] for param", "is not None: self.scheduler = get_lr_scheduler(self.optimizer, lr_scheduler) self.atoms_per_image = atoms_per_image", "in atoms_per_image ] targets = [torch.tensor(t, requires_grad=False) for t in", "[] intercept_name = \"intercept_\" + symbol slope_name = \"slope_\" +", "\"\"\"Forward propagation This is forward propagation and it returns the", "*(test_predictions, test_targets) ) atoms_per_image_test = torch.tensor( test_data.atoms_per_image, requires_grad=False ) rmse_atom_test", "saved. test : dict A dictionary used to compute the", "symbol, x.detach_()] layer_column_name = f\"layer{layer_counter}\" if layer_column_name not in columns:", "clears previous gradients, iterates over batches, accumulates the gradients, reduces", "if isinstance(m, torch.nn.Linear): # nn.init.normal_(m.weight) # , mean=0, std=0.01) torch.nn.init.xavier_uniform_(m.weight)", "pprint import pformat # Setting precision and starting logger object", "hl = len(self.hiddenlayers) if purpose == \"training\": logger.info(\" \") logger.info(\"Model\")", "list List of inputs in the feature space. Returns -------", "symbol, x.detach_().numpy()] else: data_ = [hash, index, symbol, x.detach_()] layer_column_name", "= data.get_unique_element_symbols(purpose=purpose) unique_element_symbols = unique_element_symbols[purpose] symbol_model_pair = [] for symbol", "**kwargs): super(DeepLearningModel, self).__init__() self.hiddenlayers = hiddenlayers self.activation = activation def", "are hidden-layers else: inp_dimension = self.hiddenlayers[index - 1] out_dimension =", "References ---------- 1. <NAME>. & <NAME>. Generalized Neural-Network Representation of", "Atoms per image because we are doing atom-centered methods. device", "object. atoms_per_image : list Atoms per image because we are", "ml4chem.metrics import compute_rmse from ml4chem.atomistic.models.base import DeepLearningModel, DeepLearningTrainer from ml4chem.atomistic.models.loss", "isinstance(layer, torch.nn.Linear) and counter == 0: x = layer(features) if", "[hash, index, symbol, x.detach_().numpy()] else: data_ = [hash, index, symbol,", "uncertainty != None: uncertainty = list(get_chunks(uncertainty, batch_size, svm=False)) uncertainty =", "outputs, targets[index], atoms_per_image[index], uncertainty[index] ) loss.backward() gradients = [] for", "test_model = self.model.eval() test_predictions = test_model(test_features).detach() rmse_test = client.submit( compute_rmse,", "symbol slope_name = \"slope_\" + symbol if purpose == \"training\":", "\"Data moved to GPU in {} hours {} minutes {:.2f}", ": object Class object. chunks : tensor or list Tensor", "of parameters: {}.\".format(total_params)) logger.info(\"Number of training parameters: {}.\".format(train_params)) logger.info(\" \")", "1] out_dimension = self.hiddenlayers[index] _linear = torch.nn.Linear(inp_dimension, out_dimension) linears.append(_linear) linears.append(activation[self.activation]())", ": bool Whether we want numpy arrays or tensors. Returns", "atoms_per_image self.convergence = convergence self.device = device self.epochs = epochs", "columns=columns) return df class train(DeepLearningTrainer): \"\"\"Train the model Parameters ----------", "get_lr_scheduler(self.optimizer, lr_scheduler) self.atoms_per_image = atoms_per_image self.convergence = convergence self.device =", "def trainer(self): \"\"\"Run the training class\"\"\" logger.info(\" \") logger.info(\"Starting training...\\n\")", "energies per image. \"\"\" outputs = [] for hash in", "train_batches( Cls, index, chunk, targets, uncertainty, model, lossfxn, atoms_per_image, device", "def get_activations(self, images, model=None, numpy=True): \"\"\"Get activations of each hidden-layer", "= lr_scheduler self.lossfxn = lossfxn self.checkpoint = checkpoint self.test =", "data points in batch with index. targets : tensor or", "if self.lr_scheduler is not None: self.scheduler.step(loss) print(\"Epoch {} lr {}\".format(epoch,", "hidden layers in the neural network. activation : str Activation", "False _loss = [] _rmse = [] epoch = 0", "- 1] out_dimension = 1 _linear = torch.nn.Linear(inp_dimension, out_dimension) linears.append(_linear)", "where the checkpoint is stored. Default is None and no", "Neural Network Regression with Pytorch This model is based on", "logger.info(\"Options:\") logger.info(f\" - Uncertainty penalization: {pformat(uncertainty)}\") logger.info(\"\") atoms_per_image = data.atoms_per_image", "counter = 0 layer_counter = 0 for l, layer in", "None. lr_scheduler : tuple Tuple with structure: scheduler's name and", "available only in the second batch. The # contribution of", "{:8s} {:8s} {:8s} {:8s}\".format( \"------\", \"-------------------\", \"------------\", \"------------\", \"------------\", \"------------\",", "& <NAME> : A modular approach to machine learning in", "1 by Behler and Parrinello. Parameters ---------- hiddenlayers : tuple", "the feature space. Returns ------- outputs : tensor A list", "u in uncertainty] else: self.uncertainty = uncertainty # Let the", "symbol slope_name = \"slope_\" + symbol slope = getattr(self, slope_name)", "in {} hours {} minutes {:.2f} seconds.\".format(h, m, s) )", "this model: 'training', 'inference'. \"\"\" self.input_dimension = input_dimension activation =", "output)\" ) ) layers = range(len(self.hiddenlayers) + 1) try: unique_element_symbols", "from lists df = pd.DataFrame(activations, columns=columns) return df class train(DeepLearningTrainer):", "# Stacking up the layers. linears = torch.nn.Sequential(*linears) symbol_model_pair.append([symbol, linears])", "of full training cycles. regularization : float This is the", "to use for training. Default is None. lr_scheduler : tuple", "is not None: logger.info(\"Options:\") logger.info(f\" - Uncertainty penalization: {pformat(uncertainty)}\") logger.info(\"\")", "__init__(self, hiddenlayers=(3, 3), activation=\"relu\", **kwargs): super(DeepLearningModel, self).__init__() self.hiddenlayers = hiddenlayers", "= get_lr_scheduler(self.optimizer, lr_scheduler) self.atoms_per_image = atoms_per_image self.convergence = convergence self.device", "only in the second batch. The # contribution of the", "(t)\", ) ) logger.info( \"{:6s} {:19s} {:12s} {:8s} {:8s} {:8s}", "return outputs def get_activations(self, images, model=None, numpy=True): \"\"\"Get activations of", "model = self model.eval() for hash, data in images.items(): for", "epoch, ts, loss.detach(), rmse, rmse_atom ) ) else: test_model =", "data_ = [hash, index, symbol, x.detach_().numpy()] else: data_ = [hash,", "= f\"layer{layer_counter}\" if layer_column_name not in columns: columns.append(layer_column_name) counter +=", "ts, loss.detach(), rmse, rmse_atom, rmse_test, rmse_atom_test, ) ) if self.checkpoint", "gradients. lossfxn : obj A loss function object. atoms_per_image :", "The targets. uncertainty : list A list of uncertainties that", "str Are we running cuda or cpu? Returns ------- loss", "are \"training\" and \"test\". lossfxn : obj A loss function", "f in inputs.items(): _inputs[hash] = [] for features in f:", "= {\"label\": label, \"checkpoint\": 100, \"path\": \"\"} `label` refers to", "- 1] out_dimension = self.hiddenlayers[index] _linear = torch.nn.Linear(inp_dimension, out_dimension) linears.append(_linear)", "\"Training finished in {} hours {} minutes {:.2f} seconds.\".format(h, m,", "hidden-layer of the neural network. Parameters ---------- image : dict", ") else: test_features = self.test.get(\"features\", None) test_targets = self.test.get(\"targets\", None)", "model : object A ML4Chem model object. numpy : bool", "None), regularization=None, epochs=100, convergence=None, lossfxn=None, device=\"cpu\", batch_size=None, lr_scheduler=None, uncertainty=None, checkpoint=None,", "is based on Ref. 1 by Behler and Parrinello. Parameters", "The keys,values of the dictionary are: - \"data\": a `Data`", "numpy: data_.append(x.detach_().numpy()) else: data_.append(x.detach_()) layer_column_name = f\"layer{layer_counter}\" if layer_column_name not", "function allows to extract activations of each hidden-layer of the", "the name used to save the checkpoint, `checkpoint` is a", "parameters: {}.\".format(train_params)) logger.info(\" \") logger.info(self.linears) # Iterate over all modules", "gradients, iterates over batches, accumulates the gradients, reduces the gradients,", "following structure: >>> checkpoint = {\"label\": label, \"checkpoint\": 100, \"path\":", "for hash, f in inputs.items(): _inputs[hash] = [] for features", "train.train_batches, *( index, chunk, targets, uncertainty, model, lossfxn, atoms_per_image, device,", "Network Regression with Pytorch This model is based on Ref.", "name(cls): \"\"\"Returns name of class\"\"\" return cls.NAME def __init__(self, hiddenlayers=(3,", "100, \"path\": \"\"} `label` refers to the name used to", "up the layers. linears = torch.nn.Sequential(*linears) symbol_model_pair.append([symbol, linears]) self.linears =", "0: out_dimension = self.hiddenlayers[0] _linear = torch.nn.Linear(input_dimension, out_dimension) linears.append(_linear) linears.append(activation[self.activation]())", "n_atoms in atoms_per_image ] targets = [torch.tensor(t, requires_grad=False) for t", "\"features\": a feature space obtained using `features.calculate()`. \"\"\" def __init__(", "L2 regularization. It is not the same as weight decay.", "import logging import time import torch import numpy as np", ">>> ('adam', {'lr': float, 'weight_decay'=float}) epochs : int Number of", "targets, uncertainty, model, lossfxn, atoms_per_image, device, ), ) ) dask.distributed.wait(accumulation)", "requires_grad=False, dtype=torch.float) for n_atoms in atoms_per_image ] targets = [torch.tensor(t,", "if purpose == \"training\": total_params, train_params = get_number_of_parameters(self) logger.info(\"Total number", "isinstance(m, torch.nn.Linear): # nn.init.normal_(m.weight) # , mean=0, std=0.01) torch.nn.init.xavier_uniform_(m.weight) def", "outputs def get_activations(self, images, model=None, numpy=True): \"\"\"Get activations of each", "targets = list(get_chunks(targets, batch_size, svm=False)) atoms_per_image = list(get_chunks(atoms_per_image, batch_size, svm=False))", "\"data\": data_test} The keys,values of the dictionary are: - \"data\":", "per/atom rmse = client.submit(compute_rmse, *(outputs_, self.targets)) atoms_per_image = torch.cat(self.atoms_per_image) rmse_atom", "get_lr from ml4chem.utils import convert_elapsed_time, get_chunks, get_number_of_parameters from pprint import", "checkpoint self.test = test # Data scattering client = dask.distributed.get_client()", "input_dimension : int Input's dimension. data : object Data object", "{:12s} {:8s} {:8s} {:8s} {:8s}\".format( \"------\", \"-------------------\", \"------------\", \"------------\", \"------------\",", "dict Image with structure hash, features. model : object A", "`label` refers to the name used to save the checkpoint,", "import pformat # Setting precision and starting logger object torch.set_printoptions(precision=10)" ]
[ "from hatsploit.lib.storage import LocalStorage class DB: badges = Badges() config", "LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A", "self.badges.print_error(\"No __database__ section found!\") return if database['__database__']['type'] != \"modules\": self.badges.print_error(\"Not", "Exception: self.badges.print_error(\"Failed to connect payload database!\") return if '__database__' not", "json.load(open(path)) except Exception: self.badges.print_error(\"Failed to connect plugin database!\") return if", "= Badges() config = Config() local_storage = LocalStorage() def disconnect_payload_database(self,", "not os.path.exists(path) or not str.endswith(path, \"json\"): self.badges.print_error(\"Not a database!\") return", "= { name: database } data = { name: {", "a payload database!\") return del database['__database__'] payloads = { name:", "TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR", "self.badges.print_error(\"Failed to connect payload database!\") return if '__database__' not in", "connected!\") def disconnect_module_database(self, name): if self.local_storage.get(\"connected_module_databases\"): if name in self.local_storage.get(\"connected_module_databases\"):", "rights # to use, copy, modify, merge, publish, distribute, sublicense,", "del database['__database__'] modules = { name: database } data =", "{ 'path': path } } if not self.local_storage.get(\"connected_module_databases\"): self.local_storage.set(\"connected_module_databases\", {})", "name: { 'path': path } } if not self.local_storage.get(\"connected_plugin_databases\"): self.local_storage.set(\"connected_plugin_databases\",", "name): if self.local_storage.get(\"connected_plugin_databases\"): if name in self.local_storage.get(\"connected_plugin_databases\"): self.local_storage.delete_element(\"connected_plugin_databases\", name) self.local_storage.delete_element(\"plugins\",", "portions of the Software. # # THE SOFTWARE IS PROVIDED", "if self.local_storage.get(\"connected_module_databases\"): if name in self.local_storage.get(\"connected_module_databases\"): self.badges.print_error(\"Module database already connected!\")", "path): if self.local_storage.get(\"connected_plugin_databases\"): if name in self.local_storage.get(\"connected_plugin_databases\"): self.badges.print_error(\"Plugin database already", "except Exception: self.badges.print_error(\"Failed to connect plugin database!\") return if '__database__'", "name) self.local_storage.delete_element(\"payloads\", name) return self.badges.print_error(\"No such payload database connected!\") def", "in self.local_storage.get(\"connected_plugin_databases\"): self.local_storage.delete_element(\"connected_plugin_databases\", name) self.local_storage.delete_element(\"plugins\", name) return self.badges.print_error(\"No such plugin", "not str.endswith(path, \"json\"): self.badges.print_error(\"Not a database!\") return try: database =", "self.local_storage.get(\"connected_plugin_databases\"): if name in self.local_storage.get(\"connected_plugin_databases\"): self.local_storage.delete_element(\"connected_plugin_databases\", name) self.local_storage.delete_element(\"plugins\", name) return", "# # The above copyright notice and this permission notice", "MIT License # # Copyright (c) 2020-2022 EntySec # #", "} if not self.local_storage.get(\"connected_plugin_databases\"): self.local_storage.set(\"connected_plugin_databases\", {}) self.local_storage.update(\"connected_plugin_databases\", data) if self.local_storage.get(\"plugins\"):", "database!\") return del database['__database__'] modules = { name: database }", "and associated documentation files (the \"Software\"), to deal # in", "Software without restriction, including without limitation the rights # to", "name) return self.badges.print_error(\"No such module database connected!\") def disconnect_plugin_database(self, name):", "and to permit persons to whom the Software is #", "return try: database = json.load(open(path)) except Exception: self.badges.print_error(\"Failed to connect", "copies of the Software, and to permit persons to whom", "data = { name: { 'path': path } } if", "hereby granted, free of charge, to any person obtaining a", "this permission notice shall be included in all # copies", "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE", "distribute, sublicense, and/or sell # copies of the Software, and", "path): if self.local_storage.get(\"connected_module_databases\"): if name in self.local_storage.get(\"connected_module_databases\"): self.badges.print_error(\"Module database already", "OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.", "path } } if not self.local_storage.get(\"connected_module_databases\"): self.local_storage.set(\"connected_module_databases\", {}) self.local_storage.update(\"connected_module_databases\", data)", "HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #", "\"json\"): self.badges.print_error(\"Not a database!\") return try: database = json.load(open(path)) except", "database connected!\") def connect_payload_database(self, name, path): if self.local_storage.get(\"connected_payload_databases\"): if name", "if name in self.local_storage.get(\"connected_payload_databases\"): self.local_storage.delete_element(\"connected_payload_databases\", name) self.local_storage.delete_element(\"payloads\", name) return self.badges.print_error(\"No", "payloads) def connect_module_database(self, name, path): if self.local_storage.get(\"connected_module_databases\"): if name in", "OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH", "deal # in the Software without restriction, including without limitation", "use, copy, modify, merge, publish, distribute, sublicense, and/or sell #", "import os from hatsploit.core.cli.badges import Badges from hatsploit.lib.config import Config", "database already connected!\") return if not os.path.exists(path) or not str.endswith(path,", "Config from hatsploit.lib.storage import LocalStorage class DB: badges = Badges()", "import Badges from hatsploit.lib.config import Config from hatsploit.lib.storage import LocalStorage", "module database!\") return if '__database__' not in database: self.badges.print_error(\"No __database__", "be included in all # copies or substantial portions of", "self.local_storage.get(\"connected_payload_databases\"): if name in self.local_storage.get(\"connected_payload_databases\"): self.badges.print_error(\"Payload database already connected!\") return", "section found!\") return if database['__database__']['type'] != \"plugins\": self.badges.print_error(\"Not a plugin", "} if not self.local_storage.get(\"connected_module_databases\"): self.local_storage.set(\"connected_module_databases\", {}) self.local_storage.update(\"connected_module_databases\", data) if self.local_storage.get(\"modules\"):", "the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\",", "self.local_storage.delete_element(\"payloads\", name) return self.badges.print_error(\"No such payload database connected!\") def disconnect_module_database(self,", "copy, modify, merge, publish, distribute, sublicense, and/or sell # copies", "# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR", "del database['__database__'] plugins = { name: database } data =", "if '__database__' not in database: self.badges.print_error(\"No __database__ section found!\") return", "return if not os.path.exists(path) or not str.endswith(path, \"json\"): self.badges.print_error(\"Not a", "software and associated documentation files (the \"Software\"), to deal #", "{ 'path': path } } if not self.local_storage.get(\"connected_payload_databases\"): self.local_storage.set(\"connected_payload_databases\", {})", "Badges() config = Config() local_storage = LocalStorage() def disconnect_payload_database(self, name):", "Exception: self.badges.print_error(\"Failed to connect plugin database!\") return if '__database__' not", "# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF", "database connected!\") def disconnect_plugin_database(self, name): if self.local_storage.get(\"connected_plugin_databases\"): if name in", "AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR", "the Software without restriction, including without limitation the rights #", "# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF", "if not self.local_storage.get(\"connected_plugin_databases\"): self.local_storage.set(\"connected_plugin_databases\", {}) self.local_storage.update(\"connected_plugin_databases\", data) if self.local_storage.get(\"plugins\"): self.local_storage.update(\"plugins\",", "\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #", "self.local_storage.get(\"connected_module_databases\"): self.local_storage.delete_element(\"connected_module_databases\", name) self.local_storage.delete_element(\"modules\", name) return self.badges.print_error(\"No such module database", "self.badges.print_error(\"Not a payload database!\") return try: database = json.load(open(path)) except", "os from hatsploit.core.cli.badges import Badges from hatsploit.lib.config import Config from", "self.local_storage.get(\"connected_payload_databases\"): self.badges.print_error(\"Payload database already connected!\") return if not os.path.exists(path) or", "import json import os from hatsploit.core.cli.badges import Badges from hatsploit.lib.config", "name): if self.local_storage.get(\"connected_module_databases\"): if name in self.local_storage.get(\"connected_module_databases\"): self.local_storage.delete_element(\"connected_module_databases\", name) self.local_storage.delete_element(\"modules\",", "return if database['__database__']['type'] != \"plugins\": self.badges.print_error(\"Not a plugin database!\") return", "such module database connected!\") def disconnect_plugin_database(self, name): if self.local_storage.get(\"connected_plugin_databases\"): if", "if not os.path.exists(path) or not str.endswith(path, \"json\"): self.badges.print_error(\"Not a payload", "hatsploit.core.cli.badges import Badges from hatsploit.lib.config import Config from hatsploit.lib.storage import", "included in all # copies or substantial portions of the", "self.local_storage.set(\"payloads\", payloads) def connect_module_database(self, name, path): if self.local_storage.get(\"connected_module_databases\"): if name", "# of this software and associated documentation files (the \"Software\"),", "furnished to do so, subject to the following conditions: #", "to do so, subject to the following conditions: # #", "# The above copyright notice and this permission notice shall", "SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR", "name in self.local_storage.get(\"connected_module_databases\"): self.badges.print_error(\"Module database already connected!\") return if not", "a copy # of this software and associated documentation files", "OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF", "except Exception: self.badges.print_error(\"Failed to connect payload database!\") return if '__database__'", "# Copyright (c) 2020-2022 EntySec # # Permission is hereby", "del database['__database__'] payloads = { name: database } data =", "str.endswith(path, \"json\"): self.badges.print_error(\"Not a module database!\") return try: database =", "name) return self.badges.print_error(\"No such payload database connected!\") def disconnect_module_database(self, name):", "permission notice shall be included in all # copies or", "str.endswith(path, \"json\"): self.badges.print_error(\"Not a database!\") return try: database = json.load(open(path))", "# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO", "or not str.endswith(path, \"json\"): self.badges.print_error(\"Not a module database!\") return try:", "IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS", "database: self.badges.print_error(\"No __database__ section found!\") return if database['__database__']['type'] != \"payloads\":", "self.badges.print_error(\"Plugin database already connected!\") return if not os.path.exists(path) or not", "self.local_storage.delete_element(\"connected_plugin_databases\", name) self.local_storage.delete_element(\"plugins\", name) return self.badges.print_error(\"No such plugin database connected!\")", "NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE", "try: database = json.load(open(path)) except Exception: self.badges.print_error(\"Failed to connect payload", "following conditions: # # The above copyright notice and this", "to deal # in the Software without restriction, including without", "else: self.local_storage.set(\"payloads\", payloads) def connect_module_database(self, name, path): if self.local_storage.get(\"connected_module_databases\"): if", "to connect plugin database!\") return if '__database__' not in database:", "conditions: # # The above copyright notice and this permission", "not os.path.exists(path) or not str.endswith(path, \"json\"): self.badges.print_error(\"Not a module database!\")", "SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #", "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell", "if self.local_storage.get(\"connected_module_databases\"): if name in self.local_storage.get(\"connected_module_databases\"): self.local_storage.delete_element(\"connected_module_databases\", name) self.local_storage.delete_element(\"modules\", name)", "if name in self.local_storage.get(\"connected_payload_databases\"): self.badges.print_error(\"Payload database already connected!\") return if", "IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS", "database['__database__'] payloads = { name: database } data = {", "__database__ section found!\") return if database['__database__']['type'] != \"modules\": self.badges.print_error(\"Not a", "FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN", "not str.endswith(path, \"json\"): self.badges.print_error(\"Not a payload database!\") return try: database", "plugin database connected!\") def connect_payload_database(self, name, path): if self.local_storage.get(\"connected_payload_databases\"): if", "2020-2022 EntySec # # Permission is hereby granted, free of", "return if '__database__' not in database: self.badges.print_error(\"No __database__ section found!\")", "data) if self.local_storage.get(\"modules\"): self.local_storage.update(\"modules\", modules) else: self.local_storage.set(\"modules\", modules) def connect_plugin_database(self,", "database = json.load(open(path)) except Exception: self.badges.print_error(\"Failed to connect plugin database!\")", "os.path.exists(path) or not str.endswith(path, \"json\"): self.badges.print_error(\"Not a module database!\") return", "return del database['__database__'] plugins = { name: database } data", "# # Copyright (c) 2020-2022 EntySec # # Permission is", "if name in self.local_storage.get(\"connected_module_databases\"): self.local_storage.delete_element(\"connected_module_databases\", name) self.local_storage.delete_element(\"modules\", name) return self.badges.print_error(\"No", "__database__ section found!\") return if database['__database__']['type'] != \"payloads\": self.badges.print_error(\"Not a", "in database: self.badges.print_error(\"No __database__ section found!\") return if database['__database__']['type'] !=", "DEALINGS IN THE # SOFTWARE. # import json import os", "and/or sell # copies of the Software, and to permit", "'path': path } } if not self.local_storage.get(\"connected_module_databases\"): self.local_storage.set(\"connected_module_databases\", {}) self.local_storage.update(\"connected_module_databases\",", "the rights # to use, copy, modify, merge, publish, distribute,", "self.badges.print_error(\"No __database__ section found!\") return if database['__database__']['type'] != \"payloads\": self.badges.print_error(\"Not", "all # copies or substantial portions of the Software. #", "return if database['__database__']['type'] != \"payloads\": self.badges.print_error(\"Not a payload database!\") return", "notice and this permission notice shall be included in all", "EntySec # # Permission is hereby granted, free of charge,", "{}) self.local_storage.update(\"connected_plugin_databases\", data) if self.local_storage.get(\"plugins\"): self.local_storage.update(\"plugins\", plugins) else: self.local_storage.set(\"plugins\", plugins)", "is hereby granted, free of charge, to any person obtaining", "os.path.exists(path) or not str.endswith(path, \"json\"): self.badges.print_error(\"Not a database!\") return try:", "Copyright (c) 2020-2022 EntySec # # Permission is hereby granted,", "CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR", "License # # Copyright (c) 2020-2022 EntySec # # Permission", "config = Config() local_storage = LocalStorage() def disconnect_payload_database(self, name): if", "person obtaining a copy # of this software and associated", "# # Permission is hereby granted, free of charge, to", "without restriction, including without limitation the rights # to use,", "subject to the following conditions: # # The above copyright", "WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN", "modules = { name: database } data = { name:", "database!\") return try: database = json.load(open(path)) except Exception: self.badges.print_error(\"Failed to", "self.local_storage.get(\"modules\"): self.local_storage.update(\"modules\", modules) else: self.local_storage.set(\"modules\", modules) def connect_plugin_database(self, name, path):", "THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE", "self.local_storage.update(\"connected_payload_databases\", data) if self.local_storage.get(\"payloads\"): self.local_storage.update(\"payloads\", payloads) else: self.local_storage.set(\"payloads\", payloads) def", "in self.local_storage.get(\"connected_module_databases\"): self.local_storage.delete_element(\"connected_module_databases\", name) self.local_storage.delete_element(\"modules\", name) return self.badges.print_error(\"No such module", "to connect module database!\") return if '__database__' not in database:", "or substantial portions of the Software. # # THE SOFTWARE", "BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS", "FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL", "class DB: badges = Badges() config = Config() local_storage =", "'path': path } } if not self.local_storage.get(\"connected_plugin_databases\"): self.local_storage.set(\"connected_plugin_databases\", {}) self.local_storage.update(\"connected_plugin_databases\",", "OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR", "LocalStorage class DB: badges = Badges() config = Config() local_storage", "a database!\") return try: database = json.load(open(path)) except Exception: self.badges.print_error(\"Failed", "!= \"payloads\": self.badges.print_error(\"Not a payload database!\") return del database['__database__'] payloads", "{ name: { 'path': path } } if not self.local_storage.get(\"connected_module_databases\"):", "found!\") return if database['__database__']['type'] != \"modules\": self.badges.print_error(\"Not a module database!\")", "return del database['__database__'] payloads = { name: database } data", "CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS", "IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER", "CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION", "self.local_storage.get(\"connected_plugin_databases\"): self.local_storage.set(\"connected_plugin_databases\", {}) self.local_storage.update(\"connected_plugin_databases\", data) if self.local_storage.get(\"plugins\"): self.local_storage.update(\"plugins\", plugins) else:", "if database['__database__']['type'] != \"payloads\": self.badges.print_error(\"Not a payload database!\") return del", "# Permission is hereby granted, free of charge, to any", "of charge, to any person obtaining a copy # of", "INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #", "merge, publish, distribute, sublicense, and/or sell # copies of the", "# # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY", "from hatsploit.core.cli.badges import Badges from hatsploit.lib.config import Config from hatsploit.lib.storage", "self.local_storage.get(\"connected_plugin_databases\"): self.badges.print_error(\"Plugin database already connected!\") return if not os.path.exists(path) or", "NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT", "NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR", "payload database!\") return try: database = json.load(open(path)) except Exception: self.badges.print_error(\"Failed", "data) if self.local_storage.get(\"payloads\"): self.local_storage.update(\"payloads\", payloads) else: self.local_storage.set(\"payloads\", payloads) def connect_module_database(self,", "a module database!\") return try: database = json.load(open(path)) except Exception:", "name: { 'path': path } } if not self.local_storage.get(\"connected_payload_databases\"): self.local_storage.set(\"connected_payload_databases\",", "database!\") return if '__database__' not in database: self.badges.print_error(\"No __database__ section", "} if not self.local_storage.get(\"connected_payload_databases\"): self.local_storage.set(\"connected_payload_databases\", {}) self.local_storage.update(\"connected_payload_databases\", data) if self.local_storage.get(\"payloads\"):", "LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER", "so, subject to the following conditions: # # The above", "self.local_storage.get(\"connected_plugin_databases\"): self.local_storage.delete_element(\"connected_plugin_databases\", name) self.local_storage.delete_element(\"plugins\", name) return self.badges.print_error(\"No such plugin database", "= json.load(open(path)) except Exception: self.badges.print_error(\"Failed to connect module database!\") return", "self.local_storage.set(\"connected_module_databases\", {}) self.local_storage.update(\"connected_module_databases\", data) if self.local_storage.get(\"modules\"): self.local_storage.update(\"modules\", modules) else: self.local_storage.set(\"modules\",", "AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #", "database: self.badges.print_error(\"No __database__ section found!\") return if database['__database__']['type'] != \"plugins\":", "self.badges.print_error(\"No such payload database connected!\") def disconnect_module_database(self, name): if self.local_storage.get(\"connected_module_databases\"):", "DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF", "path } } if not self.local_storage.get(\"connected_payload_databases\"): self.local_storage.set(\"connected_payload_databases\", {}) self.local_storage.update(\"connected_payload_databases\", data)", "connected!\") def disconnect_plugin_database(self, name): if self.local_storage.get(\"connected_plugin_databases\"): if name in self.local_storage.get(\"connected_plugin_databases\"):", "a payload database!\") return try: database = json.load(open(path)) except Exception:", "return self.badges.print_error(\"No such payload database connected!\") def disconnect_module_database(self, name): if", "the following conditions: # # The above copyright notice and", "FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE", "name) self.local_storage.delete_element(\"plugins\", name) return self.badges.print_error(\"No such plugin database connected!\") def", "database } data = { name: { 'path': path }", "payload database connected!\") def disconnect_module_database(self, name): if self.local_storage.get(\"connected_module_databases\"): if name", "connect module database!\") return if '__database__' not in database: self.badges.print_error(\"No", "not in database: self.badges.print_error(\"No __database__ section found!\") return if database['__database__']['type']", "!= \"modules\": self.badges.print_error(\"Not a module database!\") return del database['__database__'] modules", "self.local_storage.get(\"connected_module_databases\"): self.local_storage.set(\"connected_module_databases\", {}) self.local_storage.update(\"connected_module_databases\", data) if self.local_storage.get(\"modules\"): self.local_storage.update(\"modules\", modules) else:", "json.load(open(path)) except Exception: self.badges.print_error(\"Failed to connect payload database!\") return if", "hatsploit.lib.config import Config from hatsploit.lib.storage import LocalStorage class DB: badges", "THE USE OR OTHER DEALINGS IN THE # SOFTWARE. #", "import Config from hatsploit.lib.storage import LocalStorage class DB: badges =", "json import os from hatsploit.core.cli.badges import Badges from hatsploit.lib.config import", "name): if self.local_storage.get(\"connected_payload_databases\"): if name in self.local_storage.get(\"connected_payload_databases\"): self.local_storage.delete_element(\"connected_payload_databases\", name) self.local_storage.delete_element(\"payloads\",", "the Software, and to permit persons to whom the Software", "self.local_storage.delete_element(\"modules\", name) return self.badges.print_error(\"No such module database connected!\") def disconnect_plugin_database(self,", "payload database!\") return if '__database__' not in database: self.badges.print_error(\"No __database__", "found!\") return if database['__database__']['type'] != \"plugins\": self.badges.print_error(\"Not a plugin database!\")", "self.local_storage.update(\"connected_module_databases\", data) if self.local_storage.get(\"modules\"): self.local_storage.update(\"modules\", modules) else: self.local_storage.set(\"modules\", modules) def", "plugins = { name: database } data = { name:", "such plugin database connected!\") def connect_payload_database(self, name, path): if self.local_storage.get(\"connected_payload_databases\"):", "not str.endswith(path, \"json\"): self.badges.print_error(\"Not a module database!\") return try: database", "try: database = json.load(open(path)) except Exception: self.badges.print_error(\"Failed to connect module", "database = json.load(open(path)) except Exception: self.badges.print_error(\"Failed to connect payload database!\")", "module database connected!\") def disconnect_plugin_database(self, name): if self.local_storage.get(\"connected_plugin_databases\"): if name", "connect payload database!\") return if '__database__' not in database: self.badges.print_error(\"No", "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT", "name) self.local_storage.delete_element(\"modules\", name) return self.badges.print_error(\"No such module database connected!\") def", "self.local_storage.get(\"connected_module_databases\"): if name in self.local_storage.get(\"connected_module_databases\"): self.badges.print_error(\"Module database already connected!\") return", "persons to whom the Software is # furnished to do", "associated documentation files (the \"Software\"), to deal # in the", "self.badges.print_error(\"Not a module database!\") return del database['__database__'] modules = {", "self.badges.print_error(\"Not a payload database!\") return del database['__database__'] payloads = {", "or not str.endswith(path, \"json\"): self.badges.print_error(\"Not a database!\") return try: database", "MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN", "Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT", "from hatsploit.lib.config import Config from hatsploit.lib.storage import LocalStorage class DB:", "to any person obtaining a copy # of this software", "= json.load(open(path)) except Exception: self.badges.print_error(\"Failed to connect payload database!\") return", "self.badges.print_error(\"Module database already connected!\") return if not os.path.exists(path) or not", "if self.local_storage.get(\"connected_payload_databases\"): if name in self.local_storage.get(\"connected_payload_databases\"): self.local_storage.delete_element(\"connected_payload_databases\", name) self.local_storage.delete_element(\"payloads\", name)", "such payload database connected!\") def disconnect_module_database(self, name): if self.local_storage.get(\"connected_module_databases\"): if", "in all # copies or substantial portions of the Software.", "this software and associated documentation files (the \"Software\"), to deal", "of the Software, and to permit persons to whom the", "connect_module_database(self, name, path): if self.local_storage.get(\"connected_module_databases\"): if name in self.local_storage.get(\"connected_module_databases\"): self.badges.print_error(\"Module", "ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN", "if not self.local_storage.get(\"connected_payload_databases\"): self.local_storage.set(\"connected_payload_databases\", {}) self.local_storage.update(\"connected_payload_databases\", data) if self.local_storage.get(\"payloads\"): self.local_storage.update(\"payloads\",", "# # MIT License # # Copyright (c) 2020-2022 EntySec", "BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY,", "database['__database__'] plugins = { name: database } data = {", "shall be included in all # copies or substantial portions", "Software is # furnished to do so, subject to the", "str.endswith(path, \"json\"): self.badges.print_error(\"Not a payload database!\") return try: database =", "payloads = { name: database } data = { name:", "name: database } data = { name: { 'path': path", "PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR", "__database__ section found!\") return if database['__database__']['type'] != \"plugins\": self.badges.print_error(\"Not a", "whom the Software is # furnished to do so, subject", "SOFTWARE. # import json import os from hatsploit.core.cli.badges import Badges", "sublicense, and/or sell # copies of the Software, and to", "self.local_storage.delete_element(\"plugins\", name) return self.badges.print_error(\"No such plugin database connected!\") def connect_payload_database(self,", "name, path): if self.local_storage.get(\"connected_plugin_databases\"): if name in self.local_storage.get(\"connected_plugin_databases\"): self.badges.print_error(\"Plugin database", "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY", "substantial portions of the Software. # # THE SOFTWARE IS", "notice shall be included in all # copies or substantial", "do so, subject to the following conditions: # # The", "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,", "WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING", "{ name: { 'path': path } } if not self.local_storage.get(\"connected_plugin_databases\"):", "local_storage = LocalStorage() def disconnect_payload_database(self, name): if self.local_storage.get(\"connected_payload_databases\"): if name", "in the Software without restriction, including without limitation the rights", "name in self.local_storage.get(\"connected_module_databases\"): self.local_storage.delete_element(\"connected_module_databases\", name) self.local_storage.delete_element(\"modules\", name) return self.badges.print_error(\"No such", "# furnished to do so, subject to the following conditions:", "any person obtaining a copy # of this software and", "name) return self.badges.print_error(\"No such plugin database connected!\") def connect_payload_database(self, name,", "ARISING FROM, # OUT OF OR IN CONNECTION WITH THE", "SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,", "name in self.local_storage.get(\"connected_payload_databases\"): self.local_storage.delete_element(\"connected_payload_databases\", name) self.local_storage.delete_element(\"payloads\", name) return self.badges.print_error(\"No such", "KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO", "\"json\"): self.badges.print_error(\"Not a payload database!\") return try: database = json.load(open(path))", "Config() local_storage = LocalStorage() def disconnect_payload_database(self, name): if self.local_storage.get(\"connected_payload_databases\"): if", "\"plugins\": self.badges.print_error(\"Not a plugin database!\") return del database['__database__'] plugins =", "OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES", "except Exception: self.badges.print_error(\"Failed to connect module database!\") return if '__database__'", "not self.local_storage.get(\"connected_module_databases\"): self.local_storage.set(\"connected_module_databases\", {}) self.local_storage.update(\"connected_module_databases\", data) if self.local_storage.get(\"modules\"): self.local_storage.update(\"modules\", modules)", "restriction, including without limitation the rights # to use, copy,", "if self.local_storage.get(\"connected_plugin_databases\"): if name in self.local_storage.get(\"connected_plugin_databases\"): self.local_storage.delete_element(\"connected_plugin_databases\", name) self.local_storage.delete_element(\"plugins\", name)", "'path': path } } if not self.local_storage.get(\"connected_payload_databases\"): self.local_storage.set(\"connected_payload_databases\", {}) self.local_storage.update(\"connected_payload_databases\",", "database['__database__']['type'] != \"payloads\": self.badges.print_error(\"Not a payload database!\") return del database['__database__']", "database!\") return del database['__database__'] plugins = { name: database }", "= LocalStorage() def disconnect_payload_database(self, name): if self.local_storage.get(\"connected_payload_databases\"): if name in", "including without limitation the rights # to use, copy, modify,", "copyright notice and this permission notice shall be included in", "DB: badges = Badges() config = Config() local_storage = LocalStorage()", "ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED", "free of charge, to any person obtaining a copy #", "files (the \"Software\"), to deal # in the Software without", "if not os.path.exists(path) or not str.endswith(path, \"json\"): self.badges.print_error(\"Not a database!\")", "path): if self.local_storage.get(\"connected_payload_databases\"): if name in self.local_storage.get(\"connected_payload_databases\"): self.badges.print_error(\"Payload database already", "Badges from hatsploit.lib.config import Config from hatsploit.lib.storage import LocalStorage class", "THE # SOFTWARE. # import json import os from hatsploit.core.cli.badges", "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,", "found!\") return if database['__database__']['type'] != \"payloads\": self.badges.print_error(\"Not a payload database!\")", "# import json import os from hatsploit.core.cli.badges import Badges from", "connect plugin database!\") return if '__database__' not in database: self.badges.print_error(\"No", "of the Software. # # THE SOFTWARE IS PROVIDED \"AS", "def connect_plugin_database(self, name, path): if self.local_storage.get(\"connected_plugin_databases\"): if name in self.local_storage.get(\"connected_plugin_databases\"):", "\"modules\": self.badges.print_error(\"Not a module database!\") return del database['__database__'] modules =", "def connect_module_database(self, name, path): if self.local_storage.get(\"connected_module_databases\"): if name in self.local_storage.get(\"connected_module_databases\"):", "= json.load(open(path)) except Exception: self.badges.print_error(\"Failed to connect plugin database!\") return", "# SOFTWARE. # import json import os from hatsploit.core.cli.badges import", "{}) self.local_storage.update(\"connected_payload_databases\", data) if self.local_storage.get(\"payloads\"): self.local_storage.update(\"payloads\", payloads) else: self.local_storage.set(\"payloads\", payloads)", "} data = { name: { 'path': path } }", "name in self.local_storage.get(\"connected_payload_databases\"): self.badges.print_error(\"Payload database already connected!\") return if not", "a plugin database!\") return del database['__database__'] plugins = { name:", "self.badges.print_error(\"Not a plugin database!\") return del database['__database__'] plugins = {", "#!/usr/bin/env python3 # # MIT License # # Copyright (c)", "{}) self.local_storage.update(\"connected_module_databases\", data) if self.local_storage.get(\"modules\"): self.local_storage.update(\"modules\", modules) else: self.local_storage.set(\"modules\", modules)", "} } if not self.local_storage.get(\"connected_plugin_databases\"): self.local_storage.set(\"connected_plugin_databases\", {}) self.local_storage.update(\"connected_plugin_databases\", data) if", "if database['__database__']['type'] != \"modules\": self.badges.print_error(\"Not a module database!\") return del", "of this software and associated documentation files (the \"Software\"), to", "OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR", "OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE", "EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE", "self.local_storage.delete_element(\"connected_module_databases\", name) self.local_storage.delete_element(\"modules\", name) return self.badges.print_error(\"No such module database connected!\")", "or not str.endswith(path, \"json\"): self.badges.print_error(\"Not a payload database!\") return try:", "self.local_storage.get(\"connected_payload_databases\"): self.local_storage.delete_element(\"connected_payload_databases\", name) self.local_storage.delete_element(\"payloads\", name) return self.badges.print_error(\"No such payload database", "payload database!\") return del database['__database__'] payloads = { name: database", "if database['__database__']['type'] != \"plugins\": self.badges.print_error(\"Not a plugin database!\") return del", "# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,", "plugin database!\") return del database['__database__'] plugins = { name: database", "self.local_storage.set(\"connected_plugin_databases\", {}) self.local_storage.update(\"connected_plugin_databases\", data) if self.local_storage.get(\"plugins\"): self.local_storage.update(\"plugins\", plugins) else: self.local_storage.set(\"plugins\",", "PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS", "{ name: database } data = { name: { 'path':", "name in self.local_storage.get(\"connected_plugin_databases\"): self.badges.print_error(\"Plugin database already connected!\") return if not", "python3 # # MIT License # # Copyright (c) 2020-2022", "(the \"Software\"), to deal # in the Software without restriction,", "json.load(open(path)) except Exception: self.badges.print_error(\"Failed to connect module database!\") return if", "not os.path.exists(path) or not str.endswith(path, \"json\"): self.badges.print_error(\"Not a payload database!\")", "WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND", "name, path): if self.local_storage.get(\"connected_module_databases\"): if name in self.local_storage.get(\"connected_module_databases\"): self.badges.print_error(\"Module database", "return self.badges.print_error(\"No such module database connected!\") def disconnect_plugin_database(self, name): if", "return del database['__database__'] modules = { name: database } data", "charge, to any person obtaining a copy # of this", "permit persons to whom the Software is # furnished to", "connected!\") return if not os.path.exists(path) or not str.endswith(path, \"json\"): self.badges.print_error(\"Not", "THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE", "if name in self.local_storage.get(\"connected_module_databases\"): self.badges.print_error(\"Module database already connected!\") return if", "{ name: { 'path': path } } if not self.local_storage.get(\"connected_payload_databases\"):", "plugin database!\") return if '__database__' not in database: self.badges.print_error(\"No __database__", "the Software is # furnished to do so, subject to", "self.local_storage.get(\"connected_payload_databases\"): self.local_storage.set(\"connected_payload_databases\", {}) self.local_storage.update(\"connected_payload_databases\", data) if self.local_storage.get(\"payloads\"): self.local_storage.update(\"payloads\", payloads) else:", "hatsploit.lib.storage import LocalStorage class DB: badges = Badges() config =", "above copyright notice and this permission notice shall be included", "IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED,", "if self.local_storage.get(\"modules\"): self.local_storage.update(\"modules\", modules) else: self.local_storage.set(\"modules\", modules) def connect_plugin_database(self, name,", "A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE", "limitation the rights # to use, copy, modify, merge, publish,", "return self.badges.print_error(\"No such plugin database connected!\") def connect_payload_database(self, name, path):", "name: { 'path': path } } if not self.local_storage.get(\"connected_module_databases\"): self.local_storage.set(\"connected_module_databases\",", "PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #", "section found!\") return if database['__database__']['type'] != \"payloads\": self.badges.print_error(\"Not a payload", "self.badges.print_error(\"Failed to connect module database!\") return if '__database__' not in", "without limitation the rights # to use, copy, modify, merge,", "payloads) else: self.local_storage.set(\"payloads\", payloads) def connect_module_database(self, name, path): if self.local_storage.get(\"connected_module_databases\"):", "module database!\") return try: database = json.load(open(path)) except Exception: self.badges.print_error(\"Failed", "badges = Badges() config = Config() local_storage = LocalStorage() def", "# copies or substantial portions of the Software. # #", "EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE", "self.badges.print_error(\"Not a module database!\") return try: database = json.load(open(path)) except", "database['__database__']['type'] != \"modules\": self.badges.print_error(\"Not a module database!\") return del database['__database__']", "USE OR OTHER DEALINGS IN THE # SOFTWARE. # import", "# in the Software without restriction, including without limitation the", "documentation files (the \"Software\"), to deal # in the Software", "self.badges.print_error(\"No such plugin database connected!\") def connect_payload_database(self, name, path): if", "copies or substantial portions of the Software. # # THE", "os.path.exists(path) or not str.endswith(path, \"json\"): self.badges.print_error(\"Not a payload database!\") return", "IN THE # SOFTWARE. # import json import os from", "return if database['__database__']['type'] != \"modules\": self.badges.print_error(\"Not a module database!\") return", "def disconnect_payload_database(self, name): if self.local_storage.get(\"connected_payload_databases\"): if name in self.local_storage.get(\"connected_payload_databases\"): self.local_storage.delete_element(\"connected_payload_databases\",", "disconnect_plugin_database(self, name): if self.local_storage.get(\"connected_plugin_databases\"): if name in self.local_storage.get(\"connected_plugin_databases\"): self.local_storage.delete_element(\"connected_plugin_databases\", name)", "import LocalStorage class DB: badges = Badges() config = Config()", "\"json\"): self.badges.print_error(\"Not a module database!\") return try: database = json.load(open(path))", "self.badges.print_error(\"No such module database connected!\") def disconnect_plugin_database(self, name): if self.local_storage.get(\"connected_plugin_databases\"):", "(c) 2020-2022 EntySec # # Permission is hereby granted, free", "self.local_storage.set(\"connected_payload_databases\", {}) self.local_storage.update(\"connected_payload_databases\", data) if self.local_storage.get(\"payloads\"): self.local_storage.update(\"payloads\", payloads) else: self.local_storage.set(\"payloads\",", "'__database__' not in database: self.badges.print_error(\"No __database__ section found!\") return if", "# MIT License # # Copyright (c) 2020-2022 EntySec #", "self.local_storage.get(\"connected_module_databases\"): if name in self.local_storage.get(\"connected_module_databases\"): self.local_storage.delete_element(\"connected_module_databases\", name) self.local_storage.delete_element(\"modules\", name) return", "database['__database__'] modules = { name: database } data = {", "ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT", "sell # copies of the Software, and to permit persons", "OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT", "OTHER DEALINGS IN THE # SOFTWARE. # import json import", "self.local_storage.update(\"modules\", modules) else: self.local_storage.set(\"modules\", modules) def connect_plugin_database(self, name, path): if", "Exception: self.badges.print_error(\"Failed to connect module database!\") return if '__database__' not", "not self.local_storage.get(\"connected_plugin_databases\"): self.local_storage.set(\"connected_plugin_databases\", {}) self.local_storage.update(\"connected_plugin_databases\", data) if self.local_storage.get(\"plugins\"): self.local_storage.update(\"plugins\", plugins)", "if not self.local_storage.get(\"connected_module_databases\"): self.local_storage.set(\"connected_module_databases\", {}) self.local_storage.update(\"connected_module_databases\", data) if self.local_storage.get(\"modules\"): self.local_storage.update(\"modules\",", "OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT,", "if self.local_storage.get(\"connected_plugin_databases\"): if name in self.local_storage.get(\"connected_plugin_databases\"): self.badges.print_error(\"Plugin database already connected!\")", "publish, distribute, sublicense, and/or sell # copies of the Software,", "self.badges.print_error(\"Payload database already connected!\") return if not os.path.exists(path) or not", "to the following conditions: # # The above copyright notice", "OR OTHER DEALINGS IN THE # SOFTWARE. # import json", "!= \"plugins\": self.badges.print_error(\"Not a plugin database!\") return del database['__database__'] plugins", "already connected!\") return if not os.path.exists(path) or not str.endswith(path, \"json\"):", "name in self.local_storage.get(\"connected_plugin_databases\"): self.local_storage.delete_element(\"connected_plugin_databases\", name) self.local_storage.delete_element(\"plugins\", name) return self.badges.print_error(\"No such", "self.badges.print_error(\"No __database__ section found!\") return if database['__database__']['type'] != \"plugins\": self.badges.print_error(\"Not", "and this permission notice shall be included in all #", "def connect_payload_database(self, name, path): if self.local_storage.get(\"connected_payload_databases\"): if name in self.local_storage.get(\"connected_payload_databases\"):", "disconnect_payload_database(self, name): if self.local_storage.get(\"connected_payload_databases\"): if name in self.local_storage.get(\"connected_payload_databases\"): self.local_storage.delete_element(\"connected_payload_databases\", name)", "{ 'path': path } } if not self.local_storage.get(\"connected_plugin_databases\"): self.local_storage.set(\"connected_plugin_databases\", {})", "if self.local_storage.get(\"connected_payload_databases\"): if name in self.local_storage.get(\"connected_payload_databases\"): self.badges.print_error(\"Payload database already connected!\")", "not self.local_storage.get(\"connected_payload_databases\"): self.local_storage.set(\"connected_payload_databases\", {}) self.local_storage.update(\"connected_payload_databases\", data) if self.local_storage.get(\"payloads\"): self.local_storage.update(\"payloads\", payloads)", "database['__database__']['type'] != \"plugins\": self.badges.print_error(\"Not a plugin database!\") return del database['__database__']", "modify, merge, publish, distribute, sublicense, and/or sell # copies of", "OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION", "def disconnect_plugin_database(self, name): if self.local_storage.get(\"connected_plugin_databases\"): if name in self.local_storage.get(\"connected_plugin_databases\"): self.local_storage.delete_element(\"connected_plugin_databases\",", "path } } if not self.local_storage.get(\"connected_plugin_databases\"): self.local_storage.set(\"connected_plugin_databases\", {}) self.local_storage.update(\"connected_plugin_databases\", data)", "IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,", "database connected!\") def disconnect_module_database(self, name): if self.local_storage.get(\"connected_module_databases\"): if name in", "Software, and to permit persons to whom the Software is", "if name in self.local_storage.get(\"connected_plugin_databases\"): self.local_storage.delete_element(\"connected_plugin_databases\", name) self.local_storage.delete_element(\"plugins\", name) return self.badges.print_error(\"No", "# to use, copy, modify, merge, publish, distribute, sublicense, and/or", "OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT", "self.local_storage.delete_element(\"connected_payload_databases\", name) self.local_storage.delete_element(\"payloads\", name) return self.badges.print_error(\"No such payload database connected!\")", "self.badges.print_error(\"Failed to connect plugin database!\") return if '__database__' not in", "section found!\") return if database['__database__']['type'] != \"modules\": self.badges.print_error(\"Not a module", "\"Software\"), to deal # in the Software without restriction, including", "database = json.load(open(path)) except Exception: self.badges.print_error(\"Failed to connect module database!\")", "LocalStorage() def disconnect_payload_database(self, name): if self.local_storage.get(\"connected_payload_databases\"): if name in self.local_storage.get(\"connected_payload_databases\"):", "if name in self.local_storage.get(\"connected_plugin_databases\"): self.badges.print_error(\"Plugin database already connected!\") return if", "module database!\") return del database['__database__'] modules = { name: database", "# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR", "database!\") return del database['__database__'] payloads = { name: database }", "\"payloads\": self.badges.print_error(\"Not a payload database!\") return del database['__database__'] payloads =", "connect_payload_database(self, name, path): if self.local_storage.get(\"connected_payload_databases\"): if name in self.local_storage.get(\"connected_payload_databases\"): self.badges.print_error(\"Payload", "self.local_storage.get(\"connected_module_databases\"): self.badges.print_error(\"Module database already connected!\") return if not os.path.exists(path) or", "COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER", "in self.local_storage.get(\"connected_payload_databases\"): self.badges.print_error(\"Payload database already connected!\") return if not os.path.exists(path)", "to connect payload database!\") return if '__database__' not in database:", "in self.local_storage.get(\"connected_module_databases\"): self.badges.print_error(\"Module database already connected!\") return if not os.path.exists(path)", "self.local_storage.get(\"payloads\"): self.local_storage.update(\"payloads\", payloads) else: self.local_storage.set(\"payloads\", payloads) def connect_module_database(self, name, path):", "in self.local_storage.get(\"connected_payload_databases\"): self.local_storage.delete_element(\"connected_payload_databases\", name) self.local_storage.delete_element(\"payloads\", name) return self.badges.print_error(\"No such payload", "self.badges.print_error(\"Not a database!\") return try: database = json.load(open(path)) except Exception:", "# copies of the Software, and to permit persons to", "= Config() local_storage = LocalStorage() def disconnect_payload_database(self, name): if self.local_storage.get(\"connected_payload_databases\"):", "def disconnect_module_database(self, name): if self.local_storage.get(\"connected_module_databases\"): if name in self.local_storage.get(\"connected_module_databases\"): self.local_storage.delete_element(\"connected_module_databases\",", "self.local_storage.set(\"modules\", modules) def connect_plugin_database(self, name, path): if self.local_storage.get(\"connected_plugin_databases\"): if name", "granted, free of charge, to any person obtaining a copy", "= { name: { 'path': path } } if not", "a module database!\") return del database['__database__'] modules = { name:", "else: self.local_storage.set(\"modules\", modules) def connect_plugin_database(self, name, path): if self.local_storage.get(\"connected_plugin_databases\"): if", "database: self.badges.print_error(\"No __database__ section found!\") return if database['__database__']['type'] != \"modules\":", "obtaining a copy # of this software and associated documentation", "TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN", "is # furnished to do so, subject to the following", "to whom the Software is # furnished to do so,", "disconnect_module_database(self, name): if self.local_storage.get(\"connected_module_databases\"): if name in self.local_storage.get(\"connected_module_databases\"): self.local_storage.delete_element(\"connected_module_databases\", name)", "} } if not self.local_storage.get(\"connected_payload_databases\"): self.local_storage.set(\"connected_payload_databases\", {}) self.local_storage.update(\"connected_payload_databases\", data) if", "copy # of this software and associated documentation files (the", "THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY", "OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE.", "Permission is hereby granted, free of charge, to any person", "connected!\") def connect_payload_database(self, name, path): if self.local_storage.get(\"connected_payload_databases\"): if name in", "self.local_storage.get(\"connected_payload_databases\"): if name in self.local_storage.get(\"connected_payload_databases\"): self.local_storage.delete_element(\"connected_payload_databases\", name) self.local_storage.delete_element(\"payloads\", name) return", "in self.local_storage.get(\"connected_plugin_databases\"): self.badges.print_error(\"Plugin database already connected!\") return if not os.path.exists(path)", "self.local_storage.update(\"payloads\", payloads) else: self.local_storage.set(\"payloads\", payloads) def connect_module_database(self, name, path): if", "The above copyright notice and this permission notice shall be", "if self.local_storage.get(\"payloads\"): self.local_storage.update(\"payloads\", payloads) else: self.local_storage.set(\"payloads\", payloads) def connect_module_database(self, name,", "modules) def connect_plugin_database(self, name, path): if self.local_storage.get(\"connected_plugin_databases\"): if name in", "if not os.path.exists(path) or not str.endswith(path, \"json\"): self.badges.print_error(\"Not a module", "modules) else: self.local_storage.set(\"modules\", modules) def connect_plugin_database(self, name, path): if self.local_storage.get(\"connected_plugin_databases\"):", "WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT", "try: database = json.load(open(path)) except Exception: self.badges.print_error(\"Failed to connect plugin", "} } if not self.local_storage.get(\"connected_module_databases\"): self.local_storage.set(\"connected_module_databases\", {}) self.local_storage.update(\"connected_module_databases\", data) if", "name, path): if self.local_storage.get(\"connected_payload_databases\"): if name in self.local_storage.get(\"connected_payload_databases\"): self.badges.print_error(\"Payload database", "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES", "to permit persons to whom the Software is # furnished", "connect_plugin_database(self, name, path): if self.local_storage.get(\"connected_plugin_databases\"): if name in self.local_storage.get(\"connected_plugin_databases\"): self.badges.print_error(\"Plugin", "WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING", "self.local_storage.get(\"connected_plugin_databases\"): if name in self.local_storage.get(\"connected_plugin_databases\"): self.badges.print_error(\"Plugin database already connected!\") return" ]
[ "# The motor object does not currently implement limits. #", "object does not raise check_limits(scan([det], motor, -3, 3, 3)) #", "with pytest.raises(RuntimeError) as ctx: check_limits([]) assert str(ctx.value) == \"Bluesky event", "from bluesky.plans import scan from bluesky.simulators import (print_summary, print_summary_wrapper, summarize_plan,", "-3, 3, 3)) # check_limits should raise if limits are", "loop not running\" def test_plot_raster_path(hw): det = hw.det motor1 =", "print_summary_wrapper, plot_raster_path) with pytest.warns(UserWarning): print_summary(scan([det], motor, -1, 1, 10)) with", "# old name summarize_plan(scan([det], motor, -1, 1, 10)) # new", "to test? # with pytest.warns(UserWarning): # check_limits(scan([det], motor, -1, 1,", "test? # with pytest.warns(UserWarning): # check_limits(scan([det], motor, -1, 1, 3))", "pytest.warns(UserWarning): # check_limits(scan([det], motor, -1, 1, 3)) # monkey-patch some", "hw.motor # The motor object does not currently implement limits.", "det = hw.det motor = hw.motor motor1 = hw.motor1 motor2", "# this object does not raise check_limits(scan([det], motor, -3, 3,", "not raise motor.limits = (2, 2) check_limits(scan([det], motor, -1, 1,", "there _any_ object to test? # with pytest.warns(UserWarning): # check_limits(scan([det],", "1, 10))) with pytest.warns(UserWarning): plan = grid_scan([det], motor1, -5, 5,", "in the future. assert not hasattr(motor, 'limits') # # check_limits", "1, 10))) def test_old_module_name(hw): det = hw.det motor = hw.motor", "with pytest.warns(UserWarning): list(print_summary_wrapper(scan([det], motor, -1, 1, 10))) with pytest.warns(UserWarning): plan", "currently implement limits. # Use an assert to help us", "bluesky.plans import grid_scan def test_print_summary(hw): det = hw.det motor =", "if object raises # this object does not raise motor.limits", "def test_check_limits_needs_RE(): with pytest.raises(RuntimeError) as ctx: check_limits([]) assert str(ctx.value) ==", "= hw.det motor = hw.motor motor1 = hw.motor1 motor2 =", "if this changes in the future. assert not hasattr(motor, 'limits')", "= grid_scan([det], motor1, -5, 5, 10, motor2, -7, 7, 15,", "= hw.motor2 plan = grid_scan([det], motor1, -5, 5, 10, motor2,", "det = hw.det motor = hw.motor print_summary(scan([det], motor, -1, 1,", "motor, -1, 1, 10)) # new name list(print_summary_wrapper(scan([det], motor, -1,", "does not currently implement limits. # Use an assert to", "can't find check_value # TODO: Is there _any_ object to", "pytest.warns(UserWarning): plan = grid_scan([det], motor1, -5, 5, 10, motor2, -7,", "import (print_summary, print_summary_wrapper, plot_raster_path) with pytest.warns(UserWarning): print_summary(scan([det], motor, -1, 1,", "def test_plot_raster_path(hw): det = hw.det motor1 = hw.motor1 motor2 =", "hw.motor1 motor2 = hw.motor2 from bluesky.plan_tools import (print_summary, print_summary_wrapper, plot_raster_path)", "hw.det motor = hw.motor # The motor object does not", "an assert to help us out if this changes in", "raise if limits are equal only if object raises #", "limits are equal only if object raises # this object", "import scan from bluesky.simulators import (print_summary, print_summary_wrapper, summarize_plan, check_limits, plot_raster_path)", "_any_ object to test? # with pytest.warns(UserWarning): # check_limits(scan([det], motor,", "object to test? # with pytest.warns(UserWarning): # check_limits(scan([det], motor, -1,", "motor2 = hw.motor2 from bluesky.plan_tools import (print_summary, print_summary_wrapper, plot_raster_path) with", "The motor object does not currently implement limits. # Use", "check_limits should warn if it can't find check_value # TODO:", "from bluesky.plans import grid_scan def test_print_summary(hw): det = hw.det motor", "= hw.det motor1 = hw.motor1 motor2 = hw.motor2 plan =", "motor, -1, 1, 10))) def test_old_module_name(hw): det = hw.det motor", "motor = hw.motor # The motor object does not currently", "-1, 1, 3)) # check_limits should error if limits are", "motor, -3, 3, 3)) # check_limits should raise if limits", "test_check_limits_needs_RE(): with pytest.raises(RuntimeError) as ctx: check_limits([]) assert str(ctx.value) == \"Bluesky", "event loop not running\" def test_plot_raster_path(hw): det = hw.det motor1", "= hw.motor1 motor2 = hw.motor2 plan = grid_scan([det], motor1, -5,", "bluesky.plan_tools import (print_summary, print_summary_wrapper, plot_raster_path) with pytest.warns(UserWarning): print_summary(scan([det], motor, -1,", "= hw.motor print_summary(scan([det], motor, -1, 1, 10)) # old name", "list(print_summary_wrapper(scan([det], motor, -1, 1, 10))) def test_old_module_name(hw): det = hw.det", "assert not hasattr(motor, 'limits') # # check_limits should warn if", "print_summary_wrapper, summarize_plan, check_limits, plot_raster_path) import pytest from bluesky.plans import grid_scan", "import grid_scan def test_print_summary(hw): det = hw.det motor = hw.motor", "10, motor2, -7, 7, 15, True) plot_raster_path(plan, 'motor1', 'motor2', probe_size=.3)", "name list(print_summary_wrapper(scan([det], motor, -1, 1, 10))) def test_old_module_name(hw): det =", "= hw.motor2 from bluesky.plan_tools import (print_summary, print_summary_wrapper, plot_raster_path) with pytest.warns(UserWarning):", "plan = grid_scan([det], motor1, -5, 5, 10, motor2, -7, 7,", "= hw.det motor = hw.motor # The motor object does", "import (print_summary, print_summary_wrapper, summarize_plan, check_limits, plot_raster_path) import pytest from bluesky.plans", "Use an assert to help us out if this changes", "7, 15, True) plot_raster_path(plan, 'motor1', 'motor2', probe_size=.3) def test_check_limits(RE, hw):", "(2, 2) check_limits(scan([det], motor, -1, 1, 3)) def test_check_limits_needs_RE(): with", "-1, 1, 3)) def test_check_limits_needs_RE(): with pytest.raises(RuntimeError) as ctx: check_limits([])", "True) plot_raster_path(plan, 'motor1', 'motor2', probe_size=.3) def test_check_limits(RE, hw): det =", "(print_summary, print_summary_wrapper, plot_raster_path) with pytest.warns(UserWarning): print_summary(scan([det], motor, -1, 1, 10))", "# check_limits(scan([det], motor, -1, 1, 3)) # monkey-patch some limits", "pytest from bluesky.plans import grid_scan def test_print_summary(hw): det = hw.det", "find check_value # TODO: Is there _any_ object to test?", "implement limits. # Use an assert to help us out", "print_summary(scan([det], motor, -1, 1, 10)) # old name summarize_plan(scan([det], motor,", "raises # this object does not raise check_limits(scan([det], motor, -3,", "\"Bluesky event loop not running\" def test_plot_raster_path(hw): det = hw.det", "running\" def test_plot_raster_path(hw): det = hw.det motor1 = hw.motor1 motor2", "# monkey-patch some limits motor.limits = (-2, 2) # check_limits", "hw.motor2 from bluesky.plan_tools import (print_summary, print_summary_wrapper, plot_raster_path) with pytest.warns(UserWarning): print_summary(scan([det],", "if it can't find check_value # TODO: Is there _any_", "raises # this object does not raise motor.limits = (2,", "summarize_plan, check_limits, plot_raster_path) import pytest from bluesky.plans import grid_scan def", "motor = hw.motor motor1 = hw.motor1 motor2 = hw.motor2 from", "3)) # check_limits should error if limits are exceeded only", "= (2, 2) check_limits(scan([det], motor, -1, 1, 3)) def test_check_limits_needs_RE():", "not raise check_limits(scan([det], motor, -3, 3, 3)) # check_limits should", "motor, -1, 1, 10)) # old name summarize_plan(scan([det], motor, -1,", "-5, 5, 10, motor2, -7, 7, 15, True) plot_raster_path(plan, 'motor1',", "hw.det motor = hw.motor motor1 = hw.motor1 motor2 = hw.motor2", "det = hw.det motor = hw.motor # The motor object", "should raise if limits are equal only if object raises", "plot_raster_path(plan, 'motor1', 'motor2', probe_size=.3) def test_check_limits(RE, hw): det = hw.det", "new name list(print_summary_wrapper(scan([det], motor, -1, 1, 10))) def test_old_module_name(hw): det", "'limits') # # check_limits should warn if it can't find", "hw.motor print_summary(scan([det], motor, -1, 1, 10)) # old name summarize_plan(scan([det],", "summarize_plan(scan([det], motor, -1, 1, 10)) # new name list(print_summary_wrapper(scan([det], motor,", "10)) # new name list(print_summary_wrapper(scan([det], motor, -1, 1, 10))) def", "motor2, -7, 7, 15, True) plot_raster_path(plan, 'motor1', 'motor2', probe_size=.3) def", "exceeded only if object raises # this object does not", "'motor2', probe_size=.3) def test_check_limits(RE, hw): det = hw.det motor =", "do nothing here check_limits(scan([det], motor, -1, 1, 3)) # check_limits", "hw.motor2 plan = grid_scan([det], motor1, -5, 5, 10, motor2, -7,", "check_limits should do nothing here check_limits(scan([det], motor, -1, 1, 3))", "raise check_limits(scan([det], motor, -3, 3, 3)) # check_limits should raise", "# # check_limits should warn if it can't find check_value", "1, 10)) # old name summarize_plan(scan([det], motor, -1, 1, 10))", "# check_limits should warn if it can't find check_value #", "= hw.det motor = hw.motor print_summary(scan([det], motor, -1, 1, 10))", "hasattr(motor, 'limits') # # check_limits should warn if it can't", "test_old_module_name(hw): det = hw.det motor = hw.motor motor1 = hw.motor1", "10)) # old name summarize_plan(scan([det], motor, -1, 1, 10)) #", "# with pytest.warns(UserWarning): # check_limits(scan([det], motor, -1, 1, 3)) #", "object does not currently implement limits. # Use an assert", "check_limits should error if limits are exceeded only if object", "# new name list(print_summary_wrapper(scan([det], motor, -1, 1, 10))) def test_old_module_name(hw):", "assert to help us out if this changes in the", "3)) # check_limits should raise if limits are equal only", "2) check_limits(scan([det], motor, -1, 1, 3)) def test_check_limits_needs_RE(): with pytest.raises(RuntimeError)", "hw.motor1 motor2 = hw.motor2 plan = grid_scan([det], motor1, -5, 5,", "monkey-patch some limits motor.limits = (-2, 2) # check_limits should", "def test_old_module_name(hw): det = hw.det motor = hw.motor motor1 =", "1, 10)) with pytest.warns(UserWarning): list(print_summary_wrapper(scan([det], motor, -1, 1, 10))) with", "check_limits(scan([det], motor, -3, 3, 3)) # check_limits should raise if", "out if this changes in the future. assert not hasattr(motor,", "plot_raster_path) with pytest.warns(UserWarning): print_summary(scan([det], motor, -1, 1, 10)) with pytest.warns(UserWarning):", "us out if this changes in the future. assert not", "hw.motor motor1 = hw.motor1 motor2 = hw.motor2 from bluesky.plan_tools import", "15, True) plot_raster_path(plan, 'motor1', 'motor2', probe_size=.3) def test_check_limits(RE, hw): det", "future. assert not hasattr(motor, 'limits') # # check_limits should warn", "motor1 = hw.motor1 motor2 = hw.motor2 from bluesky.plan_tools import (print_summary,", "old name summarize_plan(scan([det], motor, -1, 1, 10)) # new name", "it can't find check_value # TODO: Is there _any_ object", "this object does not raise motor.limits = (2, 2) check_limits(scan([det],", "limits motor.limits = (-2, 2) # check_limits should do nothing", "motor = hw.motor print_summary(scan([det], motor, -1, 1, 10)) # old", "as ctx: check_limits([]) assert str(ctx.value) == \"Bluesky event loop not", "bluesky.plans import scan from bluesky.simulators import (print_summary, print_summary_wrapper, summarize_plan, check_limits,", "list(print_summary_wrapper(scan([det], motor, -1, 1, 10))) with pytest.warns(UserWarning): plan = grid_scan([det],", "not currently implement limits. # Use an assert to help", "Is there _any_ object to test? # with pytest.warns(UserWarning): #", "limits. # Use an assert to help us out if", "motor, -1, 1, 3)) def test_check_limits_needs_RE(): with pytest.raises(RuntimeError) as ctx:", "1, 10)) # new name list(print_summary_wrapper(scan([det], motor, -1, 1, 10)))", "with pytest.warns(UserWarning): print_summary(scan([det], motor, -1, 1, 10)) with pytest.warns(UserWarning): list(print_summary_wrapper(scan([det],", "motor, -1, 1, 10))) with pytest.warns(UserWarning): plan = grid_scan([det], motor1,", "'motor1', 'motor2', probe_size=.3) def test_check_limits(RE, hw): det = hw.det motor", "pytest.warns(UserWarning): list(print_summary_wrapper(scan([det], motor, -1, 1, 10))) with pytest.warns(UserWarning): plan =", "det = hw.det motor1 = hw.motor1 motor2 = hw.motor2 plan", "1, 3)) # check_limits should error if limits are exceeded", "not hasattr(motor, 'limits') # # check_limits should warn if it", "== \"Bluesky event loop not running\" def test_plot_raster_path(hw): det =", "test_check_limits(RE, hw): det = hw.det motor = hw.motor # The", "ctx: check_limits([]) assert str(ctx.value) == \"Bluesky event loop not running\"", "should error if limits are exceeded only if object raises", "def test_print_summary(hw): det = hw.det motor = hw.motor print_summary(scan([det], motor,", "= hw.motor motor1 = hw.motor1 motor2 = hw.motor2 from bluesky.plan_tools", "motor object does not currently implement limits. # Use an", "test_plot_raster_path(hw): det = hw.det motor1 = hw.motor1 motor2 = hw.motor2", "# TODO: Is there _any_ object to test? # with", "str(ctx.value) == \"Bluesky event loop not running\" def test_plot_raster_path(hw): det", "-1, 1, 10)) # new name list(print_summary_wrapper(scan([det], motor, -1, 1,", "nothing here check_limits(scan([det], motor, -1, 1, 3)) # check_limits should", "from bluesky.simulators import (print_summary, print_summary_wrapper, summarize_plan, check_limits, plot_raster_path) import pytest", "name summarize_plan(scan([det], motor, -1, 1, 10)) # new name list(print_summary_wrapper(scan([det],", "hw.det motor1 = hw.motor1 motor2 = hw.motor2 plan = grid_scan([det],", "-7, 7, 15, True) plot_raster_path(plan, 'motor1', 'motor2', probe_size=.3) def test_check_limits(RE,", "(print_summary, print_summary_wrapper, summarize_plan, check_limits, plot_raster_path) import pytest from bluesky.plans import", "= (-2, 2) # check_limits should do nothing here check_limits(scan([det],", "check_limits should raise if limits are equal only if object", "motor, -1, 1, 3)) # monkey-patch some limits motor.limits =", "are equal only if object raises # this object does", "the future. assert not hasattr(motor, 'limits') # # check_limits should", "does not raise motor.limits = (2, 2) check_limits(scan([det], motor, -1,", "1, 3)) def test_check_limits_needs_RE(): with pytest.raises(RuntimeError) as ctx: check_limits([]) assert", "import pytest from bluesky.plans import grid_scan def test_print_summary(hw): det =", "# check_limits should raise if limits are equal only if", "does not raise check_limits(scan([det], motor, -3, 3, 3)) # check_limits", "raise motor.limits = (2, 2) check_limits(scan([det], motor, -1, 1, 3))", "should do nothing here check_limits(scan([det], motor, -1, 1, 3)) #", "def test_check_limits(RE, hw): det = hw.det motor = hw.motor #", "# check_limits should do nothing here check_limits(scan([det], motor, -1, 1,", "3)) def test_check_limits_needs_RE(): with pytest.raises(RuntimeError) as ctx: check_limits([]) assert str(ctx.value)", "here check_limits(scan([det], motor, -1, 1, 3)) # check_limits should error", "error if limits are exceeded only if object raises #", "some limits motor.limits = (-2, 2) # check_limits should do", "if object raises # this object does not raise check_limits(scan([det],", "10))) with pytest.warns(UserWarning): plan = grid_scan([det], motor1, -5, 5, 10,", "pytest.raises(RuntimeError) as ctx: check_limits([]) assert str(ctx.value) == \"Bluesky event loop", "TODO: Is there _any_ object to test? # with pytest.warns(UserWarning):", "hw.det motor = hw.motor print_summary(scan([det], motor, -1, 1, 10)) #", "check_limits, plot_raster_path) import pytest from bluesky.plans import grid_scan def test_print_summary(hw):", "from bluesky.plan_tools import (print_summary, print_summary_wrapper, plot_raster_path) with pytest.warns(UserWarning): print_summary(scan([det], motor,", "= hw.motor # The motor object does not currently implement", "check_limits(scan([det], motor, -1, 1, 3)) # check_limits should error if", "# Use an assert to help us out if this", "pytest.warns(UserWarning): print_summary(scan([det], motor, -1, 1, 10)) with pytest.warns(UserWarning): list(print_summary_wrapper(scan([det], motor,", "check_limits(scan([det], motor, -1, 1, 3)) # monkey-patch some limits motor.limits", "limits are exceeded only if object raises # this object", "if limits are equal only if object raises # this", "only if object raises # this object does not raise", "with pytest.warns(UserWarning): # check_limits(scan([det], motor, -1, 1, 3)) # monkey-patch", "this changes in the future. assert not hasattr(motor, 'limits') #", "check_limits([]) assert str(ctx.value) == \"Bluesky event loop not running\" def", "assert str(ctx.value) == \"Bluesky event loop not running\" def test_plot_raster_path(hw):", "# check_limits should error if limits are exceeded only if", "motor.limits = (-2, 2) # check_limits should do nothing here", "check_limits(scan([det], motor, -1, 1, 3)) def test_check_limits_needs_RE(): with pytest.raises(RuntimeError) as", "bluesky.simulators import (print_summary, print_summary_wrapper, summarize_plan, check_limits, plot_raster_path) import pytest from", "scan from bluesky.simulators import (print_summary, print_summary_wrapper, summarize_plan, check_limits, plot_raster_path) import", "probe_size=.3) def test_check_limits(RE, hw): det = hw.det motor = hw.motor", "motor, -1, 1, 10)) with pytest.warns(UserWarning): list(print_summary_wrapper(scan([det], motor, -1, 1,", "grid_scan([det], motor1, -5, 5, 10, motor2, -7, 7, 15, True)", "changes in the future. assert not hasattr(motor, 'limits') # #", "this object does not raise check_limits(scan([det], motor, -3, 3, 3))", "object does not raise motor.limits = (2, 2) check_limits(scan([det], motor,", "not running\" def test_plot_raster_path(hw): det = hw.det motor1 = hw.motor1", "motor1 = hw.motor1 motor2 = hw.motor2 plan = grid_scan([det], motor1,", "3, 3)) # check_limits should raise if limits are equal", "5, 10, motor2, -7, 7, 15, True) plot_raster_path(plan, 'motor1', 'motor2',", "-1, 1, 10)) with pytest.warns(UserWarning): list(print_summary_wrapper(scan([det], motor, -1, 1, 10)))", "should warn if it can't find check_value # TODO: Is", "hw): det = hw.det motor = hw.motor # The motor", "1, 3)) # monkey-patch some limits motor.limits = (-2, 2)", "2) # check_limits should do nothing here check_limits(scan([det], motor, -1,", "motor, -1, 1, 3)) # check_limits should error if limits", "with pytest.warns(UserWarning): plan = grid_scan([det], motor1, -5, 5, 10, motor2,", "-1, 1, 10)) # old name summarize_plan(scan([det], motor, -1, 1,", "motor1, -5, 5, 10, motor2, -7, 7, 15, True) plot_raster_path(plan,", "check_value # TODO: Is there _any_ object to test? #", "test_print_summary(hw): det = hw.det motor = hw.motor print_summary(scan([det], motor, -1,", "10)) with pytest.warns(UserWarning): list(print_summary_wrapper(scan([det], motor, -1, 1, 10))) with pytest.warns(UserWarning):", "warn if it can't find check_value # TODO: Is there", "-1, 1, 3)) # monkey-patch some limits motor.limits = (-2,", "# this object does not raise motor.limits = (2, 2)", "print_summary(scan([det], motor, -1, 1, 10)) with pytest.warns(UserWarning): list(print_summary_wrapper(scan([det], motor, -1,", "-1, 1, 10))) def test_old_module_name(hw): det = hw.det motor =", "equal only if object raises # this object does not", "to help us out if this changes in the future.", "-1, 1, 10))) with pytest.warns(UserWarning): plan = grid_scan([det], motor1, -5,", "10))) def test_old_module_name(hw): det = hw.det motor = hw.motor motor1", "(-2, 2) # check_limits should do nothing here check_limits(scan([det], motor,", "= hw.motor1 motor2 = hw.motor2 from bluesky.plan_tools import (print_summary, print_summary_wrapper,", "object raises # this object does not raise motor.limits =", "plot_raster_path) import pytest from bluesky.plans import grid_scan def test_print_summary(hw): det", "3)) # monkey-patch some limits motor.limits = (-2, 2) #", "object raises # this object does not raise check_limits(scan([det], motor,", "help us out if this changes in the future. assert", "if limits are exceeded only if object raises # this", "motor2 = hw.motor2 plan = grid_scan([det], motor1, -5, 5, 10,", "grid_scan def test_print_summary(hw): det = hw.det motor = hw.motor print_summary(scan([det],", "are exceeded only if object raises # this object does", "motor.limits = (2, 2) check_limits(scan([det], motor, -1, 1, 3)) def" ]
[ "j+=1 i +=1 else: value = False return value def", "= i+1 while j< len(numbers_list): if numbers_list[i] + numbers_list[j] ==", "str(games_played) + \"\\nGames Won: \" + str(games_won) + \"\\nGames Lost:", "def all_less_than_7(): less_than_7 = True i = 0 while i", "enter a number that is available: \")) except ValueError: print(\"Invalid", "two dice. Please enter either '1' or '2': \")) except", "6) i+=1 return total def choose_dice_amount(): amount = 0 while", "\" + str(numbers_list) + \" to get to \" +", "i < len(numbers_list): if i < len(numbers_list)-1: result += str(numbers_list[i])", "or n: \")) except ValueError: print(\"Invalid choice; please try again\")", "\"y\": return True else: return False keep_playing = True while", "return amount else: print(\"INVALID ENTRY PLEASE TRY AGAIN!\") continue return", "if entered not in numbers_list or entered in entered_numbers: print(\"Invalid", "str(numbers_list)) games_played += 1 games_lost += 1 total_score += score_game()", "entered = int(input(\"Please enter a number that is available: \"))", "numbers_list[k] == rolled: return False l = k+1 while l", "55: game_won = win_game() if game_won: print(\"Congrats you won!!!!\") games_played", "score_game() average_score = total_score/games_played game_won = False print(\"STATS:\\n Games Played:", "= 0 average_score = 0 total_score = 0 def welcome():", "while True: try: amount = int(input(\"You choose to roll one", "= True i = 0 while i < len(numbers_list): if", "= int(input(\"Please enter a number that is available: \")) except", "0 while i < len(numbers_list): score += numbers_list[i] i+=1 return", "y or n: \")) except ValueError: print(\"Invalid choice; please try", "j< len(numbers_list): if numbers_list[i] + numbers_list[j] == rolled: return False", "check_lost_game(rolled): value = True if rolled not in numbers_list: i", "i+=1 return score def all_less_than_7(): less_than_7 = True i =", "1 total_score += score_game() average_score = total_score/games_played game_won = False", "return amount def choose_number_to_drop(target_amount): entered = 0 goal = target_amount", "to \" + str(target_amount)) entered = int(input(\"Please enter a number", "choose_number_to_drop(dice_total) roll_total += dice_total if roll_total == 55: game_won =", "= \"\" while i < len(numbers_list): if i < len(numbers_list)-1:", "= True return game_won def score_game(): score = 0 i", "False #Stats games_played = 0 games_won = 0 games_lost =", "win_game(): game_won = True return game_won def score_game(): score =", "l < len(numbers_list): if numbers_list[i] + numbers_list[j] + numbers_list[k] +", "return False k = j+1 while k < len(numbers_list): if", "rolled: return False l = k+1 while l < len(numbers_list):", "or two dice. Please enter either '1' or '2': \"))", "games_played = 0 games_won = 0 games_lost = 0 average_score", "number that is available: \")) except ValueError: print(\"Invalid Entry, please", "less_than_7 def keep_playing_input(): while True: try: continue_playing = (input(\"Do you", "+ str(games_played) + \"\\nGames Won: \" + str(games_won) + \"\\nGames", "one or two dice. Please enter either '1' or '2':", "impossible to continue the game with this roll\") break choose_number_to_drop(dice_total)", "except ValueError: print(\"INVALID ENTRY PLEASE TRY AGAIN\") continue if amount", "i += 1 return less_than_7 def keep_playing_input(): while True: try:", "= dice_roll(dice_amount) print(\"Your roll is: \" + str(dice_total)) if check_lost_game(dice_total):", "0 while i < len(entered_numbers): numbers_list.remove(entered_numbers[i]) i += 1 def", "j = i+1 while j< len(numbers_list): if numbers_list[i] + numbers_list[j]", "0: goal = target_amount entered_numbers = list() i = 0", "= target_amount entered_numbers = list() i = 0 while i", "0 while i < len(numbers_list): if numbers_list[i] > 6: less_than_7", "break choose_number_to_drop(dice_total) roll_total += dice_total if roll_total == 55: game_won", "less_than_7 = True i = 0 while i < len(numbers_list):", "= 0 def welcome(): welcome_message = \"Welcome to shut the", "or '2': \")) except ValueError: print(\"INVALID ENTRY PLEASE TRY AGAIN\")", "roll one or two dice. Please enter either '1' or", "the game with this roll\") break choose_number_to_drop(dice_total) roll_total += dice_total", "entered_numbers: print(\"Invalid Entry, please try again\") continue else: goal -=", "game_completed = True return game_completed def win_game(): game_won = True", "games_won +=1 else: print(\"You lose, your score is \" +", "def end_game(): game_completed = True return game_completed def win_game(): game_won", "(input(\"Do you wish to keep playing? y or n: \"))", "choice; please try again\") continue if continue_playing.lower == \"y\": return", "roll_total < 55: dice_amount = 2 if all_less_than_7(): dice_amount =", "total_score += score_game() average_score = total_score/games_played game_won = False print(\"STATS:\\n", "welcome() roll_total = 0 while roll_total < 55: dice_amount =", "+ str(numbers_list)) games_played += 1 games_lost += 1 total_score +=", "+ numbers_list[k] + numbers_list[l] == rolled: return False l+=1 k+=1", "continue if entered not in numbers_list or entered in entered_numbers:", "+ \" to get to \" + str(target_amount)) entered =", "please try again\") continue if entered not in numbers_list or", "< 55: dice_amount = 2 if all_less_than_7(): dice_amount = choose_dice_amount()", "\" + str(games_played) + \"\\nGames Won: \" + str(games_won) +", "else: goal -= entered entered_numbers.append(entered) if goal < 0: goal", "continue return amount def choose_number_to_drop(target_amount): entered = 0 goal =", "random numbers_list = [1,2,3,4,5,6,7,8,9,10] game_won = False game_completed = False", "= False print(\"STATS:\\n Games Played: \" + str(games_played) + \"\\nGames", "print(\"Invalid choice; please try again\") continue if continue_playing.lower == \"y\":", "score is \" + str(score_game())) print(\"Numbers remaining: \" + str(numbers_list))", "+ str(games_lost) + \"\\nAverage Score: \" + str(average_score) + \"\\nTotal", "len(numbers_list): if numbers_list[i] + numbers_list[j] + numbers_list[k] == rolled: return", "goal -= entered entered_numbers.append(entered) if goal < 0: goal =", "average_score = total_score/games_played game_won = False print(\"STATS:\\n Games Played: \"", "False l = k+1 while l < len(numbers_list): if numbers_list[i]", "= 0 games_lost = 0 average_score = 0 total_score =", "keep playing? y or n: \")) except ValueError: print(\"Invalid choice;", "0 while i < len(numbers_list): j = i+1 while j<", "dice_roll(amount): total = 0 i = 0 while i <", "+ str(score_game())) print(\"Numbers remaining: \" + str(numbers_list)) games_played += 1", "+ \"\\nGames Lost: \" + str(games_lost) + \"\\nAverage Score: \"", "while i < len(numbers_list): score += numbers_list[i] i+=1 return score", "continue if continue_playing.lower == \"y\": return True else: return False", "Score: \" + str(average_score) + \"\\nTotal Score: \" + str(total_score))", "check_lost_game(dice_total): print(\"It is impossible to continue the game with this", "= choose_dice_amount() dice_total = dice_roll(dice_amount) print(\"Your roll is: \" +", "i = 0 while i < len(numbers_list): if numbers_list[i] >", "= k+1 while l < len(numbers_list): if numbers_list[i] + numbers_list[j]", "False keep_playing = True while keep_playing: numbers_list = [1,2,3,4,5,6,7,8,9,10] welcome()", "to get to \" + str(target_amount)) entered = int(input(\"Please enter", "while k < len(numbers_list): if numbers_list[i] + numbers_list[j] + numbers_list[k]", "+ \"\\nGames Won: \" + str(games_won) + \"\\nGames Lost: \"", "again\") continue else: goal -= entered entered_numbers.append(entered) if goal <", "+ numbers_list[j] + numbers_list[k] == rolled: return False l =", "+ str(games_won) + \"\\nGames Lost: \" + str(games_lost) + \"\\nAverage", "'2': \")) except ValueError: print(\"INVALID ENTRY PLEASE TRY AGAIN\") continue", "\")) except ValueError: print(\"Invalid Entry, please try again\") continue if", "that is available: \")) except ValueError: print(\"Invalid Entry, please try", "random.randint(1, 6) i+=1 return total def choose_dice_amount(): amount = 0", "game with this roll\") break choose_number_to_drop(dice_total) roll_total += dice_total if", "[1,2,3,4,5,6,7,8,9,10] welcome() roll_total = 0 while roll_total < 55: dice_amount", "= 0 i = 0 while i < len(numbers_list): score", "keep_playing = True while keep_playing: numbers_list = [1,2,3,4,5,6,7,8,9,10] welcome() roll_total", "game_won = False print(\"STATS:\\n Games Played: \" + str(games_played) +", "if numbers_list[i] > 6: less_than_7 = False i += 1", "print(\"INVALID ENTRY PLEASE TRY AGAIN\") continue if amount == 1", "+= 1 return less_than_7 def keep_playing_input(): while True: try: continue_playing", "l = k+1 while l < len(numbers_list): if numbers_list[i] +", "0 goal = target_amount entered_numbers = list() while goal !=", "while l < len(numbers_list): if numbers_list[i] + numbers_list[j] + numbers_list[k]", "entered entered_numbers.append(entered) if goal < 0: goal = target_amount entered_numbers", "1 def check_lost_game(rolled): value = True if rolled not in", "len(numbers_list): if numbers_list[i] + numbers_list[j] + numbers_list[k] + numbers_list[l] ==", "if numbers_list[i] + numbers_list[j] + numbers_list[k] + numbers_list[l] == rolled:", "def keep_playing_input(): while True: try: continue_playing = (input(\"Do you wish", "if goal < 0: goal = target_amount entered_numbers = list()", "\" + str(numbers_list)) games_played += 1 games_lost += 1 total_score", "\"\\nGames Won: \" + str(games_won) + \"\\nGames Lost: \" +", "score_game(): score = 0 i = 0 while i <", "goal != 0: try: print(\"Available numbers: \" + str(numbers_list) +", "print(\"Invalid Entry, please try again\") continue if entered not in", "numbers_list[j] + numbers_list[k] == rolled: return False l = k+1", "wish to keep playing? y or n: \")) except ValueError:", "= win_game() if game_won: print(\"Congrats you won!!!!\") games_played +=1 games_won", "55: dice_amount = 2 if all_less_than_7(): dice_amount = choose_dice_amount() dice_total", "= \"Welcome to shut the box\" print(welcome_message) i = 0", "def check_lost_game(rolled): value = True if rolled not in numbers_list:", "k+1 while l < len(numbers_list): if numbers_list[i] + numbers_list[j] +", "while True: try: continue_playing = (input(\"Do you wish to keep", "+ str(numbers_list) + \" to get to \" + str(target_amount))", "0: try: print(\"Available numbers: \" + str(numbers_list) + \" to", "continue the game with this roll\") break choose_number_to_drop(dice_total) roll_total +=", "False l+=1 k+=1 j+=1 i +=1 else: value = False", "again\") continue if entered not in numbers_list or entered in", "0 i = 0 while i < len(numbers_list): score +=", "== rolled: return False l = k+1 while l <", "amount = int(input(\"You choose to roll one or two dice.", "def choose_dice_amount(): amount = 0 while True: try: amount =", "entered_numbers = list() while goal != 0: try: print(\"Available numbers:", "total = 0 i = 0 while i < amount:", "\" + str(dice_total)) if check_lost_game(dice_total): print(\"It is impossible to continue", "if game_won: print(\"Congrats you won!!!!\") games_played +=1 games_won +=1 else:", "= 0 total_score = 0 def welcome(): welcome_message = \"Welcome", "len(entered_numbers): numbers_list.remove(entered_numbers[i]) i += 1 def check_lost_game(rolled): value = True", "= j+1 while k < len(numbers_list): if numbers_list[i] + numbers_list[j]", "= 0 while i < len(numbers_list): score += numbers_list[i] i+=1", "= total_score/games_played game_won = False print(\"STATS:\\n Games Played: \" +", "True else: return False keep_playing = True while keep_playing: numbers_list", "'1' or '2': \")) except ValueError: print(\"INVALID ENTRY PLEASE TRY", "0 while True: try: amount = int(input(\"You choose to roll", "keep_playing_input(): while True: try: continue_playing = (input(\"Do you wish to", "i < len(numbers_list): j = i+1 while j< len(numbers_list): if", "< len(numbers_list): if numbers_list[i] + numbers_list[j] + numbers_list[k] == rolled:", "again\") continue if continue_playing.lower == \"y\": return True else: return", "return False l+=1 k+=1 j+=1 i +=1 else: value =", "numbers_list[l] == rolled: return False l+=1 k+=1 j+=1 i +=1", "i +=1 else: value = False return value def end_game():", "= [1,2,3,4,5,6,7,8,9,10] welcome() roll_total = 0 while roll_total < 55:", "end_game(): game_completed = True return game_completed def win_game(): game_won =", "print(\"Available numbers: \" + str(numbers_list) + \" to get to", "dice_roll(dice_amount) print(\"Your roll is: \" + str(dice_total)) if check_lost_game(dice_total): print(\"It", "games_played +=1 games_won +=1 else: print(\"You lose, your score is", "numbers: \" + str(numbers_list) + \" to get to \"", "= True return game_completed def win_game(): game_won = True return", "i += 1 def check_lost_game(rolled): value = True if rolled", "+ \" \" else: result += str(numbers_list[i]) i+=1 print(result) def", "+ str(dice_total)) if check_lost_game(dice_total): print(\"It is impossible to continue the", "TRY AGAIN\") continue if amount == 1 or amount ==", "numbers_list[i] + numbers_list[j] + numbers_list[k] == rolled: return False l", "+=1 else: value = False return value def end_game(): game_completed", "all_less_than_7(): less_than_7 = True i = 0 while i <", "def win_game(): game_won = True return game_won def score_game(): score", "True return game_won def score_game(): score = 0 i =", "rolled: return False l+=1 k+=1 j+=1 i +=1 else: value", "else: value = False return value def end_game(): game_completed =", "roll_total += dice_total if roll_total == 55: game_won = win_game()", "entered_numbers.append(entered) if goal < 0: goal = target_amount entered_numbers =", "while roll_total < 55: dice_amount = 2 if all_less_than_7(): dice_amount", "AGAIN!\") continue return amount def choose_number_to_drop(target_amount): entered = 0 goal", "i = 0 result = \"\" while i < len(numbers_list):", "numbers_list[i] + numbers_list[j] == rolled: return False k = j+1", "numbers_list[k] + numbers_list[l] == rolled: return False l+=1 k+=1 j+=1", "win_game() if game_won: print(\"Congrats you won!!!!\") games_played +=1 games_won +=1", "while i < amount: total += random.randint(1, 6) i+=1 return", "= False game_completed = False #Stats games_played = 0 games_won", "except ValueError: print(\"Invalid Entry, please try again\") continue if entered", "def dice_roll(amount): total = 0 i = 0 while i", "False i += 1 return less_than_7 def keep_playing_input(): while True:", "not in numbers_list or entered in entered_numbers: print(\"Invalid Entry, please", "roll_total = 0 while roll_total < 55: dice_amount = 2", "numbers_list[i] + numbers_list[j] + numbers_list[k] + numbers_list[l] == rolled: return", "numbers_list or entered in entered_numbers: print(\"Invalid Entry, please try again\")", "enter either '1' or '2': \")) except ValueError: print(\"INVALID ENTRY", "numbers_list = [1,2,3,4,5,6,7,8,9,10] welcome() roll_total = 0 while roll_total <", "if roll_total == 55: game_won = win_game() if game_won: print(\"Congrats", "ENTRY PLEASE TRY AGAIN\") continue if amount == 1 or", "len(numbers_list): if i < len(numbers_list)-1: result += str(numbers_list[i]) + \"", "i < len(entered_numbers): numbers_list.remove(entered_numbers[i]) i += 1 def check_lost_game(rolled): value", "playing? y or n: \")) except ValueError: print(\"Invalid choice; please", "try: print(\"Available numbers: \" + str(numbers_list) + \" to get", "-= entered entered_numbers.append(entered) if goal < 0: goal = target_amount", "> 6: less_than_7 = False i += 1 return less_than_7", "dice_amount = 2 if all_less_than_7(): dice_amount = choose_dice_amount() dice_total =", "Games Played: \" + str(games_played) + \"\\nGames Won: \" +", "you won!!!!\") games_played +=1 games_won +=1 else: print(\"You lose, your", "= [1,2,3,4,5,6,7,8,9,10] game_won = False game_completed = False #Stats games_played", "str(target_amount)) entered = int(input(\"Please enter a number that is available:", "numbers_list[j] == rolled: return False k = j+1 while k", "= 0 while i < len(entered_numbers): numbers_list.remove(entered_numbers[i]) i += 1", "+= dice_total if roll_total == 55: game_won = win_game() if", "0 games_won = 0 games_lost = 0 average_score = 0", "[1,2,3,4,5,6,7,8,9,10] game_won = False game_completed = False #Stats games_played =", "with this roll\") break choose_number_to_drop(dice_total) roll_total += dice_total if roll_total", "goal < 0: goal = target_amount entered_numbers = list() i", "6: less_than_7 = False i += 1 return less_than_7 def", "amount == 2: return amount else: print(\"INVALID ENTRY PLEASE TRY", "0 i = 0 while i < amount: total +=", "lose, your score is \" + str(score_game())) print(\"Numbers remaining: \"", "Played: \" + str(games_played) + \"\\nGames Won: \" + str(games_won)", "1 return less_than_7 def keep_playing_input(): while True: try: continue_playing =", "\" + str(average_score) + \"\\nTotal Score: \" + str(total_score)) keep_playing_input()", "= list() while goal != 0: try: print(\"Available numbers: \"", "except ValueError: print(\"Invalid choice; please try again\") continue if continue_playing.lower", "else: print(\"INVALID ENTRY PLEASE TRY AGAIN!\") continue return amount def", "numbers_list.remove(entered_numbers[i]) i += 1 def check_lost_game(rolled): value = True if", "== 1 or amount == 2: return amount else: print(\"INVALID", "False k = j+1 while k < len(numbers_list): if numbers_list[i]", "<filename>shutTheBox/main.py import random numbers_list = [1,2,3,4,5,6,7,8,9,10] game_won = False game_completed", "continue if amount == 1 or amount == 2: return", "while keep_playing: numbers_list = [1,2,3,4,5,6,7,8,9,10] welcome() roll_total = 0 while", "j+1 while k < len(numbers_list): if numbers_list[i] + numbers_list[j] +", "print(\"Numbers remaining: \" + str(numbers_list)) games_played += 1 games_lost +=", "str(dice_total)) if check_lost_game(dice_total): print(\"It is impossible to continue the game", "ENTRY PLEASE TRY AGAIN!\") continue return amount def choose_number_to_drop(target_amount): entered", "= int(input(\"You choose to roll one or two dice. Please", "get to \" + str(target_amount)) entered = int(input(\"Please enter a", "i < len(numbers_list): if numbers_list[i] > 6: less_than_7 = False", "value = False return value def end_game(): game_completed = True", "entered = 0 goal = target_amount entered_numbers = list() while", "\"\\nAverage Score: \" + str(average_score) + \"\\nTotal Score: \" +", "numbers_list[i] > 6: less_than_7 = False i += 1 return", "print(\"Invalid Entry, please try again\") continue else: goal -= entered", "+= 1 total_score += score_game() average_score = total_score/games_played game_won =", "\" \" else: result += str(numbers_list[i]) i+=1 print(result) def dice_roll(amount):", "return game_won def score_game(): score = 0 i = 0", "== rolled: return False k = j+1 while k <", "def choose_number_to_drop(target_amount): entered = 0 goal = target_amount entered_numbers =", "games_won = 0 games_lost = 0 average_score = 0 total_score", "dice_total if roll_total == 55: game_won = win_game() if game_won:", "i < amount: total += random.randint(1, 6) i+=1 return total", "game_completed def win_game(): game_won = True return game_won def score_game():", "def score_game(): score = 0 i = 0 while i", "goal = target_amount entered_numbers = list() while goal != 0:", "to continue the game with this roll\") break choose_number_to_drop(dice_total) roll_total", "= target_amount entered_numbers = list() while goal != 0: try:", "= 0 while True: try: amount = int(input(\"You choose to", "TRY AGAIN!\") continue return amount def choose_number_to_drop(target_amount): entered = 0", "print(\"Congrats you won!!!!\") games_played +=1 games_won +=1 else: print(\"You lose,", "False game_completed = False #Stats games_played = 0 games_won =", "print(\"Your roll is: \" + str(dice_total)) if check_lost_game(dice_total): print(\"It is", "goal = target_amount entered_numbers = list() i = 0 while", "\" else: result += str(numbers_list[i]) i+=1 print(result) def dice_roll(amount): total", "score = 0 i = 0 while i < len(numbers_list):", "print(welcome_message) i = 0 result = \"\" while i <", "= 0 result = \"\" while i < len(numbers_list): if", "< 0: goal = target_amount entered_numbers = list() i =", "else: result += str(numbers_list[i]) i+=1 print(result) def dice_roll(amount): total =", "target_amount entered_numbers = list() i = 0 while i <", "dice_total = dice_roll(dice_amount) print(\"Your roll is: \" + str(dice_total)) if", "i < len(numbers_list)-1: result += str(numbers_list[i]) + \" \" else:", "entered not in numbers_list or entered in entered_numbers: print(\"Invalid Entry,", "< len(numbers_list): score += numbers_list[i] i+=1 return score def all_less_than_7():", "= True while keep_playing: numbers_list = [1,2,3,4,5,6,7,8,9,10] welcome() roll_total =", "not in numbers_list: i = 0 while i < len(numbers_list):", "+ str(target_amount)) entered = int(input(\"Please enter a number that is", "total_score/games_played game_won = False print(\"STATS:\\n Games Played: \" + str(games_played)", "numbers_list = [1,2,3,4,5,6,7,8,9,10] game_won = False game_completed = False #Stats", "= True if rolled not in numbers_list: i = 0", "< len(entered_numbers): numbers_list.remove(entered_numbers[i]) i += 1 def check_lost_game(rolled): value =", "either '1' or '2': \")) except ValueError: print(\"INVALID ENTRY PLEASE", "please try again\") continue else: goal -= entered entered_numbers.append(entered) if", "False print(\"STATS:\\n Games Played: \" + str(games_played) + \"\\nGames Won:", "k = j+1 while k < len(numbers_list): if numbers_list[i] +", "amount: total += random.randint(1, 6) i+=1 return total def choose_dice_amount():", "games_lost = 0 average_score = 0 total_score = 0 def", "while i < len(numbers_list): j = i+1 while j< len(numbers_list):", "+=1 else: print(\"You lose, your score is \" + str(score_game()))", "def welcome(): welcome_message = \"Welcome to shut the box\" print(welcome_message)", "box\" print(welcome_message) i = 0 result = \"\" while i", "i = 0 while i < len(numbers_list): score += numbers_list[i]", "print(\"STATS:\\n Games Played: \" + str(games_played) + \"\\nGames Won: \"", "0 def welcome(): welcome_message = \"Welcome to shut the box\"", "str(games_won) + \"\\nGames Lost: \" + str(games_lost) + \"\\nAverage Score:", "len(numbers_list): if numbers_list[i] > 6: less_than_7 = False i +=", "is \" + str(score_game())) print(\"Numbers remaining: \" + str(numbers_list)) games_played", "game_completed = False #Stats games_played = 0 games_won = 0", "\" + str(games_lost) + \"\\nAverage Score: \" + str(average_score) +", "return game_completed def win_game(): game_won = True return game_won def", "game_won def score_game(): score = 0 i = 0 while", "#Stats games_played = 0 games_won = 0 games_lost = 0", "len(numbers_list)-1: result += str(numbers_list[i]) + \" \" else: result +=", "games_lost += 1 total_score += score_game() average_score = total_score/games_played game_won", "score def all_less_than_7(): less_than_7 = True i = 0 while", "shut the box\" print(welcome_message) i = 0 result = \"\"", "0 while roll_total < 55: dice_amount = 2 if all_less_than_7():", "< len(numbers_list)-1: result += str(numbers_list[i]) + \" \" else: result", "0 result = \"\" while i < len(numbers_list): if i", "Entry, please try again\") continue if entered not in numbers_list", "True: try: continue_playing = (input(\"Do you wish to keep playing?", "value def end_game(): game_completed = True return game_completed def win_game():", "entered_numbers = list() i = 0 while i < len(entered_numbers):", "return total def choose_dice_amount(): amount = 0 while True: try:", "len(numbers_list): if numbers_list[i] + numbers_list[j] == rolled: return False k", "Won: \" + str(games_won) + \"\\nGames Lost: \" + str(games_lost)", "if i < len(numbers_list)-1: result += str(numbers_list[i]) + \" \"", "+=1 games_won +=1 else: print(\"You lose, your score is \"", "game_won = False game_completed = False #Stats games_played = 0", "ValueError: print(\"Invalid choice; please try again\") continue if continue_playing.lower ==", "list() while goal != 0: try: print(\"Available numbers: \" +", "len(numbers_list): score += numbers_list[i] i+=1 return score def all_less_than_7(): less_than_7", "str(score_game())) print(\"Numbers remaining: \" + str(numbers_list)) games_played += 1 games_lost", "value = True if rolled not in numbers_list: i =", "i+=1 return total def choose_dice_amount(): amount = 0 while True:", "\"\\nGames Lost: \" + str(games_lost) + \"\\nAverage Score: \" +", "True: try: amount = int(input(\"You choose to roll one or", "= 0 while roll_total < 55: dice_amount = 2 if", "k < len(numbers_list): if numbers_list[i] + numbers_list[j] + numbers_list[k] ==", "n: \")) except ValueError: print(\"Invalid choice; please try again\") continue", "if amount == 1 or amount == 2: return amount", "while i < len(numbers_list): if i < len(numbers_list)-1: result +=", "+= str(numbers_list[i]) + \" \" else: result += str(numbers_list[i]) i+=1", "result += str(numbers_list[i]) + \" \" else: result += str(numbers_list[i])", "this roll\") break choose_number_to_drop(dice_total) roll_total += dice_total if roll_total ==", "if continue_playing.lower == \"y\": return True else: return False keep_playing", "AGAIN\") continue if amount == 1 or amount == 2:", "in numbers_list: i = 0 while i < len(numbers_list): j", "ValueError: print(\"INVALID ENTRY PLEASE TRY AGAIN\") continue if amount ==", "welcome_message = \"Welcome to shut the box\" print(welcome_message) i =", "== 2: return amount else: print(\"INVALID ENTRY PLEASE TRY AGAIN!\")", "= 0 while i < len(numbers_list): if numbers_list[i] > 6:", "int(input(\"You choose to roll one or two dice. Please enter", "you wish to keep playing? y or n: \")) except", "amount def choose_number_to_drop(target_amount): entered = 0 goal = target_amount entered_numbers", "i+=1 print(result) def dice_roll(amount): total = 0 i = 0", "= list() i = 0 while i < len(entered_numbers): numbers_list.remove(entered_numbers[i])", "game_won = True return game_won def score_game(): score = 0", "dice_amount = choose_dice_amount() dice_total = dice_roll(dice_amount) print(\"Your roll is: \"", "= False i += 1 return less_than_7 def keep_playing_input(): while", "+= str(numbers_list[i]) i+=1 print(result) def dice_roll(amount): total = 0 i", "a number that is available: \")) except ValueError: print(\"Invalid Entry,", "all_less_than_7(): dice_amount = choose_dice_amount() dice_total = dice_roll(dice_amount) print(\"Your roll is:", "Lost: \" + str(games_lost) + \"\\nAverage Score: \" + str(average_score)", "else: print(\"You lose, your score is \" + str(score_game())) print(\"Numbers", "list() i = 0 while i < len(entered_numbers): numbers_list.remove(entered_numbers[i]) i", "True while keep_playing: numbers_list = [1,2,3,4,5,6,7,8,9,10] welcome() roll_total = 0", "to roll one or two dice. Please enter either '1'", "roll\") break choose_number_to_drop(dice_total) roll_total += dice_total if roll_total == 55:", "if numbers_list[i] + numbers_list[j] + numbers_list[k] == rolled: return False", "while j< len(numbers_list): if numbers_list[i] + numbers_list[j] == rolled: return", "else: return False keep_playing = True while keep_playing: numbers_list =", "in numbers_list or entered in entered_numbers: print(\"Invalid Entry, please try", "\" + str(target_amount)) entered = int(input(\"Please enter a number that", "result += str(numbers_list[i]) i+=1 print(result) def dice_roll(amount): total = 0", "print(result) def dice_roll(amount): total = 0 i = 0 while", "= 0 i = 0 while i < amount: total", "Entry, please try again\") continue else: goal -= entered entered_numbers.append(entered)", "numbers_list: i = 0 while i < len(numbers_list): j =", "= 2 if all_less_than_7(): dice_amount = choose_dice_amount() dice_total = dice_roll(dice_amount)", "+= 1 games_lost += 1 total_score += score_game() average_score =", "roll_total == 55: game_won = win_game() if game_won: print(\"Congrats you", "total_score = 0 def welcome(): welcome_message = \"Welcome to shut", "less_than_7 = False i += 1 return less_than_7 def keep_playing_input():", "+= 1 def check_lost_game(rolled): value = True if rolled not", "target_amount entered_numbers = list() while goal != 0: try: print(\"Available", "0 total_score = 0 def welcome(): welcome_message = \"Welcome to", "+= score_game() average_score = total_score/games_played game_won = False print(\"STATS:\\n Games", "= 0 games_won = 0 games_lost = 0 average_score =", "2: return amount else: print(\"INVALID ENTRY PLEASE TRY AGAIN!\") continue", "str(numbers_list) + \" to get to \" + str(target_amount)) entered", "is: \" + str(dice_total)) if check_lost_game(dice_total): print(\"It is impossible to", "choose_dice_amount(): amount = 0 while True: try: amount = int(input(\"You", "amount == 1 or amount == 2: return amount else:", "< len(numbers_list): if i < len(numbers_list)-1: result += str(numbers_list[i]) +", "continue else: goal -= entered entered_numbers.append(entered) if goal < 0:", "True return game_completed def win_game(): game_won = True return game_won", "True if rolled not in numbers_list: i = 0 while", "return False keep_playing = True while keep_playing: numbers_list = [1,2,3,4,5,6,7,8,9,10]", "== rolled: return False l+=1 k+=1 j+=1 i +=1 else:", "dice. Please enter either '1' or '2': \")) except ValueError:", "the box\" print(welcome_message) i = 0 result = \"\" while", "return False l = k+1 while l < len(numbers_list): if", "choose to roll one or two dice. Please enter either", "game_won: print(\"Congrats you won!!!!\") games_played +=1 games_won +=1 else: print(\"You", "amount = 0 while True: try: amount = int(input(\"You choose", "k+=1 j+=1 i +=1 else: value = False return value", "if check_lost_game(dice_total): print(\"It is impossible to continue the game with", "games_played += 1 games_lost += 1 total_score += score_game() average_score", "i = 0 while i < len(entered_numbers): numbers_list.remove(entered_numbers[i]) i +=", "False return value def end_game(): game_completed = True return game_completed", "or entered in entered_numbers: print(\"Invalid Entry, please try again\") continue", "+ numbers_list[j] + numbers_list[k] + numbers_list[l] == rolled: return False", "total += random.randint(1, 6) i+=1 return total def choose_dice_amount(): amount", "rolled not in numbers_list: i = 0 while i <", "< len(numbers_list): if numbers_list[i] + numbers_list[j] + numbers_list[k] + numbers_list[l]", "\" + str(score_game())) print(\"Numbers remaining: \" + str(numbers_list)) games_played +=", "0 while i < amount: total += random.randint(1, 6) i+=1", "len(numbers_list): j = i+1 while j< len(numbers_list): if numbers_list[i] +", "try again\") continue else: goal -= entered entered_numbers.append(entered) if goal", "continue_playing = (input(\"Do you wish to keep playing? y or", "2 if all_less_than_7(): dice_amount = choose_dice_amount() dice_total = dice_roll(dice_amount) print(\"Your", "numbers_list[j] + numbers_list[k] + numbers_list[l] == rolled: return False l+=1", "\" to get to \" + str(target_amount)) entered = int(input(\"Please", "remaining: \" + str(numbers_list)) games_played += 1 games_lost += 1", "while i < len(numbers_list): if numbers_list[i] > 6: less_than_7 =", "choose_number_to_drop(target_amount): entered = 0 goal = target_amount entered_numbers = list()", "< amount: total += random.randint(1, 6) i+=1 return total def", "1 or amount == 2: return amount else: print(\"INVALID ENTRY", "while i < len(entered_numbers): numbers_list.remove(entered_numbers[i]) i += 1 def check_lost_game(rolled):", "PLEASE TRY AGAIN!\") continue return amount def choose_number_to_drop(target_amount): entered =", "0 average_score = 0 total_score = 0 def welcome(): welcome_message", "import random numbers_list = [1,2,3,4,5,6,7,8,9,10] game_won = False game_completed =", "in entered_numbers: print(\"Invalid Entry, please try again\") continue else: goal", "try: amount = int(input(\"You choose to roll one or two", "is impossible to continue the game with this roll\") break", "+= random.randint(1, 6) i+=1 return total def choose_dice_amount(): amount =", "i = 0 while i < amount: total += random.randint(1,", "+ numbers_list[l] == rolled: return False l+=1 k+=1 j+=1 i", "entered in entered_numbers: print(\"Invalid Entry, please try again\") continue else:", "int(input(\"Please enter a number that is available: \")) except ValueError:", "= 0 while i < len(numbers_list): j = i+1 while", "numbers_list[i] i+=1 return score def all_less_than_7(): less_than_7 = True i", "score += numbers_list[i] i+=1 return score def all_less_than_7(): less_than_7 =", "Please enter either '1' or '2': \")) except ValueError: print(\"INVALID", "or amount == 2: return amount else: print(\"INVALID ENTRY PLEASE", "return value def end_game(): game_completed = True return game_completed def", "your score is \" + str(score_game())) print(\"Numbers remaining: \" +", "= (input(\"Do you wish to keep playing? y or n:", "print(\"INVALID ENTRY PLEASE TRY AGAIN!\") continue return amount def choose_number_to_drop(target_amount):", "roll is: \" + str(dice_total)) if check_lost_game(dice_total): print(\"It is impossible", "< len(numbers_list): j = i+1 while j< len(numbers_list): if numbers_list[i]", "if numbers_list[i] + numbers_list[j] == rolled: return False k =", "return less_than_7 def keep_playing_input(): while True: try: continue_playing = (input(\"Do", "True i = 0 while i < len(numbers_list): if numbers_list[i]", "choose_dice_amount() dice_total = dice_roll(dice_amount) print(\"Your roll is: \" + str(dice_total))", "str(games_lost) + \"\\nAverage Score: \" + str(average_score) + \"\\nTotal Score:", "available: \")) except ValueError: print(\"Invalid Entry, please try again\") continue", "is available: \")) except ValueError: print(\"Invalid Entry, please try again\")", "+= numbers_list[i] i+=1 return score def all_less_than_7(): less_than_7 = True", "\"\" while i < len(numbers_list): if i < len(numbers_list)-1: result", "total def choose_dice_amount(): amount = 0 while True: try: amount", "\")) except ValueError: print(\"INVALID ENTRY PLEASE TRY AGAIN\") continue if", "\" + str(games_won) + \"\\nGames Lost: \" + str(games_lost) +", "!= 0: try: print(\"Available numbers: \" + str(numbers_list) + \"", "print(\"You lose, your score is \" + str(score_game())) print(\"Numbers remaining:", "+ numbers_list[j] == rolled: return False k = j+1 while", "return score def all_less_than_7(): less_than_7 = True i = 0", "< len(numbers_list): if numbers_list[i] > 6: less_than_7 = False i", "\"Welcome to shut the box\" print(welcome_message) i = 0 result", "try: continue_playing = (input(\"Do you wish to keep playing? y", "ValueError: print(\"Invalid Entry, please try again\") continue if entered not", "won!!!!\") games_played +=1 games_won +=1 else: print(\"You lose, your score", "= 0 while i < amount: total += random.randint(1, 6)", "l+=1 k+=1 j+=1 i +=1 else: value = False return", "while goal != 0: try: print(\"Available numbers: \" + str(numbers_list)", "+ \"\\nAverage Score: \" + str(average_score) + \"\\nTotal Score: \"", "keep_playing: numbers_list = [1,2,3,4,5,6,7,8,9,10] welcome() roll_total = 0 while roll_total", "PLEASE TRY AGAIN\") continue if amount == 1 or amount", "str(numbers_list[i]) + \" \" else: result += str(numbers_list[i]) i+=1 print(result)", "+ numbers_list[k] == rolled: return False l = k+1 while", "please try again\") continue if continue_playing.lower == \"y\": return True", "\")) except ValueError: print(\"Invalid choice; please try again\") continue if", "print(\"It is impossible to continue the game with this roll\")", "== 55: game_won = win_game() if game_won: print(\"Congrats you won!!!!\")", "welcome(): welcome_message = \"Welcome to shut the box\" print(welcome_message) i", "= False return value def end_game(): game_completed = True return", "result = \"\" while i < len(numbers_list): if i <", "= 0 goal = target_amount entered_numbers = list() while goal", "return True else: return False keep_playing = True while keep_playing:", "i+1 while j< len(numbers_list): if numbers_list[i] + numbers_list[j] == rolled:", "0 games_lost = 0 average_score = 0 total_score = 0", "i < len(numbers_list): score += numbers_list[i] i+=1 return score def", "to keep playing? y or n: \")) except ValueError: print(\"Invalid", "1 games_lost += 1 total_score += score_game() average_score = total_score/games_played", "== \"y\": return True else: return False keep_playing = True", "if all_less_than_7(): dice_amount = choose_dice_amount() dice_total = dice_roll(dice_amount) print(\"Your roll", "try again\") continue if entered not in numbers_list or entered", "i = 0 while i < len(numbers_list): j = i+1", "average_score = 0 total_score = 0 def welcome(): welcome_message =", "= False #Stats games_played = 0 games_won = 0 games_lost", "str(numbers_list[i]) i+=1 print(result) def dice_roll(amount): total = 0 i =", "continue_playing.lower == \"y\": return True else: return False keep_playing =", "to shut the box\" print(welcome_message) i = 0 result =", "amount else: print(\"INVALID ENTRY PLEASE TRY AGAIN!\") continue return amount", "if rolled not in numbers_list: i = 0 while i", "try again\") continue if continue_playing.lower == \"y\": return True else:", "game_won = win_game() if game_won: print(\"Congrats you won!!!!\") games_played +=1", "rolled: return False k = j+1 while k < len(numbers_list):" ]
[ "reason=reason_to_skip_msg) def test_selinux_enabled_permissive(monkeypatch): \"\"\" Test case SELinux is enabled in", "True, 'runtime_mode': 'permissive', 'static_mode': 'permissive'} assert SELinuxFacts(**expected_data) == get_selinux_status() @pytest.mark.skipif(no_selinux,", "expected_data = {'policy': 'targeted', 'mls_enabled': False, 'enabled': False, 'runtime_mode': 'permissive',", "due to library unavailability.', ImportWarning) reason_to_skip_msg = \"Selinux is not", "get_selinux_status() class MockNoConfigFileOSError(object): def __init__(self): raise OSError @pytest.mark.skipif(no_selinux, reason=reason_to_skip_msg) def", "mode \"\"\" monkeypatch.setattr(selinux, 'is_selinux_mls_enabled', lambda: 1) monkeypatch.setattr(selinux, 'security_getenforce', lambda: 1)", "is enabled in permissive mode \"\"\" monkeypatch.setattr(selinux, 'is_selinux_mls_enabled', lambda: 1)", "'enabled': True, 'runtime_mode': 'enforcing', 'static_mode': 'enforcing'} assert SELinuxFacts(**expected_data) == get_selinux_status()", "try: import selinux except ImportError: no_selinux = True warnings.warn( 'Tests", "'is_selinux_mls_enabled', lambda: 0) monkeypatch.setattr(selinux, 'security_getenforce', lambda: 0) monkeypatch.setattr(selinux, 'selinux_getenforcemode', MockNoConfigFileOSError)", "False, 'enabled': False, 'runtime_mode': 'permissive', 'static_mode': 'disabled'} assert SELinuxFacts(**expected_data) ==", "\"\"\" Test case SELinux is enabled in permissive mode \"\"\"", "MockNoConfigFileOSError) monkeypatch.setattr(selinux, 'is_selinux_enabled', lambda: 0) monkeypatch.setattr(selinux, 'selinux_getpolicytype', lambda: [0, 'targeted'])", "1) monkeypatch.setattr(selinux, 'selinux_getenforcemode', lambda: [0, 1]) monkeypatch.setattr(selinux, 'is_selinux_enabled', lambda: 1)", "0) monkeypatch.setattr(selinux, 'selinux_getenforcemode', MockNoConfigFileOSError) monkeypatch.setattr(selinux, 'is_selinux_enabled', lambda: 0) monkeypatch.setattr(selinux, 'selinux_getpolicytype',", "Test case SELinux is disabled \"\"\" monkeypatch.setattr(selinux, 'is_selinux_mls_enabled', lambda: 0)", "no_selinux = False try: import selinux except ImportError: no_selinux =", "create valid tests... @pytest.mark.skipif(no_selinux, reason=reason_to_skip_msg) def test_selinux_enabled_enforcing(monkeypatch): \"\"\" Test case", "True, 'runtime_mode': 'enforcing', 'static_mode': 'enforcing'} assert SELinuxFacts(**expected_data) == get_selinux_status() @pytest.mark.skipif(no_selinux,", "'is_selinux_enabled', lambda: 0) monkeypatch.setattr(selinux, 'selinux_getpolicytype', lambda: [0, 'targeted']) expected_data =", "monkeypatch.setattr(selinux, 'is_selinux_mls_enabled', lambda: 1) monkeypatch.setattr(selinux, 'security_getenforce', lambda: 1) monkeypatch.setattr(selinux, 'selinux_getenforcemode',", "'runtime_mode': 'permissive', 'static_mode': 'permissive'} assert SELinuxFacts(**expected_data) == get_selinux_status() class MockNoConfigFileOSError(object):", "leapp.models import SELinuxFacts no_selinux = False try: import selinux except", "False, 'enabled': False, 'runtime_mode': 'permissive', 'static_mode': 'permissive'} assert SELinuxFacts(**expected_data) ==", "# FIXME: create valid tests... @pytest.mark.skipif(no_selinux, reason=reason_to_skip_msg) def test_selinux_enabled_enforcing(monkeypatch): \"\"\"", "'selinux_getenforcemode', lambda: [0, 0]) monkeypatch.setattr(selinux, 'is_selinux_enabled', lambda: 0) monkeypatch.setattr(selinux, 'selinux_getpolicytype',", "'selinux_getpolicytype', lambda: [0, 'targeted']) expected_data = {'policy': 'targeted', 'mls_enabled': False,", "is enabled in enforcing mode \"\"\" monkeypatch.setattr(selinux, 'is_selinux_mls_enabled', lambda: 1)", "permissive mode \"\"\" monkeypatch.setattr(selinux, 'is_selinux_mls_enabled', lambda: 1) monkeypatch.setattr(selinux, 'security_getenforce', lambda:", "test_selinux_enabled_permissive(monkeypatch): \"\"\" Test case SELinux is enabled in permissive mode", "lambda: 1) monkeypatch.setattr(selinux, 'security_getenforce', lambda: 1) monkeypatch.setattr(selinux, 'selinux_getenforcemode', lambda: [0,", "[0, 'targeted']) expected_data = {'policy': 'targeted', 'mls_enabled': True, 'enabled': True,", "case SELinux is enabled in permissive mode \"\"\" monkeypatch.setattr(selinux, 'is_selinux_mls_enabled',", "lambda: 0) monkeypatch.setattr(selinux, 'security_getenforce', lambda: 0) monkeypatch.setattr(selinux, 'selinux_getenforcemode', lambda: [0,", "'is_selinux_mls_enabled', lambda: 0) monkeypatch.setattr(selinux, 'security_getenforce', lambda: 0) monkeypatch.setattr(selinux, 'selinux_getenforcemode', lambda:", "{'policy': 'targeted', 'mls_enabled': True, 'enabled': True, 'runtime_mode': 'enforcing', 'static_mode': 'enforcing'}", "'static_mode': 'enforcing'} assert SELinuxFacts(**expected_data) == get_selinux_status() @pytest.mark.skipif(no_selinux, reason=reason_to_skip_msg) def test_selinux_enabled_permissive(monkeypatch):", "enabled in permissive mode \"\"\" monkeypatch.setattr(selinux, 'is_selinux_mls_enabled', lambda: 1) monkeypatch.setattr(selinux,", "warnings.warn( 'Tests which uses `selinux` will be skipped' ' due", "lambda: 1) monkeypatch.setattr(selinux, 'selinux_getpolicytype', lambda: [0, 'targeted']) expected_data = {'policy':", "class MockNoConfigFileOSError(object): def __init__(self): raise OSError @pytest.mark.skipif(no_selinux, reason=reason_to_skip_msg) def test_selinux_disabled_no_config_file(monkeypatch):", "monkeypatch.setattr(selinux, 'is_selinux_enabled', lambda: 1) monkeypatch.setattr(selinux, 'selinux_getpolicytype', lambda: [0, 'targeted']) expected_data", "reason=reason_to_skip_msg) def test_selinux_disabled_no_config_file(monkeypatch): \"\"\" Test case SELinux is disabled \"\"\"", "import warnings import pytest from leapp.libraries.actor.systemfacts import get_selinux_status from leapp.models", "'runtime_mode': 'enforcing', 'static_mode': 'enforcing'} assert SELinuxFacts(**expected_data) == get_selinux_status() @pytest.mark.skipif(no_selinux, reason=reason_to_skip_msg)", "' due to library unavailability.', ImportWarning) reason_to_skip_msg = \"Selinux is", "monkeypatch.setattr(selinux, 'security_getenforce', lambda: 0) monkeypatch.setattr(selinux, 'selinux_getenforcemode', lambda: [0, 0]) monkeypatch.setattr(selinux,", "SELinuxFacts(**expected_data) == get_selinux_status() @pytest.mark.skipif(no_selinux, reason=reason_to_skip_msg) def test_selinux_enabled_permissive(monkeypatch): \"\"\" Test case", "\"\"\" Test case SELinux is disabled \"\"\" monkeypatch.setattr(selinux, 'is_selinux_mls_enabled', lambda:", "which uses `selinux` will be skipped' ' due to library", "'security_getenforce', lambda: 0) monkeypatch.setattr(selinux, 'selinux_getenforcemode', lambda: [0, 0]) monkeypatch.setattr(selinux, 'is_selinux_enabled',", "`selinux` will be skipped' ' due to library unavailability.', ImportWarning)", "'security_getenforce', lambda: 1) monkeypatch.setattr(selinux, 'selinux_getenforcemode', lambda: [0, 1]) monkeypatch.setattr(selinux, 'is_selinux_enabled',", "reason=reason_to_skip_msg) def test_selinux_disabled(monkeypatch): \"\"\" Test case SELinux is disabled \"\"\"", "ImportError: no_selinux = True warnings.warn( 'Tests which uses `selinux` will", "'mls_enabled': True, 'enabled': True, 'runtime_mode': 'enforcing', 'static_mode': 'enforcing'} assert SELinuxFacts(**expected_data)", "lambda: 0) monkeypatch.setattr(selinux, 'security_getenforce', lambda: 0) monkeypatch.setattr(selinux, 'selinux_getenforcemode', MockNoConfigFileOSError) monkeypatch.setattr(selinux,", "0) monkeypatch.setattr(selinux, 'selinux_getenforcemode', lambda: [0, 0]) monkeypatch.setattr(selinux, 'is_selinux_enabled', lambda: 0)", "tests... @pytest.mark.skipif(no_selinux, reason=reason_to_skip_msg) def test_selinux_enabled_enforcing(monkeypatch): \"\"\" Test case SELinux is", "SELinux is enabled in enforcing mode \"\"\" monkeypatch.setattr(selinux, 'is_selinux_mls_enabled', lambda:", "lambda: 1) monkeypatch.setattr(selinux, 'selinux_getenforcemode', lambda: [0, 1]) monkeypatch.setattr(selinux, 'is_selinux_enabled', lambda:", "1) monkeypatch.setattr(selinux, 'security_getenforce', lambda: 0) monkeypatch.setattr(selinux, 'selinux_getenforcemode', lambda: [0, 0])", "test_selinux_disabled(monkeypatch): \"\"\" Test case SELinux is disabled \"\"\" monkeypatch.setattr(selinux, 'is_selinux_mls_enabled',", "'Tests which uses `selinux` will be skipped' ' due to", "expected_data = {'policy': 'targeted', 'mls_enabled': True, 'enabled': True, 'runtime_mode': 'enforcing',", "0) monkeypatch.setattr(selinux, 'selinux_getpolicytype', lambda: [0, 'targeted']) expected_data = {'policy': 'targeted',", "= True warnings.warn( 'Tests which uses `selinux` will be skipped'", "in permissive mode \"\"\" monkeypatch.setattr(selinux, 'is_selinux_mls_enabled', lambda: 1) monkeypatch.setattr(selinux, 'security_getenforce',", "'is_selinux_mls_enabled', lambda: 1) monkeypatch.setattr(selinux, 'security_getenforce', lambda: 0) monkeypatch.setattr(selinux, 'selinux_getenforcemode', lambda:", "OSError @pytest.mark.skipif(no_selinux, reason=reason_to_skip_msg) def test_selinux_disabled_no_config_file(monkeypatch): \"\"\" Test case SELinux is", "'targeted', 'mls_enabled': False, 'enabled': False, 'runtime_mode': 'permissive', 'static_mode': 'disabled'} assert", "not available\" # FIXME: create valid tests... @pytest.mark.skipif(no_selinux, reason=reason_to_skip_msg) def", "= {'policy': 'targeted', 'mls_enabled': True, 'enabled': True, 'runtime_mode': 'enforcing', 'static_mode':", "import SELinuxFacts no_selinux = False try: import selinux except ImportError:", "'targeted']) expected_data = {'policy': 'targeted', 'mls_enabled': False, 'enabled': False, 'runtime_mode':", "0]) monkeypatch.setattr(selinux, 'is_selinux_enabled', lambda: 0) monkeypatch.setattr(selinux, 'selinux_getpolicytype', lambda: [0, 'targeted'])", "'permissive', 'static_mode': 'permissive'} assert SELinuxFacts(**expected_data) == get_selinux_status() @pytest.mark.skipif(no_selinux, reason=reason_to_skip_msg) def", "monkeypatch.setattr(selinux, 'security_getenforce', lambda: 1) monkeypatch.setattr(selinux, 'selinux_getenforcemode', lambda: [0, 1]) monkeypatch.setattr(selinux,", "True, 'enabled': True, 'runtime_mode': 'permissive', 'static_mode': 'permissive'} assert SELinuxFacts(**expected_data) ==", "FIXME: create valid tests... @pytest.mark.skipif(no_selinux, reason=reason_to_skip_msg) def test_selinux_enabled_enforcing(monkeypatch): \"\"\" Test", "disabled \"\"\" monkeypatch.setattr(selinux, 'is_selinux_mls_enabled', lambda: 0) monkeypatch.setattr(selinux, 'security_getenforce', lambda: 0)", "0) monkeypatch.setattr(selinux, 'selinux_getenforcemode', lambda: [0, 0]) monkeypatch.setattr(selinux, 'is_selinux_enabled', lambda: 1)", "case SELinux is enabled in enforcing mode \"\"\" monkeypatch.setattr(selinux, 'is_selinux_mls_enabled',", "import pytest from leapp.libraries.actor.systemfacts import get_selinux_status from leapp.models import SELinuxFacts", "warnings import pytest from leapp.libraries.actor.systemfacts import get_selinux_status from leapp.models import", "'static_mode': 'permissive'} assert SELinuxFacts(**expected_data) == get_selinux_status() class MockNoConfigFileOSError(object): def __init__(self):", "in enforcing mode \"\"\" monkeypatch.setattr(selinux, 'is_selinux_mls_enabled', lambda: 1) monkeypatch.setattr(selinux, 'security_getenforce',", "\"\"\" monkeypatch.setattr(selinux, 'is_selinux_mls_enabled', lambda: 1) monkeypatch.setattr(selinux, 'security_getenforce', lambda: 1) monkeypatch.setattr(selinux,", "lambda: 1) monkeypatch.setattr(selinux, 'security_getenforce', lambda: 0) monkeypatch.setattr(selinux, 'selinux_getenforcemode', lambda: [0,", "SELinuxFacts(**expected_data) == get_selinux_status() @pytest.mark.skipif(no_selinux, reason=reason_to_skip_msg) def test_selinux_disabled(monkeypatch): \"\"\" Test case", "\"\"\" Test case SELinux is enabled in enforcing mode \"\"\"", "'selinux_getenforcemode', lambda: [0, 0]) monkeypatch.setattr(selinux, 'is_selinux_enabled', lambda: 1) monkeypatch.setattr(selinux, 'selinux_getpolicytype',", "'security_getenforce', lambda: 0) monkeypatch.setattr(selinux, 'selinux_getenforcemode', MockNoConfigFileOSError) monkeypatch.setattr(selinux, 'is_selinux_enabled', lambda: 0)", "uses `selinux` will be skipped' ' due to library unavailability.',", "'targeted']) expected_data = {'policy': 'targeted', 'mls_enabled': True, 'enabled': True, 'runtime_mode':", "False try: import selinux except ImportError: no_selinux = True warnings.warn(", "= \"Selinux is not available\" # FIXME: create valid tests...", "def test_selinux_enabled_permissive(monkeypatch): \"\"\" Test case SELinux is enabled in permissive", "'enabled': True, 'runtime_mode': 'permissive', 'static_mode': 'permissive'} assert SELinuxFacts(**expected_data) == get_selinux_status()", "'mls_enabled': False, 'enabled': False, 'runtime_mode': 'permissive', 'static_mode': 'permissive'} assert SELinuxFacts(**expected_data)", "'static_mode': 'permissive'} assert SELinuxFacts(**expected_data) == get_selinux_status() @pytest.mark.skipif(no_selinux, reason=reason_to_skip_msg) def test_selinux_disabled(monkeypatch):", "monkeypatch.setattr(selinux, 'selinux_getenforcemode', MockNoConfigFileOSError) monkeypatch.setattr(selinux, 'is_selinux_enabled', lambda: 0) monkeypatch.setattr(selinux, 'selinux_getpolicytype', lambda:", "True warnings.warn( 'Tests which uses `selinux` will be skipped' '", "'selinux_getpolicytype', lambda: [0, 'targeted']) expected_data = {'policy': 'targeted', 'mls_enabled': True,", "lambda: [0, 'targeted']) expected_data = {'policy': 'targeted', 'mls_enabled': False, 'enabled':", "selinux except ImportError: no_selinux = True warnings.warn( 'Tests which uses", "SELinux is enabled in permissive mode \"\"\" monkeypatch.setattr(selinux, 'is_selinux_mls_enabled', lambda:", "is not available\" # FIXME: create valid tests... @pytest.mark.skipif(no_selinux, reason=reason_to_skip_msg)", "\"\"\" monkeypatch.setattr(selinux, 'is_selinux_mls_enabled', lambda: 0) monkeypatch.setattr(selinux, 'security_getenforce', lambda: 0) monkeypatch.setattr(selinux,", "leapp.libraries.actor.systemfacts import get_selinux_status from leapp.models import SELinuxFacts no_selinux = False", "Test case SELinux is enabled in permissive mode \"\"\" monkeypatch.setattr(selinux,", "@pytest.mark.skipif(no_selinux, reason=reason_to_skip_msg) def test_selinux_disabled_no_config_file(monkeypatch): \"\"\" Test case SELinux is disabled", "1]) monkeypatch.setattr(selinux, 'is_selinux_enabled', lambda: 1) monkeypatch.setattr(selinux, 'selinux_getpolicytype', lambda: [0, 'targeted'])", "'selinux_getenforcemode', MockNoConfigFileOSError) monkeypatch.setattr(selinux, 'is_selinux_enabled', lambda: 0) monkeypatch.setattr(selinux, 'selinux_getpolicytype', lambda: [0,", "'mls_enabled': False, 'enabled': False, 'runtime_mode': 'permissive', 'static_mode': 'disabled'} assert SELinuxFacts(**expected_data)", "enabled in enforcing mode \"\"\" monkeypatch.setattr(selinux, 'is_selinux_mls_enabled', lambda: 1) monkeypatch.setattr(selinux,", "to library unavailability.', ImportWarning) reason_to_skip_msg = \"Selinux is not available\"", "[0, 'targeted']) expected_data = {'policy': 'targeted', 'mls_enabled': False, 'enabled': False,", "except ImportError: no_selinux = True warnings.warn( 'Tests which uses `selinux`", "test_selinux_enabled_enforcing(monkeypatch): \"\"\" Test case SELinux is enabled in enforcing mode", "Test case SELinux is enabled in enforcing mode \"\"\" monkeypatch.setattr(selinux,", "monkeypatch.setattr(selinux, 'is_selinux_enabled', lambda: 0) monkeypatch.setattr(selinux, 'selinux_getpolicytype', lambda: [0, 'targeted']) expected_data", "True, 'enabled': True, 'runtime_mode': 'enforcing', 'static_mode': 'enforcing'} assert SELinuxFacts(**expected_data) ==", "1) monkeypatch.setattr(selinux, 'security_getenforce', lambda: 1) monkeypatch.setattr(selinux, 'selinux_getenforcemode', lambda: [0, 1])", "'enabled': False, 'runtime_mode': 'permissive', 'static_mode': 'permissive'} assert SELinuxFacts(**expected_data) == get_selinux_status()", "'permissive'} assert SELinuxFacts(**expected_data) == get_selinux_status() class MockNoConfigFileOSError(object): def __init__(self): raise", "'targeted', 'mls_enabled': True, 'enabled': True, 'runtime_mode': 'enforcing', 'static_mode': 'enforcing'} assert", "enforcing mode \"\"\" monkeypatch.setattr(selinux, 'is_selinux_mls_enabled', lambda: 1) monkeypatch.setattr(selinux, 'security_getenforce', lambda:", "import get_selinux_status from leapp.models import SELinuxFacts no_selinux = False try:", "valid tests... @pytest.mark.skipif(no_selinux, reason=reason_to_skip_msg) def test_selinux_enabled_enforcing(monkeypatch): \"\"\" Test case SELinux", "monkeypatch.setattr(selinux, 'selinux_getenforcemode', lambda: [0, 0]) monkeypatch.setattr(selinux, 'is_selinux_enabled', lambda: 0) monkeypatch.setattr(selinux,", "def test_selinux_disabled(monkeypatch): \"\"\" Test case SELinux is disabled \"\"\" monkeypatch.setattr(selinux,", "case SELinux is disabled \"\"\" monkeypatch.setattr(selinux, 'is_selinux_mls_enabled', lambda: 0) monkeypatch.setattr(selinux,", "lambda: [0, 'targeted']) expected_data = {'policy': 'targeted', 'mls_enabled': True, 'enabled':", "lambda: [0, 0]) monkeypatch.setattr(selinux, 'is_selinux_enabled', lambda: 1) monkeypatch.setattr(selinux, 'selinux_getpolicytype', lambda:", "1) monkeypatch.setattr(selinux, 'selinux_getpolicytype', lambda: [0, 'targeted']) expected_data = {'policy': 'targeted',", "SELinuxFacts no_selinux = False try: import selinux except ImportError: no_selinux", "library unavailability.', ImportWarning) reason_to_skip_msg = \"Selinux is not available\" #", "[0, 1]) monkeypatch.setattr(selinux, 'is_selinux_enabled', lambda: 1) monkeypatch.setattr(selinux, 'selinux_getpolicytype', lambda: [0,", "'permissive'} assert SELinuxFacts(**expected_data) == get_selinux_status() @pytest.mark.skipif(no_selinux, reason=reason_to_skip_msg) def test_selinux_disabled(monkeypatch): \"\"\"", "monkeypatch.setattr(selinux, 'selinux_getenforcemode', lambda: [0, 1]) monkeypatch.setattr(selinux, 'is_selinux_enabled', lambda: 1) monkeypatch.setattr(selinux,", "lambda: 0) monkeypatch.setattr(selinux, 'selinux_getpolicytype', lambda: [0, 'targeted']) expected_data = {'policy':", "will be skipped' ' due to library unavailability.', ImportWarning) reason_to_skip_msg", "== get_selinux_status() class MockNoConfigFileOSError(object): def __init__(self): raise OSError @pytest.mark.skipif(no_selinux, reason=reason_to_skip_msg)", "skipped' ' due to library unavailability.', ImportWarning) reason_to_skip_msg = \"Selinux", "[0, 0]) monkeypatch.setattr(selinux, 'is_selinux_enabled', lambda: 0) monkeypatch.setattr(selinux, 'selinux_getpolicytype', lambda: [0,", "'targeted', 'mls_enabled': False, 'enabled': False, 'runtime_mode': 'permissive', 'static_mode': 'permissive'} assert", "monkeypatch.setattr(selinux, 'selinux_getpolicytype', lambda: [0, 'targeted']) expected_data = {'policy': 'targeted', 'mls_enabled':", "= False try: import selinux except ImportError: no_selinux = True", "import selinux except ImportError: no_selinux = True warnings.warn( 'Tests which", "'enabled': False, 'runtime_mode': 'permissive', 'static_mode': 'disabled'} assert SELinuxFacts(**expected_data) == get_selinux_status()", "'is_selinux_mls_enabled', lambda: 1) monkeypatch.setattr(selinux, 'security_getenforce', lambda: 1) monkeypatch.setattr(selinux, 'selinux_getenforcemode', lambda:", "@pytest.mark.skipif(no_selinux, reason=reason_to_skip_msg) def test_selinux_enabled_permissive(monkeypatch): \"\"\" Test case SELinux is enabled", "SELinux is disabled \"\"\" monkeypatch.setattr(selinux, 'is_selinux_mls_enabled', lambda: 0) monkeypatch.setattr(selinux, 'security_getenforce',", "== get_selinux_status() @pytest.mark.skipif(no_selinux, reason=reason_to_skip_msg) def test_selinux_enabled_permissive(monkeypatch): \"\"\" Test case SELinux", "def test_selinux_disabled_no_config_file(monkeypatch): \"\"\" Test case SELinux is disabled \"\"\" monkeypatch.setattr(selinux,", "0) monkeypatch.setattr(selinux, 'security_getenforce', lambda: 0) monkeypatch.setattr(selinux, 'selinux_getenforcemode', MockNoConfigFileOSError) monkeypatch.setattr(selinux, 'is_selinux_enabled',", "monkeypatch.setattr(selinux, 'selinux_getenforcemode', lambda: [0, 0]) monkeypatch.setattr(selinux, 'is_selinux_enabled', lambda: 1) monkeypatch.setattr(selinux,", "from leapp.libraries.actor.systemfacts import get_selinux_status from leapp.models import SELinuxFacts no_selinux =", "'is_selinux_enabled', lambda: 1) monkeypatch.setattr(selinux, 'selinux_getpolicytype', lambda: [0, 'targeted']) expected_data =", "= {'policy': 'targeted', 'mls_enabled': False, 'enabled': False, 'runtime_mode': 'permissive', 'static_mode':", "SELinuxFacts(**expected_data) == get_selinux_status() class MockNoConfigFileOSError(object): def __init__(self): raise OSError @pytest.mark.skipif(no_selinux,", "assert SELinuxFacts(**expected_data) == get_selinux_status() @pytest.mark.skipif(no_selinux, reason=reason_to_skip_msg) def test_selinux_disabled(monkeypatch): \"\"\" Test", "assert SELinuxFacts(**expected_data) == get_selinux_status() class MockNoConfigFileOSError(object): def __init__(self): raise OSError", "lambda: [0, 1]) monkeypatch.setattr(selinux, 'is_selinux_enabled', lambda: 1) monkeypatch.setattr(selinux, 'selinux_getpolicytype', lambda:", "from leapp.models import SELinuxFacts no_selinux = False try: import selinux", "raise OSError @pytest.mark.skipif(no_selinux, reason=reason_to_skip_msg) def test_selinux_disabled_no_config_file(monkeypatch): \"\"\" Test case SELinux", "False, 'runtime_mode': 'permissive', 'static_mode': 'permissive'} assert SELinuxFacts(**expected_data) == get_selinux_status() class", "def test_selinux_enabled_enforcing(monkeypatch): \"\"\" Test case SELinux is enabled in enforcing", "0) monkeypatch.setattr(selinux, 'security_getenforce', lambda: 0) monkeypatch.setattr(selinux, 'selinux_getenforcemode', lambda: [0, 0])", "= {'policy': 'targeted', 'mls_enabled': True, 'enabled': True, 'runtime_mode': 'permissive', 'static_mode':", "reason_to_skip_msg = \"Selinux is not available\" # FIXME: create valid", "{'policy': 'targeted', 'mls_enabled': False, 'enabled': False, 'runtime_mode': 'permissive', 'static_mode': 'disabled'}", "get_selinux_status() @pytest.mark.skipif(no_selinux, reason=reason_to_skip_msg) def test_selinux_disabled(monkeypatch): \"\"\" Test case SELinux is", "monkeypatch.setattr(selinux, 'security_getenforce', lambda: 0) monkeypatch.setattr(selinux, 'selinux_getenforcemode', MockNoConfigFileOSError) monkeypatch.setattr(selinux, 'is_selinux_enabled', lambda:", "'enforcing'} assert SELinuxFacts(**expected_data) == get_selinux_status() @pytest.mark.skipif(no_selinux, reason=reason_to_skip_msg) def test_selinux_enabled_permissive(monkeypatch): \"\"\"", "{'policy': 'targeted', 'mls_enabled': True, 'enabled': True, 'runtime_mode': 'permissive', 'static_mode': 'permissive'}", "get_selinux_status from leapp.models import SELinuxFacts no_selinux = False try: import", "'selinux_getenforcemode', lambda: [0, 1]) monkeypatch.setattr(selinux, 'is_selinux_enabled', lambda: 1) monkeypatch.setattr(selinux, 'selinux_getpolicytype',", "is disabled \"\"\" monkeypatch.setattr(selinux, 'is_selinux_mls_enabled', lambda: 0) monkeypatch.setattr(selinux, 'security_getenforce', lambda:", "'permissive', 'static_mode': 'permissive'} assert SELinuxFacts(**expected_data) == get_selinux_status() class MockNoConfigFileOSError(object): def", "lambda: 0) monkeypatch.setattr(selinux, 'selinux_getenforcemode', MockNoConfigFileOSError) monkeypatch.setattr(selinux, 'is_selinux_enabled', lambda: 0) monkeypatch.setattr(selinux,", "be skipped' ' due to library unavailability.', ImportWarning) reason_to_skip_msg =", "== get_selinux_status() @pytest.mark.skipif(no_selinux, reason=reason_to_skip_msg) def test_selinux_disabled(monkeypatch): \"\"\" Test case SELinux", "@pytest.mark.skipif(no_selinux, reason=reason_to_skip_msg) def test_selinux_disabled(monkeypatch): \"\"\" Test case SELinux is disabled", "available\" # FIXME: create valid tests... @pytest.mark.skipif(no_selinux, reason=reason_to_skip_msg) def test_selinux_enabled_enforcing(monkeypatch):", "get_selinux_status() @pytest.mark.skipif(no_selinux, reason=reason_to_skip_msg) def test_selinux_enabled_permissive(monkeypatch): \"\"\" Test case SELinux is", "[0, 0]) monkeypatch.setattr(selinux, 'is_selinux_enabled', lambda: 1) monkeypatch.setattr(selinux, 'selinux_getpolicytype', lambda: [0,", "'enforcing', 'static_mode': 'enforcing'} assert SELinuxFacts(**expected_data) == get_selinux_status() @pytest.mark.skipif(no_selinux, reason=reason_to_skip_msg) def", "monkeypatch.setattr(selinux, 'is_selinux_mls_enabled', lambda: 0) monkeypatch.setattr(selinux, 'security_getenforce', lambda: 0) monkeypatch.setattr(selinux, 'selinux_getenforcemode',", "@pytest.mark.skipif(no_selinux, reason=reason_to_skip_msg) def test_selinux_enabled_enforcing(monkeypatch): \"\"\" Test case SELinux is enabled", "monkeypatch.setattr(selinux, 'is_selinux_mls_enabled', lambda: 1) monkeypatch.setattr(selinux, 'security_getenforce', lambda: 0) monkeypatch.setattr(selinux, 'selinux_getenforcemode',", "'runtime_mode': 'permissive', 'static_mode': 'permissive'} assert SELinuxFacts(**expected_data) == get_selinux_status() @pytest.mark.skipif(no_selinux, reason=reason_to_skip_msg)", "def __init__(self): raise OSError @pytest.mark.skipif(no_selinux, reason=reason_to_skip_msg) def test_selinux_disabled_no_config_file(monkeypatch): \"\"\" Test", "0]) monkeypatch.setattr(selinux, 'is_selinux_enabled', lambda: 1) monkeypatch.setattr(selinux, 'selinux_getpolicytype', lambda: [0, 'targeted'])", "'targeted', 'mls_enabled': True, 'enabled': True, 'runtime_mode': 'permissive', 'static_mode': 'permissive'} assert", "lambda: 0) monkeypatch.setattr(selinux, 'selinux_getenforcemode', lambda: [0, 0]) monkeypatch.setattr(selinux, 'is_selinux_enabled', lambda:", "lambda: [0, 0]) monkeypatch.setattr(selinux, 'is_selinux_enabled', lambda: 0) monkeypatch.setattr(selinux, 'selinux_getpolicytype', lambda:", "test_selinux_disabled_no_config_file(monkeypatch): \"\"\" Test case SELinux is disabled \"\"\" monkeypatch.setattr(selinux, 'is_selinux_mls_enabled',", "mode \"\"\" monkeypatch.setattr(selinux, 'is_selinux_mls_enabled', lambda: 1) monkeypatch.setattr(selinux, 'security_getenforce', lambda: 0)", "pytest from leapp.libraries.actor.systemfacts import get_selinux_status from leapp.models import SELinuxFacts no_selinux", "\"\"\" monkeypatch.setattr(selinux, 'is_selinux_mls_enabled', lambda: 1) monkeypatch.setattr(selinux, 'security_getenforce', lambda: 0) monkeypatch.setattr(selinux,", "reason=reason_to_skip_msg) def test_selinux_enabled_enforcing(monkeypatch): \"\"\" Test case SELinux is enabled in", "expected_data = {'policy': 'targeted', 'mls_enabled': True, 'enabled': True, 'runtime_mode': 'permissive',", "MockNoConfigFileOSError(object): def __init__(self): raise OSError @pytest.mark.skipif(no_selinux, reason=reason_to_skip_msg) def test_selinux_disabled_no_config_file(monkeypatch): \"\"\"", "ImportWarning) reason_to_skip_msg = \"Selinux is not available\" # FIXME: create", "{'policy': 'targeted', 'mls_enabled': False, 'enabled': False, 'runtime_mode': 'permissive', 'static_mode': 'permissive'}", "__init__(self): raise OSError @pytest.mark.skipif(no_selinux, reason=reason_to_skip_msg) def test_selinux_disabled_no_config_file(monkeypatch): \"\"\" Test case", "unavailability.', ImportWarning) reason_to_skip_msg = \"Selinux is not available\" # FIXME:", "'mls_enabled': True, 'enabled': True, 'runtime_mode': 'permissive', 'static_mode': 'permissive'} assert SELinuxFacts(**expected_data)", "\"Selinux is not available\" # FIXME: create valid tests... @pytest.mark.skipif(no_selinux,", "assert SELinuxFacts(**expected_data) == get_selinux_status() @pytest.mark.skipif(no_selinux, reason=reason_to_skip_msg) def test_selinux_enabled_permissive(monkeypatch): \"\"\" Test", "no_selinux = True warnings.warn( 'Tests which uses `selinux` will be" ]
[ "integer is a palindrome or not. Note: An integer is", "price of each day): [224, 236, 247, 258, 259, 225]", "M matrix of numbers line by line in forward >", "given array. Sample Output: 5 4 4. Write a Python", "array of integers, sorted in ascending order. If the target", "one transaction i.e., buy one and sell one share of", "225] Output: 35 Explanation: 236 - 224 = 12 247", "5. Write a Python program to remove all instances of", "= 1 225 - 258 = -33 225 - 259", "224 = 23 258 - 224 = 34 259 -", "258 = 1 225 - 258 = -33 225 -", "such that each element appear only once and return the", "Python program to check whether a given integer is a", "print a given N by M matrix of numbers line", "15 dollars. Sample Output: 10 7 0 5. Write a", "maximum profit in one transaction i.e., buy one and sell", "value is 15 dollars. Sample Output: 10 7 0 5.", "not palindromic. Sample Output: False True False 3. Write a", "Output: 1 2 3 4 8 7 6 5 0", "0 3 2 9. Write a Python program to compute", "value = 4 Output: [0, 0] Sample Output: [0, 5]", "Sample Output: [0, 5] [0, 0] 7. The price of", "a Python program to check whether a given integer is", "profit in one transaction i.e., buy one and sell one", "a Python program to print a given N by M", "to remove all instances of a given value from a", "given N by M matrix of numbers line by line", "line in forward > backwards > forward >... order. Input", "a stock before you buy one. Input (Stock price of", "True False 3. Write a Python program to remove the", "of numbers line by line in forward > backwards >", "- 258 = 1 225 - 258 = -33 225", "8], [0, 6, 2, 8], [2, 3, 0, 2]] Output:", "14] target value = 4 Output: [0, 0] Sample Output:", "10. Write a Python program to find the first missing", "1 225 - 258 = -33 225 - 259 =", "- 224 = 1 247 - 236 = 11 258", "247 = -22 259 - 258 = 1 225 -", "an array. Write a Python program to find the maximum", "\"\"\" 1. Write a Python program to reverse only the", "Explanation: 236 - 224 = 12 247 - 224 =", "program to remove the duplicate elements of a given array", "Write a Python program to compute the largest product of", "4000 8 120 10. Write a Python program to find", "[1, 3, 6, 9, 13, 14] target value = 4", "chronological order. For example, given [8, 10, 7, 5, 7,", "in ascending order. If the target is not found in", "numbers are not palindromic. Sample Output: False True False 3.", "Input: [5, 7, 7, 8, 8, 8] target value =", "ascending order. If the target is not found in the", "order. If the target is not found in the array,", "258 - 224 = 34 259 - 224 = 35", "5 0 6 2 8 2 0 3 2 9.", "program to find the starting and ending position of a", "Output: [0, 5] [0, 0] 7. The price of a", "11 258 - 236 = 22 259 - 236 =", "stock before you buy one. Input (Stock price of each", "profit from selling and buying values of stock. An array", "6 0 5 0 6. Write a Python program to", "225 - 224 = 1 247 - 236 = 11", "Negative numbers are not palindromic. Sample Output: False True False", "- 236 = 23 225 - 236 = -11 258", "find the starting and ending position of a given value", "a given N by M matrix of numbers line by", "[0, 0] Sample Output: [0, 5] [0, 0] 7. The", "7 0 5. Write a Python program to remove all", "2]] Output: 1 2 3 4 8 7 6 5", "Write a Python program to find the first missing positive", "5 dollars and sell value is 15 dollars. Sample Output:", "6, 7, 8], [0, 6, 2, 8], [2, 3, 0,", "from selling and buying values of stock. An array of", "by M matrix of numbers line by line in forward", "Sample Output: 10 7 0 5. Write a Python program", "and sell value is 15 dollars. Sample Output: 6 0", "check whether a given integer is a palindrome or not.", "6, 2, 8], [2, 3, 0, 2]] Output: 1 2", "4 8 7 6 5 0 6 2 8 2", "225 - 258 = -33 225 - 259 = -34", "a given value in a given array of integers, sorted", "7, 15], the function will return 10, since the buying", "13, 14] target value = 4 Output: [0, 0] Sample", "- 236 = 11 258 - 236 = 22 259", "given [8, 10, 7, 5, 7, 15], the function will", "Write a Python program to calculate the maximum profit from", "4 4. Write a Python program to calculate the maximum", "to calculate the maximum profit from selling and buying values", "length of the new array. For example, given [8, 10,", "the array, return [0, 0]. Input: [5, 7, 7, 8,", "selling and buying values of stock. An array of numbers", "2 9. Write a Python program to compute the largest", "a Python program to remove the duplicate elements of a", "value of the said array. You cannot sell a stock", "of numbers such that each element appear only once and", "whether a given integer is a palindrome or not. Note:", "2 8 2 0 3 2 9. Write a Python", "you buy one. Input (Stock price of each day): [224,", "buy one and sell one share of the stock from", "is 15 dollars. Sample Output: 10 7 0 5. Write", "a given integer is a palindrome or not. Note: An", "the stock prices in chronological order. For example, given [8,", "a given array of integers, sorted in ascending order. If", "= 8 Output: [0, 5] Input: [1, 3, 6, 9,", "225 - 236 = -11 258 - 247 = 11", "to find the maximum profit in one transaction i.e., buy", "2, 8], [2, 3, 0, 2]] Output: 1 2 3", "vowels of a given string. Sample Output: w3resuorce Python Perl", "values of stock. An array of numbers represent the stock", "> backwards > forward >... order. Input matrix: [[1, 2,", "Python program to find the starting and ending position of", "to print a given N by M matrix of numbers", "10, 7, 5, 7, 15], the function will return 10,", "0 6. Write a Python program to find the starting", "8. Write a Python program to print a given N", "the buying value of the stock is 5 dollars and", "of the said array. You cannot sell a stock before", "value in a given array of integers, sorted in ascending", "is a palindrome when it reads the same backward as", "Python program to find the first missing positive integer that", "a given stock on each day is stored in an", "of a given stock on each day is stored in", "forward. Negative numbers are not palindromic. Sample Output: False True", "order. Input matrix: [[1, 2, 3,4], [5, 6, 7, 8],", "prices in chronological order. For example, given [8, 10, 7,", "reads the same backward as forward. Negative numbers are not", "all instances of a given value from a given array", "259, 225] Output: 35 Explanation: 236 - 224 = 12", "Output: w3resuorce Python Perl ASU 2. Write a Python program", "6. Write a Python program to find the starting and", "given list of integers. Sample Output: 4000 8 120 10.", "8] target value = 8 Output: [0, 5] Input: [1,", "price value of the said array. You cannot sell a", "given array of integers, sorted in ascending order. If the", "236, 247, 258, 259, 225] Output: 35 Explanation: 236 -", "247 - 236 = 11 258 - 236 = 22", "array of integers and find the length of the new", "of each day): [224, 236, 247, 258, 259, 225] Output:", "program to find the maximum profit in one transaction i.e.,", "found in the array, return [0, 0]. Input: [5, 7,", "to find the first missing positive integer that does not", "Write a Python program to find the maximum profit in", "given array of numbers such that each element appear only", "sell one share of the stock from the given price", "224 = 35 225 - 224 = 1 247 -", "22 259 - 236 = 23 225 - 236 =", "-11 258 - 247 = 11 259 - 247 =", "Output: False True False 3. Write a Python program to", "247 - 224 = 23 258 - 224 = 34", "value of the stock is 5 dollars and sell value", "the largest product of three integers from a given list", "dollars and sell value is 15 dollars. Sample Output: 6", "cannot sell a stock before you buy one. Input (Stock", "same backward as forward. Negative numbers are not palindromic. Sample", "appear only once and return the new length of the", "one. Input (Stock price of each day): [224, 236, 247,", "15 dollars. Sample Output: 6 0 5 0 6. Write", "= 23 225 - 236 = -11 258 - 247", "Python program to calculate the maximum profit from selling and", "new length of the given array. Sample Output: 5 4", "not found in the array, return [0, 0]. Input: [5,", "the same backward as forward. Negative numbers are not palindromic.", "the duplicate elements of a given array of numbers such", "a given array of numbers such that each element appear", "a Python program to find the starting and ending position", "Write a Python program to find the starting and ending", "sell value is 15 dollars. Sample Output: 10 7 0", "in chronological order. For example, given [8, 10, 7, 5,", "a palindrome or not. Note: An integer is a palindrome", "= -33 225 - 259 = -34 8. Write a", "35 225 - 224 = 1 247 - 236 =", "list of integers. Sample Output: 4000 8 120 10. Write", "said array. You cannot sell a stock before you buy", "stock is 5 dollars and sell value is 15 dollars.", "3,4], [5, 6, 7, 8], [0, 6, 2, 8], [2,", "5] [0, 0] 7. The price of a given stock", "4 Output: [0, 0] Sample Output: [0, 5] [0, 0]", "= 23 258 - 224 = 34 259 - 224", "For example, given [8, 10, 7, 5, 7, 15], the", "and ending position of a given value in a given", "[5, 6, 7, 8], [0, 6, 2, 8], [2, 3,", "False True False 3. Write a Python program to remove", "in forward > backwards > forward >... order. Input matrix:", "0 6 2 8 2 0 3 2 9. Write", "120 10. Write a Python program to find the first", "array. Sample Output: 5 4 4. Write a Python program", "(Stock price of each day): [224, 236, 247, 258, 259,", "the stock is 5 dollars and sell value is 15", "6 2 8 2 0 3 2 9. Write a", "236 - 224 = 12 247 - 224 = 23", "of the stock is 5 dollars and sell value is", "Output: [0, 5] Input: [1, 3, 6, 9, 13, 14]", "Python Perl ASU 2. Write a Python program to check", "224 = 34 259 - 224 = 35 225 -", "each day is stored in an array. Write a Python", "- 236 = 22 259 - 236 = 23 225", "from a given list of integers. Sample Output: 4000 8", "first missing positive integer that does not exist in a", "a Python program to compute the largest product of three", "from the given price value of the said array. You", "8], [2, 3, 0, 2]] Output: 1 2 3 4", "15], the function will return 10, since the buying value", "element appear only once and return the new length of", "once and return the new length of the given array.", "-33 225 - 259 = -34 8. Write a Python", "Python program to find the maximum profit in one transaction", "Write a Python program to check whether a given integer", "the stock from the given price value of the said", "sell value is 15 dollars. Sample Output: 6 0 5", "= 35 225 - 224 = 1 247 - 236", "sell a stock before you buy one. Input (Stock price", "6, 9, 13, 14] target value = 4 Output: [0,", "-22 259 - 258 = 1 225 - 258 =", "Output: 35 Explanation: 236 - 224 = 12 247 -", "given value from a given array of integers and find", "return 10, since the buying value of the stock is", "to find the starting and ending position of a given", "5 4 4. Write a Python program to calculate the", "is not found in the array, return [0, 0]. Input:", "0 5 0 6. Write a Python program to find", "Input: [1, 3, 6, 9, 13, 14] target value =", "12 247 - 224 = 23 258 - 224 =", "program to print a given N by M matrix of", "of integers, sorted in ascending order. If the target is", "program to calculate the maximum profit from selling and buying", "1 247 - 236 = 11 258 - 236 =", "return [0, 0]. Input: [5, 7, 7, 8, 8, 8]", "247, 258, 259, 225] Output: 35 Explanation: 236 - 224", "by line in forward > backwards > forward >... order.", "stored in an array. Write a Python program to find", "3 2 9. Write a Python program to compute the", "stock from the given price value of the said array.", "7, 8, 8, 8] target value = 8 Output: [0,", "the given price value of the said array. You cannot", "dollars. Sample Output: 10 7 0 5. Write a Python", "258 - 236 = 22 259 - 236 = 23", "line by line in forward > backwards > forward >...", "numbers such that each element appear only once and return", "starting and ending position of a given value in a", "9, 13, 14] target value = 4 Output: [0, 0]", "Write a Python program to remove all instances of a", "Python program to remove all instances of a given value", "9. Write a Python program to compute the largest product", "0, 2]] Output: 1 2 3 4 8 7 6", "- 247 = 11 259 - 247 = 12 225", "= 1 247 - 236 = 11 258 - 236", "day): [224, 236, 247, 258, 259, 225] Output: 35 Explanation:", "Sample Output: w3resuorce Python Perl ASU 2. Write a Python", "are not palindromic. Sample Output: False True False 3. Write", "stock. An array of numbers represent the stock prices in", "instances of a given value from a given array of", "represent the stock prices in chronological order. For example, given", "value = 8 Output: [0, 5] Input: [1, 3, 6,", "224 = 12 247 - 224 = 23 258 -", "duplicate elements of a given array of numbers such that", "array. For example, given [8, 10, 7, 5, 7, 15],", "array. You cannot sell a stock before you buy one.", "value from a given array of integers and find the", "from a given array of integers and find the length", "8, 8, 8] target value = 8 Output: [0, 5]", "forward >... order. Input matrix: [[1, 2, 3,4], [5, 6,", "224 = 1 247 - 236 = 11 258 -", "of three integers from a given list of integers. Sample", "not. Note: An integer is a palindrome when it reads", "a palindrome when it reads the same backward as forward.", "of stock. An array of numbers represent the stock prices", "23 225 - 236 = -11 258 - 247 =", "8 120 10. Write a Python program to find the", "given value in a given array of integers, sorted in", "Output: 6 0 5 0 6. Write a Python program", "= 11 258 - 236 = 22 259 - 236", "one and sell one share of the stock from the", "stock prices in chronological order. For example, given [8, 10,", "numbers line by line in forward > backwards > forward", "2. Write a Python program to check whether a given", "[5, 7, 7, 8, 8, 8] target value = 8", "dollars and sell value is 15 dollars. Sample Output: 10", "program to reverse only the vowels of a given string.", "program to check whether a given integer is a palindrome", "on each day is stored in an array. Write a", "share of the stock from the given price value of", "in one transaction i.e., buy one and sell one share", "Input matrix: [[1, 2, 3,4], [5, 6, 7, 8], [0,", ">... order. Input matrix: [[1, 2, 3,4], [5, 6, 7,", "buying values of stock. An array of numbers represent the", "- 224 = 35 225 - 224 = 1 247", "string. Sample Output: w3resuorce Python Perl ASU 2. Write a", "i.e., buy one and sell one share of the stock", "7, 8], [0, 6, 2, 8], [2, 3, 0, 2]]", "Write a Python program to reverse only the vowels of", "236 = 22 259 - 236 = 23 225 -", "find the length of the new array. For example, given", "You cannot sell a stock before you buy one. Input", "2 0 3 2 9. Write a Python program to", "Output: 10 7 0 5. Write a Python program to", "given stock on each day is stored in an array.", "- 258 = -33 225 - 259 = -34 8.", "forward > backwards > forward >... order. Input matrix: [[1,", "dollars. Sample Output: 6 0 5 0 6. Write a", "N by M matrix of numbers line by line in", "Note: An integer is a palindrome when it reads the", "247 = 12 225 - 247 = -22 259 -", "a Python program to find the first missing positive integer", "the new length of the given array. Sample Output: 5", "of the new array. For example, given [8, 10, 7,", "= 12 247 - 224 = 23 258 - 224", "matrix: [[1, 2, 3,4], [5, 6, 7, 8], [0, 6,", "order. For example, given [8, 10, 7, 5, 7, 15],", "[0, 0]. Input: [5, 7, 7, 8, 8, 8] target", "the said array. You cannot sell a stock before you", "= 12 225 - 247 = -22 259 - 258", "day is stored in an array. Write a Python program", "target value = 8 Output: [0, 5] Input: [1, 3,", "- 247 = 12 225 - 247 = -22 259", "and return the new length of the given array. Sample", "the vowels of a given string. Sample Output: w3resuorce Python", "in the array, return [0, 0]. Input: [5, 7, 7,", "[224, 236, 247, 258, 259, 225] Output: 35 Explanation: 236", "8 Output: [0, 5] Input: [1, 3, 6, 9, 13,", "reverse only the vowels of a given string. Sample Output:", "- 259 = -34 8. Write a Python program to", "5, 7, 15], the function will return 10, since the", "ASU 2. Write a Python program to check whether a", "Sample Output: 4000 8 120 10. Write a Python program", "is a palindrome or not. Note: An integer is a", "Python program to compute the largest product of three integers", "258 - 247 = 11 259 - 247 = 12", "11 259 - 247 = 12 225 - 247 =", "> forward >... order. Input matrix: [[1, 2, 3,4], [5,", "three integers from a given list of integers. Sample Output:", "- 224 = 23 258 - 224 = 34 259", "to remove the duplicate elements of a given array of", "225 - 259 = -34 8. Write a Python program", "1. Write a Python program to reverse only the vowels", "palindrome or not. Note: An integer is a palindrome when", "= 11 259 - 247 = 12 225 - 247", "-34 8. Write a Python program to print a given", "6 5 0 6 2 8 2 0 3 2", "given integer is a palindrome or not. Note: An integer", "when it reads the same backward as forward. Negative numbers", "0]. Input: [5, 7, 7, 8, 8, 8] target value", "given price value of the said array. You cannot sell", "to reverse only the vowels of a given string. Sample", "[0, 0] 7. The price of a given stock on", "= 4 Output: [0, 0] Sample Output: [0, 5] [0,", "buying value of the stock is 5 dollars and sell", "given string. Sample Output: w3resuorce Python Perl ASU 2. Write", "product of three integers from a given list of integers.", "to compute the largest product of three integers from a", "to check whether a given integer is a palindrome or", "7. The price of a given stock on each day", "8 7 6 5 0 6 2 8 2 0", "a given value from a given array of integers and", "array. Write a Python program to find the maximum profit", "each day): [224, 236, 247, 258, 259, 225] Output: 35", "a given list of integers. Sample Output: 4000 8 120", "<gh_stars>1-10 \"\"\" 1. Write a Python program to reverse only", "a given array of integers and find the length of", "Output: 5 4 4. Write a Python program to calculate", "0] 7. The price of a given stock on each", "remove the duplicate elements of a given array of numbers", "The price of a given stock on each day is", "buy one. Input (Stock price of each day): [224, 236,", "the length of the new array. For example, given [8,", "of a given value from a given array of integers", "= 22 259 - 236 = 23 225 - 236", "calculate the maximum profit from selling and buying values of", "= -11 258 - 247 = 11 259 - 247", "target is not found in the array, return [0, 0].", "[0, 6, 2, 8], [2, 3, 0, 2]] Output: 1", "259 - 236 = 23 225 - 236 = -11", "integers and find the length of the new array. For", "35 Explanation: 236 - 224 = 12 247 - 224", "new array. For example, given [8, 10, 7, 5, 7,", "is stored in an array. Write a Python program to", "a Python program to reverse only the vowels of a", "3, 0, 2]] Output: 1 2 3 4 8 7", "and sell value is 15 dollars. Sample Output: 10 7", "0] Sample Output: [0, 5] [0, 0] 7. The price", "- 247 = -22 259 - 258 = 1 225", "and find the length of the new array. For example,", "find the first missing positive integer that does not exist", "the target is not found in the array, return [0,", "the starting and ending position of a given value in", "transaction i.e., buy one and sell one share of the", "array of numbers such that each element appear only once", "array, return [0, 0]. Input: [5, 7, 7, 8, 8,", "one share of the stock from the given price value", "program to compute the largest product of three integers from", "integers. Sample Output: 4000 8 120 10. Write a Python", "backward as forward. Negative numbers are not palindromic. Sample Output:", "7, 5, 7, 15], the function will return 10, since", "258 = -33 225 - 259 = -34 8. Write", "[0, 5] Input: [1, 3, 6, 9, 13, 14] target", "maximum profit from selling and buying values of stock. An", "Perl ASU 2. Write a Python program to check whether", "- 236 = -11 258 - 247 = 11 259", "backwards > forward >... order. Input matrix: [[1, 2, 3,4],", "as forward. Negative numbers are not palindromic. Sample Output: False", "value is 15 dollars. Sample Output: 6 0 5 0", "example, given [8, 10, 7, 5, 7, 15], the function", "price of a given stock on each day is stored", "integer that does not exist in a given list. \"\"\"", "247 = 11 259 - 247 = 12 225 -", "8 2 0 3 2 9. Write a Python program", "only the vowels of a given string. Sample Output: w3resuorce", "Python program to reverse only the vowels of a given", "23 258 - 224 = 34 259 - 224 =", "Sample Output: 5 4 4. Write a Python program to", "the function will return 10, since the buying value of", "- 224 = 34 259 - 224 = 35 225", "An array of numbers represent the stock prices in chronological", "program to remove all instances of a given value from", "Write a Python program to remove the duplicate elements of", "in a given array of integers, sorted in ascending order.", "236 = 11 258 - 236 = 22 259 -", "12 225 - 247 = -22 259 - 258 =", "of the given array. Sample Output: 5 4 4. Write", "7 6 5 0 6 2 8 2 0 3", "integers from a given list of integers. Sample Output: 4000", "elements of a given array of numbers such that each", "258, 259, 225] Output: 35 Explanation: 236 - 224 =", "it reads the same backward as forward. Negative numbers are", "the given array. Sample Output: 5 4 4. Write a", "a Python program to remove all instances of a given", "1 2 3 4 8 7 6 5 0 6", "only once and return the new length of the given", "of integers and find the length of the new array.", "Python program to remove the duplicate elements of a given", "a Python program to calculate the maximum profit from selling", "and buying values of stock. An array of numbers represent", "positive integer that does not exist in a given list.", "will return 10, since the buying value of the stock", "the first missing positive integer that does not exist in", "of the stock from the given price value of the", "236 = -11 258 - 247 = 11 259 -", "a Python program to find the maximum profit in one", "largest product of three integers from a given list of", "palindromic. Sample Output: False True False 3. Write a Python", "Sample Output: False True False 3. Write a Python program", "and sell one share of the stock from the given", "2, 3,4], [5, 6, 7, 8], [0, 6, 2, 8],", "array of numbers represent the stock prices in chronological order.", "numbers represent the stock prices in chronological order. For example,", "False 3. Write a Python program to remove the duplicate", "target value = 4 Output: [0, 0] Sample Output: [0,", "find the maximum profit in one transaction i.e., buy one", "return the new length of the given array. Sample Output:", "259 - 247 = 12 225 - 247 = -22", "stock on each day is stored in an array. Write", "sorted in ascending order. If the target is not found", "= -22 259 - 258 = 1 225 - 258", "3 4 8 7 6 5 0 6 2 8", "the maximum profit in one transaction i.e., buy one and", "in an array. Write a Python program to find the", "of numbers represent the stock prices in chronological order. For", "= 34 259 - 224 = 35 225 - 224", "34 259 - 224 = 35 225 - 224 =", "[2, 3, 0, 2]] Output: 1 2 3 4 8", "8, 8] target value = 8 Output: [0, 5] Input:", "integer is a palindrome when it reads the same backward", "[8, 10, 7, 5, 7, 15], the function will return", "is 5 dollars and sell value is 15 dollars. Sample", "remove all instances of a given value from a given", "225 - 247 = -22 259 - 258 = 1", "position of a given value in a given array of", "- 224 = 12 247 - 224 = 23 258", "236 = 23 225 - 236 = -11 258 -", "w3resuorce Python Perl ASU 2. Write a Python program to", "[[1, 2, 3,4], [5, 6, 7, 8], [0, 6, 2,", "5] Input: [1, 3, 6, 9, 13, 14] target value", "missing positive integer that does not exist in a given", "10 7 0 5. Write a Python program to remove", "Python program to print a given N by M matrix", "matrix of numbers line by line in forward > backwards", "of a given value in a given array of integers,", "function will return 10, since the buying value of the", "10, since the buying value of the stock is 5", "4. Write a Python program to calculate the maximum profit", "a given string. Sample Output: w3resuorce Python Perl ASU 2.", "or not. Note: An integer is a palindrome when it", "259 - 224 = 35 225 - 224 = 1", "integers, sorted in ascending order. If the target is not", "each element appear only once and return the new length", "since the buying value of the stock is 5 dollars", "palindrome when it reads the same backward as forward. Negative", "Output: 4000 8 120 10. Write a Python program to", "program to find the first missing positive integer that does", "Sample Output: 6 0 5 0 6. Write a Python", "the new array. For example, given [8, 10, 7, 5,", "5 0 6. Write a Python program to find the", "before you buy one. Input (Stock price of each day):", "259 - 258 = 1 225 - 258 = -33", "of a given string. Sample Output: w3resuorce Python Perl ASU", "Input (Stock price of each day): [224, 236, 247, 258,", "3. Write a Python program to remove the duplicate elements", "= -34 8. Write a Python program to print a", "that each element appear only once and return the new", "7, 7, 8, 8, 8] target value = 8 Output:", "2 3 4 8 7 6 5 0 6 2", "0 5. Write a Python program to remove all instances", "259 = -34 8. Write a Python program to print", "the maximum profit from selling and buying values of stock.", "length of the given array. Sample Output: 5 4 4.", "3, 6, 9, 13, 14] target value = 4 Output:", "of integers. Sample Output: 4000 8 120 10. Write a", "If the target is not found in the array, return", "is 15 dollars. Sample Output: 6 0 5 0 6.", "Output: [0, 0] Sample Output: [0, 5] [0, 0] 7.", "An integer is a palindrome when it reads the same", "Write a Python program to print a given N by", "given array of integers and find the length of the", "of a given array of numbers such that each element", "ending position of a given value in a given array", "[0, 5] [0, 0] 7. The price of a given", "compute the largest product of three integers from a given" ]
[ ") @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1010, version=0) class Microsoft_Windows_IPxlatCfg_1010_0(Etw): pattern = Struct( \"InterfaceLuid\"", "Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1002, version=0) class Microsoft_Windows_IPxlatCfg_1002_0(Etw): pattern = Struct(", "Int32ul, Int64sl, Int64ul, Bytes, Double, Float32l, Struct from etl.utils import", "Microsoft_Windows_IPxlatCfg_1103_0(Etw): pattern = Struct( \"InterfaceLuid\" / Int64ul, \"PrefixLength\" / Int32ul", "-*- \"\"\" Microsoft-Windows-IPxlatCfg GUID : 3e5ac668-af52-4c15-b99b-a3e7a6616ebd \"\"\" from construct import", "Float32l, Struct from etl.utils import WString, CString, SystemTime, Guid from", ") @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1008, version=0) class Microsoft_Windows_IPxlatCfg_1008_0(Etw): pattern = Struct( \"InterfaceLuid\"", "/ CString, \"InterfaceLuid\" / Int64ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1007, version=0) class", "\"PrefixLength\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1008, version=0) class Microsoft_Windows_IPxlatCfg_1008_0(Etw): pattern", "Microsoft_Windows_IPxlatCfg_1002_0(Etw): pattern = Struct( \"ErrorString\" / CString, \"ErrorCode\" / Int32ul,", "version=0) class Microsoft_Windows_IPxlatCfg_1009_0(Etw): pattern = Struct( \"InterfaceLuid\" / Int64ul )", "\"\"\" Microsoft-Windows-IPxlatCfg GUID : 3e5ac668-af52-4c15-b99b-a3e7a6616ebd \"\"\" from construct import Int8sl,", "/ Int64ul, \"IPv4Address\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1009, version=0) class", "pattern = Struct( \"ErrorString\" / CString, \"ErrorCode\" / Int32ul )", "event_id=1003, version=0) class Microsoft_Windows_IPxlatCfg_1003_0(Etw): pattern = Struct( \"InfoString\" / CString", "Struct from etl.utils import WString, CString, SystemTime, Guid from etl.dtyp", "\"ErrorCode\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1002, version=0) class Microsoft_Windows_IPxlatCfg_1002_0(Etw): pattern", "= Struct( \"InfoString\" / CString, \"InterfaceLuid\" / Int64ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"),", "/ Int32ul, \"RemotePrefixLength\" / Int32ul, \"LocalPrefixLength\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"),", "\"LocalPrefixLength\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1102, version=0) class Microsoft_Windows_IPxlatCfg_1102_0(Etw): pattern", ") @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1103, version=0) class Microsoft_Windows_IPxlatCfg_1103_0(Etw): pattern = Struct( \"InterfaceLuid\"", "\"\"\" from construct import Int8sl, Int8ul, Int16ul, Int16sl, Int32sl, Int32ul,", "pattern = Struct( \"InterfaceLuid\" / Int64ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1011, version=0)", "Int64ul, \"Metric\" / Int32ul, \"RemotePrefixLength\" / Int32ul, \"LocalPrefixLength\" / Int32ul", "Bytes, Double, Float32l, Struct from etl.utils import WString, CString, SystemTime,", "\"IPv4Address\" / Int32ul, \"IPv4Prefix\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1006, version=0)", "Int8ul, Int16ul, Int16sl, Int32sl, Int32ul, Int64sl, Int64ul, Bytes, Double, Float32l,", "version=0) class Microsoft_Windows_IPxlatCfg_1006_0(Etw): pattern = Struct( \"InfoString\" / CString, \"InterfaceLuid\"", "@declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1007, version=0) class Microsoft_Windows_IPxlatCfg_1007_0(Etw): pattern = Struct( \"InterfaceLuid\" /", "import Sid from etl.parsers.etw.core import Etw, declare, guid @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1001,", "/ Int64ul, \"Metric\" / Int32ul, \"RemotePrefixLength\" / Int32ul, \"LocalPrefixLength\" /", "declare, guid @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1001, version=0) class Microsoft_Windows_IPxlatCfg_1001_0(Etw): pattern = Struct(", "event_id=1011, version=0) class Microsoft_Windows_IPxlatCfg_1011_0(Etw): pattern = Struct( \"InfoString\" / CString,", "Sid from etl.parsers.etw.core import Etw, declare, guid @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1001, version=0)", "guid @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1001, version=0) class Microsoft_Windows_IPxlatCfg_1001_0(Etw): pattern = Struct( \"ErrorString\"", "/ Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1002, version=0) class Microsoft_Windows_IPxlatCfg_1002_0(Etw): pattern =", "Int32ul, \"RemotePrefixLength\" / Int32ul, \"LocalPrefixLength\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1102,", "\"ErrorString\" / CString, \"ErrorCode\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1002, version=0)", "pattern = Struct( \"IPv4Address\" / Int32ul, \"IPv4Prefix\" / Int32ul )", "version=0) class Microsoft_Windows_IPxlatCfg_1008_0(Etw): pattern = Struct( \"InterfaceLuid\" / Int64ul, \"IPv4Address\"", "\"IPv4Address\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1009, version=0) class Microsoft_Windows_IPxlatCfg_1009_0(Etw): pattern", "= Struct( \"ErrorString\" / CString, \"ErrorCode\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"),", ") @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1101, version=0) class Microsoft_Windows_IPxlatCfg_1101_0(Etw): pattern = Struct( \"InterfaceLuid\"", "coding: utf-8 -*- \"\"\" Microsoft-Windows-IPxlatCfg GUID : 3e5ac668-af52-4c15-b99b-a3e7a6616ebd \"\"\" from", "@declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1005, version=0) class Microsoft_Windows_IPxlatCfg_1005_0(Etw): pattern = Struct( \"IPv4Address\" /", "/ Int32ul, \"LocalPrefixLength\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1102, version=0) class", "@declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1011, version=0) class Microsoft_Windows_IPxlatCfg_1011_0(Etw): pattern = Struct( \"InfoString\" /", "\"InterfaceLuid\" / Int64ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1007, version=0) class Microsoft_Windows_IPxlatCfg_1007_0(Etw): pattern", "Struct( \"InterfaceLuid\" / Int64ul, \"PrefixLength\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1008,", "\"InfoString\" / CString, \"MTU\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1101, version=0)", "Int32ul, \"LocalPrefixLength\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1103, version=0) class Microsoft_Windows_IPxlatCfg_1103_0(Etw):", "\"InterfaceLuid\" / Int64ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1011, version=0) class Microsoft_Windows_IPxlatCfg_1011_0(Etw): pattern", "/ CString, \"MTU\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1101, version=0) class", "event_id=1005, version=0) class Microsoft_Windows_IPxlatCfg_1005_0(Etw): pattern = Struct( \"IPv4Address\" / Int32ul,", "Microsoft_Windows_IPxlatCfg_1006_0(Etw): pattern = Struct( \"InfoString\" / CString, \"InterfaceLuid\" / Int64ul", ") @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1003, version=0) class Microsoft_Windows_IPxlatCfg_1003_0(Etw): pattern = Struct( \"InfoString\"", "/ Int32ul, \"LocalPrefixLength\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1103, version=0) class", "\"LocalPrefixLength\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1103, version=0) class Microsoft_Windows_IPxlatCfg_1103_0(Etw): pattern", "from etl.parsers.etw.core import Etw, declare, guid @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1001, version=0) class", "\"ErrorCode\" / Int32ul, \"InterfaceLuid\" / Int64ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1003, version=0)", "Etw, declare, guid @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1001, version=0) class Microsoft_Windows_IPxlatCfg_1001_0(Etw): pattern =", "Int8sl, Int8ul, Int16ul, Int16sl, Int32sl, Int32ul, Int64sl, Int64ul, Bytes, Double,", ") @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1102, version=0) class Microsoft_Windows_IPxlatCfg_1102_0(Etw): pattern = Struct( \"InterfaceLuid\"", "pattern = Struct( \"InterfaceLuid\" / Int64ul, \"IPv4Address\" / Int32ul )", "@declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1101, version=0) class Microsoft_Windows_IPxlatCfg_1101_0(Etw): pattern = Struct( \"InterfaceLuid\" /", "import Etw, declare, guid @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1001, version=0) class Microsoft_Windows_IPxlatCfg_1001_0(Etw): pattern", "Microsoft_Windows_IPxlatCfg_1005_0(Etw): pattern = Struct( \"IPv4Address\" / Int32ul, \"IPv4Prefix\" / Int32ul", "/ Int64ul, \"PrefixLength\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1008, version=0) class", "class Microsoft_Windows_IPxlatCfg_1003_0(Etw): pattern = Struct( \"InfoString\" / CString ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"),", "@declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1103, version=0) class Microsoft_Windows_IPxlatCfg_1103_0(Etw): pattern = Struct( \"InterfaceLuid\" /", ": 3e5ac668-af52-4c15-b99b-a3e7a6616ebd \"\"\" from construct import Int8sl, Int8ul, Int16ul, Int16sl,", "@declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1008, version=0) class Microsoft_Windows_IPxlatCfg_1008_0(Etw): pattern = Struct( \"InterfaceLuid\" /", "\"InfoString\" / CString ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1005, version=0) class Microsoft_Windows_IPxlatCfg_1005_0(Etw): pattern", "event_id=1010, version=0) class Microsoft_Windows_IPxlatCfg_1010_0(Etw): pattern = Struct( \"InterfaceLuid\" / Int64ul", ") @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1011, version=0) class Microsoft_Windows_IPxlatCfg_1011_0(Etw): pattern = Struct( \"InfoString\"", "Microsoft_Windows_IPxlatCfg_1007_0(Etw): pattern = Struct( \"InterfaceLuid\" / Int64ul, \"PrefixLength\" / Int32ul", "/ Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1009, version=0) class Microsoft_Windows_IPxlatCfg_1009_0(Etw): pattern =", "class Microsoft_Windows_IPxlatCfg_1010_0(Etw): pattern = Struct( \"InterfaceLuid\" / Int64ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"),", "= Struct( \"IPv4Address\" / Int32ul, \"IPv4Prefix\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"),", "/ Int32ul, \"IPv4Prefix\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1006, version=0) class", "Microsoft_Windows_IPxlatCfg_1101_0(Etw): pattern = Struct( \"InterfaceLuid\" / Int64ul, \"Metric\" / Int32ul,", "Microsoft-Windows-IPxlatCfg GUID : 3e5ac668-af52-4c15-b99b-a3e7a6616ebd \"\"\" from construct import Int8sl, Int8ul,", "/ Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1006, version=0) class Microsoft_Windows_IPxlatCfg_1006_0(Etw): pattern =", "/ Int64ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1007, version=0) class Microsoft_Windows_IPxlatCfg_1007_0(Etw): pattern =", "version=0) class Microsoft_Windows_IPxlatCfg_1005_0(Etw): pattern = Struct( \"IPv4Address\" / Int32ul, \"IPv4Prefix\"", "Microsoft_Windows_IPxlatCfg_1001_0(Etw): pattern = Struct( \"ErrorString\" / CString, \"ErrorCode\" / Int32ul", "@declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1003, version=0) class Microsoft_Windows_IPxlatCfg_1003_0(Etw): pattern = Struct( \"InfoString\" /", "pattern = Struct( \"InterfaceLuid\" / Int64ul, \"PrefixLength\" / Int32ul )", "Int64ul, \"PrefixLength\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1008, version=0) class Microsoft_Windows_IPxlatCfg_1008_0(Etw):", "Struct( \"InterfaceLuid\" / Int64ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1011, version=0) class Microsoft_Windows_IPxlatCfg_1011_0(Etw):", "Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1008, version=0) class Microsoft_Windows_IPxlatCfg_1008_0(Etw): pattern = Struct(", "WString, CString, SystemTime, Guid from etl.dtyp import Sid from etl.parsers.etw.core", "@declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1010, version=0) class Microsoft_Windows_IPxlatCfg_1010_0(Etw): pattern = Struct( \"InterfaceLuid\" /", "version=0) class Microsoft_Windows_IPxlatCfg_1101_0(Etw): pattern = Struct( \"InterfaceLuid\" / Int64ul, \"Metric\"", "Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1102, version=0) class Microsoft_Windows_IPxlatCfg_1102_0(Etw): pattern = Struct(", "version=0) class Microsoft_Windows_IPxlatCfg_1103_0(Etw): pattern = Struct( \"InterfaceLuid\" / Int64ul, \"PrefixLength\"", "Int16sl, Int32sl, Int32ul, Int64sl, Int64ul, Bytes, Double, Float32l, Struct from", "CString, SystemTime, Guid from etl.dtyp import Sid from etl.parsers.etw.core import", "Int32ul, \"IPv4Prefix\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1006, version=0) class Microsoft_Windows_IPxlatCfg_1006_0(Etw):", "import WString, CString, SystemTime, Guid from etl.dtyp import Sid from", "class Microsoft_Windows_IPxlatCfg_1008_0(Etw): pattern = Struct( \"InterfaceLuid\" / Int64ul, \"IPv4Address\" /", "CString, \"MTU\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1101, version=0) class Microsoft_Windows_IPxlatCfg_1101_0(Etw):", "/ Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1103, version=0) class Microsoft_Windows_IPxlatCfg_1103_0(Etw): pattern =", "\"InterfaceLuid\" / Int64ul, \"IPv4Address\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1009, version=0)", "\"MTU\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1101, version=0) class Microsoft_Windows_IPxlatCfg_1101_0(Etw): pattern", "Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1009, version=0) class Microsoft_Windows_IPxlatCfg_1009_0(Etw): pattern = Struct(", "\"InfoString\" / CString, \"InterfaceLuid\" / Int64ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1007, version=0)", "= Struct( \"InterfaceLuid\" / Int64ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1011, version=0) class", "= Struct( \"InfoString\" / CString ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1005, version=0) class", "Microsoft_Windows_IPxlatCfg_1009_0(Etw): pattern = Struct( \"InterfaceLuid\" / Int64ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1010,", "Struct( \"InfoString\" / CString ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1005, version=0) class Microsoft_Windows_IPxlatCfg_1005_0(Etw):", "Struct( \"InterfaceLuid\" / Int64ul, \"Metric\" / Int32ul, \"RemotePrefixLength\" / Int32ul,", "SystemTime, Guid from etl.dtyp import Sid from etl.parsers.etw.core import Etw,", "Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1101, version=0) class Microsoft_Windows_IPxlatCfg_1101_0(Etw): pattern = Struct(", "class Microsoft_Windows_IPxlatCfg_1002_0(Etw): pattern = Struct( \"ErrorString\" / CString, \"ErrorCode\" /", "Struct( \"ErrorString\" / CString, \"ErrorCode\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1002,", "Microsoft_Windows_IPxlatCfg_1011_0(Etw): pattern = Struct( \"InfoString\" / CString, \"MTU\" / Int32ul", "event_id=1009, version=0) class Microsoft_Windows_IPxlatCfg_1009_0(Etw): pattern = Struct( \"InterfaceLuid\" / Int64ul", "@declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1102, version=0) class Microsoft_Windows_IPxlatCfg_1102_0(Etw): pattern = Struct( \"InterfaceLuid\" /", "Struct( \"ErrorString\" / CString, \"ErrorCode\" / Int32ul, \"InterfaceLuid\" / Int64ul", "version=0) class Microsoft_Windows_IPxlatCfg_1011_0(Etw): pattern = Struct( \"InfoString\" / CString, \"MTU\"", "/ CString ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1005, version=0) class Microsoft_Windows_IPxlatCfg_1005_0(Etw): pattern =", "Struct( \"IPv4Address\" / Int32ul, \"IPv4Prefix\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1006,", "version=0) class Microsoft_Windows_IPxlatCfg_1102_0(Etw): pattern = Struct( \"InterfaceLuid\" / Int64ul, \"Metric\"", "Int16ul, Int16sl, Int32sl, Int32ul, Int64sl, Int64ul, Bytes, Double, Float32l, Struct", "Int32sl, Int32ul, Int64sl, Int64ul, Bytes, Double, Float32l, Struct from etl.utils", ") @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1005, version=0) class Microsoft_Windows_IPxlatCfg_1005_0(Etw): pattern = Struct( \"IPv4Address\"", "= Struct( \"InterfaceLuid\" / Int64ul, \"PrefixLength\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"),", "Int32ul, \"LocalPrefixLength\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1102, version=0) class Microsoft_Windows_IPxlatCfg_1102_0(Etw):", "GUID : 3e5ac668-af52-4c15-b99b-a3e7a6616ebd \"\"\" from construct import Int8sl, Int8ul, Int16ul,", "\"IPv4Prefix\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1006, version=0) class Microsoft_Windows_IPxlatCfg_1006_0(Etw): pattern", "event_id=1008, version=0) class Microsoft_Windows_IPxlatCfg_1008_0(Etw): pattern = Struct( \"InterfaceLuid\" / Int64ul,", "\"Metric\" / Int32ul, \"RemotePrefixLength\" / Int32ul, \"LocalPrefixLength\" / Int32ul )", "CString, \"ErrorCode\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1002, version=0) class Microsoft_Windows_IPxlatCfg_1002_0(Etw):", "Int32ul, \"InterfaceLuid\" / Int64ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1003, version=0) class Microsoft_Windows_IPxlatCfg_1003_0(Etw):", "event_id=1002, version=0) class Microsoft_Windows_IPxlatCfg_1002_0(Etw): pattern = Struct( \"ErrorString\" / CString,", ") @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1002, version=0) class Microsoft_Windows_IPxlatCfg_1002_0(Etw): pattern = Struct( \"ErrorString\"", "Struct( \"InterfaceLuid\" / Int64ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1010, version=0) class Microsoft_Windows_IPxlatCfg_1010_0(Etw):", "from construct import Int8sl, Int8ul, Int16ul, Int16sl, Int32sl, Int32ul, Int64sl,", "/ Int64ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1010, version=0) class Microsoft_Windows_IPxlatCfg_1010_0(Etw): pattern =", "@declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1001, version=0) class Microsoft_Windows_IPxlatCfg_1001_0(Etw): pattern = Struct( \"ErrorString\" /", "pattern = Struct( \"ErrorString\" / CString, \"ErrorCode\" / Int32ul, \"InterfaceLuid\"", "CString ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1005, version=0) class Microsoft_Windows_IPxlatCfg_1005_0(Etw): pattern = Struct(", "Struct( \"InfoString\" / CString, \"InterfaceLuid\" / Int64ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1007,", "pattern = Struct( \"InfoString\" / CString, \"InterfaceLuid\" / Int64ul )", "/ Int64ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1011, version=0) class Microsoft_Windows_IPxlatCfg_1011_0(Etw): pattern =", "\"InterfaceLuid\" / Int64ul, \"Metric\" / Int32ul, \"RemotePrefixLength\" / Int32ul, \"LocalPrefixLength\"", "class Microsoft_Windows_IPxlatCfg_1006_0(Etw): pattern = Struct( \"InfoString\" / CString, \"InterfaceLuid\" /", "event_id=1001, version=0) class Microsoft_Windows_IPxlatCfg_1001_0(Etw): pattern = Struct( \"ErrorString\" / CString,", "\"InterfaceLuid\" / Int64ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1010, version=0) class Microsoft_Windows_IPxlatCfg_1010_0(Etw): pattern", "/ Int64ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1003, version=0) class Microsoft_Windows_IPxlatCfg_1003_0(Etw): pattern =", "@declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1002, version=0) class Microsoft_Windows_IPxlatCfg_1002_0(Etw): pattern = Struct( \"ErrorString\" /", "construct import Int8sl, Int8ul, Int16ul, Int16sl, Int32sl, Int32ul, Int64sl, Int64ul,", "/ CString, \"ErrorCode\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1002, version=0) class", "version=0) class Microsoft_Windows_IPxlatCfg_1003_0(Etw): pattern = Struct( \"InfoString\" / CString )", "Microsoft_Windows_IPxlatCfg_1003_0(Etw): pattern = Struct( \"InfoString\" / CString ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1005,", "pattern = Struct( \"InterfaceLuid\" / Int64ul, \"Metric\" / Int32ul, \"RemotePrefixLength\"", "class Microsoft_Windows_IPxlatCfg_1011_0(Etw): pattern = Struct( \"InfoString\" / CString, \"MTU\" /", "class Microsoft_Windows_IPxlatCfg_1001_0(Etw): pattern = Struct( \"ErrorString\" / CString, \"ErrorCode\" /", "etl.utils import WString, CString, SystemTime, Guid from etl.dtyp import Sid", "Int64ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1007, version=0) class Microsoft_Windows_IPxlatCfg_1007_0(Etw): pattern = Struct(", "\"RemotePrefixLength\" / Int32ul, \"LocalPrefixLength\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1102, version=0)", "class Microsoft_Windows_IPxlatCfg_1103_0(Etw): pattern = Struct( \"InterfaceLuid\" / Int64ul, \"PrefixLength\" /", "= Struct( \"InfoString\" / CString, \"MTU\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"),", "/ Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1008, version=0) class Microsoft_Windows_IPxlatCfg_1008_0(Etw): pattern =", "version=0) class Microsoft_Windows_IPxlatCfg_1001_0(Etw): pattern = Struct( \"ErrorString\" / CString, \"ErrorCode\"", "Int64ul, Bytes, Double, Float32l, Struct from etl.utils import WString, CString,", "Double, Float32l, Struct from etl.utils import WString, CString, SystemTime, Guid", "\"InterfaceLuid\" / Int64ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1003, version=0) class Microsoft_Windows_IPxlatCfg_1003_0(Etw): pattern", "/ CString, \"ErrorCode\" / Int32ul, \"InterfaceLuid\" / Int64ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"),", "/ Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1102, version=0) class Microsoft_Windows_IPxlatCfg_1102_0(Etw): pattern =", ") @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1009, version=0) class Microsoft_Windows_IPxlatCfg_1009_0(Etw): pattern = Struct( \"InterfaceLuid\"", "Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1103, version=0) class Microsoft_Windows_IPxlatCfg_1103_0(Etw): pattern = Struct(", "pattern = Struct( \"InterfaceLuid\" / Int64ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1010, version=0)", "/ Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1101, version=0) class Microsoft_Windows_IPxlatCfg_1101_0(Etw): pattern =", ") @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1006, version=0) class Microsoft_Windows_IPxlatCfg_1006_0(Etw): pattern = Struct( \"InfoString\"", "Microsoft_Windows_IPxlatCfg_1010_0(Etw): pattern = Struct( \"InterfaceLuid\" / Int64ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1011,", "event_id=1101, version=0) class Microsoft_Windows_IPxlatCfg_1101_0(Etw): pattern = Struct( \"InterfaceLuid\" / Int64ul,", "Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1006, version=0) class Microsoft_Windows_IPxlatCfg_1006_0(Etw): pattern = Struct(", ") @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1007, version=0) class Microsoft_Windows_IPxlatCfg_1007_0(Etw): pattern = Struct( \"InterfaceLuid\"", "pattern = Struct( \"InfoString\" / CString, \"MTU\" / Int32ul )", "= Struct( \"ErrorString\" / CString, \"ErrorCode\" / Int32ul, \"InterfaceLuid\" /", "3e5ac668-af52-4c15-b99b-a3e7a6616ebd \"\"\" from construct import Int8sl, Int8ul, Int16ul, Int16sl, Int32sl,", "from etl.dtyp import Sid from etl.parsers.etw.core import Etw, declare, guid", "Int64ul, \"IPv4Address\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1009, version=0) class Microsoft_Windows_IPxlatCfg_1009_0(Etw):", "class Microsoft_Windows_IPxlatCfg_1009_0(Etw): pattern = Struct( \"InterfaceLuid\" / Int64ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"),", "Struct( \"InterfaceLuid\" / Int64ul, \"IPv4Address\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1009,", "etl.parsers.etw.core import Etw, declare, guid @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1001, version=0) class Microsoft_Windows_IPxlatCfg_1001_0(Etw):", "event_id=1007, version=0) class Microsoft_Windows_IPxlatCfg_1007_0(Etw): pattern = Struct( \"InterfaceLuid\" / Int64ul,", "-*- coding: utf-8 -*- \"\"\" Microsoft-Windows-IPxlatCfg GUID : 3e5ac668-af52-4c15-b99b-a3e7a6616ebd \"\"\"", "\"InterfaceLuid\" / Int64ul, \"PrefixLength\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1008, version=0)", "CString, \"ErrorCode\" / Int32ul, \"InterfaceLuid\" / Int64ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1003,", "@declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1006, version=0) class Microsoft_Windows_IPxlatCfg_1006_0(Etw): pattern = Struct( \"InfoString\" /", "# -*- coding: utf-8 -*- \"\"\" Microsoft-Windows-IPxlatCfg GUID : 3e5ac668-af52-4c15-b99b-a3e7a6616ebd", "\"ErrorString\" / CString, \"ErrorCode\" / Int32ul, \"InterfaceLuid\" / Int64ul )", "@declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1009, version=0) class Microsoft_Windows_IPxlatCfg_1009_0(Etw): pattern = Struct( \"InterfaceLuid\" /", "= Struct( \"InterfaceLuid\" / Int64ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1010, version=0) class", "from etl.utils import WString, CString, SystemTime, Guid from etl.dtyp import", "class Microsoft_Windows_IPxlatCfg_1101_0(Etw): pattern = Struct( \"InterfaceLuid\" / Int64ul, \"Metric\" /", "/ Int32ul, \"InterfaceLuid\" / Int64ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1003, version=0) class", "version=0) class Microsoft_Windows_IPxlatCfg_1010_0(Etw): pattern = Struct( \"InterfaceLuid\" / Int64ul )", "version=0) class Microsoft_Windows_IPxlatCfg_1002_0(Etw): pattern = Struct( \"ErrorString\" / CString, \"ErrorCode\"", "CString, \"InterfaceLuid\" / Int64ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1007, version=0) class Microsoft_Windows_IPxlatCfg_1007_0(Etw):", "event_id=1006, version=0) class Microsoft_Windows_IPxlatCfg_1006_0(Etw): pattern = Struct( \"InfoString\" / CString,", "Guid from etl.dtyp import Sid from etl.parsers.etw.core import Etw, declare,", "class Microsoft_Windows_IPxlatCfg_1005_0(Etw): pattern = Struct( \"IPv4Address\" / Int32ul, \"IPv4Prefix\" /", "class Microsoft_Windows_IPxlatCfg_1007_0(Etw): pattern = Struct( \"InterfaceLuid\" / Int64ul, \"PrefixLength\" /", "Microsoft_Windows_IPxlatCfg_1102_0(Etw): pattern = Struct( \"InterfaceLuid\" / Int64ul, \"Metric\" / Int32ul,", "\"RemotePrefixLength\" / Int32ul, \"LocalPrefixLength\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1103, version=0)", "Int64ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1010, version=0) class Microsoft_Windows_IPxlatCfg_1010_0(Etw): pattern = Struct(", "Struct( \"InfoString\" / CString, \"MTU\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1101,", "= Struct( \"InterfaceLuid\" / Int64ul, \"Metric\" / Int32ul, \"RemotePrefixLength\" /", "Int32ul, \"RemotePrefixLength\" / Int32ul, \"LocalPrefixLength\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1103,", "Int64ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1003, version=0) class Microsoft_Windows_IPxlatCfg_1003_0(Etw): pattern = Struct(", "import Int8sl, Int8ul, Int16ul, Int16sl, Int32sl, Int32ul, Int64sl, Int64ul, Bytes,", "pattern = Struct( \"InfoString\" / CString ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1005, version=0)", "= Struct( \"InterfaceLuid\" / Int64ul, \"IPv4Address\" / Int32ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"),", "utf-8 -*- \"\"\" Microsoft-Windows-IPxlatCfg GUID : 3e5ac668-af52-4c15-b99b-a3e7a6616ebd \"\"\" from construct", "Int64sl, Int64ul, Bytes, Double, Float32l, Struct from etl.utils import WString,", "event_id=1102, version=0) class Microsoft_Windows_IPxlatCfg_1102_0(Etw): pattern = Struct( \"InterfaceLuid\" / Int64ul,", "event_id=1103, version=0) class Microsoft_Windows_IPxlatCfg_1103_0(Etw): pattern = Struct( \"InterfaceLuid\" / Int64ul,", "version=0) class Microsoft_Windows_IPxlatCfg_1007_0(Etw): pattern = Struct( \"InterfaceLuid\" / Int64ul, \"PrefixLength\"", "class Microsoft_Windows_IPxlatCfg_1102_0(Etw): pattern = Struct( \"InterfaceLuid\" / Int64ul, \"Metric\" /", "etl.dtyp import Sid from etl.parsers.etw.core import Etw, declare, guid @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"),", "Microsoft_Windows_IPxlatCfg_1008_0(Etw): pattern = Struct( \"InterfaceLuid\" / Int64ul, \"IPv4Address\" / Int32ul", "Int64ul ) @declare(guid=guid(\"3e5ac668-af52-4c15-b99b-a3e7a6616ebd\"), event_id=1011, version=0) class Microsoft_Windows_IPxlatCfg_1011_0(Etw): pattern = Struct(" ]
[ "import strtobool class Config: DEBUG = bool(strtobool(os.getenv('DEBUG', \"False\"))) DATABASE_URI =", "WORKERS = int(os.getenv('WORKERS', 2)) LOGO = os.getenv('LOGO', None) HOST =", "bool(strtobool(os.getenv('DEBUG', \"False\"))) DATABASE_URI = os.getenv('DATABASE_URI', '127.0.0.1:27017') WORKERS = int(os.getenv('WORKERS', 2))", "int(os.getenv('WORKERS', 2)) LOGO = os.getenv('LOGO', None) HOST = os.getenv('HOST', '127.0.0.1')", "= os.getenv('LOGO', None) HOST = os.getenv('HOST', '127.0.0.1') PORT = int(os.getenv('PORT',", "None) HOST = os.getenv('HOST', '127.0.0.1') PORT = int(os.getenv('PORT', 8000)) SECRET", "DATABASE_URI = os.getenv('DATABASE_URI', '127.0.0.1:27017') WORKERS = int(os.getenv('WORKERS', 2)) LOGO =", "os from distutils.util import strtobool class Config: DEBUG = bool(strtobool(os.getenv('DEBUG',", "8000)) SECRET = os.getenv('SECRET', 'secret') LOGIN_MIN_LENGTH = int(os.getenv('LOGIN_MIN_LENGTH', 1)) LOGIN_MAX_LENGTH", "2)) LOGO = os.getenv('LOGO', None) HOST = os.getenv('HOST', '127.0.0.1') PORT", "utf-8 -*- import os from distutils.util import strtobool class Config:", "= int(os.getenv('WORKERS', 2)) LOGO = os.getenv('LOGO', None) HOST = os.getenv('HOST',", "= os.getenv('DATABASE_URI', '127.0.0.1:27017') WORKERS = int(os.getenv('WORKERS', 2)) LOGO = os.getenv('LOGO',", "os.getenv('SECRET', 'secret') LOGIN_MIN_LENGTH = int(os.getenv('LOGIN_MIN_LENGTH', 1)) LOGIN_MAX_LENGTH = int(os.getenv('LOGIN_MAX_LENGTH', 32))", "coding: utf-8 -*- import os from distutils.util import strtobool class", "HOST = os.getenv('HOST', '127.0.0.1') PORT = int(os.getenv('PORT', 8000)) SECRET =", "= os.getenv('SECRET', 'secret') LOGIN_MIN_LENGTH = int(os.getenv('LOGIN_MIN_LENGTH', 1)) LOGIN_MAX_LENGTH = int(os.getenv('LOGIN_MAX_LENGTH',", "<reponame>Levakin/sanic-test-app # -*- coding: utf-8 -*- import os from distutils.util", "import os from distutils.util import strtobool class Config: DEBUG =", "-*- coding: utf-8 -*- import os from distutils.util import strtobool", "PORT = int(os.getenv('PORT', 8000)) SECRET = os.getenv('SECRET', 'secret') LOGIN_MIN_LENGTH =", "-*- import os from distutils.util import strtobool class Config: DEBUG", "Config: DEBUG = bool(strtobool(os.getenv('DEBUG', \"False\"))) DATABASE_URI = os.getenv('DATABASE_URI', '127.0.0.1:27017') WORKERS", "= os.getenv('HOST', '127.0.0.1') PORT = int(os.getenv('PORT', 8000)) SECRET = os.getenv('SECRET',", "= int(os.getenv('PORT', 8000)) SECRET = os.getenv('SECRET', 'secret') LOGIN_MIN_LENGTH = int(os.getenv('LOGIN_MIN_LENGTH',", "int(os.getenv('PORT', 8000)) SECRET = os.getenv('SECRET', 'secret') LOGIN_MIN_LENGTH = int(os.getenv('LOGIN_MIN_LENGTH', 1))", "\"False\"))) DATABASE_URI = os.getenv('DATABASE_URI', '127.0.0.1:27017') WORKERS = int(os.getenv('WORKERS', 2)) LOGO", "os.getenv('DATABASE_URI', '127.0.0.1:27017') WORKERS = int(os.getenv('WORKERS', 2)) LOGO = os.getenv('LOGO', None)", "strtobool class Config: DEBUG = bool(strtobool(os.getenv('DEBUG', \"False\"))) DATABASE_URI = os.getenv('DATABASE_URI',", "DEBUG = bool(strtobool(os.getenv('DEBUG', \"False\"))) DATABASE_URI = os.getenv('DATABASE_URI', '127.0.0.1:27017') WORKERS =", "os.getenv('LOGO', None) HOST = os.getenv('HOST', '127.0.0.1') PORT = int(os.getenv('PORT', 8000))", "class Config: DEBUG = bool(strtobool(os.getenv('DEBUG', \"False\"))) DATABASE_URI = os.getenv('DATABASE_URI', '127.0.0.1:27017')", "'127.0.0.1') PORT = int(os.getenv('PORT', 8000)) SECRET = os.getenv('SECRET', 'secret') LOGIN_MIN_LENGTH", "from distutils.util import strtobool class Config: DEBUG = bool(strtobool(os.getenv('DEBUG', \"False\")))", "= bool(strtobool(os.getenv('DEBUG', \"False\"))) DATABASE_URI = os.getenv('DATABASE_URI', '127.0.0.1:27017') WORKERS = int(os.getenv('WORKERS',", "LOGO = os.getenv('LOGO', None) HOST = os.getenv('HOST', '127.0.0.1') PORT =", "SECRET = os.getenv('SECRET', 'secret') LOGIN_MIN_LENGTH = int(os.getenv('LOGIN_MIN_LENGTH', 1)) LOGIN_MAX_LENGTH =", "'127.0.0.1:27017') WORKERS = int(os.getenv('WORKERS', 2)) LOGO = os.getenv('LOGO', None) HOST", "os.getenv('HOST', '127.0.0.1') PORT = int(os.getenv('PORT', 8000)) SECRET = os.getenv('SECRET', 'secret')", "distutils.util import strtobool class Config: DEBUG = bool(strtobool(os.getenv('DEBUG', \"False\"))) DATABASE_URI", "# -*- coding: utf-8 -*- import os from distutils.util import" ]
[ "y : y, z: z, }} const = lambda x,", "\\y -> x; y <- const #true #true; z <-", "const <- \\x -> \\y -> x; y <- const", "# CHECK-TREE: { const <- \\x -> \\y -> x;", "const #true #true; z <- const #false #false; #record {", "y, z: z, }} const = lambda x, y: x", "const, y : y, z: z, }} const = lambda", "x, y: x y = const(True, True) z = const(False,", "{ const <- \\x -> \\y -> x; y <-", "<reponame>Temurson/semantic<gh_stars>1000+ # CHECK-TREE: { const <- \\x -> \\y ->", "<- \\x -> \\y -> x; y <- const #true", "#true; z <- const #false #false; #record { const: const,", "-> \\y -> x; y <- const #true #true; z", "-> x; y <- const #true #true; z <- const", "lambda x, y: x y = const(True, True) z =", ": y, z: z, }} const = lambda x, y:", "CHECK-TREE: { const <- \\x -> \\y -> x; y", "\\x -> \\y -> x; y <- const #true #true;", "#true #true; z <- const #false #false; #record { const:", "z, }} const = lambda x, y: x y =", "= lambda x, y: x y = const(True, True) z", "#false; #record { const: const, y : y, z: z,", "z: z, }} const = lambda x, y: x y", "#false #false; #record { const: const, y : y, z:", "z <- const #false #false; #record { const: const, y", "const = lambda x, y: x y = const(True, True)", "x; y <- const #true #true; z <- const #false", "y: x y = const(True, True) z = const(False, False)", "y <- const #true #true; z <- const #false #false;", "#record { const: const, y : y, z: z, }}", "const: const, y : y, z: z, }} const =", "<- const #true #true; z <- const #false #false; #record", "const #false #false; #record { const: const, y : y,", "}} const = lambda x, y: x y = const(True,", "{ const: const, y : y, z: z, }} const", "<- const #false #false; #record { const: const, y :" ]
[ "- train_op: function used to get the right parameters to", "image_input) #-------------------------- # MAIN #-------------------------- if __name__ == \"__main__\": run_tests()", "project_tests as tests #-------------------------- # USER-SPECIFIED DATA #-------------------------- # Tune", "higher accuracy logits, train_op, cross_entropy_loss = optimize(model_output, correct_label, learning_rate, NUMBER_OF_CLASSES)", "# The resulting network architecture from adding a decoder on", "#-------------------------- # MAIN #-------------------------- if __name__ == \"__main__\": run_tests() run()", "model if we can't find it where it should be", "top of the given vgg model model_output = layers(layer3, layer4,", "run(): \"\"\" Run a train a model and save output", "a GPU if not tf.test.gpu_device_name(): warnings.warn('No GPU found. Please use", "all_training_losses.append(training_loss) print(\"------------------\") print(\"epoch: \", epoch + 1, \" of \",", "= tf.placeholder(tf.float32, [None, IMAGE_SHAPE[0], IMAGE_SHAPE[1], NUMBER_OF_CLASSES]) learning_rate = tf.placeholder(tf.float32) keep_prob", "kernel_size = (1, 1), strides = (1, 1), name =", "layer_name = \"layer4conv1x1\") layer7x = conv_1x1(layer = layer7, layer_name =", "Note: the kernel size and strides are the same as", "conv_1x1(layer = layer4, layer_name = \"layer4conv1x1\") layer7x = conv_1x1(layer =", "(-1, num_classes)) class_labels = tf.reshape(correct_label, (-1, num_classes)) # The cross_entropy_loss", "} _, partial_loss = sess.run([train_op, cross_entropy_loss], feed_dict = feed) print(\"--->", "/ len(losses) all_training_losses.append(training_loss) print(\"------------------\") print(\"epoch: \", epoch + 1, \"", "layer_name = \"decoderlayer1\") decoderlayer2 = tf.add(decoderlayer1, layer4x, name = \"decoderlayer2\")", "label image learning_rate: TF Placeholder for the learning rate num_classes:", "= class_labels) cross_entropy_loss = tf.reduce_mean(cross_entropy) # The model implements this", "to visualize if our training is going well given parameters", "Run the model with the test images and save each", ">= LooseVersion('1.0'), 'Please use TensorFlow version 1.0 or newer. You", "4, s = 2, layer_name = \"decoderlayer3\") decoderlayer4 = tf.add(decoderlayer3,", "def load_vgg(sess, vgg_path): \"\"\" Load Pretrained VGG Model into TensorFlow.", "input_image: images, correct_label: labels, keep_prob: DROPOUT, learning_rate: LEARNING_RATE } _,", "# Note: the kernel size and strides are the same", "helper.maybe_download_pretrained_vgg(DATA_DIRECTORY) # A function to get batches get_batches_fn = helper.gen_batch_function(TRAINING_DATA_DIRECTORY,", "class_labels) cross_entropy_loss = tf.reduce_mean(cross_entropy) # The model implements this operation", "vgg_layerX_out: TF Tensor for VGG Layer X output num_classes: Number", "feed_dict = feed) print(\"---> iteration: \", i, \" partial loss:\",", "a class # - train_op: function used to get the", "return: Tuple of Tensors from VGG model (image_input, keep_prob, layer3,", "in get_batches_fn(BATCH_SIZE): i += 1 feed = { input_image: images,", "session, IMAGE_SHAPE, logits, keep_prob, image_input) #-------------------------- # MAIN #-------------------------- if", "a shorter variable name for simplicity layer3, layer4, layer7 =", "GPU if not tf.test.gpu_device_name(): warnings.warn('No GPU found. Please use a", "batch_size: Batch size get_batches_fn: Function to get batches of training", "# Run the model with the test images and save", "tf.Session() as session: # Returns the three layers, keep probability", "[], 0 for images, labels in get_batches_fn(BATCH_SIZE): i += 1", "# The model implements this operation to find the weights/parameters", "training. sess: TF Session epochs: Number of epochs batch_size: Batch", "training_loss = sum(losses) / len(losses) all_training_losses.append(training_loss) print(\"------------------\") print(\"epoch: \", epoch", "= tf.nn.softmax_cross_entropy_with_logits(logits = logits, labels = class_labels) cross_entropy_loss = tf.reduce_mean(cross_entropy)", "filters = NUMBER_OF_CLASSES, kernel_size = (1, 1), strides = (1,", "Please use a GPU to train your neural network.') else:", "test images and save each painted output image (roads painted", "and optimizer operations. nn_last_layer: TF Tensor of the last layer", "= \"layer4conv1x1\") layer7x = conv_1x1(layer = layer7, layer_name = \"layer7conv1x1\")", "labels in get_batches_fn(BATCH_SIZE): i += 1 feed = { input_image:", "as tf import os.path import warnings from distutils.version import LooseVersion", "tensorflow as tf import os.path import warnings from distutils.version import", "and \"saved_model.pb\" return: Tuple of Tensors from VGG model (image_input,", "The Tensor for the last layer of output \"\"\" #", "= 2, layer_name = \"decoderlayer3\") decoderlayer4 = tf.add(decoderlayer3, layer3x, name", "decoderlayer2 = tf.add(decoderlayer1, layer4x, name = \"decoderlayer2\") decoderlayer3 = upsample(layer", "print(\"---> iteration: \", i, \" partial loss:\", partial_loss) losses.append(partial_loss) training_loss", "labels, keep_prob: DROPOUT, learning_rate: LEARNING_RATE } _, partial_loss = sess.run([train_op,", "save output images resulting from the test image fed on", "learning_rate = tf.placeholder(tf.float32) keep_prob = tf.placeholder(tf.float32) #-------------------------- # FUNCTIONS #--------------------------", "Tune these parameters NUMBER_OF_CLASSES = 2 IMAGE_SHAPE = (160, 576)", "(image_input, keep_prob, layer3, layer4, layer7) \"\"\" # load the model", "= decoderlayer4, k = 16, s = 8, layer_name =", "accuracy cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits = logits, labels = class_labels) cross_entropy_loss", "\"\"\" # Get vgg model if we can't find it", "VGG Model into TensorFlow. sess: TensorFlow Session vgg_path: Path to", "skip connections and upsampling # Note: the kernel size and", "GPU found. Please use a GPU to train your neural", "vgg architecture image_input, keep_prob, layer3, layer4, layer7 = load_vgg(session, VGG_PATH)", "epochs batch_size: Batch size get_batches_fn: Function to get batches of", "# USER-SPECIFIED DATA #-------------------------- # Tune these parameters NUMBER_OF_CLASSES =", "model_output = layers(layer3, layer4, layer7, NUMBER_OF_CLASSES) # Returns the output", "session.run(tf.local_variables_initializer()) # Train the neural network train_nn(session, EPOCHS, BATCH_SIZE, get_batches_fn,", "padding = 'same', name = layer_name) def layers(vgg_layer3_out, vgg_layer4_out, vgg_layer7_out,", "= tf.train.AdamOptimizer(learning_rate).minimize(cross_entropy_loss) return logits, train_op, cross_entropy_loss def train_nn(sess, epochs, batch_size,", "network architecture from adding a decoder on top of the", "cost operation to be used # - logits: each row", "cost should yield higher accuracy logits, train_op, cross_entropy_loss = optimize(model_output,", "import helper import project_tests as tests #-------------------------- # USER-SPECIFIED DATA", "Use a shorter variable name for simplicity layer3, layer4, layer7", "print('Default GPU Device: {}'.format(tf.test.gpu_device_name())) #-------------------------- # PLACEHOLDER TENSORS #-------------------------- correct_label", "minimize to yield higher accuracy cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits = logits,", "layers(vgg_layer3_out, vgg_layer4_out, vgg_layer7_out, num_classes = NUMBER_OF_CLASSES): \"\"\" Create the layers", "tf.placeholder(tf.float32) keep_prob = tf.placeholder(tf.float32) #-------------------------- # FUNCTIONS #-------------------------- def load_vgg(sess,", "and weights model = tf.saved_model.loader.load(sess, ['vgg16'], vgg_path) # Get Tensors", "network.') else: print('Default GPU Device: {}'.format(tf.test.gpu_device_name())) #-------------------------- # PLACEHOLDER TENSORS", "TF Tensor for the amount of loss input_image: TF Placeholder", "and cost operation to be used # - logits: each", "and print out the loss during training. sess: TF Session", "network with skip connections and upsampling # Note: the kernel", "import warnings from distutils.version import LooseVersion import glob import helper", "# PLACEHOLDER TENSORS #-------------------------- correct_label = tf.placeholder(tf.float32, [None, IMAGE_SHAPE[0], IMAGE_SHAPE[1],", "= tf.add(decoderlayer1, layer4x, name = \"decoderlayer2\") decoderlayer3 = upsample(layer =", "image (roads painted green) helper.save_inference_samples(RUNS_DIRECTORY, DATA_DIRECTORY, session, IMAGE_SHAPE, logits, keep_prob,", "correct_label, learning_rate, NUMBER_OF_CLASSES) # Initialize all variables session.run(tf.global_variables_initializer()) session.run(tf.local_variables_initializer()) #", "from the test image fed on the trained model print(all_training_losses)", "for the learning rate num_classes: Number of classes to classify", "to get batches get_batches_fn = helper.gen_batch_function(TRAINING_DATA_DIRECTORY, IMAGE_SHAPE) with tf.Session() as", "[None, IMAGE_SHAPE[0], IMAGE_SHAPE[1], NUMBER_OF_CLASSES]) learning_rate = tf.placeholder(tf.float32) keep_prob = tf.placeholder(tf.float32)", "for simplicity layer3, layer4, layer7 = vgg_layer3_out, vgg_layer4_out, vgg_layer7_out #", "images, correct_label: labels, keep_prob: DROPOUT, learning_rate: LEARNING_RATE } _, partial_loss", "for images, labels in get_batches_fn(BATCH_SIZE): i += 1 feed =", "correct_label: TF Placeholder for the correct label image learning_rate: TF", "= layers(layer3, layer4, layer7, NUMBER_OF_CLASSES) # Returns the output logits,", "to minimize to yield higher accuracy cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits =", "layer7 = load_vgg(session, VGG_PATH) # The resulting network architecture from", "= 1 LEARNING_RATE = 0.0001 DROPOUT = 0.75 # Specify", "layer4 = graph.get_tensor_by_name('layer4_out:0') layer7 = graph.get_tensor_by_name('layer7_out:0') return image_input, keep_prob, layer3,", "s \"\"\" return tf.layers.conv2d_transpose(inputs = layer, filters = NUMBER_OF_CLASSES, kernel_size", "- logits: each row represents a pixel, each column a", "print('TensorFlow Version: {}'.format(tf.__version__)) # Check for a GPU if not", "Check TensorFlow Version assert LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please use TensorFlow", "find the weights/parameters that would yield correct pixel labels train_op", "You are using {}'.format(tf.__version__) print('TensorFlow Version: {}'.format(tf.__version__)) # Check for", "layer4, layer7) \"\"\" # load the model and weights model", "implements this operation to find the weights/parameters that would yield", "from the vgg architecture image_input, keep_prob, layer3, layer4, layer7 =", "correct label image learning_rate: TF Placeholder for the learning rate", "each column a class logits = tf.reshape(nn_last_layer, (-1, num_classes)) class_labels", "model and save output images resulting from the test image", "for plotting to visualize if our training is going well", "= tf.reshape(correct_label, (-1, num_classes)) # The cross_entropy_loss is the cost", "\", i, \" partial loss:\", partial_loss) losses.append(partial_loss) training_loss = sum(losses)", "keep_prob, layer3, layer4, layer7 = load_vgg(session, VGG_PATH) # The resulting", "= conv_1x1(layer = layer3, layer_name = \"layer3conv1x1\") layer4x = conv_1x1(layer", "# A function to get batches get_batches_fn = helper.gen_batch_function(TRAINING_DATA_DIRECTORY, IMAGE_SHAPE)", "# Returns the three layers, keep probability and input layer", "len(glob.glob('./data/data_road/training/calib/*.*')) VGG_PATH = './data/vgg' all_training_losses = [] # Used for", "Create the layers for a fully convolutional network. Build skip-layers", "learning_rate) # Run the model with the test images and", "nn_last_layer: TF Tensor of the last layer in the neural", "train_op: function used to get the right parameters to the", "TF Session epochs: Number of epochs batch_size: Batch size get_batches_fn:", "tf.placeholder(tf.float32, [None, IMAGE_SHAPE[0], IMAGE_SHAPE[1], NUMBER_OF_CLASSES]) learning_rate = tf.placeholder(tf.float32) keep_prob =", "= \"layer7conv1x1\") # Add decoder layers to the network with", "correct pixel labels train_op = tf.train.AdamOptimizer(learning_rate).minimize(cross_entropy_loss) return logits, train_op, cross_entropy_loss", "as tests #-------------------------- # USER-SPECIFIED DATA #-------------------------- # Tune these", "# Add decoder layers to the network with skip connections", "layer3 = graph.get_tensor_by_name('layer3_out:0') layer4 = graph.get_tensor_by_name('layer4_out:0') layer7 = graph.get_tensor_by_name('layer7_out:0') return", "layer_name = \"layer3conv1x1\") layer4x = conv_1x1(layer = layer4, layer_name =", "the output of a 1x1 convolution of a layer \"\"\"", "get batches get_batches_fn = helper.gen_batch_function(TRAINING_DATA_DIRECTORY, IMAGE_SHAPE) with tf.Session() as session:", "network train_nn(session, EPOCHS, BATCH_SIZE, get_batches_fn, train_op, cross_entropy_loss, image_input, correct_label, keep_prob,", "correct_label, learning_rate, num_classes = NUMBER_OF_CLASSES): \"\"\" Build the TensorFLow loss", "size get_batches_fn: Function to get batches of training data. Call", "TensorFLow loss and optimizer operations. nn_last_layer: TF Tensor of the", "learning_rate: TF Placeholder for learning rate \"\"\" for epoch in", "graph graph = tf.get_default_graph() image_input = graph.get_tensor_by_name('image_input:0') keep_prob = graph.get_tensor_by_name('keep_prob:0')", "logits, training operation and cost operation to be used #", "k, s, layer_name): \"\"\" Return the output of transpose convolution", "example in Udacity Lectures # Semantic Segmentation Scene Understanding Lesson", "name for simplicity layer3, layer4, layer7 = vgg_layer3_out, vgg_layer4_out, vgg_layer7_out", "= feed) print(\"---> iteration: \", i, \" partial loss:\", partial_loss)", "labels = class_labels) cross_entropy_loss = tf.reduce_mean(cross_entropy) # The model implements", "the vgg layers. vgg_layerX_out: TF Tensor for VGG Layer X", "using the vgg layers. vgg_layerX_out: TF Tensor for VGG Layer", "newer. You are using {}'.format(tf.__version__) print('TensorFlow Version: {}'.format(tf.__version__)) # Check", "Load Pretrained VGG Model into TensorFlow. sess: TensorFlow Session vgg_path:", "name = layer_name) def upsample(layer, k, s, layer_name): \"\"\" Return", "= len(glob.glob('./data/data_road/training/calib/*.*')) VGG_PATH = './data/vgg' all_training_losses = [] # Used", "'./data/vgg' all_training_losses = [] # Used for plotting to visualize", "= layer3, layer_name = \"layer3conv1x1\") layer4x = conv_1x1(layer = layer4,", "num_classes)) # The cross_entropy_loss is the cost which we are", "The model implements this operation to find the weights/parameters that", "function outputting the cost which we are minimizing, lower cost", "right parameters to the model to correctly label the pixels", "Tuple of (logits, train_op, cross_entropy_loss) \"\"\" # Reshape 4D tensors", "TF Operation to train the neural network cross_entropy_loss: TF Tensor", "tf import os.path import warnings from distutils.version import LooseVersion import", "the model and weights model = tf.saved_model.loader.load(sess, ['vgg16'], vgg_path) #", "= './data/vgg' all_training_losses = [] # Used for plotting to", "\"layer4conv1x1\") layer7x = conv_1x1(layer = layer7, layer_name = \"layer7conv1x1\") #", "Tensor for the last layer of output \"\"\" # Use", "16, s = 8, layer_name = \"decoderlayer_output\") return decoderlayer_output def", "we are minimizing, lower cost should yield higher accuracy logits,", "= upsample(layer = layer7x, k = 4, s = 2,", "layer, filters = NUMBER_OF_CLASSES, kernel_size = (1, 1), strides =", "TF Placeholder for the learning rate num_classes: Number of classes", "Tensor of the last layer in the neural network correct_label:", "tensors to 2D, each row represents a pixel, each column", "#-------------------------- # USER-SPECIFIED DATA #-------------------------- # Tune these parameters NUMBER_OF_CLASSES", "8, layer_name = \"decoderlayer_output\") return decoderlayer_output def optimize(nn_last_layer, correct_label, learning_rate,", "a fully convolutional network. Build skip-layers using the vgg layers.", "= layer, filters = NUMBER_OF_CLASSES, kernel_size = (k, k), strides", "these directory paths DATA_DIRECTORY = './data' RUNS_DIRECTORY = './runs' TRAINING_DATA_DIRECTORY", "# Run a train a model and save output images", "the output logits, training operation and cost operation to be", "input_image, correct_label, keep_prob, learning_rate): \"\"\" Train neural network and print", "1x1 convolution of a layer \"\"\" return tf.layers.conv2d(inputs = layer,", "keep_prob, layer3, layer4, layer7 def conv_1x1(layer, layer_name): \"\"\" Return the", "classes to classify return: The Tensor for the last layer", "= load_vgg(session, VGG_PATH) # The resulting network architecture from adding", "cross_entropy_loss = optimize(model_output, correct_label, learning_rate, NUMBER_OF_CLASSES) # Initialize all variables", "in range(EPOCHS): losses, i = [], 0 for images, labels", "the last layer of output \"\"\" # Use a shorter", "and save output images resulting from the test image fed", "decoderlayer4 = tf.add(decoderlayer3, layer3x, name = \"decoderlayer4\") decoderlayer_output = upsample(layer", "resulting from the test image fed on the trained model", "(roads painted green) helper.save_inference_samples(RUNS_DIRECTORY, DATA_DIRECTORY, session, IMAGE_SHAPE, logits, keep_prob, image_input)", "# load the model and weights model = tf.saved_model.loader.load(sess, ['vgg16'],", "layer_name) def upsample(layer, k, s, layer_name): \"\"\" Return the output", "not tf.test.gpu_device_name(): warnings.warn('No GPU found. Please use a GPU to", "of classes to classify return: Tuple of (logits, train_op, cross_entropy_loss)", "logits, keep_prob, image_input) #-------------------------- # MAIN #-------------------------- if __name__ ==", "directory paths DATA_DIRECTORY = './data' RUNS_DIRECTORY = './runs' TRAINING_DATA_DIRECTORY ='./data/data_road/training'", "helper import project_tests as tests #-------------------------- # USER-SPECIFIED DATA #--------------------------", "version 1.0 or newer. You are using {}'.format(tf.__version__) print('TensorFlow Version:", "= layer_name) def layers(vgg_layer3_out, vgg_layer4_out, vgg_layer7_out, num_classes = NUMBER_OF_CLASSES): \"\"\"", "layer3, layer4, layer7 = vgg_layer3_out, vgg_layer4_out, vgg_layer7_out # Apply a", "= './runs' TRAINING_DATA_DIRECTORY ='./data/data_road/training' NUMBER_OF_IMAGES = len(glob.glob('./data/data_road/training/calib/*.*')) VGG_PATH = './data/vgg'", "this operation to find the weights/parameters that would yield correct", "weights model = tf.saved_model.loader.load(sess, ['vgg16'], vgg_path) # Get Tensors to", "as the example in Udacity Lectures # Semantic Segmentation Scene", "optimizer operations. nn_last_layer: TF Tensor of the last layer in", "decoderlayer_output = upsample(layer = decoderlayer4, k = 16, s =", "tf.nn.softmax_cross_entropy_with_logits(logits = logits, labels = class_labels) cross_entropy_loss = tf.reduce_mean(cross_entropy) #", "the model with the test images and save each painted", "else: print('Default GPU Device: {}'.format(tf.test.gpu_device_name())) #-------------------------- # PLACEHOLDER TENSORS #--------------------------", "output logits, training operation and cost operation to be used", "where it should be helper.maybe_download_pretrained_vgg(DATA_DIRECTORY) # A function to get", "a decoder on top of the given vgg model model_output", "decoder on top of the given vgg model model_output =", "{}'.format(tf.test.gpu_device_name())) #-------------------------- # PLACEHOLDER TENSORS #-------------------------- correct_label = tf.placeholder(tf.float32, [None,", "# MAIN #-------------------------- if __name__ == \"__main__\": run_tests() run() #", "VGG_PATH) # The resulting network architecture from adding a decoder", "Segmentation Scene Understanding Lesson 10-9: FCN-8 - Decoder decoderlayer1 =", "tf.test.gpu_device_name(): warnings.warn('No GPU found. Please use a GPU to train", "parameters #-------------------------- # DEPENDENCY CHECK #-------------------------- # Check TensorFlow Version", "learning rate num_classes: Number of classes to classify return: Tuple", "use TensorFlow version 1.0 or newer. You are using {}'.format(tf.__version__)", "paths DATA_DIRECTORY = './data' RUNS_DIRECTORY = './runs' TRAINING_DATA_DIRECTORY ='./data/data_road/training' NUMBER_OF_IMAGES", "loss and optimizer operations. nn_last_layer: TF Tensor of the last", "training_loss) print(\"------------------\") def run_tests(): tests.test_layers(layers) tests.test_optimize(optimize) tests.test_for_kitti_dataset(DATA_DIRECTORY) tests.test_train_nn(train_nn) def run():", "layer7) \"\"\" # load the model and weights model =", "for the correct label image learning_rate: TF Placeholder for the", "in the neural network correct_label: TF Placeholder for the correct", "epochs: Number of epochs batch_size: Batch size get_batches_fn: Function to", "the test image fed on the trained model \"\"\" #", "Lectures # Semantic Segmentation Scene Understanding Lesson 10-9: FCN-8 -", "keep probability and input layer from the vgg architecture image_input,", "layer7 = vgg_layer3_out, vgg_layer4_out, vgg_layer7_out # Apply a 1x1 convolution", "\"__main__\": run_tests() run() # Run a train a model and", "LooseVersion import glob import helper import project_tests as tests #--------------------------", "\"decoderlayer3\") decoderlayer4 = tf.add(decoderlayer3, layer3x, name = \"decoderlayer4\") decoderlayer_output =", "(k, k), strides = (s, s), padding = 'same', name", "Tensor for VGG Layer X output num_classes: Number of classes", "\"\"\" Train neural network and print out the loss during", "for learning rate \"\"\" for epoch in range(EPOCHS): losses, i", "MAIN #-------------------------- if __name__ == \"__main__\": run_tests() run() # Run", "visualize if our training is going well given parameters #--------------------------", "partial_loss = sess.run([train_op, cross_entropy_loss], feed_dict = feed) print(\"---> iteration: \",", "decoder layers to the network with skip connections and upsampling", "to classify return: Tuple of (logits, train_op, cross_entropy_loss) \"\"\" #", "batch_size, get_batches_fn, train_op, cross_entropy_loss, input_image, correct_label, keep_prob, learning_rate): \"\"\" Train", "# Used for plotting to visualize if our training is", "Returns the three layers, keep probability and input layer from", "the example in Udacity Lectures # Semantic Segmentation Scene Understanding", "train_nn(sess, epochs, batch_size, get_batches_fn, train_op, cross_entropy_loss, input_image, correct_label, keep_prob, learning_rate):", "tf.layers.conv2d(inputs = layer, filters = NUMBER_OF_CLASSES, kernel_size = (1, 1),", "def upsample(layer, k, s, layer_name): \"\"\" Return the output of", "NUMBER_OF_CLASSES): \"\"\" Create the layers for a fully convolutional network.", "correct_label, keep_prob, learning_rate): \"\"\" Train neural network and print out", "Placeholder for learning rate \"\"\" for epoch in range(EPOCHS): losses,", "the trained model \"\"\" # Get vgg model if we", "\"decoderlayer2\") decoderlayer3 = upsample(layer = decoderlayer2, k = 4, s", "= (160, 576) EPOCHS = 20 BATCH_SIZE = 1 LEARNING_RATE", "X output num_classes: Number of classes to classify return: The", "Scene Understanding Lesson 10-9: FCN-8 - Decoder decoderlayer1 = upsample(layer", "sess: TF Session epochs: Number of epochs batch_size: Batch size", "losses.append(partial_loss) training_loss = sum(losses) / len(losses) all_training_losses.append(training_loss) print(\"------------------\") print(\"epoch: \",", "neural network train_nn(session, EPOCHS, BATCH_SIZE, get_batches_fn, train_op, cross_entropy_loss, image_input, correct_label,", "assert LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please use TensorFlow version 1.0 or", "print(\"------------------\") def run_tests(): tests.test_layers(layers) tests.test_optimize(optimize) tests.test_for_kitti_dataset(DATA_DIRECTORY) tests.test_train_nn(train_nn) def run(): \"\"\"", "\"\"\" Run a train a model and save output images", "0.75 # Specify these directory paths DATA_DIRECTORY = './data' RUNS_DIRECTORY", "feed = { input_image: images, correct_label: labels, keep_prob: DROPOUT, learning_rate:", "represents a pixel, each column a class # - train_op:", "tf.reduce_mean(cross_entropy) # The model implements this operation to find the", "Return the output of transpose convolution given kernel_size k and", "TF Tensor of the last layer in the neural network", "outputting the cost which we are minimizing, lower cost should", "keep_prob = graph.get_tensor_by_name('keep_prob:0') layer3 = graph.get_tensor_by_name('layer3_out:0') layer4 = graph.get_tensor_by_name('layer4_out:0') layer7", "Get Tensors to be returned from graph graph = tf.get_default_graph()", "keep_prob, layer3, layer4, layer7) \"\"\" # load the model and", "warnings from distutils.version import LooseVersion import glob import helper import", "distutils.version import LooseVersion import glob import helper import project_tests as", "each row represents a pixel, each column a class logits", "encoder layers layer3x = conv_1x1(layer = layer3, layer_name = \"layer3conv1x1\")", "= NUMBER_OF_CLASSES, kernel_size = (k, k), strides = (s, s),", "conv_1x1(layer = layer7, layer_name = \"layer7conv1x1\") # Add decoder layers", "TF Placeholder for input images correct_label: TF Placeholder for label", "using {}'.format(tf.__version__) print('TensorFlow Version: {}'.format(tf.__version__)) # Check for a GPU", "\", EPOCHS, \"training loss: \", training_loss) print(\"------------------\") def run_tests(): tests.test_layers(layers)", "# - cross_entropy_loss: function outputting the cost which we are", "DATA_DIRECTORY, session, IMAGE_SHAPE, logits, keep_prob, image_input) #-------------------------- # MAIN #--------------------------", "IMAGE_SHAPE[1], NUMBER_OF_CLASSES]) learning_rate = tf.placeholder(tf.float32) keep_prob = tf.placeholder(tf.float32) #-------------------------- #", "layer3x, name = \"decoderlayer4\") decoderlayer_output = upsample(layer = decoderlayer4, k", "= 16, s = 8, layer_name = \"decoderlayer_output\") return decoderlayer_output", "loss:\", partial_loss) losses.append(partial_loss) training_loss = sum(losses) / len(losses) all_training_losses.append(training_loss) print(\"------------------\")", "from graph graph = tf.get_default_graph() image_input = graph.get_tensor_by_name('image_input:0') keep_prob =", "plotting to visualize if our training is going well given", "def conv_1x1(layer, layer_name): \"\"\" Return the output of a 1x1", "helper.save_inference_samples(RUNS_DIRECTORY, DATA_DIRECTORY, session, IMAGE_SHAPE, logits, keep_prob, image_input) #-------------------------- # MAIN", "= conv_1x1(layer = layer4, layer_name = \"layer4conv1x1\") layer7x = conv_1x1(layer", "of the last layer in the neural network correct_label: TF", "which we are minimizing, lower cost should yield higher accuracy", "keep_prob, image_input) #-------------------------- # MAIN #-------------------------- if __name__ == \"__main__\":", "the test images and save each painted output image (roads", "conv_1x1(layer, layer_name): \"\"\" Return the output of a 1x1 convolution", "train_op, cross_entropy_loss, input_image, correct_label, keep_prob, learning_rate): \"\"\" Train neural network", "# The cross_entropy_loss is the cost which we are trying", "(1, 1), strides = (1, 1), name = layer_name) def", "pixel, each column a class logits = tf.reshape(nn_last_layer, (-1, num_classes))", "dropout keep probability learning_rate: TF Placeholder for learning rate \"\"\"", "from distutils.version import LooseVersion import glob import helper import project_tests", "well given parameters #-------------------------- # DEPENDENCY CHECK #-------------------------- # Check", "found. Please use a GPU to train your neural network.')", "to yield higher accuracy cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits = logits, labels", "IMAGE_SHAPE, logits, keep_prob, image_input) #-------------------------- # MAIN #-------------------------- if __name__", "decoderlayer4, k = 16, s = 8, layer_name = \"decoderlayer_output\")", "network. Build skip-layers using the vgg layers. vgg_layerX_out: TF Tensor", "cost which we are minimizing, lower cost should yield higher", "= layer, filters = NUMBER_OF_CLASSES, kernel_size = (1, 1), strides", "model model_output = layers(layer3, layer4, layer7, NUMBER_OF_CLASSES) # Returns the", "= \"decoderlayer1\") decoderlayer2 = tf.add(decoderlayer1, layer4x, name = \"decoderlayer2\") decoderlayer3", "a 1x1 convolution of a layer \"\"\" return tf.layers.conv2d(inputs =", "learning_rate, NUMBER_OF_CLASSES) # Initialize all variables session.run(tf.global_variables_initializer()) session.run(tf.local_variables_initializer()) # Train", "layer \"\"\" return tf.layers.conv2d(inputs = layer, filters = NUMBER_OF_CLASSES, kernel_size", "Build the TensorFLow loss and optimizer operations. nn_last_layer: TF Tensor", "NUMBER_OF_CLASSES, kernel_size = (1, 1), strides = (1, 1), name", "layer_name = \"decoderlayer_output\") return decoderlayer_output def optimize(nn_last_layer, correct_label, learning_rate, num_classes", "#-------------------------- # Check TensorFlow Version assert LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please", "filters = NUMBER_OF_CLASSES, kernel_size = (k, k), strides = (s,", "= 8, layer_name = \"decoderlayer_output\") return decoderlayer_output def optimize(nn_last_layer, correct_label,", "train_op, cross_entropy_loss) \"\"\" # Reshape 4D tensors to 2D, each", "= (k, k), strides = (s, s), padding = 'same',", "Get vgg model if we can't find it where it", "LEARNING_RATE } _, partial_loss = sess.run([train_op, cross_entropy_loss], feed_dict = feed)", "and upsampling # Note: the kernel size and strides are", "print out the loss during training. sess: TF Session epochs:", "NUMBER_OF_CLASSES) # Returns the output logits, training operation and cost", "run_tests(): tests.test_layers(layers) tests.test_optimize(optimize) tests.test_for_kitti_dataset(DATA_DIRECTORY) tests.test_train_nn(train_nn) def run(): \"\"\" Run a", "it where it should be helper.maybe_download_pretrained_vgg(DATA_DIRECTORY) # A function to", "fully convolutional network. Build skip-layers using the vgg layers. vgg_layerX_out:", "4D tensors to 2D, each row represents a pixel, each", "= graph.get_tensor_by_name('image_input:0') keep_prob = graph.get_tensor_by_name('keep_prob:0') layer3 = graph.get_tensor_by_name('layer3_out:0') layer4 =", "label images keep_prob: TF Placeholder for dropout keep probability learning_rate:", "tf.reshape(correct_label, (-1, num_classes)) # The cross_entropy_loss is the cost which", "probability learning_rate: TF Placeholder for learning rate \"\"\" for epoch", "the TensorFLow loss and optimizer operations. nn_last_layer: TF Tensor of", "- Decoder decoderlayer1 = upsample(layer = layer7x, k = 4,", "\"variables/\" and \"saved_model.pb\" return: Tuple of Tensors from VGG model", "model (image_input, keep_prob, layer3, layer4, layer7) \"\"\" # load the", "for a fully convolutional network. Build skip-layers using the vgg", "(logits, train_op, cross_entropy_loss) \"\"\" # Reshape 4D tensors to 2D,", "pixel labels train_op = tf.train.AdamOptimizer(learning_rate).minimize(cross_entropy_loss) return logits, train_op, cross_entropy_loss def", "\"\"\" return tf.layers.conv2d_transpose(inputs = layer, filters = NUMBER_OF_CLASSES, kernel_size =", "a 1x1 convolution to encoder layers layer3x = conv_1x1(layer =", "layer_name = \"decoderlayer3\") decoderlayer4 = tf.add(decoderlayer3, layer3x, name = \"decoderlayer4\")", "train a model and save output images resulting from the", "layer3, layer4, layer7 def conv_1x1(layer, layer_name): \"\"\" Return the output", "VGG Layer X output num_classes: Number of classes to classify", "# Specify these directory paths DATA_DIRECTORY = './data' RUNS_DIRECTORY =", "classify return: The Tensor for the last layer of output", "cross_entropy_loss) \"\"\" # Reshape 4D tensors to 2D, each row", "the correct label image learning_rate: TF Placeholder for the learning", "= [], 0 for images, labels in get_batches_fn(BATCH_SIZE): i +=", "TF Tensor for VGG Layer X output num_classes: Number of", "image_input, correct_label, keep_prob, learning_rate) # Run the model with the", "k = 4, s = 2, layer_name = \"decoderlayer3\") decoderlayer4", "train_op, cross_entropy_loss, image_input, correct_label, keep_prob, learning_rate) # Run the model", "epoch + 1, \" of \", EPOCHS, \"training loss: \",", "\"\"\" Create the layers for a fully convolutional network. Build", "operation to find the weights/parameters that would yield correct pixel", "a train a model and save output images resulting from", "cross_entropy_loss def train_nn(sess, epochs, batch_size, get_batches_fn, train_op, cross_entropy_loss, input_image, correct_label,", "painted green) helper.save_inference_samples(RUNS_DIRECTORY, DATA_DIRECTORY, session, IMAGE_SHAPE, logits, keep_prob, image_input) #--------------------------", "find it where it should be helper.maybe_download_pretrained_vgg(DATA_DIRECTORY) # A function", "vgg_path): \"\"\" Load Pretrained VGG Model into TensorFlow. sess: TensorFlow", "i = [], 0 for images, labels in get_batches_fn(BATCH_SIZE): i", "on the trained model \"\"\" # Get vgg model if", "1 LEARNING_RATE = 0.0001 DROPOUT = 0.75 # Specify these", "\"decoderlayer4\") decoderlayer_output = upsample(layer = decoderlayer4, k = 16, s", "GPU Device: {}'.format(tf.test.gpu_device_name())) #-------------------------- # PLACEHOLDER TENSORS #-------------------------- correct_label =", "_, partial_loss = sess.run([train_op, cross_entropy_loss], feed_dict = feed) print(\"---> iteration:", "= layer7x, k = 4, s = 2, layer_name =", "# Use a shorter variable name for simplicity layer3, layer4,", "= graph.get_tensor_by_name('layer7_out:0') return image_input, keep_prob, layer3, layer4, layer7 def conv_1x1(layer,", "last layer in the neural network correct_label: TF Placeholder for", "folder, containing \"variables/\" and \"saved_model.pb\" return: Tuple of Tensors from", "during training. sess: TF Session epochs: Number of epochs batch_size:", "graph = tf.get_default_graph() image_input = graph.get_tensor_by_name('image_input:0') keep_prob = graph.get_tensor_by_name('keep_prob:0') layer3", "the neural network train_nn(session, EPOCHS, BATCH_SIZE, get_batches_fn, train_op, cross_entropy_loss, image_input,", "run() # Run a train a model and save output", "4, s = 2, layer_name = \"decoderlayer1\") decoderlayer2 = tf.add(decoderlayer1,", "get_batches_fn, train_op, cross_entropy_loss, input_image, correct_label, keep_prob, learning_rate): \"\"\" Train neural", "operations. nn_last_layer: TF Tensor of the last layer in the", "convolution of a layer \"\"\" return tf.layers.conv2d(inputs = layer, filters", "Version assert LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please use TensorFlow version 1.0", "upsample(layer = decoderlayer4, k = 16, s = 8, layer_name", "layer3, layer4, layer7 = load_vgg(session, VGG_PATH) # The resulting network", "NUMBER_OF_CLASSES) # Initialize all variables session.run(tf.global_variables_initializer()) session.run(tf.local_variables_initializer()) # Train the", "TF Placeholder for dropout keep probability learning_rate: TF Placeholder for", "output images resulting from the test image fed on the", "using get_batches_fn(batch_size) train_op: TF Operation to train the neural network", "= \"decoderlayer3\") decoderlayer4 = tf.add(decoderlayer3, layer3x, name = \"decoderlayer4\") decoderlayer_output", "upsample(layer, k, s, layer_name): \"\"\" Return the output of transpose", "going well given parameters #-------------------------- # DEPENDENCY CHECK #-------------------------- #", "= \"layer3conv1x1\") layer4x = conv_1x1(layer = layer4, layer_name = \"layer4conv1x1\")", "yield higher accuracy cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits = logits, labels =", "Initialize all variables session.run(tf.global_variables_initializer()) session.run(tf.local_variables_initializer()) # Train the neural network", "cross_entropy_loss, image_input, correct_label, keep_prob, learning_rate) # Run the model with", "range(EPOCHS): losses, i = [], 0 for images, labels in", "num_classes = NUMBER_OF_CLASSES): \"\"\" Create the layers for a fully", "session.run(tf.global_variables_initializer()) session.run(tf.local_variables_initializer()) # Train the neural network train_nn(session, EPOCHS, BATCH_SIZE,", "tf.get_default_graph() image_input = graph.get_tensor_by_name('image_input:0') keep_prob = graph.get_tensor_by_name('keep_prob:0') layer3 = graph.get_tensor_by_name('layer3_out:0')", "logits, labels = class_labels) cross_entropy_loss = tf.reduce_mean(cross_entropy) # The model", "# Check for a GPU if not tf.test.gpu_device_name(): warnings.warn('No GPU", "num_classes)) class_labels = tf.reshape(correct_label, (-1, num_classes)) # The cross_entropy_loss is", "the same as the example in Udacity Lectures # Semantic", "#-------------------------- if __name__ == \"__main__\": run_tests() run() # Run a", "= optimize(model_output, correct_label, learning_rate, NUMBER_OF_CLASSES) # Initialize all variables session.run(tf.global_variables_initializer())", "#-------------------------- def load_vgg(sess, vgg_path): \"\"\" Load Pretrained VGG Model into", "input layer from the vgg architecture image_input, keep_prob, layer3, layer4,", "amount of loss input_image: TF Placeholder for input images correct_label:", "layer4, layer7 = vgg_layer3_out, vgg_layer4_out, vgg_layer7_out # Apply a 1x1", "Number of classes to classify return: The Tensor for the", "= NUMBER_OF_CLASSES, kernel_size = (1, 1), strides = (1, 1),", "Number of classes to classify return: Tuple of (logits, train_op,", "RUNS_DIRECTORY = './runs' TRAINING_DATA_DIRECTORY ='./data/data_road/training' NUMBER_OF_IMAGES = len(glob.glob('./data/data_road/training/calib/*.*')) VGG_PATH =", "strides = (s, s), padding = 'same', name = layer_name)", "= 4, s = 2, layer_name = \"decoderlayer1\") decoderlayer2 =", "= 2 IMAGE_SHAPE = (160, 576) EPOCHS = 20 BATCH_SIZE", "Layer X output num_classes: Number of classes to classify return:", "return logits, train_op, cross_entropy_loss def train_nn(sess, epochs, batch_size, get_batches_fn, train_op,", "keep probability learning_rate: TF Placeholder for learning rate \"\"\" for", "save each painted output image (roads painted green) helper.save_inference_samples(RUNS_DIRECTORY, DATA_DIRECTORY,", "layers, keep probability and input layer from the vgg architecture", "\"\"\" Return the output of transpose convolution given kernel_size k", "or newer. You are using {}'.format(tf.__version__) print('TensorFlow Version: {}'.format(tf.__version__)) #", "for a GPU if not tf.test.gpu_device_name(): warnings.warn('No GPU found. Please", "keep_prob, learning_rate): \"\"\" Train neural network and print out the", "#-------------------------- # FUNCTIONS #-------------------------- def load_vgg(sess, vgg_path): \"\"\" Load Pretrained", "given parameters #-------------------------- # DEPENDENCY CHECK #-------------------------- # Check TensorFlow", "IMAGE_SHAPE[0], IMAGE_SHAPE[1], NUMBER_OF_CLASSES]) learning_rate = tf.placeholder(tf.float32) keep_prob = tf.placeholder(tf.float32) #--------------------------", "train_op, cross_entropy_loss def train_nn(sess, epochs, batch_size, get_batches_fn, train_op, cross_entropy_loss, input_image,", "#-------------------------- # PLACEHOLDER TENSORS #-------------------------- correct_label = tf.placeholder(tf.float32, [None, IMAGE_SHAPE[0],", "# DEPENDENCY CHECK #-------------------------- # Check TensorFlow Version assert LooseVersion(tf.__version__)", "DATA #-------------------------- # Tune these parameters NUMBER_OF_CLASSES = 2 IMAGE_SHAPE", "DROPOUT = 0.75 # Specify these directory paths DATA_DIRECTORY =", "vgg_path: Path to vgg folder, containing \"variables/\" and \"saved_model.pb\" return:", "neural network correct_label: TF Placeholder for the correct label image", "Version: {}'.format(tf.__version__)) # Check for a GPU if not tf.test.gpu_device_name():", "and strides are the same as the example in Udacity", "yield correct pixel labels train_op = tf.train.AdamOptimizer(learning_rate).minimize(cross_entropy_loss) return logits, train_op,", "each row represents a pixel, each column a class #", "0.0001 DROPOUT = 0.75 # Specify these directory paths DATA_DIRECTORY", "lower cost should yield higher accuracy logits, train_op, cross_entropy_loss =", "== \"__main__\": run_tests() run() # Run a train a model", "= (1, 1), name = layer_name) def upsample(layer, k, s,", "output of a 1x1 convolution of a layer \"\"\" return", "= vgg_layer3_out, vgg_layer4_out, vgg_layer7_out # Apply a 1x1 convolution to", "tf.add(decoderlayer1, layer4x, name = \"decoderlayer2\") decoderlayer3 = upsample(layer = decoderlayer2,", "TF Placeholder for the correct label image learning_rate: TF Placeholder", "Batch size get_batches_fn: Function to get batches of training data.", "images keep_prob: TF Placeholder for dropout keep probability learning_rate: TF", "k and strides s \"\"\" return tf.layers.conv2d_transpose(inputs = layer, filters", "architecture from adding a decoder on top of the given", "if __name__ == \"__main__\": run_tests() run() # Run a train", "layers for a fully convolutional network. Build skip-layers using the", "= \"decoderlayer_output\") return decoderlayer_output def optimize(nn_last_layer, correct_label, learning_rate, num_classes =", "# Tune these parameters NUMBER_OF_CLASSES = 2 IMAGE_SHAPE = (160,", "return tf.layers.conv2d(inputs = layer, filters = NUMBER_OF_CLASSES, kernel_size = (1,", "to get the right parameters to the model to correctly", "from adding a decoder on top of the given vgg", "name = layer_name) def layers(vgg_layer3_out, vgg_layer4_out, vgg_layer7_out, num_classes = NUMBER_OF_CLASSES):", "\"\"\" # Reshape 4D tensors to 2D, each row represents", "weights/parameters that would yield correct pixel labels train_op = tf.train.AdamOptimizer(learning_rate).minimize(cross_entropy_loss)", "of the given vgg model model_output = layers(layer3, layer4, layer7,", "operation to be used # - logits: each row represents", "to correctly label the pixels # - cross_entropy_loss: function outputting", "learning rate \"\"\" for epoch in range(EPOCHS): losses, i =", "output image (roads painted green) helper.save_inference_samples(RUNS_DIRECTORY, DATA_DIRECTORY, session, IMAGE_SHAPE, logits,", "the neural network cross_entropy_loss: TF Tensor for the amount of", "for label images keep_prob: TF Placeholder for dropout keep probability", "optimize(model_output, correct_label, learning_rate, NUMBER_OF_CLASSES) # Initialize all variables session.run(tf.global_variables_initializer()) session.run(tf.local_variables_initializer())", "(160, 576) EPOCHS = 20 BATCH_SIZE = 1 LEARNING_RATE =", "GPU to train your neural network.') else: print('Default GPU Device:", "of transpose convolution given kernel_size k and strides s \"\"\"", "__name__ == \"__main__\": run_tests() run() # Run a train a", "\"layer7conv1x1\") # Add decoder layers to the network with skip", "learning_rate: LEARNING_RATE } _, partial_loss = sess.run([train_op, cross_entropy_loss], feed_dict =", "# Train the neural network train_nn(session, EPOCHS, BATCH_SIZE, get_batches_fn, train_op,", "= helper.gen_batch_function(TRAINING_DATA_DIRECTORY, IMAGE_SHAPE) with tf.Session() as session: # Returns the", "network and print out the loss during training. sess: TF", "batches of training data. Call using get_batches_fn(batch_size) train_op: TF Operation", "def optimize(nn_last_layer, correct_label, learning_rate, num_classes = NUMBER_OF_CLASSES): \"\"\" Build the", "len(losses) all_training_losses.append(training_loss) print(\"------------------\") print(\"epoch: \", epoch + 1, \" of", "function to get batches get_batches_fn = helper.gen_batch_function(TRAINING_DATA_DIRECTORY, IMAGE_SHAPE) with tf.Session()", "= layer7, layer_name = \"layer7conv1x1\") # Add decoder layers to", "kernel_size k and strides s \"\"\" return tf.layers.conv2d_transpose(inputs = layer,", "Return the output of a 1x1 convolution of a layer", "num_classes: Number of classes to classify return: Tuple of (logits,", "partial loss:\", partial_loss) losses.append(partial_loss) training_loss = sum(losses) / len(losses) all_training_losses.append(training_loss)", "the model to correctly label the pixels # - cross_entropy_loss:", "\"decoderlayer1\") decoderlayer2 = tf.add(decoderlayer1, layer4x, name = \"decoderlayer2\") decoderlayer3 =", "1, \" of \", EPOCHS, \"training loss: \", training_loss) print(\"------------------\")", "of output \"\"\" # Use a shorter variable name for", "decoderlayer3 = upsample(layer = decoderlayer2, k = 4, s =", "#-------------------------- # Tune these parameters NUMBER_OF_CLASSES = 2 IMAGE_SHAPE =", "of training data. Call using get_batches_fn(batch_size) train_op: TF Operation to", "tf.saved_model.loader.load(sess, ['vgg16'], vgg_path) # Get Tensors to be returned from", "return decoderlayer_output def optimize(nn_last_layer, correct_label, learning_rate, num_classes = NUMBER_OF_CLASSES): \"\"\"", "strides s \"\"\" return tf.layers.conv2d_transpose(inputs = layer, filters = NUMBER_OF_CLASSES,", "tests.test_for_kitti_dataset(DATA_DIRECTORY) tests.test_train_nn(train_nn) def run(): \"\"\" Run a train a model", "NUMBER_OF_CLASSES]) learning_rate = tf.placeholder(tf.float32) keep_prob = tf.placeholder(tf.float32) #-------------------------- # FUNCTIONS", "in Udacity Lectures # Semantic Segmentation Scene Understanding Lesson 10-9:", "to train your neural network.') else: print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))", "\"\"\" Build the TensorFLow loss and optimizer operations. nn_last_layer: TF", "given kernel_size k and strides s \"\"\" return tf.layers.conv2d_transpose(inputs =", "to get batches of training data. Call using get_batches_fn(batch_size) train_op:", "Placeholder for input images correct_label: TF Placeholder for label images", "which we are trying to minimize to yield higher accuracy", "resulting network architecture from adding a decoder on top of", "TRAINING_DATA_DIRECTORY ='./data/data_road/training' NUMBER_OF_IMAGES = len(glob.glob('./data/data_road/training/calib/*.*')) VGG_PATH = './data/vgg' all_training_losses =", "cross_entropy_loss is the cost which we are trying to minimize", "the right parameters to the model to correctly label the", "image learning_rate: TF Placeholder for the learning rate num_classes: Number", "decoderlayer_output def optimize(nn_last_layer, correct_label, learning_rate, num_classes = NUMBER_OF_CLASSES): \"\"\" Build", "\" of \", EPOCHS, \"training loss: \", training_loss) print(\"------------------\") def", "with tf.Session() as session: # Returns the three layers, keep", "network correct_label: TF Placeholder for the correct label image learning_rate:", "probability and input layer from the vgg architecture image_input, keep_prob,", "batches get_batches_fn = helper.gen_batch_function(TRAINING_DATA_DIRECTORY, IMAGE_SHAPE) with tf.Session() as session: #", "column a class logits = tf.reshape(nn_last_layer, (-1, num_classes)) class_labels =", "row represents a pixel, each column a class # -", "training data. Call using get_batches_fn(batch_size) train_op: TF Operation to train", "sum(losses) / len(losses) all_training_losses.append(training_loss) print(\"------------------\") print(\"epoch: \", epoch + 1,", "['vgg16'], vgg_path) # Get Tensors to be returned from graph", "to encoder layers layer3x = conv_1x1(layer = layer3, layer_name =", "output num_classes: Number of classes to classify return: The Tensor", "simplicity layer3, layer4, layer7 = vgg_layer3_out, vgg_layer4_out, vgg_layer7_out # Apply", "is the cost which we are trying to minimize to", "strides are the same as the example in Udacity Lectures", "CHECK #-------------------------- # Check TensorFlow Version assert LooseVersion(tf.__version__) >= LooseVersion('1.0'),", "training operation and cost operation to be used # -", "model = tf.saved_model.loader.load(sess, ['vgg16'], vgg_path) # Get Tensors to be", "name = \"decoderlayer2\") decoderlayer3 = upsample(layer = decoderlayer2, k =", "used to get the right parameters to the model to", "classes to classify return: Tuple of (logits, train_op, cross_entropy_loss) \"\"\"", "(-1, num_classes)) # The cross_entropy_loss is the cost which we", "conv_1x1(layer = layer3, layer_name = \"layer3conv1x1\") layer4x = conv_1x1(layer =", "='./data/data_road/training' NUMBER_OF_IMAGES = len(glob.glob('./data/data_road/training/calib/*.*')) VGG_PATH = './data/vgg' all_training_losses = []", "the learning rate num_classes: Number of classes to classify return:", "Placeholder for label images keep_prob: TF Placeholder for dropout keep", "Train the neural network train_nn(session, EPOCHS, BATCH_SIZE, get_batches_fn, train_op, cross_entropy_loss,", "= tf.placeholder(tf.float32) keep_prob = tf.placeholder(tf.float32) #-------------------------- # FUNCTIONS #-------------------------- def", "= (s, s), padding = 'same', name = layer_name) def", "return: The Tensor for the last layer of output \"\"\"", "from the test image fed on the trained model \"\"\"", "row represents a pixel, each column a class logits =", "#-------------------------- correct_label = tf.placeholder(tf.float32, [None, IMAGE_SHAPE[0], IMAGE_SHAPE[1], NUMBER_OF_CLASSES]) learning_rate =", "Placeholder for the correct label image learning_rate: TF Placeholder for", "Tuple of Tensors from VGG model (image_input, keep_prob, layer3, layer4,", "NUMBER_OF_CLASSES = 2 IMAGE_SHAPE = (160, 576) EPOCHS = 20", "\"saved_model.pb\" return: Tuple of Tensors from VGG model (image_input, keep_prob,", "if our training is going well given parameters #-------------------------- #", "train_op = tf.train.AdamOptimizer(learning_rate).minimize(cross_entropy_loss) return logits, train_op, cross_entropy_loss def train_nn(sess, epochs,", "iteration: \", i, \" partial loss:\", partial_loss) losses.append(partial_loss) training_loss =", "decoderlayer1 = upsample(layer = layer7x, k = 4, s =", "higher accuracy cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits = logits, labels = class_labels)", "Tensors from VGG model (image_input, keep_prob, layer3, layer4, layer7) \"\"\"", "partial_loss) losses.append(partial_loss) training_loss = sum(losses) / len(losses) all_training_losses.append(training_loss) print(\"------------------\") print(\"epoch:", "given vgg model model_output = layers(layer3, layer4, layer7, NUMBER_OF_CLASSES) #", "= tf.reshape(nn_last_layer, (-1, num_classes)) class_labels = tf.reshape(correct_label, (-1, num_classes)) #", "the cost which we are trying to minimize to yield", "import os.path import warnings from distutils.version import LooseVersion import glob", "FUNCTIONS #-------------------------- def load_vgg(sess, vgg_path): \"\"\" Load Pretrained VGG Model", "k = 16, s = 8, layer_name = \"decoderlayer_output\") return", "the pixels # - cross_entropy_loss: function outputting the cost which", "logits, train_op, cross_entropy_loss = optimize(model_output, correct_label, learning_rate, NUMBER_OF_CLASSES) # Initialize", "= tf.placeholder(tf.float32) #-------------------------- # FUNCTIONS #-------------------------- def load_vgg(sess, vgg_path): \"\"\"", "# FUNCTIONS #-------------------------- def load_vgg(sess, vgg_path): \"\"\" Load Pretrained VGG", "a pixel, each column a class logits = tf.reshape(nn_last_layer, (-1,", "Build skip-layers using the vgg layers. vgg_layerX_out: TF Tensor for", "576) EPOCHS = 20 BATCH_SIZE = 1 LEARNING_RATE = 0.0001", "label the pixels # - cross_entropy_loss: function outputting the cost", "= './data' RUNS_DIRECTORY = './runs' TRAINING_DATA_DIRECTORY ='./data/data_road/training' NUMBER_OF_IMAGES = len(glob.glob('./data/data_road/training/calib/*.*'))", "\"\"\" Return the output of a 1x1 convolution of a", "(1, 1), name = layer_name) def upsample(layer, k, s, layer_name):", "Session epochs: Number of epochs batch_size: Batch size get_batches_fn: Function", "= upsample(layer = decoderlayer4, k = 16, s = 8,", "'./data' RUNS_DIRECTORY = './runs' TRAINING_DATA_DIRECTORY ='./data/data_road/training' NUMBER_OF_IMAGES = len(glob.glob('./data/data_road/training/calib/*.*')) VGG_PATH", "= tf.reduce_mean(cross_entropy) # The model implements this operation to find", "get_batches_fn = helper.gen_batch_function(TRAINING_DATA_DIRECTORY, IMAGE_SHAPE) with tf.Session() as session: # Returns", "1.0 or newer. You are using {}'.format(tf.__version__) print('TensorFlow Version: {}'.format(tf.__version__))", "layer4x, name = \"decoderlayer2\") decoderlayer3 = upsample(layer = decoderlayer2, k", "PLACEHOLDER TENSORS #-------------------------- correct_label = tf.placeholder(tf.float32, [None, IMAGE_SHAPE[0], IMAGE_SHAPE[1], NUMBER_OF_CLASSES])", "learning_rate: TF Placeholder for the learning rate num_classes: Number of", "# Initialize all variables session.run(tf.global_variables_initializer()) session.run(tf.local_variables_initializer()) # Train the neural", "used # - logits: each row represents a pixel, each", "cross_entropy_loss: TF Tensor for the amount of loss input_image: TF", "tf.reshape(nn_last_layer, (-1, num_classes)) class_labels = tf.reshape(correct_label, (-1, num_classes)) # The", "optimize(nn_last_layer, correct_label, learning_rate, num_classes = NUMBER_OF_CLASSES): \"\"\" Build the TensorFLow", "Session vgg_path: Path to vgg folder, containing \"variables/\" and \"saved_model.pb\"", "A function to get batches get_batches_fn = helper.gen_batch_function(TRAINING_DATA_DIRECTORY, IMAGE_SHAPE) with", "# - train_op: function used to get the right parameters", "= upsample(layer = decoderlayer2, k = 4, s = 2,", "layers to the network with skip connections and upsampling #", "represents a pixel, each column a class logits = tf.reshape(nn_last_layer,", "EPOCHS = 20 BATCH_SIZE = 1 LEARNING_RATE = 0.0001 DROPOUT", "upsample(layer = decoderlayer2, k = 4, s = 2, layer_name", "\"\"\" Load Pretrained VGG Model into TensorFlow. sess: TensorFlow Session", "last layer of output \"\"\" # Use a shorter variable", "vgg_layer3_out, vgg_layer4_out, vgg_layer7_out # Apply a 1x1 convolution to encoder", "i, \" partial loss:\", partial_loss) losses.append(partial_loss) training_loss = sum(losses) /", "correctly label the pixels # - cross_entropy_loss: function outputting the", "return image_input, keep_prob, layer3, layer4, layer7 def conv_1x1(layer, layer_name): \"\"\"", "# Apply a 1x1 convolution to encoder layers layer3x =", "num_classes: Number of classes to classify return: The Tensor for", "correct_label: TF Placeholder for label images keep_prob: TF Placeholder for", "we can't find it where it should be helper.maybe_download_pretrained_vgg(DATA_DIRECTORY) #", "BATCH_SIZE, get_batches_fn, train_op, cross_entropy_loss, image_input, correct_label, keep_prob, learning_rate) # Run", "graph.get_tensor_by_name('layer3_out:0') layer4 = graph.get_tensor_by_name('layer4_out:0') layer7 = graph.get_tensor_by_name('layer7_out:0') return image_input, keep_prob,", "convolutional network. Build skip-layers using the vgg layers. vgg_layerX_out: TF", "get_batches_fn: Function to get batches of training data. Call using", "upsampling # Note: the kernel size and strides are the", "2 IMAGE_SHAPE = (160, 576) EPOCHS = 20 BATCH_SIZE =", "be helper.maybe_download_pretrained_vgg(DATA_DIRECTORY) # A function to get batches get_batches_fn =", "layer7 = graph.get_tensor_by_name('layer7_out:0') return image_input, keep_prob, layer3, layer4, layer7 def", "# Check TensorFlow Version assert LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please use", "image_input, keep_prob, layer3, layer4, layer7 def conv_1x1(layer, layer_name): \"\"\" Return", "load_vgg(sess, vgg_path): \"\"\" Load Pretrained VGG Model into TensorFlow. sess:", "NUMBER_OF_CLASSES, kernel_size = (k, k), strides = (s, s), padding", "Understanding Lesson 10-9: FCN-8 - Decoder decoderlayer1 = upsample(layer =", "\", epoch + 1, \" of \", EPOCHS, \"training loss:", "Function to get batches of training data. Call using get_batches_fn(batch_size)", "tests.test_layers(layers) tests.test_optimize(optimize) tests.test_for_kitti_dataset(DATA_DIRECTORY) tests.test_train_nn(train_nn) def run(): \"\"\" Run a train", "1x1 convolution to encoder layers layer3x = conv_1x1(layer = layer3,", "s = 2, layer_name = \"decoderlayer1\") decoderlayer2 = tf.add(decoderlayer1, layer4x,", "The resulting network architecture from adding a decoder on top", "= graph.get_tensor_by_name('layer3_out:0') layer4 = graph.get_tensor_by_name('layer4_out:0') layer7 = graph.get_tensor_by_name('layer7_out:0') return image_input,", "all_training_losses = [] # Used for plotting to visualize if", "layer4, layer7, NUMBER_OF_CLASSES) # Returns the output logits, training operation", "= layer4, layer_name = \"layer4conv1x1\") layer7x = conv_1x1(layer = layer7,", "for the last layer of output \"\"\" # Use a", "with the test images and save each painted output image", "to find the weights/parameters that would yield correct pixel labels", "train_op, cross_entropy_loss = optimize(model_output, correct_label, learning_rate, NUMBER_OF_CLASSES) # Initialize all", "trained model \"\"\" # Get vgg model if we can't", "transpose convolution given kernel_size k and strides s \"\"\" return", "Path to vgg folder, containing \"variables/\" and \"saved_model.pb\" return: Tuple", "shorter variable name for simplicity layer3, layer4, layer7 = vgg_layer3_out,", "and save each painted output image (roads painted green) helper.save_inference_samples(RUNS_DIRECTORY,", "train your neural network.') else: print('Default GPU Device: {}'.format(tf.test.gpu_device_name())) #--------------------------", "graph.get_tensor_by_name('layer7_out:0') return image_input, keep_prob, layer3, layer4, layer7 def conv_1x1(layer, layer_name):", "sess: TensorFlow Session vgg_path: Path to vgg folder, containing \"variables/\"", "\"\"\" # Use a shorter variable name for simplicity layer3,", "layer7x, k = 4, s = 2, layer_name = \"decoderlayer1\")", "are minimizing, lower cost should yield higher accuracy logits, train_op,", "layer_name): \"\"\" Return the output of transpose convolution given kernel_size", "input_image: TF Placeholder for input images correct_label: TF Placeholder for", "correct_label: labels, keep_prob: DROPOUT, learning_rate: LEARNING_RATE } _, partial_loss =", "to vgg folder, containing \"variables/\" and \"saved_model.pb\" return: Tuple of", "for epoch in range(EPOCHS): losses, i = [], 0 for", "DEPENDENCY CHECK #-------------------------- # Check TensorFlow Version assert LooseVersion(tf.__version__) >=", "TensorFlow Session vgg_path: Path to vgg folder, containing \"variables/\" and", "s, layer_name): \"\"\" Return the output of transpose convolution given", "of loss input_image: TF Placeholder for input images correct_label: TF", "class # - train_op: function used to get the right", "vgg_layer7_out # Apply a 1x1 convolution to encoder layers layer3x", "2, layer_name = \"decoderlayer3\") decoderlayer4 = tf.add(decoderlayer3, layer3x, name =", "if not tf.test.gpu_device_name(): warnings.warn('No GPU found. Please use a GPU", "layers. vgg_layerX_out: TF Tensor for VGG Layer X output num_classes:", "variable name for simplicity layer3, layer4, layer7 = vgg_layer3_out, vgg_layer4_out,", "+ 1, \" of \", EPOCHS, \"training loss: \", training_loss)", "vgg_layer4_out, vgg_layer7_out # Apply a 1x1 convolution to encoder layers", "import tensorflow as tf import os.path import warnings from distutils.version", "= \"decoderlayer2\") decoderlayer3 = upsample(layer = decoderlayer2, k = 4,", "network cross_entropy_loss: TF Tensor for the amount of loss input_image:", "= NUMBER_OF_CLASSES): \"\"\" Create the layers for a fully convolutional", "DATA_DIRECTORY = './data' RUNS_DIRECTORY = './runs' TRAINING_DATA_DIRECTORY ='./data/data_road/training' NUMBER_OF_IMAGES =", "learning_rate, num_classes = NUMBER_OF_CLASSES): \"\"\" Build the TensorFLow loss and", "logits, train_op, cross_entropy_loss def train_nn(sess, epochs, batch_size, get_batches_fn, train_op, cross_entropy_loss,", "can't find it where it should be helper.maybe_download_pretrained_vgg(DATA_DIRECTORY) # A", "'./runs' TRAINING_DATA_DIRECTORY ='./data/data_road/training' NUMBER_OF_IMAGES = len(glob.glob('./data/data_road/training/calib/*.*')) VGG_PATH = './data/vgg' all_training_losses", "def layers(vgg_layer3_out, vgg_layer4_out, vgg_layer7_out, num_classes = NUMBER_OF_CLASSES): \"\"\" Create the", "be returned from graph graph = tf.get_default_graph() image_input = graph.get_tensor_by_name('image_input:0')", "losses, i = [], 0 for images, labels in get_batches_fn(BATCH_SIZE):", "s = 8, layer_name = \"decoderlayer_output\") return decoderlayer_output def optimize(nn_last_layer,", "Decoder decoderlayer1 = upsample(layer = layer7x, k = 4, s", "our training is going well given parameters #-------------------------- # DEPENDENCY", "the kernel size and strides are the same as the", "Operation to train the neural network cross_entropy_loss: TF Tensor for", "EPOCHS, \"training loss: \", training_loss) print(\"------------------\") def run_tests(): tests.test_layers(layers) tests.test_optimize(optimize)", "loss: \", training_loss) print(\"------------------\") def run_tests(): tests.test_layers(layers) tests.test_optimize(optimize) tests.test_for_kitti_dataset(DATA_DIRECTORY) tests.test_train_nn(train_nn)", "test image fed on the trained model \"\"\" # Get", "= logits, labels = class_labels) cross_entropy_loss = tf.reduce_mean(cross_entropy) # The", "pixel, each column a class # - train_op: function used", "= conv_1x1(layer = layer7, layer_name = \"layer7conv1x1\") # Add decoder", "LEARNING_RATE = 0.0001 DROPOUT = 0.75 # Specify these directory", "\"\"\" # load the model and weights model = tf.saved_model.loader.load(sess,", "images and save each painted output image (roads painted green)", "= sum(losses) / len(losses) all_training_losses.append(training_loss) print(\"------------------\") print(\"epoch: \", epoch +", "layer from the vgg architecture image_input, keep_prob, layer3, layer4, layer7", "layers layer3x = conv_1x1(layer = layer3, layer_name = \"layer3conv1x1\") layer4x", "the amount of loss input_image: TF Placeholder for input images", "of classes to classify return: The Tensor for the last", "(s, s), padding = 'same', name = layer_name) def layers(vgg_layer3_out,", "# - logits: each row represents a pixel, each column", "# Get Tensors to be returned from graph graph =", "The cross_entropy_loss is the cost which we are trying to", "that would yield correct pixel labels train_op = tf.train.AdamOptimizer(learning_rate).minimize(cross_entropy_loss) return", "= \"decoderlayer4\") decoderlayer_output = upsample(layer = decoderlayer4, k = 16,", "IMAGE_SHAPE) with tf.Session() as session: # Returns the three layers,", "neural network.') else: print('Default GPU Device: {}'.format(tf.test.gpu_device_name())) #-------------------------- # PLACEHOLDER", "tests.test_train_nn(train_nn) def run(): \"\"\" Run a train a model and", "\"\"\" return tf.layers.conv2d(inputs = layer, filters = NUMBER_OF_CLASSES, kernel_size =", "= tf.get_default_graph() image_input = graph.get_tensor_by_name('image_input:0') keep_prob = graph.get_tensor_by_name('keep_prob:0') layer3 =", "model \"\"\" # Get vgg model if we can't find", "load the model and weights model = tf.saved_model.loader.load(sess, ['vgg16'], vgg_path)", "# Get vgg model if we can't find it where", "Pretrained VGG Model into TensorFlow. sess: TensorFlow Session vgg_path: Path", "Apply a 1x1 convolution to encoder layers layer3x = conv_1x1(layer", "return tf.layers.conv2d_transpose(inputs = layer, filters = NUMBER_OF_CLASSES, kernel_size = (k,", "'same', name = layer_name) def layers(vgg_layer3_out, vgg_layer4_out, vgg_layer7_out, num_classes =", "output of transpose convolution given kernel_size k and strides s", "TENSORS #-------------------------- correct_label = tf.placeholder(tf.float32, [None, IMAGE_SHAPE[0], IMAGE_SHAPE[1], NUMBER_OF_CLASSES]) learning_rate", "model and weights model = tf.saved_model.loader.load(sess, ['vgg16'], vgg_path) # Get", "layer7x = conv_1x1(layer = layer7, layer_name = \"layer7conv1x1\") # Add", "Udacity Lectures # Semantic Segmentation Scene Understanding Lesson 10-9: FCN-8", "to train the neural network cross_entropy_loss: TF Tensor for the", "USER-SPECIFIED DATA #-------------------------- # Tune these parameters NUMBER_OF_CLASSES = 2", "cross_entropy_loss: function outputting the cost which we are minimizing, lower", "would yield correct pixel labels train_op = tf.train.AdamOptimizer(learning_rate).minimize(cross_entropy_loss) return logits,", "the vgg architecture image_input, keep_prob, layer3, layer4, layer7 = load_vgg(session,", "of epochs batch_size: Batch size get_batches_fn: Function to get batches", "def run(): \"\"\" Run a train a model and save", "model implements this operation to find the weights/parameters that would", "i += 1 feed = { input_image: images, correct_label: labels,", "model with the test images and save each painted output", "the cost which we are minimizing, lower cost should yield", "= 0.0001 DROPOUT = 0.75 # Specify these directory paths", "convolution to encoder layers layer3x = conv_1x1(layer = layer3, layer_name", "1), name = layer_name) def upsample(layer, k, s, layer_name): \"\"\"", "Semantic Segmentation Scene Understanding Lesson 10-9: FCN-8 - Decoder decoderlayer1", "epoch in range(EPOCHS): losses, i = [], 0 for images,", "def run_tests(): tests.test_layers(layers) tests.test_optimize(optimize) tests.test_for_kitti_dataset(DATA_DIRECTORY) tests.test_train_nn(train_nn) def run(): \"\"\" Run", "to be returned from graph graph = tf.get_default_graph() image_input =", "get_batches_fn, train_op, cross_entropy_loss, image_input, correct_label, keep_prob, learning_rate) # Run the", "s), padding = 'same', name = layer_name) def layers(vgg_layer3_out, vgg_layer4_out,", "TensorFlow version 1.0 or newer. You are using {}'.format(tf.__version__) print('TensorFlow", "cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits = logits, labels = class_labels) cross_entropy_loss =", "tf.layers.conv2d_transpose(inputs = layer, filters = NUMBER_OF_CLASSES, kernel_size = (k, k),", "tests #-------------------------- # USER-SPECIFIED DATA #-------------------------- # Tune these parameters", "layer, filters = NUMBER_OF_CLASSES, kernel_size = (k, k), strides =", "adding a decoder on top of the given vgg model", "graph.get_tensor_by_name('image_input:0') keep_prob = graph.get_tensor_by_name('keep_prob:0') layer3 = graph.get_tensor_by_name('layer3_out:0') layer4 = graph.get_tensor_by_name('layer4_out:0')", "upsample(layer = layer7x, k = 4, s = 2, layer_name", "train_op: TF Operation to train the neural network cross_entropy_loss: TF", "image fed on the trained model \"\"\" # Get vgg", "layer3, layer4, layer7) \"\"\" # load the model and weights", "and input layer from the vgg architecture image_input, keep_prob, layer3,", "to the model to correctly label the pixels # -", "vgg_path) # Get Tensors to be returned from graph graph", "layer4x = conv_1x1(layer = layer4, layer_name = \"layer4conv1x1\") layer7x =", "= graph.get_tensor_by_name('keep_prob:0') layer3 = graph.get_tensor_by_name('layer3_out:0') layer4 = graph.get_tensor_by_name('layer4_out:0') layer7 =", "layer of output \"\"\" # Use a shorter variable name", "the neural network correct_label: TF Placeholder for the correct label", "pixels # - cross_entropy_loss: function outputting the cost which we", "= tf.add(decoderlayer3, layer3x, name = \"decoderlayer4\") decoderlayer_output = upsample(layer =", "rate \"\"\" for epoch in range(EPOCHS): losses, i = [],", "[] # Used for plotting to visualize if our training", "0 for images, labels in get_batches_fn(BATCH_SIZE): i += 1 feed", "TF Placeholder for label images keep_prob: TF Placeholder for dropout", "10-9: FCN-8 - Decoder decoderlayer1 = upsample(layer = layer7x, k", "keep_prob, learning_rate) # Run the model with the test images", "graph.get_tensor_by_name('keep_prob:0') layer3 = graph.get_tensor_by_name('layer3_out:0') layer4 = graph.get_tensor_by_name('layer4_out:0') layer7 = graph.get_tensor_by_name('layer7_out:0')", "loss during training. sess: TF Session epochs: Number of epochs", "for the amount of loss input_image: TF Placeholder for input", "\" partial loss:\", partial_loss) losses.append(partial_loss) training_loss = sum(losses) / len(losses)", "cost which we are trying to minimize to yield higher", "2, layer_name = \"decoderlayer1\") decoderlayer2 = tf.add(decoderlayer1, layer4x, name =", "on top of the given vgg model model_output = layers(layer3,", "strides = (1, 1), name = layer_name) def upsample(layer, k,", "k), strides = (s, s), padding = 'same', name =", "\"\"\" for epoch in range(EPOCHS): losses, i = [], 0", "fed on the trained model \"\"\" # Get vgg model", "from VGG model (image_input, keep_prob, layer3, layer4, layer7) \"\"\" #", "variables session.run(tf.global_variables_initializer()) session.run(tf.local_variables_initializer()) # Train the neural network train_nn(session, EPOCHS,", "FCN-8 - Decoder decoderlayer1 = upsample(layer = layer7x, k =", "Call using get_batches_fn(batch_size) train_op: TF Operation to train the neural", "images correct_label: TF Placeholder for label images keep_prob: TF Placeholder", "import LooseVersion import glob import helper import project_tests as tests", "if we can't find it where it should be helper.maybe_download_pretrained_vgg(DATA_DIRECTORY)", "get_batches_fn(BATCH_SIZE): i += 1 feed = { input_image: images, correct_label:", "neural network cross_entropy_loss: TF Tensor for the amount of loss", "into TensorFlow. sess: TensorFlow Session vgg_path: Path to vgg folder,", "of \", EPOCHS, \"training loss: \", training_loss) print(\"------------------\") def run_tests():", "warnings.warn('No GPU found. Please use a GPU to train your", "the network with skip connections and upsampling # Note: the", "parameters to the model to correctly label the pixels #", "vgg model if we can't find it where it should", "'Please use TensorFlow version 1.0 or newer. You are using", "= 0.75 # Specify these directory paths DATA_DIRECTORY = './data'", "we are trying to minimize to yield higher accuracy cross_entropy", "cross_entropy_loss], feed_dict = feed) print(\"---> iteration: \", i, \" partial", "os.path import warnings from distutils.version import LooseVersion import glob import", "correct_label, keep_prob, learning_rate) # Run the model with the test", "skip-layers using the vgg layers. vgg_layerX_out: TF Tensor for VGG", "Specify these directory paths DATA_DIRECTORY = './data' RUNS_DIRECTORY = './runs'", "out the loss during training. sess: TF Session epochs: Number", "\", training_loss) print(\"------------------\") def run_tests(): tests.test_layers(layers) tests.test_optimize(optimize) tests.test_for_kitti_dataset(DATA_DIRECTORY) tests.test_train_nn(train_nn) def", "the output of transpose convolution given kernel_size k and strides", "decoderlayer2, k = 4, s = 2, layer_name = \"decoderlayer3\")", "return: Tuple of (logits, train_op, cross_entropy_loss) \"\"\" # Reshape 4D", "print(\"epoch: \", epoch + 1, \" of \", EPOCHS, \"training", "with skip connections and upsampling # Note: the kernel size", "sess.run([train_op, cross_entropy_loss], feed_dict = feed) print(\"---> iteration: \", i, \"", "train_nn(session, EPOCHS, BATCH_SIZE, get_batches_fn, train_op, cross_entropy_loss, image_input, correct_label, keep_prob, learning_rate)", "Device: {}'.format(tf.test.gpu_device_name())) #-------------------------- # PLACEHOLDER TENSORS #-------------------------- correct_label = tf.placeholder(tf.float32,", "a class logits = tf.reshape(nn_last_layer, (-1, num_classes)) class_labels = tf.reshape(correct_label,", "kernel size and strides are the same as the example", "loss input_image: TF Placeholder for input images correct_label: TF Placeholder", "be used # - logits: each row represents a pixel,", "IMAGE_SHAPE = (160, 576) EPOCHS = 20 BATCH_SIZE = 1", "= NUMBER_OF_CLASSES): \"\"\" Build the TensorFLow loss and optimizer operations.", "= 4, s = 2, layer_name = \"decoderlayer3\") decoderlayer4 =", "1 feed = { input_image: images, correct_label: labels, keep_prob: DROPOUT,", "{}'.format(tf.__version__)) # Check for a GPU if not tf.test.gpu_device_name(): warnings.warn('No", "model to correctly label the pixels # - cross_entropy_loss: function", "Reshape 4D tensors to 2D, each row represents a pixel,", "Returns the output logits, training operation and cost operation to", "are trying to minimize to yield higher accuracy cross_entropy =", "keep_prob: DROPOUT, learning_rate: LEARNING_RATE } _, partial_loss = sess.run([train_op, cross_entropy_loss],", "= 2, layer_name = \"decoderlayer1\") decoderlayer2 = tf.add(decoderlayer1, layer4x, name", "= { input_image: images, correct_label: labels, keep_prob: DROPOUT, learning_rate: LEARNING_RATE", "Add decoder layers to the network with skip connections and", "graph.get_tensor_by_name('layer4_out:0') layer7 = graph.get_tensor_by_name('layer7_out:0') return image_input, keep_prob, layer3, layer4, layer7", "a pixel, each column a class # - train_op: function", "logits = tf.reshape(nn_last_layer, (-1, num_classes)) class_labels = tf.reshape(correct_label, (-1, num_classes))", "Used for plotting to visualize if our training is going", "kernel_size = (k, k), strides = (s, s), padding =", "Placeholder for the learning rate num_classes: Number of classes to", "correct_label = tf.placeholder(tf.float32, [None, IMAGE_SHAPE[0], IMAGE_SHAPE[1], NUMBER_OF_CLASSES]) learning_rate = tf.placeholder(tf.float32)", "returned from graph graph = tf.get_default_graph() image_input = graph.get_tensor_by_name('image_input:0') keep_prob", "the loss during training. sess: TF Session epochs: Number of", "vgg_layer7_out, num_classes = NUMBER_OF_CLASSES): \"\"\" Create the layers for a", "Lesson 10-9: FCN-8 - Decoder decoderlayer1 = upsample(layer = layer7x,", "glob import helper import project_tests as tests #-------------------------- # USER-SPECIFIED", "20 BATCH_SIZE = 1 LEARNING_RATE = 0.0001 DROPOUT = 0.75", "is going well given parameters #-------------------------- # DEPENDENCY CHECK #--------------------------", "green) helper.save_inference_samples(RUNS_DIRECTORY, DATA_DIRECTORY, session, IMAGE_SHAPE, logits, keep_prob, image_input) #-------------------------- #", "for input images correct_label: TF Placeholder for label images keep_prob:", "= [] # Used for plotting to visualize if our", "classify return: Tuple of (logits, train_op, cross_entropy_loss) \"\"\" # Reshape", "the layers for a fully convolutional network. Build skip-layers using", "Train neural network and print out the loss during training.", "use a GPU to train your neural network.') else: print('Default", "vgg model model_output = layers(layer3, layer4, layer7, NUMBER_OF_CLASSES) # Returns", "the given vgg model model_output = layers(layer3, layer4, layer7, NUMBER_OF_CLASSES)", "column a class # - train_op: function used to get", "2D, each row represents a pixel, each column a class", "k = 4, s = 2, layer_name = \"decoderlayer1\") decoderlayer2", "= tf.saved_model.loader.load(sess, ['vgg16'], vgg_path) # Get Tensors to be returned", "= 'same', name = layer_name) def layers(vgg_layer3_out, vgg_layer4_out, vgg_layer7_out, num_classes", "layer7, layer_name = \"layer7conv1x1\") # Add decoder layers to the", "function used to get the right parameters to the model", "<filename>main.py import tensorflow as tf import os.path import warnings from", "Number of epochs batch_size: Batch size get_batches_fn: Function to get", "{ input_image: images, correct_label: labels, keep_prob: DROPOUT, learning_rate: LEARNING_RATE }", "the last layer in the neural network correct_label: TF Placeholder", "layer3, layer_name = \"layer3conv1x1\") layer4x = conv_1x1(layer = layer4, layer_name", "= 20 BATCH_SIZE = 1 LEARNING_RATE = 0.0001 DROPOUT =", "layer in the neural network correct_label: TF Placeholder for the", "tests.test_optimize(optimize) tests.test_for_kitti_dataset(DATA_DIRECTORY) tests.test_train_nn(train_nn) def run(): \"\"\" Run a train a", "as session: # Returns the three layers, keep probability and", "a GPU to train your neural network.') else: print('Default GPU", "get batches of training data. Call using get_batches_fn(batch_size) train_op: TF", "{}'.format(tf.__version__) print('TensorFlow Version: {}'.format(tf.__version__)) # Check for a GPU if", "labels train_op = tf.train.AdamOptimizer(learning_rate).minimize(cross_entropy_loss) return logits, train_op, cross_entropy_loss def train_nn(sess,", "all variables session.run(tf.global_variables_initializer()) session.run(tf.local_variables_initializer()) # Train the neural network train_nn(session,", "#-------------------------- # DEPENDENCY CHECK #-------------------------- # Check TensorFlow Version assert", "training is going well given parameters #-------------------------- # DEPENDENCY CHECK", "layer_name): \"\"\" Return the output of a 1x1 convolution of", "EPOCHS, BATCH_SIZE, get_batches_fn, train_op, cross_entropy_loss, image_input, correct_label, keep_prob, learning_rate) #", "each painted output image (roads painted green) helper.save_inference_samples(RUNS_DIRECTORY, DATA_DIRECTORY, session,", "a layer \"\"\" return tf.layers.conv2d(inputs = layer, filters = NUMBER_OF_CLASSES,", "input images correct_label: TF Placeholder for label images keep_prob: TF", "Check for a GPU if not tf.test.gpu_device_name(): warnings.warn('No GPU found.", "image_input = graph.get_tensor_by_name('image_input:0') keep_prob = graph.get_tensor_by_name('keep_prob:0') layer3 = graph.get_tensor_by_name('layer3_out:0') layer4", "vgg_layer4_out, vgg_layer7_out, num_classes = NUMBER_OF_CLASSES): \"\"\" Create the layers for", "tf.train.AdamOptimizer(learning_rate).minimize(cross_entropy_loss) return logits, train_op, cross_entropy_loss def train_nn(sess, epochs, batch_size, get_batches_fn,", "for dropout keep probability learning_rate: TF Placeholder for learning rate", "Placeholder for dropout keep probability learning_rate: TF Placeholder for learning", "LooseVersion('1.0'), 'Please use TensorFlow version 1.0 or newer. You are", "# Semantic Segmentation Scene Understanding Lesson 10-9: FCN-8 - Decoder", "load_vgg(session, VGG_PATH) # The resulting network architecture from adding a", "these parameters NUMBER_OF_CLASSES = 2 IMAGE_SHAPE = (160, 576) EPOCHS", "output \"\"\" # Use a shorter variable name for simplicity", "each column a class # - train_op: function used to", "images resulting from the test image fed on the trained", "Model into TensorFlow. sess: TensorFlow Session vgg_path: Path to vgg", "connections and upsampling # Note: the kernel size and strides", "= layer_name) def upsample(layer, k, s, layer_name): \"\"\" Return the", "= decoderlayer2, k = 4, s = 2, layer_name =", "tf.add(decoderlayer3, layer3x, name = \"decoderlayer4\") decoderlayer_output = upsample(layer = decoderlayer4,", "to 2D, each row represents a pixel, each column a", "- cross_entropy_loss: function outputting the cost which we are minimizing,", "are using {}'.format(tf.__version__) print('TensorFlow Version: {}'.format(tf.__version__)) # Check for a", "vgg folder, containing \"variables/\" and \"saved_model.pb\" return: Tuple of Tensors", "to be used # - logits: each row represents a", "convolution given kernel_size k and strides s \"\"\" return tf.layers.conv2d_transpose(inputs", "to the network with skip connections and upsampling # Note:", "Run a train a model and save output images resulting", "to classify return: The Tensor for the last layer of", "of a layer \"\"\" return tf.layers.conv2d(inputs = layer, filters =", "layer4, layer7 def conv_1x1(layer, layer_name): \"\"\" Return the output of", "the weights/parameters that would yield correct pixel labels train_op =", "VGG model (image_input, keep_prob, layer3, layer4, layer7) \"\"\" # load", "BATCH_SIZE = 1 LEARNING_RATE = 0.0001 DROPOUT = 0.75 #", "vgg layers. vgg_layerX_out: TF Tensor for VGG Layer X output", "feed) print(\"---> iteration: \", i, \" partial loss:\", partial_loss) losses.append(partial_loss)", "the three layers, keep probability and input layer from the", "three layers, keep probability and input layer from the vgg", "cross_entropy_loss, input_image, correct_label, keep_prob, learning_rate): \"\"\" Train neural network and", "and strides s \"\"\" return tf.layers.conv2d_transpose(inputs = layer, filters =", "cross_entropy_loss = tf.reduce_mean(cross_entropy) # The model implements this operation to", "logits: each row represents a pixel, each column a class", "of a 1x1 convolution of a layer \"\"\" return tf.layers.conv2d(inputs", "of (logits, train_op, cross_entropy_loss) \"\"\" # Reshape 4D tensors to", "operation and cost operation to be used # - logits:", "minimizing, lower cost should yield higher accuracy logits, train_op, cross_entropy_loss", "layer7, NUMBER_OF_CLASSES) # Returns the output logits, training operation and", "your neural network.') else: print('Default GPU Device: {}'.format(tf.test.gpu_device_name())) #-------------------------- #", "+= 1 feed = { input_image: images, correct_label: labels, keep_prob:", "image_input, keep_prob, layer3, layer4, layer7 = load_vgg(session, VGG_PATH) # The", "layer3x = conv_1x1(layer = layer3, layer_name = \"layer3conv1x1\") layer4x =", "get_batches_fn(batch_size) train_op: TF Operation to train the neural network cross_entropy_loss:", "run_tests() run() # Run a train a model and save", "architecture image_input, keep_prob, layer3, layer4, layer7 = load_vgg(session, VGG_PATH) #", "are the same as the example in Udacity Lectures #", "layer4, layer_name = \"layer4conv1x1\") layer7x = conv_1x1(layer = layer7, layer_name", "Tensor for the amount of loss input_image: TF Placeholder for", "\"training loss: \", training_loss) print(\"------------------\") def run_tests(): tests.test_layers(layers) tests.test_optimize(optimize) tests.test_for_kitti_dataset(DATA_DIRECTORY)", "layer7 def conv_1x1(layer, layer_name): \"\"\" Return the output of a", "TensorFlow Version assert LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please use TensorFlow version", "layer_name = \"layer7conv1x1\") # Add decoder layers to the network", "class_labels = tf.reshape(correct_label, (-1, num_classes)) # The cross_entropy_loss is the", "print(\"------------------\") print(\"epoch: \", epoch + 1, \" of \", EPOCHS,", "images, labels in get_batches_fn(BATCH_SIZE): i += 1 feed = {", "layer_name) def layers(vgg_layer3_out, vgg_layer4_out, vgg_layer7_out, num_classes = NUMBER_OF_CLASSES): \"\"\" Create", "import project_tests as tests #-------------------------- # USER-SPECIFIED DATA #-------------------------- #", "keep_prob: TF Placeholder for dropout keep probability learning_rate: TF Placeholder", "\"layer3conv1x1\") layer4x = conv_1x1(layer = layer4, layer_name = \"layer4conv1x1\") layer7x", "= (1, 1), strides = (1, 1), name = layer_name)", "# Reshape 4D tensors to 2D, each row represents a", "for VGG Layer X output num_classes: Number of classes to", "epochs, batch_size, get_batches_fn, train_op, cross_entropy_loss, input_image, correct_label, keep_prob, learning_rate): \"\"\"", "tf.placeholder(tf.float32) #-------------------------- # FUNCTIONS #-------------------------- def load_vgg(sess, vgg_path): \"\"\" Load", "name = \"decoderlayer4\") decoderlayer_output = upsample(layer = decoderlayer4, k =", "neural network and print out the loss during training. sess:", "train the neural network cross_entropy_loss: TF Tensor for the amount", "= sess.run([train_op, cross_entropy_loss], feed_dict = feed) print(\"---> iteration: \", i,", "Tensors to be returned from graph graph = tf.get_default_graph() image_input", "helper.gen_batch_function(TRAINING_DATA_DIRECTORY, IMAGE_SHAPE) with tf.Session() as session: # Returns the three", "trying to minimize to yield higher accuracy cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits", "accuracy logits, train_op, cross_entropy_loss = optimize(model_output, correct_label, learning_rate, NUMBER_OF_CLASSES) #", "VGG_PATH = './data/vgg' all_training_losses = [] # Used for plotting", "same as the example in Udacity Lectures # Semantic Segmentation", "NUMBER_OF_CLASSES): \"\"\" Build the TensorFLow loss and optimizer operations. nn_last_layer:", "of Tensors from VGG model (image_input, keep_prob, layer3, layer4, layer7)", "def train_nn(sess, epochs, batch_size, get_batches_fn, train_op, cross_entropy_loss, input_image, correct_label, keep_prob,", "it should be helper.maybe_download_pretrained_vgg(DATA_DIRECTORY) # A function to get batches", "= graph.get_tensor_by_name('layer4_out:0') layer7 = graph.get_tensor_by_name('layer7_out:0') return image_input, keep_prob, layer3, layer4,", "import glob import helper import project_tests as tests #-------------------------- #", "containing \"variables/\" and \"saved_model.pb\" return: Tuple of Tensors from VGG", "DROPOUT, learning_rate: LEARNING_RATE } _, partial_loss = sess.run([train_op, cross_entropy_loss], feed_dict", "learning_rate): \"\"\" Train neural network and print out the loss", "data. Call using get_batches_fn(batch_size) train_op: TF Operation to train the", "# Returns the output logits, training operation and cost operation", "yield higher accuracy logits, train_op, cross_entropy_loss = optimize(model_output, correct_label, learning_rate,", "keep_prob = tf.placeholder(tf.float32) #-------------------------- # FUNCTIONS #-------------------------- def load_vgg(sess, vgg_path):", "rate num_classes: Number of classes to classify return: Tuple of", "a model and save output images resulting from the test", "NUMBER_OF_IMAGES = len(glob.glob('./data/data_road/training/calib/*.*')) VGG_PATH = './data/vgg' all_training_losses = [] #", "layers(layer3, layer4, layer7, NUMBER_OF_CLASSES) # Returns the output logits, training", "parameters NUMBER_OF_CLASSES = 2 IMAGE_SHAPE = (160, 576) EPOCHS =", "size and strides are the same as the example in", "should be helper.maybe_download_pretrained_vgg(DATA_DIRECTORY) # A function to get batches get_batches_fn", "session: # Returns the three layers, keep probability and input", "painted output image (roads painted green) helper.save_inference_samples(RUNS_DIRECTORY, DATA_DIRECTORY, session, IMAGE_SHAPE,", "1), strides = (1, 1), name = layer_name) def upsample(layer,", "\"decoderlayer_output\") return decoderlayer_output def optimize(nn_last_layer, correct_label, learning_rate, num_classes = NUMBER_OF_CLASSES):", "num_classes = NUMBER_OF_CLASSES): \"\"\" Build the TensorFLow loss and optimizer", "s = 2, layer_name = \"decoderlayer3\") decoderlayer4 = tf.add(decoderlayer3, layer3x,", "TF Placeholder for learning rate \"\"\" for epoch in range(EPOCHS):", "layer4, layer7 = load_vgg(session, VGG_PATH) # The resulting network architecture", "LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please use TensorFlow version 1.0 or newer.", "class logits = tf.reshape(nn_last_layer, (-1, num_classes)) class_labels = tf.reshape(correct_label, (-1,", "should yield higher accuracy logits, train_op, cross_entropy_loss = optimize(model_output, correct_label,", "get the right parameters to the model to correctly label", "TensorFlow. sess: TensorFlow Session vgg_path: Path to vgg folder, containing" ]
[ "log_sinks) expected_violations = set([ lsre.Rule.RuleViolation( resource_type='sink', resource_id='billing_logs', resource_name='billingAccounts/ABCD-1234/sinks/billing_logs', full_name='organization/234/billingAccount/ABCD-1234/billing_logs/', rule_name=('Only", "'projects/proj-3'] self.assertEqual(expected_rule_resources, sorted(self_rule_resources)) child_rule_resources = [] for resource in rules_engine.rule_book.resource_rules_map['children']:", "log_sinks) expected_violations = set([ lsre.Rule.RuleViolation( resource_name='234', resource_type='organization', resource_id='234', full_name='organization/234/', rule_name='Require", "permissions and # limitations under the License. \"\"\"Tests the LogSinkRulesEngine.\"\"\"", "sorted(self_rule_resources)) child_rule_resources = [] for resource in rules_engine.rule_book.resource_rules_map['children']: child_rule_resources.append(resource.name) expected_rule_resources", "the License. \"\"\"Tests the LogSinkRulesEngine.\"\"\" import unittest import mock from", "| # | # +-----------------------> proj-3 self.org_234 = Organization( '234',", "created.\"\"\" rules_local_path = get_datafile_path( __file__, 'log_sink_test_invalid_rules.yaml') rules_engine = self.lsre.LogSinkRulesEngine( rules_file_path=rules_local_path)", "def test_folder_with_no_violations(self): \"\"\"Tests that no violations are produced for a", "data='fake_folder_data456456') self.proj_1 = Project( 'proj-1', project_number=11223344, display_name='My project 1', parent=self.org_234,", "= rules_engine.find_violations(self.folder_56, []) self.assertEqual(set(), actual_violations) def test_billing_account_with_no_violations(self): \"\"\"Tests that no", "rules_engine = self.get_engine_with_valid_rules() # Rules disallow any folder-level LogSinks. log_sinks", "'whitelist', }, { 'name': 'Bad mode', 'resource': [valid_resource], 'sink': valid_sink_spec,", "2.0 (the \"License\"); # you may not use this file", "that no violations are produced for a correct organization.\"\"\" rules_engine", "full_name='organization/234/folder/56/project/proj-2/', rule_name='Require a PubSub sink in folder-56 projects.', rule_index=3, violation_type='LOG_SINK_VIOLATION',", "<gh_stars>0 # Copyright 2018 The Forseti Security Authors. All rights", "parent=self.org_234, full_name='organization/234/project/proj-1/', data='fake_project_data_2341') self.proj_2 = Project( 'proj-2', project_number=223344, display_name='My project", "'datasets/proj_1_logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.proj_1, raw_json='_SINK_1_' ), LogSink( sink_id='compute_logs_saver', destination=('bigquery.googleapis.com/projects/proj_1/'", "# proj-1 needs an Audit Log sink. log_sinks = [", "rules raises exceptions.\"\"\" rule_book = self.lsre.LogSinkRuleBook(global_configs=None) valid_resource = { 'type':", "self.lsre.LOGGER = mock.MagicMock() # Set up resources in the following", "# limitations under the License. \"\"\"Tests the LogSinkRulesEngine.\"\"\" import unittest", "'bucket', 'applies_to': 'self', 'resource_ids': ['bucket-1'] }], 'sink': valid_sink_spec, 'mode': 'whitelist'", "violations are produced for a correct project.\"\"\" rules_engine = self.get_engine_with_valid_rules()", "Level audit log sink.', rule_index=1, violation_type='LOG_SINK_VIOLATION', sink_destination='^.*$', sink_filter=('^logName\\\\:\\\\\"logs\\\\/' 'cloudaudit\\\\.googleapis\\\\.com\\\\\"$'), sink_include_children=True,", "rules_engine.find_violations( self.billing_acct_abcd, log_sinks) self.assertEqual(set(), actual_violations) def test_org_with_no_violations(self): \"\"\"Tests that no", "= rules_engine.find_violations( self.proj_2, log_sinks) expected_violations = set([ lsre.Rule.RuleViolation( resource_name='proj-2', resource_type='project',", "by folder-level rules. log_sinks = [ LogSink( sink_id='non_audit_logs_to_bq', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/proj_2_logs'),", "import ForsetiTestCase from tests.unittest_utils import get_datafile_path from google.cloud.forseti.common.gcp_type.billing_account import BillingAccount", "# Rules disallow any folder-level LogSinks. actual_violations = rules_engine.find_violations(self.folder_56, [])", "display_name='Billing Account ABCD', full_name='organization/234/billingAccount/ABCD-1234/', data='fake_billing_account_data_abcd') self.folder_56 = Folder( '56', display_name='Folder", "BigQuery sinks. log_sinks = [ LogSink( sink_id='audit_logs_to_bq', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/proj_1_logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"',", "actual_violations = rules_engine.find_violations( self.billing_acct_abcd, log_sinks) expected_violations = set([ lsre.Rule.RuleViolation( resource_type='sink',", "violations are produced for an org missing required sinks.\"\"\" rules_engine", "an Audit Log sink. log_sinks = [ LogSink( sink_id='audit_logs_to_bq', destination=('bigquery.googleapis.com/projects/my-audit-logs/'", "writer_identity='serviceAccount:<EMAIL>', parent=self.folder_56, raw_json='__SINK_1__' ) ] actual_violations = rules_engine.find_violations( self.folder_56, log_sinks)", "= [ LogSink( sink_id='audit_logs_to_bq', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/proj_1_logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.proj_3,", "'other', }, { 'name': 'Bad resource type', 'resource': [{ 'type':", "rules_engine.find_violations(self.folder_56, []) self.assertEqual(set(), actual_violations) def test_billing_account_with_no_violations(self): \"\"\"Tests that no violations", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "[ LogSink( sink_id='non_audit_logs_to_bq', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/proj_2_logs'), sink_filter='logName:\"logs/non-cloudaudit.googleapis.com\"', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.proj_2, raw_json='__SINK_1__'", "expected_violations = set([ lsre.Rule.RuleViolation( resource_name='234', resource_type='organization', resource_id='234', full_name='organization/234/', rule_name='Require an", "sink_id='sink_with_wrong_filter', destination=('pubsub.googleapis.com/projects/proj-3/topics/' 'org-more-logs'), sink_filter='logName:\"logs/otherapi.googleapis.com\"', include_children=True, writer_identity='serviceAccount:<EMAIL>', parent=self.org_234, raw_json='__SINK_2__' ) ]", "= [ LogSink( sink_id='billing_logs', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/billing_logs'), sink_filter='', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.billing_acct_abcd,", "rules_engine = self.get_engine_with_valid_rules() # proj-3 can only have BigQuery sinks.", "self.assertEqual(expected_violations, actual_violations) def test_org_missing_required_sinks(self): \"\"\"Tests violations are produced for an", "'sink': valid_sink_spec, 'mode': 'other', }, { 'name': 'Bad resource type',", "def setUp(self): \"\"\"Set up GCP resources for tests.\"\"\" self.lsre =", "destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/billing_logs'), sink_filter='', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.billing_acct_abcd, raw_json='__SINK_1__' ), ] actual_violations", "+-----> billing_acct_abcd # | # | # +-----------------------> proj-1 #", "'filter': '', 'include_children': '*' } rule_book.add_rule( { 'name': 'Valid rule',", "self.lsre.LogSinkRulesEngine( rules_file_path=rules_local_path) with self.assertRaises(InvalidRulesSchemaError): rules_engine.build_rule_book() def test_project_with_no_violations(self): \"\"\"Tests that no", "= rules_engine.find_violations( self.org_234, log_sinks) expected_violations = set([ lsre.Rule.RuleViolation( resource_name='234', resource_type='organization',", "rule_name='Require an Org Level audit log sink.', rule_index=1, violation_type='LOG_SINK_VIOLATION', sink_destination='^.*$',", "= [ LogSink( sink_id='billing_logs', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/wrong_dataset'), sink_filter='', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.billing_acct_abcd,", "'resource': [{ 'type': 'folder', 'applies_to': 'self_and_children', 'resource_ids': ['56'] }], 'sink':", "= rules_engine.find_violations( self.billing_acct_abcd, log_sinks) expected_violations = set([ lsre.Rule.RuleViolation( resource_type='sink', resource_id='billing_logs',", "}, 'mode': 'whitelist' } ] for rule in bad_rules: with", "ABCD', full_name='organization/234/billingAccount/ABCD-1234/', data='fake_billing_account_data_abcd') self.folder_56 = Folder( '56', display_name='Folder 56', full_name='organization/234/folder/56/',", "'datasets/wrong_dataset'), sink_filter='', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.billing_acct_abcd, raw_json='__SINK_1__' ), ] actual_violations =", "# proj-3 can only have BigQuery sinks. log_sinks = [", "[ LogSink( sink_id='audit_logs_to_bq', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/folder_logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.folder_56, raw_json='__SINK_1__'", "including children. log_sinks = [ LogSink( sink_id='sink_not_including_children', destination=('pubsub.googleapis.com/projects/proj-3/topics/' 'org-audit-logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"',", "test_project_whitelist_violation(self): \"\"\"Tests violations are produced for non-whitelisted sinks.\"\"\" rules_engine =", "full_name='organization/234/', rule_name='Require an Org Level audit log sink.', rule_index=1, violation_type='LOG_SINK_VIOLATION',", "LogSinks. actual_violations = rules_engine.find_violations(self.folder_56, []) self.assertEqual(set(), actual_violations) def test_billing_account_with_no_violations(self): \"\"\"Tests", "LogSink( sink_id='compute_logs_saver', destination=('bigquery.googleapis.com/projects/proj_1/' 'datasets/compute_logs'), sink_filter='resource.type=\"gce_instance\"', include_children=False, writer_identity=('serviceAccount:<PASSWORD>@' 'gcp-sa-logging.iam.gserviceaccount.com'), parent=self.proj_1, raw_json='_SINK_2_'", "sinks.\"\"\" rules_engine = self.get_engine_with_valid_rules() log_sinks = [ LogSink( sink_id='billing_logs', destination=('bigquery.googleapis.com/projects/my-audit-logs/'", "resource_type='sink', resource_id='billing_logs', resource_name='billingAccounts/ABCD-1234/sinks/billing_logs', full_name='organization/234/billingAccount/ABCD-1234/billing_logs/', rule_name=('Only allow Billing Account sinks to", "'sink': { 'destination': 'bigquery.*', 'include_children': '*' }, 'mode': 'whitelist' },", "be created.\"\"\" rules_local_path = get_datafile_path( __file__, 'log_sink_test_invalid_rules.yaml') rules_engine = self.lsre.LogSinkRulesEngine(", "sink, but to any destination. log_sinks = [ LogSink( sink_id='audit_logs_to_pubsub',", "use this file except in compliance with the License. #", "log_sinks) self.assertEqual(set(), actual_violations) def test_org_with_no_violations(self): \"\"\"Tests that no violations are", "Copyright 2018 The Forseti Security Authors. All rights reserved. #", "resource_name='proj-2', resource_type='project', resource_id='proj-2', full_name='organization/234/folder/56/project/proj-2/', rule_name='Require Audit Log sinks in all", "'sink': { 'destination': 'bigquery.*', 'filter': '*', 'include_children': 'Yes' }, 'mode':", "proj-1 needs an Audit Log sink. log_sinks = [ LogSink(", "sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.org_234, raw_json='__SINK_1__' ), LogSink( sink_id='sink_with_wrong_filter', destination=('pubsub.googleapis.com/projects/proj-3/topics/' 'org-more-logs'),", "reserved. # # Licensed under the Apache License, Version 2.0", "'Mising Resource', 'mode': 'whitelist', 'sink': valid_sink_spec, }, { 'name': 'Mising", "self.get_engine_with_valid_rules() # Org needs an Audit Log sink, but to", "\"\"\"Tests violations are produced for blacklisted sinks.\"\"\" rules_engine = self.get_engine_with_valid_rules()", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "resource_name='folders/56/sinks/audit_logs_to_bq', resource_type='sink', resource_id='audit_logs_to_bq', full_name='organization/234/folder/56/audit_logs_to_bq/', rule_name='Disallow folder sinks.', rule_index=2, violation_type='LOG_SINK_VIOLATION', sink_destination=('bigquery.googleapis.com/projects/'", "'project.'), rule_index=6, violation_type='LOG_SINK_VIOLATION', sink_destination=('bigquery.googleapis.com/projects/' 'my-audit-logs/datasets/wrong_dataset'), sink_filter='', sink_include_children=False, resource_data='__SINK_1__') ]) self.assertEqual(expected_violations,", "from tests.unittest_utils import ForsetiTestCase from tests.unittest_utils import get_datafile_path from google.cloud.forseti.common.gcp_type.billing_account", "org-level rules, and a pubsub # sink, by folder-level rules.", "License. # You may obtain a copy of the License", "raw_json='__SINK_1__' ), LogSink( sink_id='compute_logs_saver', destination=('bigquery.googleapis.com/projects/proj_2/' 'datasets/compute_logs'), sink_filter='resource.type=\"gce_instance\"', include_children=False, writer_identity=('serviceAccount:p12345-67890@' 'gcp-sa-logging.iam.gserviceaccount.com'),", "sink_filter='', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.billing_acct_abcd, raw_json='__SINK_1__' ), ] actual_violations = rules_engine.find_violations(", "= [] for resource in rules_engine.rule_book.resource_rules_map['children']: child_rule_resources.append(resource.name) expected_rule_resources = ['folders/56',", "self.org_234 = Organization( '234', display_name='Organization 234', full_name='organization/234/', data='fake_org_data_234') self.billing_acct_abcd =", "resource_name='projects/proj-3/sinks/audit_logs_to_pubsub', resource_type='sink', resource_id='audit_logs_to_pubsub', full_name='organization/234/project/proj-3/audit_logs_to_pubsub/', rule_name='Only allow BigQuery sinks in Proj-1", "{ 'name': 'Bad mode', 'resource': [valid_resource], 'sink': valid_sink_spec, 'mode': 'other',", "] for rule in bad_rules: with self.assertRaises(InvalidRulesSchemaError): rule_book.add_rule(rule, 1) if", "]) self.assertEqual(expected_violations, actual_violations) def test_project_whitelist_violation(self): \"\"\"Tests violations are produced for", "sink_destination=('bigquery.googleapis.com/projects/' 'my-audit-logs/datasets/wrong_dataset'), sink_filter='', sink_include_children=False, resource_data='__SINK_1__') ]) self.assertEqual(expected_violations, actual_violations) def test_org_missing_required_sinks(self):", "InvalidRulesSchemaError class LogSinkRulesEngineTest(ForsetiTestCase): \"\"\"Tests for the LogSinkRulesEngine.\"\"\" def setUp(self): \"\"\"Set", "the LogSinkRulesEngine.\"\"\" def setUp(self): \"\"\"Set up GCP resources for tests.\"\"\"", "actual_violations = rules_engine.find_violations( self.billing_acct_abcd, log_sinks) self.assertEqual(set(), actual_violations) def test_org_with_no_violations(self): \"\"\"Tests", "to any destination. log_sinks = [ LogSink( sink_id='audit_logs_to_pubsub', destination=('pubsub.googleapis.com/projects/proj-3/topics/' 'org-audit-logs'),", "raw_json='__SINK_1__' ), LogSink( sink_id='audit_logs_to_pubsub', destination=('pubsub.googleapis.com/projects/proj-3/topics/' 'proj-audit-logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=True, writer_identity='serviceAccount:<EMAIL>', parent=self.proj_3,", "expected_violations = set([ lsre.Rule.RuleViolation( resource_name='projects/proj-3/sinks/audit_logs_to_pubsub', resource_type='sink', resource_id='audit_logs_to_pubsub', full_name='organization/234/project/proj-3/audit_logs_to_pubsub/', rule_name='Only allow", "under the License is distributed on an \"AS IS\" BASIS,", "are produced for billing account sinks.\"\"\" rules_engine = self.get_engine_with_valid_rules() log_sinks", "lsre.Rule.RuleViolation( resource_type='sink', resource_id='billing_logs', resource_name='billingAccounts/ABCD-1234/sinks/billing_logs', full_name='organization/234/billingAccount/ABCD-1234/billing_logs/', rule_name=('Only allow Billing Account sinks", "}, { 'name': 'Bad resource type', 'resource': [{ 'type': 'bucket',", "actual_violations) def test_folder_with_no_violations(self): \"\"\"Tests that no violations are produced for", "License for the specific language governing permissions and # limitations", "difference resources and 'children' rules # for 2. self.assertEqual( 6,", "resource_data='' ) ]) self.assertEqual(expected_violations, actual_violations) def test_project_whitelist_violation(self): \"\"\"Tests violations are", "for non-whitelisted sinks.\"\"\" rules_engine = self.get_engine_with_valid_rules() # proj-3 can only", "\"\"\"Create a rule engine build with a valid rules file.\"\"\"", "rules for 5 difference resources and 'children' rules # for", "'billingAccounts/ABCD-1234', 'folders/56', 'organizations/234', 'projects/proj-1', 'projects/proj-2', 'projects/proj-3'] self.assertEqual(expected_rule_resources, sorted(self_rule_resources)) child_rule_resources =", "violation_type='LOG_SINK_VIOLATION', sink_destination=('bigquery.googleapis.com/projects/' 'my-audit-logs/datasets/wrong_dataset'), sink_filter='', sink_include_children=False, resource_data='__SINK_1__') ]) self.assertEqual(expected_violations, actual_violations) def", "self.get_engine_with_valid_rules() log_sinks = [ LogSink( sink_id='billing_logs', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/wrong_dataset'), sink_filter='', include_children=False,", "= get_datafile_path( __file__, 'log_sink_test_invalid_rules.yaml') rules_engine = self.lsre.LogSinkRulesEngine( rules_file_path=rules_local_path) with self.assertRaises(InvalidRulesSchemaError):", "needs an Audit Log sink, by org-level rules, and a", "\"\"\"Tests that no violations are produced for a correct organization.\"\"\"", "def test_billing_account_with_whitelist_violations(self): \"\"\"Tests violations are produced for billing account sinks.\"\"\"", "google.cloud.forseti.common.gcp_type.project import Project from google.cloud.forseti.scanner.audit import log_sink_rules_engine as lsre from", "google.cloud.forseti.common.gcp_type.organization import Organization from google.cloud.forseti.common.gcp_type.project import Project from google.cloud.forseti.scanner.audit import", "Account sinks to audit logs ' 'project.'), rule_index=6, violation_type='LOG_SINK_VIOLATION', sink_destination=('bigquery.googleapis.com/projects/'", ") ] actual_violations = rules_engine.find_violations( self.org_234, log_sinks) self.assertEqual(set(), actual_violations) def", "violation_type='LOG_SINK_VIOLATION', sink_destination=('^bigquery\\\\.googleapis\\\\.com\\\\/projects\\\\/' 'my\\\\-audit\\\\-logs\\\\/datasets\\\\/.+$'), sink_filter=('^logName\\\\:\\\\\"logs\\\\/' 'cloudaudit\\\\.googleapis\\\\.com\\\\\"$'), sink_include_children='*', resource_data='' ), lsre.Rule.RuleViolation( resource_name='proj-2',", "project_number=33445566, display_name='My project 3', parent=self.org_234, full_name='organization/234/project/proj-3/', data='fake_project_data_1233') def get_engine_with_valid_rules(self): \"\"\"Create", "'name': 'Bad mode', 'resource': [valid_resource], 'sink': valid_sink_spec, 'mode': 'other', },", "log_sinks = [ LogSink( sink_id='audit_logs_to_pubsub', destination=('pubsub.googleapis.com/projects/proj-3/topics/' 'org-audit-logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=True, writer_identity='serviceAccount:<EMAIL>',", "test_folder_blacklist_violation(self): \"\"\"Tests violations are produced for blacklisted sinks.\"\"\" rules_engine =", "self.proj_2 = Project( 'proj-2', project_number=223344, display_name='My project 2', parent=self.folder_56, full_name='organization/234/folder/56/project/proj-2/',", "'Mising sink', 'resource': [valid_resource], 'mode': 'whitelist', }, { 'name': 'Bad", "full_name='organization/234/folder/56/', data='fake_folder_data456456') self.proj_1 = Project( 'proj-1', project_number=11223344, display_name='My project 1',", "sinks to audit logs ' 'project.'), rule_index=6, violation_type='LOG_SINK_VIOLATION', sink_destination=('bigquery.googleapis.com/projects/' 'my-audit-logs/datasets/wrong_dataset'),", "actual_violations) def test_org_with_no_violations(self): \"\"\"Tests that no violations are produced for", "actual_violations) def test_project_whitelist_violation(self): \"\"\"Tests violations are produced for non-whitelisted sinks.\"\"\"", "[ LogSink( sink_id='audit_logs_to_pubsub', destination=('pubsub.googleapis.com/projects/proj-3/topics/' 'org-audit-logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=True, writer_identity='serviceAccount:<EMAIL>', parent=self.org_234, raw_json='__SINK_1__'", "correct folder.\"\"\" rules_engine = self.get_engine_with_valid_rules() # Rules disallow any folder-level", "'datasets/proj_2_logs'), sink_filter='logName:\"logs/non-cloudaudit.googleapis.com\"', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.proj_2, raw_json='__SINK_1__' ), LogSink( sink_id='compute_logs_saver', destination=('bigquery.googleapis.com/projects/proj_2/'", "in compliance with the License. # You may obtain a", "sink in folder-56 projects.', rule_index=3, violation_type='LOG_SINK_VIOLATION', sink_destination='^pubsub\\\\.googleapis\\\\.com\\\\/.+$', sink_filter='^$', sink_include_children='*', resource_data=''", "tests.unittest_utils import ForsetiTestCase from tests.unittest_utils import get_datafile_path from google.cloud.forseti.common.gcp_type.billing_account import", "all projects.', rule_index=0, violation_type='LOG_SINK_VIOLATION', sink_destination=('^bigquery\\\\.googleapis\\\\.com\\\\/projects\\\\/' 'my\\\\-audit\\\\-logs\\\\/datasets\\\\/.+$'), sink_filter=('^logName\\\\:\\\\\"logs\\\\/' 'cloudaudit\\\\.googleapis\\\\.com\\\\\"$'), sink_include_children='*', resource_data=''", "software # distributed under the License is distributed on an", "def test_project_whitelist_violation(self): \"\"\"Tests violations are produced for non-whitelisted sinks.\"\"\" rules_engine", "'resource_ids': ['bucket-1'] }], 'sink': valid_sink_spec, 'mode': 'whitelist' }, { 'name':", "# Org needs an Audit Log sink, but to any", "ForsetiTestCase from tests.unittest_utils import get_datafile_path from google.cloud.forseti.common.gcp_type.billing_account import BillingAccount from", "# | # +-----------------------> proj-3 self.org_234 = Organization( '234', display_name='Organization", "self.billing_acct_abcd = BillingAccount( 'ABCD-1234', display_name='Billing Account ABCD', full_name='organization/234/billingAccount/ABCD-1234/', data='fake_billing_account_data_abcd') self.folder_56", "any folder-level LogSinks. log_sinks = [ LogSink( sink_id='audit_logs_to_bq', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/folder_logs'),", "that a RuleBook is built correctly with a yaml file.\"\"\"", "sink. log_sinks = [ LogSink( sink_id='audit_logs_to_bq', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/proj_1_logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=False,", "PubSub sink in folder-56 projects.', rule_index=3, violation_type='LOG_SINK_VIOLATION', sink_destination='^pubsub\\\\.googleapis\\\\.com\\\\/.+$', sink_filter='^$', sink_include_children='*',", "}, { 'name': 'Bad include_children', 'resource': [valid_resource], 'sink': { 'destination':", "'resource': [valid_resource], 'mode': 'whitelist', }, { 'name': 'Bad mode', 'resource':", "blacklisted sinks.\"\"\" rules_engine = self.get_engine_with_valid_rules() # Rules disallow any folder-level", "LogSink( sink_id='sink_not_including_children', destination=('pubsub.googleapis.com/projects/proj-3/topics/' 'org-audit-logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.org_234, raw_json='__SINK_1__' ),", "'proj-1', project_number=11223344, display_name='My project 1', parent=self.org_234, full_name='organization/234/project/proj-1/', data='fake_project_data_2341') self.proj_2 =", "def get_engine_with_valid_rules(self): \"\"\"Create a rule engine build with a valid", "and # limitations under the License. \"\"\"Tests the LogSinkRulesEngine.\"\"\" import", "= self.lsre.LogSinkRulesEngine( rules_file_path=rules_local_path) rules_engine.build_rule_book() return rules_engine def test_build_rule_book_from_local_yaml_file_works(self): \"\"\"Tests that", "billing account sinks.\"\"\" rules_engine = self.get_engine_with_valid_rules() log_sinks = [ LogSink(", "[valid_resource], 'sink': valid_sink_spec, 'mode': 'other', }, { 'name': 'Bad resource", "display_name='My project 2', parent=self.folder_56, full_name='organization/234/folder/56/project/proj-2/', data='fake_project_data_4562') self.proj_3 = Project( 'proj-3',", "[valid_resource], 'mode': 'whitelist', }, { 'name': 'Bad mode', 'resource': [valid_resource],", "'whitelist' }, { 'name': 'Bad include_children', 'resource': [valid_resource], 'sink': {", "no violations are produced for a correct billing acct.\"\"\" rules_engine", "'name': 'Bad applies to type', 'resource': [{ 'type': 'billing_account', 'applies_to':", "rule_index=0, violation_type='LOG_SINK_VIOLATION', sink_destination=('^bigquery\\\\.googleapis\\\\.com\\\\/projects\\\\/' 'my\\\\-audit\\\\-logs\\\\/datasets\\\\/.+$'), sink_filter=('^logName\\\\:\\\\\"logs\\\\/' 'cloudaudit\\\\.googleapis\\\\.com\\\\\"$'), sink_include_children='*', resource_data='' ), lsre.Rule.RuleViolation(", "get_engine_with_valid_rules(self): \"\"\"Create a rule engine build with a valid rules", "sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', sink_include_children=False, resource_data='__SINK_1__') ]) self.assertEqual(expected_violations, actual_violations) def test_billing_account_with_whitelist_violations(self): \"\"\"Tests violations", "get_datafile_path( __file__, 'log_sink_test_invalid_rules.yaml') rules_engine = self.lsre.LogSinkRulesEngine( rules_file_path=rules_local_path) with self.assertRaises(InvalidRulesSchemaError): rules_engine.build_rule_book()", "Proj-3.', rule_index=4, violation_type='LOG_SINK_VIOLATION', sink_destination=('pubsub.googleapis.com/projects/proj-3/' 'topics/proj-audit-logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', sink_include_children=True, resource_data='__SINK_2__' ) ])", "[] }], 'sink': valid_sink_spec, 'mode': 'whitelist' }, { 'name': 'Missing", "rules_engine def test_build_rule_book_from_local_yaml_file_works(self): \"\"\"Tests that a RuleBook is built correctly", "billing acct.\"\"\" rules_engine = self.get_engine_with_valid_rules() log_sinks = [ LogSink( sink_id='billing_logs',", "sinks in Proj-1 and Proj-3.', rule_index=4, violation_type='LOG_SINK_VIOLATION', sink_destination=('pubsub.googleapis.com/projects/proj-3/' 'topics/proj-audit-logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"',", "destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/proj_2_logs'), sink_filter='logName:\"logs/non-cloudaudit.googleapis.com\"', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.proj_2, raw_json='__SINK_1__' ), LogSink( sink_id='compute_logs_saver',", "produced for an org missing required sinks.\"\"\" rules_engine = self.get_engine_with_valid_rules()", "'filter': '*', 'include_children': 'Yes' }, 'mode': 'whitelist' } ] for", "'proj-2', project_number=223344, display_name='My project 2', parent=self.folder_56, full_name='organization/234/folder/56/project/proj-2/', data='fake_project_data_4562') self.proj_3 =", "actual_violations = rules_engine.find_violations( self.org_234, log_sinks) self.assertEqual(set(), actual_violations) def test_project_missing_required_sinks(self): \"\"\"Tests", "parent=self.folder_56, raw_json='__SINK_1__' ) ] actual_violations = rules_engine.find_violations( self.folder_56, log_sinks) expected_violations", "'mode': 'other', }, { 'name': 'Bad resource type', 'resource': [{", "# +-----> billing_acct_abcd # | # | # +-----------------------> proj-1", "violation_type='LOG_SINK_VIOLATION', sink_destination='^pubsub\\\\.googleapis\\\\.com\\\\/.+$', sink_filter='^$', sink_include_children='*', resource_data='' ) ]) self.assertEqual(expected_violations, actual_violations) def", "self.get_engine_with_valid_rules() # Org needs an Audit Log sink, including children.", "import Organization from google.cloud.forseti.common.gcp_type.project import Project from google.cloud.forseti.scanner.audit import log_sink_rules_engine", "a correct billing acct.\"\"\" rules_engine = self.get_engine_with_valid_rules() log_sinks = [", "only have BigQuery sinks. log_sinks = [ LogSink( sink_id='audit_logs_to_bq', destination=('bigquery.googleapis.com/projects/my-audit-logs/'", "resource_data='' ), lsre.Rule.RuleViolation( resource_name='proj-2', resource_type='project', resource_id='proj-2', full_name='organization/234/folder/56/project/proj-2/', rule_name='Require a PubSub", "test_org_missing_required_sinks(self): \"\"\"Tests violations are produced for an org missing required", "'my-audit-logs/datasets/wrong_dataset'), sink_filter='', sink_include_children=False, resource_data='__SINK_1__') ]) self.assertEqual(expected_violations, actual_violations) def test_org_missing_required_sinks(self): \"\"\"Tests", "folder sinks.', rule_index=2, violation_type='LOG_SINK_VIOLATION', sink_destination=('bigquery.googleapis.com/projects/' 'my-audit-logs/datasets/folder_logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', sink_include_children=False, resource_data='__SINK_1__') ])", "google.cloud.forseti.common.gcp_type.log_sink import LogSink from google.cloud.forseti.common.gcp_type.organization import Organization from google.cloud.forseti.common.gcp_type.project import", "sink_filter='resource.type=\"gce_instance\"', include_children=False, writer_identity=('serviceAccount:<PASSWORD>@' 'gcp-sa-logging.iam.gserviceaccount.com'), parent=self.proj_1, raw_json='_SINK_2_' ) ] actual_violations =", "import mock from tests.unittest_utils import ForsetiTestCase from tests.unittest_utils import get_datafile_path", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "are produced for blacklisted sinks.\"\"\" rules_engine = self.get_engine_with_valid_rules() # Rules", "'name': 'Valid rule', 'resource': [valid_resource], 'sink': valid_sink_spec, 'mode': 'whitelist' },", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "in bad_rules: with self.assertRaises(InvalidRulesSchemaError): rule_book.add_rule(rule, 1) if __name__ == '__main__':", "test_billing_account_with_whitelist_violations(self): \"\"\"Tests violations are produced for billing account sinks.\"\"\" rules_engine", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "an Audit Log sink, by org-level rules, and a pubsub", "lsre.Rule.RuleViolation( resource_name='folders/56/sinks/audit_logs_to_bq', resource_type='sink', resource_id='audit_logs_to_bq', full_name='organization/234/folder/56/audit_logs_to_bq/', rule_name='Disallow folder sinks.', rule_index=2, violation_type='LOG_SINK_VIOLATION',", "test_add_invalid_rules(self): \"\"\"Tests that adding invalid rules raises exceptions.\"\"\" rule_book =", "include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.proj_3, raw_json='__SINK_1__' ), LogSink( sink_id='audit_logs_to_pubsub', destination=('pubsub.googleapis.com/projects/proj-3/topics/' 'proj-audit-logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"',", "to in writing, software # distributed under the License is", "= lsre self.lsre.LOGGER = mock.MagicMock() # Set up resources in", "'datasets/billing_logs'), sink_filter='', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.billing_acct_abcd, raw_json='__SINK_1__' ), ] actual_violations =", "'name': 'Missing filter', 'resource': [valid_resource], 'sink': { 'destination': 'bigquery.*', 'include_children':", "# See the License for the specific language governing permissions", "\"\"\"Tests for the LogSinkRulesEngine.\"\"\" def setUp(self): \"\"\"Set up GCP resources", "{ 'type': 'organization', 'applies_to': 'children', 'resource_ids': ['1234'] } valid_sink_spec =", "actual_violations = rules_engine.find_violations( self.proj_3, log_sinks) expected_violations = set([ lsre.Rule.RuleViolation( resource_name='projects/proj-3/sinks/audit_logs_to_pubsub',", "self.get_engine_with_valid_rules() # proj-1 needs an Audit Log sink. log_sinks =", "destination. log_sinks = [ LogSink( sink_id='audit_logs_to_pubsub', destination=('pubsub.googleapis.com/projects/proj-3/topics/' 'org-audit-logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=True,", "raw_json='__SINK_1__' ) ] actual_violations = rules_engine.find_violations( self.org_234, log_sinks) self.assertEqual(set(), actual_violations)", "full_name='organization/234/billingAccount/ABCD-1234/billing_logs/', rule_name=('Only allow Billing Account sinks to audit logs '", "'mode': 'whitelist' }, { 'name': 'Missing filter', 'resource': [valid_resource], 'sink':", "= { 'destination': 'bigquery.*', 'filter': '', 'include_children': '*' } rule_book.add_rule(", "or agreed to in writing, software # distributed under the", "produced for a correct folder.\"\"\" rules_engine = self.get_engine_with_valid_rules() # Rules", "'resource_ids': ['ABCD-1234'] }], 'sink': valid_sink_spec, 'mode': 'whitelist' }, { 'name':", "required by applicable law or agreed to in writing, software", "'proj-3', project_number=33445566, display_name='My project 3', parent=self.org_234, full_name='organization/234/project/proj-3/', data='fake_project_data_1233') def get_engine_with_valid_rules(self):", "'gcp-sa-logging.iam.gserviceaccount.com'), parent=self.proj_1, raw_json='_SINK_2_' ) ] actual_violations = rules_engine.find_violations( self.proj_1, log_sinks)", "sink_filter='^$', sink_include_children='*', resource_data='' ) ]) self.assertEqual(expected_violations, actual_violations) def test_project_whitelist_violation(self): \"\"\"Tests", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "}, { 'name': 'Missing filter', 'resource': [valid_resource], 'sink': { 'destination':", "), LogSink( sink_id='audit_logs_to_pubsub', destination=('pubsub.googleapis.com/projects/proj-3/topics/' 'proj-audit-logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=True, writer_identity='serviceAccount:<EMAIL>', parent=self.proj_3, raw_json='__SINK_2__'", "are produced for a correct billing acct.\"\"\" rules_engine = self.get_engine_with_valid_rules()", "folder-level LogSinks. log_sinks = [ LogSink( sink_id='audit_logs_to_bq', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/folder_logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"',", "with the License. # You may obtain a copy of", "raw_json='__SINK_1__' ), ] actual_violations = rules_engine.find_violations( self.billing_acct_abcd, log_sinks) expected_violations =", "folder-level LogSinks. actual_violations = rules_engine.find_violations(self.folder_56, []) self.assertEqual(set(), actual_violations) def test_billing_account_with_no_violations(self):", "self.proj_3, log_sinks) expected_violations = set([ lsre.Rule.RuleViolation( resource_name='projects/proj-3/sinks/audit_logs_to_pubsub', resource_type='sink', resource_id='audit_logs_to_pubsub', full_name='organization/234/project/proj-3/audit_logs_to_pubsub/',", "valid_sink_spec, 'mode': 'other', }, { 'name': 'Bad resource type', 'resource':", "produced for a correct billing acct.\"\"\" rules_engine = self.get_engine_with_valid_rules() log_sinks", "'datasets/folder_logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.folder_56, raw_json='__SINK_1__' ) ] actual_violations =", "Folder from google.cloud.forseti.common.gcp_type.log_sink import LogSink from google.cloud.forseti.common.gcp_type.organization import Organization from", "proj-1 # | # | # org_234 +-----> folder_56 +----->", "with a yaml file.\"\"\" rules_engine = self.get_engine_with_valid_rules() # Creates 'self'", "account sinks.\"\"\" rules_engine = self.get_engine_with_valid_rules() log_sinks = [ LogSink( sink_id='billing_logs',", "audit logs ' 'project.'), rule_index=6, violation_type='LOG_SINK_VIOLATION', sink_destination=('bigquery.googleapis.com/projects/' 'my-audit-logs/datasets/wrong_dataset'), sink_filter='', sink_include_children=False,", "'whitelist' }, 0) bad_rules = [ {}, { 'name': 'Mising", "sink_destination=('^bigquery\\\\.googleapis\\\\.com\\\\/projects\\\\/' 'my\\\\-audit\\\\-logs\\\\/datasets\\\\/.+$'), sink_filter=('^logName\\\\:\\\\\"logs\\\\/' 'cloudaudit\\\\.googleapis\\\\.com\\\\\"$'), sink_include_children='*', resource_data='' ), lsre.Rule.RuleViolation( resource_name='proj-2', resource_type='project',", "= [ {}, { 'name': 'Mising Resource', 'mode': 'whitelist', 'sink':", "'resource': [{ 'type': 'billing_account', 'applies_to': 'children', 'resource_ids': ['ABCD-1234'] }], 'sink':", "Project from google.cloud.forseti.scanner.audit import log_sink_rules_engine as lsre from google.cloud.forseti.scanner.audit.errors import", "] actual_violations = rules_engine.find_violations( self.org_234, log_sinks) expected_violations = set([ lsre.Rule.RuleViolation(", "'56', display_name='Folder 56', full_name='organization/234/folder/56/', data='fake_folder_data456456') self.proj_1 = Project( 'proj-1', project_number=11223344,", "resource_type='sink', resource_id='audit_logs_to_pubsub', full_name='organization/234/project/proj-3/audit_logs_to_pubsub/', rule_name='Only allow BigQuery sinks in Proj-1 and", "sink_id='audit_logs_to_pubsub', destination=('pubsub.googleapis.com/projects/proj-3/topics/' 'proj-audit-logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=True, writer_identity='serviceAccount:<EMAIL>', parent=self.proj_3, raw_json='__SINK_2__' ) ]", "correctly with a yaml file.\"\"\" rules_engine = self.get_engine_with_valid_rules() # Creates", "['ABCD-1234'] }], 'sink': valid_sink_spec, 'mode': 'whitelist' }, { 'name': 'Empty", "Org Level audit log sink.', rule_index=1, violation_type='LOG_SINK_VIOLATION', sink_destination='^.*$', sink_filter=('^logName\\\\:\\\\\"logs\\\\/' 'cloudaudit\\\\.googleapis\\\\.com\\\\\"$'),", "'whitelist' }, { 'name': 'Bad applies to type', 'resource': [{", "self.assertEqual(expected_violations, actual_violations) def test_billing_account_with_whitelist_violations(self): \"\"\"Tests violations are produced for billing", "produced for non-whitelisted sinks.\"\"\" rules_engine = self.get_engine_with_valid_rules() # proj-3 can", "'Empty resource_ids', 'resource': [{ 'type': 'project', 'applies_to': 'self', 'resource_ids': []", "'resource': [valid_resource], 'sink': { 'destination': 'bigquery.*', 'filter': '*', 'include_children': 'Yes'", "compliance with the License. # You may obtain a copy", "log_sinks) expected_violations = set([ lsre.Rule.RuleViolation( resource_name='projects/proj-3/sinks/audit_logs_to_pubsub', resource_type='sink', resource_id='audit_logs_to_pubsub', full_name='organization/234/project/proj-3/audit_logs_to_pubsub/', rule_name='Only", "agreed to in writing, software # distributed under the License", "correct organization.\"\"\" rules_engine = self.get_engine_with_valid_rules() # Org needs an Audit", "\"\"\"Tests the LogSinkRulesEngine.\"\"\" import unittest import mock from tests.unittest_utils import", "log_sinks = [ LogSink( sink_id='non_audit_logs_to_bq', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/proj_2_logs'), sink_filter='logName:\"logs/non-cloudaudit.googleapis.com\"', include_children=False, writer_identity='serviceAccount:<EMAIL>',", "a RuleBook is built correctly with a yaml file.\"\"\" rules_engine", "self.assertEqual(set(), actual_violations) def test_folder_with_no_violations(self): \"\"\"Tests that no violations are produced", "have BigQuery sinks. log_sinks = [ LogSink( sink_id='audit_logs_to_bq', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/proj_1_logs'),", "resource_type='organization', resource_id='234', full_name='organization/234/', rule_name='Require an Org Level audit log sink.',", "actual_violations) def test_folder_blacklist_violation(self): \"\"\"Tests violations are produced for blacklisted sinks.\"\"\"", "self.billing_acct_abcd, log_sinks) expected_violations = set([ lsre.Rule.RuleViolation( resource_type='sink', resource_id='billing_logs', resource_name='billingAccounts/ABCD-1234/sinks/billing_logs', full_name='organization/234/billingAccount/ABCD-1234/billing_logs/',", "type', 'resource': [{ 'type': 'bucket', 'applies_to': 'self', 'resource_ids': ['bucket-1'] }],", "distributed under the License is distributed on an \"AS IS\"", "proj-3 self.org_234 = Organization( '234', display_name='Organization 234', full_name='organization/234/', data='fake_org_data_234') self.billing_acct_abcd", "valid_sink_spec = { 'destination': 'bigquery.*', 'filter': '', 'include_children': '*' }", "project 3', parent=self.org_234, full_name='organization/234/project/proj-3/', data='fake_project_data_1233') def get_engine_with_valid_rules(self): \"\"\"Create a rule", "= self.get_engine_with_valid_rules() # proj-2 needs an Audit Log sink, by", "that no violations are produced for a correct project.\"\"\" rules_engine", "'children' rules # for 2. self.assertEqual( 6, len(rules_engine.rule_book.resource_rules_map['self'])) self.assertEqual( 2,", "invalid rules raises exceptions.\"\"\" rule_book = self.lsre.LogSinkRuleBook(global_configs=None) valid_resource = {", "Billing Account sinks to audit logs ' 'project.'), rule_index=6, violation_type='LOG_SINK_VIOLATION',", "resource type', 'resource': [{ 'type': 'bucket', 'applies_to': 'self', 'resource_ids': ['bucket-1']", "'type': 'billing_account', 'applies_to': 'children', 'resource_ids': ['ABCD-1234'] }], 'sink': valid_sink_spec, 'mode':", "express or implied. # See the License for the specific", "in the following hierarchy: # +-----> billing_acct_abcd # | #", "except in compliance with the License. # You may obtain", "parent=self.proj_2, raw_json='__SINK_2__' ) ] actual_violations = rules_engine.find_violations( self.proj_2, log_sinks) expected_violations", "'cloudaudit\\\\.googleapis\\\\.com\\\\\"$'), sink_include_children='*', resource_data='' ), lsre.Rule.RuleViolation( resource_name='proj-2', resource_type='project', resource_id='proj-2', full_name='organization/234/folder/56/project/proj-2/', rule_name='Require", "= { 'type': 'organization', 'applies_to': 'children', 'resource_ids': ['1234'] } valid_sink_spec", "are produced for a correct project.\"\"\" rules_engine = self.get_engine_with_valid_rules() #", "raw_json='_SINK_1_' ), LogSink( sink_id='compute_logs_saver', destination=('bigquery.googleapis.com/projects/proj_1/' 'datasets/compute_logs'), sink_filter='resource.type=\"gce_instance\"', include_children=False, writer_identity=('serviceAccount:<PASSWORD>@' 'gcp-sa-logging.iam.gserviceaccount.com'),", "and Proj-3.', rule_index=4, violation_type='LOG_SINK_VIOLATION', sink_destination=('pubsub.googleapis.com/projects/proj-3/' 'topics/proj-audit-logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', sink_include_children=True, resource_data='__SINK_2__' )", "= BillingAccount( 'ABCD-1234', display_name='Billing Account ABCD', full_name='organization/234/billingAccount/ABCD-1234/', data='fake_billing_account_data_abcd') self.folder_56 =", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "log_sinks = [ LogSink( sink_id='sink_not_including_children', destination=('pubsub.googleapis.com/projects/proj-3/topics/' 'org-audit-logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=False, writer_identity='serviceAccount:<EMAIL>',", "filter', 'resource': [valid_resource], 'sink': { 'destination': 'bigquery.*', 'include_children': '*' },", "from google.cloud.forseti.common.gcp_type.log_sink import LogSink from google.cloud.forseti.common.gcp_type.organization import Organization from google.cloud.forseti.common.gcp_type.project", "sink', 'resource': [valid_resource], 'mode': 'whitelist', }, { 'name': 'Bad mode',", "not use this file except in compliance with the License.", "'mode': 'whitelist' }, { 'name': 'Bad include_children', 'resource': [valid_resource], 'sink':", "'resource_ids': ['56'] }], 'sink': valid_sink_spec, 'mode': 'whitelist' }, { 'name':", "LogSink( sink_id='audit_logs_to_bq', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/proj_1_logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.proj_3, raw_json='__SINK_1__' ),", "\"\"\"Tests violations are produced for project missing required sinks.\"\"\" rules_engine", "rules_engine = self.get_engine_with_valid_rules() # Rules disallow any folder-level LogSinks. actual_violations", "parent=self.proj_3, raw_json='__SINK_2__' ) ] actual_violations = rules_engine.find_violations( self.proj_3, log_sinks) expected_violations", "writing, software # distributed under the License is distributed on", "'include_children': 'Yes' }, 'mode': 'whitelist' } ] for rule in", "'applies_to': 'children', 'resource_ids': ['ABCD-1234'] }], 'sink': valid_sink_spec, 'mode': 'whitelist' },", "resource_data='__SINK_2__' ) ]) self.assertEqual(expected_violations, actual_violations) def test_folder_blacklist_violation(self): \"\"\"Tests violations are", "you may not use this file except in compliance with", "BillingAccount( 'ABCD-1234', display_name='Billing Account ABCD', full_name='organization/234/billingAccount/ABCD-1234/', data='fake_billing_account_data_abcd') self.folder_56 = Folder(", "sink_id='non_audit_logs_to_bq', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/proj_2_logs'), sink_filter='logName:\"logs/non-cloudaudit.googleapis.com\"', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.proj_2, raw_json='__SINK_1__' ), LogSink(", "get_datafile_path( __file__, 'log_sink_test_valid_rules.yaml') rules_engine = self.lsre.LogSinkRulesEngine( rules_file_path=rules_local_path) rules_engine.build_rule_book() return rules_engine", ") ]) self.assertEqual(expected_violations, actual_violations) def test_project_whitelist_violation(self): \"\"\"Tests violations are produced", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "for a correct billing acct.\"\"\" rules_engine = self.get_engine_with_valid_rules() log_sinks =", "sink_id='sink_not_including_children', destination=('pubsub.googleapis.com/projects/proj-3/topics/' 'org-audit-logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.org_234, raw_json='__SINK_1__' ), LogSink(", "valid_sink_spec, 'mode': 'whitelist' }, { 'name': 'Missing filter', 'resource': [valid_resource],", "'self', 'resource_ids': ['bucket-1'] }], 'sink': valid_sink_spec, 'mode': 'whitelist' }, {", "writer_identity='serviceAccount:<EMAIL>', parent=self.proj_3, raw_json='__SINK_1__' ), LogSink( sink_id='audit_logs_to_pubsub', destination=('pubsub.googleapis.com/projects/proj-3/topics/' 'proj-audit-logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=True,", "}, { 'name': 'Bad mode', 'resource': [valid_resource], 'sink': valid_sink_spec, 'mode':", "{ 'name': 'Bad include_children', 'resource': [valid_resource], 'sink': { 'destination': 'bigquery.*',", "Audit Log sink, but to any destination. log_sinks = [", "set([ lsre.Rule.RuleViolation( resource_type='sink', resource_id='billing_logs', resource_name='billingAccounts/ABCD-1234/sinks/billing_logs', full_name='organization/234/billingAccount/ABCD-1234/billing_logs/', rule_name=('Only allow Billing Account", "parent=self.billing_acct_abcd, raw_json='__SINK_1__' ), ] actual_violations = rules_engine.find_violations( self.billing_acct_abcd, log_sinks) expected_violations", "'sink': valid_sink_spec, 'mode': 'whitelist' }, 0) bad_rules = [ {},", "] actual_violations = rules_engine.find_violations( self.org_234, log_sinks) self.assertEqual(set(), actual_violations) def test_project_missing_required_sinks(self):", "project.\"\"\" rules_engine = self.get_engine_with_valid_rules() # proj-1 needs an Audit Log", "destination=('pubsub.googleapis.com/projects/proj-3/topics/' 'proj-audit-logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=True, writer_identity='serviceAccount:<EMAIL>', parent=self.proj_3, raw_json='__SINK_2__' ) ] actual_violations", "valid rules file.\"\"\" rules_local_path = get_datafile_path( __file__, 'log_sink_test_valid_rules.yaml') rules_engine =", "violations are produced for billing account sinks.\"\"\" rules_engine = self.get_engine_with_valid_rules()", "2. self.assertEqual( 6, len(rules_engine.rule_book.resource_rules_map['self'])) self.assertEqual( 2, len(rules_engine.rule_book.resource_rules_map['children'])) self_rule_resources = []", "sink_include_children='*', resource_data='' ), lsre.Rule.RuleViolation( resource_name='proj-2', resource_type='project', resource_id='proj-2', full_name='organization/234/folder/56/project/proj-2/', rule_name='Require a", "pubsub # sink, by folder-level rules. log_sinks = [ LogSink(", "resources for tests.\"\"\" self.lsre = lsre self.lsre.LOGGER = mock.MagicMock() #", "def test_add_invalid_rules(self): \"\"\"Tests that adding invalid rules raises exceptions.\"\"\" rule_book", "resource_ids', 'resource': [{ 'type': 'project', 'applies_to': 'self', 'resource_ids': [] }],", "BigQuery sinks in Proj-1 and Proj-3.', rule_index=4, violation_type='LOG_SINK_VIOLATION', sink_destination=('pubsub.googleapis.com/projects/proj-3/' 'topics/proj-audit-logs'),", "no violations are produced for a correct folder.\"\"\" rules_engine =", "test_project_with_no_violations(self): \"\"\"Tests that no violations are produced for a correct", "violations are produced for a correct billing acct.\"\"\" rules_engine =", "bad_rules = [ {}, { 'name': 'Mising Resource', 'mode': 'whitelist',", "| # org_234 +-----> folder_56 +-----> proj-2 # | #", "CONDITIONS OF ANY KIND, either express or implied. # See", "\"\"\"Tests that no violations are produced for a correct project.\"\"\"", "Audit Log sinks in all projects.', rule_index=0, violation_type='LOG_SINK_VIOLATION', sink_destination=('^bigquery\\\\.googleapis\\\\.com\\\\/projects\\\\/' 'my\\\\-audit\\\\-logs\\\\/datasets\\\\/.+$'),", "'destination': 'bigquery.*', 'include_children': '*' }, 'mode': 'whitelist' }, { 'name':", "+-----> folder_56 +-----> proj-2 # | # | # +----------------------->", "language governing permissions and # limitations under the License. \"\"\"Tests", "display_name='My project 3', parent=self.org_234, full_name='organization/234/project/proj-3/', data='fake_project_data_1233') def get_engine_with_valid_rules(self): \"\"\"Create a", "]) self.assertEqual(expected_violations, actual_violations) def test_org_missing_required_sinks(self): \"\"\"Tests violations are produced for", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "self.assertEqual(expected_rule_resources, sorted(child_rule_resources)) def test_build_rule_book_invalid_applies_to_fails(self): \"\"\"Tests that a rule with invalid", "sinks.\"\"\" rules_engine = self.get_engine_with_valid_rules() # proj-3 can only have BigQuery", "Log sink, by org-level rules, and a pubsub # sink,", "log_sinks = [ LogSink( sink_id='billing_logs', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/billing_logs'), sink_filter='', include_children=False, writer_identity='serviceAccount:<EMAIL>',", "LogSinks. log_sinks = [ LogSink( sink_id='audit_logs_to_bq', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/folder_logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=False,", "raw_json='__SINK_2__' ) ] actual_violations = rules_engine.find_violations( self.org_234, log_sinks) expected_violations =", "that no violations are produced for a correct billing acct.\"\"\"", "to type', 'resource': [{ 'type': 'billing_account', 'applies_to': 'children', 'resource_ids': ['ABCD-1234']", "rule_index=2, violation_type='LOG_SINK_VIOLATION', sink_destination=('bigquery.googleapis.com/projects/' 'my-audit-logs/datasets/folder_logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', sink_include_children=False, resource_data='__SINK_1__') ]) self.assertEqual(expected_violations, actual_violations)", "Org needs an Audit Log sink, but to any destination.", "needs an Audit Log sink, including children. log_sinks = [", "actual_violations) def test_project_missing_required_sinks(self): \"\"\"Tests violations are produced for project missing", "= rules_engine.find_violations( self.org_234, log_sinks) self.assertEqual(set(), actual_violations) def test_project_missing_required_sinks(self): \"\"\"Tests violations", "sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=True, writer_identity='serviceAccount:<EMAIL>', parent=self.proj_3, raw_json='__SINK_2__' ) ] actual_violations = rules_engine.find_violations(", "'organization', 'applies_to': 'children', 'resource_ids': ['1234'] } valid_sink_spec = { 'destination':", "'projects/proj-1', 'projects/proj-2', 'projects/proj-3'] self.assertEqual(expected_rule_resources, sorted(self_rule_resources)) child_rule_resources = [] for resource", "set([ lsre.Rule.RuleViolation( resource_name='proj-2', resource_type='project', resource_id='proj-2', full_name='organization/234/folder/56/project/proj-2/', rule_name='Require Audit Log sinks", "| # +-----------------------> proj-3 self.org_234 = Organization( '234', display_name='Organization 234',", "disallow any folder-level LogSinks. actual_violations = rules_engine.find_violations(self.folder_56, []) self.assertEqual(set(), actual_violations)", "self_rule_resources = [] for resource in rules_engine.rule_book.resource_rules_map['self']: self_rule_resources.append(resource.name) expected_rule_resources =", "The Forseti Security Authors. All rights reserved. # # Licensed", "sink_id='audit_logs_to_pubsub', destination=('pubsub.googleapis.com/projects/proj-3/topics/' 'org-audit-logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=True, writer_identity='serviceAccount:<EMAIL>', parent=self.org_234, raw_json='__SINK_1__' ) ]", "\"\"\"Set up GCP resources for tests.\"\"\" self.lsre = lsre self.lsre.LOGGER", "include_children=True, writer_identity='serviceAccount:<EMAIL>', parent=self.org_234, raw_json='__SINK_1__' ) ] actual_violations = rules_engine.find_violations( self.org_234,", "'topics/proj-audit-logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', sink_include_children=True, resource_data='__SINK_2__' ) ]) self.assertEqual(expected_violations, actual_violations) def test_folder_blacklist_violation(self):", "test_build_rule_book_from_local_yaml_file_works(self): \"\"\"Tests that a RuleBook is built correctly with a", "'org-audit-logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=True, writer_identity='serviceAccount:<EMAIL>', parent=self.org_234, raw_json='__SINK_1__' ) ] actual_violations =", "data='fake_org_data_234') self.billing_acct_abcd = BillingAccount( 'ABCD-1234', display_name='Billing Account ABCD', full_name='organization/234/billingAccount/ABCD-1234/', data='fake_billing_account_data_abcd')", "= [ LogSink( sink_id='audit_logs_to_bq', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/folder_logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.folder_56,", "in rules_engine.rule_book.resource_rules_map['children']: child_rule_resources.append(resource.name) expected_rule_resources = ['folders/56', 'organizations/234'] self.assertEqual(expected_rule_resources, sorted(child_rule_resources)) def", "resource_id='billing_logs', resource_name='billingAccounts/ABCD-1234/sinks/billing_logs', full_name='organization/234/billingAccount/ABCD-1234/billing_logs/', rule_name=('Only allow Billing Account sinks to audit", "{ 'name': 'Bad applies to type', 'resource': [{ 'type': 'billing_account',", "Rules disallow any folder-level LogSinks. actual_violations = rules_engine.find_violations(self.folder_56, []) self.assertEqual(set(),", "for project missing required sinks.\"\"\" rules_engine = self.get_engine_with_valid_rules() # proj-2", "rule_name='Only allow BigQuery sinks in Proj-1 and Proj-3.', rule_index=4, violation_type='LOG_SINK_VIOLATION',", "self.org_234, log_sinks) expected_violations = set([ lsre.Rule.RuleViolation( resource_name='234', resource_type='organization', resource_id='234', full_name='organization/234/',", "self.assertEqual(expected_violations, actual_violations) def test_project_whitelist_violation(self): \"\"\"Tests violations are produced for non-whitelisted", "+-----> proj-2 # | # | # +-----------------------> proj-3 self.org_234", "valid_sink_spec, 'mode': 'whitelist' }, { 'name': 'Bad applies to type',", "Organization( '234', display_name='Organization 234', full_name='organization/234/', data='fake_org_data_234') self.billing_acct_abcd = BillingAccount( 'ABCD-1234',", "Proj-1 and Proj-3.', rule_index=4, violation_type='LOG_SINK_VIOLATION', sink_destination=('pubsub.googleapis.com/projects/proj-3/' 'topics/proj-audit-logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', sink_include_children=True, resource_data='__SINK_2__'", "# +-----------------------> proj-3 self.org_234 = Organization( '234', display_name='Organization 234', full_name='organization/234/',", "def test_billing_account_with_no_violations(self): \"\"\"Tests that no violations are produced for a", "needs an Audit Log sink. log_sinks = [ LogSink( sink_id='audit_logs_to_bq',", "self.get_engine_with_valid_rules() # Rules disallow any folder-level LogSinks. actual_violations = rules_engine.find_violations(self.folder_56,", "bad_rules: with self.assertRaises(InvalidRulesSchemaError): rule_book.add_rule(rule, 1) if __name__ == '__main__': unittest.main()", "= self.get_engine_with_valid_rules() # Creates 'self' rules for 5 difference resources", "[]) self.assertEqual(set(), actual_violations) def test_billing_account_with_no_violations(self): \"\"\"Tests that no violations are", "a yaml file.\"\"\" rules_engine = self.get_engine_with_valid_rules() # Creates 'self' rules", "valid_sink_spec, }, { 'name': 'Mising sink', 'resource': [valid_resource], 'mode': 'whitelist',", "actual_violations = rules_engine.find_violations( self.org_234, log_sinks) expected_violations = set([ lsre.Rule.RuleViolation( resource_name='234',", "self.get_engine_with_valid_rules() # Creates 'self' rules for 5 difference resources and", "rules_file_path=rules_local_path) with self.assertRaises(InvalidRulesSchemaError): rules_engine.build_rule_book() def test_project_with_no_violations(self): \"\"\"Tests that no violations", "resource_id='234', full_name='organization/234/', rule_name='Require an Org Level audit log sink.', rule_index=1,", "OR CONDITIONS OF ANY KIND, either express or implied. #", "6, len(rules_engine.rule_book.resource_rules_map['self'])) self.assertEqual( 2, len(rules_engine.rule_book.resource_rules_map['children'])) self_rule_resources = [] for resource", "type', 'resource': [{ 'type': 'billing_account', 'applies_to': 'children', 'resource_ids': ['ABCD-1234'] }],", "folder_56 +-----> proj-2 # | # | # +-----------------------> proj-3", "def test_org_with_no_violations(self): \"\"\"Tests that no violations are produced for a", "'Valid rule', 'resource': [valid_resource], 'sink': valid_sink_spec, 'mode': 'whitelist' }, 0)", "the License is distributed on an \"AS IS\" BASIS, #", "# Set up resources in the following hierarchy: # +----->", "rules_engine.find_violations( self.proj_3, log_sinks) expected_violations = set([ lsre.Rule.RuleViolation( resource_name='projects/proj-3/sinks/audit_logs_to_pubsub', resource_type='sink', resource_id='audit_logs_to_pubsub',", "LogSink( sink_id='audit_logs_to_pubsub', destination=('pubsub.googleapis.com/projects/proj-3/topics/' 'proj-audit-logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=True, writer_identity='serviceAccount:<EMAIL>', parent=self.proj_3, raw_json='__SINK_2__' )", "2', parent=self.folder_56, full_name='organization/234/folder/56/project/proj-2/', data='fake_project_data_4562') self.proj_3 = Project( 'proj-3', project_number=33445566, display_name='My", "a correct folder.\"\"\" rules_engine = self.get_engine_with_valid_rules() # Rules disallow any", "'gcp-sa-logging.iam.gserviceaccount.com'), parent=self.proj_2, raw_json='__SINK_2__' ) ] actual_violations = rules_engine.find_violations( self.proj_2, log_sinks)", "log_sinks) expected_violations = set([ lsre.Rule.RuleViolation( resource_name='proj-2', resource_type='project', resource_id='proj-2', full_name='organization/234/folder/56/project/proj-2/', rule_name='Require", "{ 'name': 'Mising sink', 'resource': [valid_resource], 'mode': 'whitelist', }, {", "are produced for project missing required sinks.\"\"\" rules_engine = self.get_engine_with_valid_rules()", "rule_index=4, violation_type='LOG_SINK_VIOLATION', sink_destination=('pubsub.googleapis.com/projects/proj-3/' 'topics/proj-audit-logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', sink_include_children=True, resource_data='__SINK_2__' ) ]) self.assertEqual(expected_violations,", "data='fake_project_data_2341') self.proj_2 = Project( 'proj-2', project_number=223344, display_name='My project 2', parent=self.folder_56,", "[ LogSink( sink_id='audit_logs_to_bq', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/proj_1_logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.proj_3, raw_json='__SINK_1__'", "def test_build_rule_book_from_local_yaml_file_works(self): \"\"\"Tests that a RuleBook is built correctly with", "self.billing_acct_abcd, log_sinks) self.assertEqual(set(), actual_violations) def test_org_with_no_violations(self): \"\"\"Tests that no violations", "actual_violations) def test_billing_account_with_whitelist_violations(self): \"\"\"Tests violations are produced for billing account", "self.get_engine_with_valid_rules() # proj-3 can only have BigQuery sinks. log_sinks =", "rules_engine.rule_book.resource_rules_map['self']: self_rule_resources.append(resource.name) expected_rule_resources = [ 'billingAccounts/ABCD-1234', 'folders/56', 'organizations/234', 'projects/proj-1', 'projects/proj-2',", "'mode': 'whitelist' }, { 'name': 'Empty resource_ids', 'resource': [{ 'type':", "sinks.\"\"\" rules_engine = self.get_engine_with_valid_rules() # proj-2 needs an Audit Log", "proj-2 needs an Audit Log sink, by org-level rules, and", "writer_identity='serviceAccount:<EMAIL>', parent=self.proj_2, raw_json='__SINK_1__' ), LogSink( sink_id='compute_logs_saver', destination=('bigquery.googleapis.com/projects/proj_2/' 'datasets/compute_logs'), sink_filter='resource.type=\"gce_instance\"', include_children=False,", "= set([ lsre.Rule.RuleViolation( resource_name='folders/56/sinks/audit_logs_to_bq', resource_type='sink', resource_id='audit_logs_to_bq', full_name='organization/234/folder/56/audit_logs_to_bq/', rule_name='Disallow folder sinks.',", "up GCP resources for tests.\"\"\" self.lsre = lsre self.lsre.LOGGER =", "'datasets/proj_1_logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.proj_3, raw_json='__SINK_1__' ), LogSink( sink_id='audit_logs_to_pubsub', destination=('pubsub.googleapis.com/projects/proj-3/topics/'", "self_rule_resources.append(resource.name) expected_rule_resources = [ 'billingAccounts/ABCD-1234', 'folders/56', 'organizations/234', 'projects/proj-1', 'projects/proj-2', 'projects/proj-3']", "writer_identity='serviceAccount:<EMAIL>', parent=self.proj_3, raw_json='__SINK_2__' ) ] actual_violations = rules_engine.find_violations( self.proj_3, log_sinks)", "full_name='organization/234/project/proj-3/audit_logs_to_pubsub/', rule_name='Only allow BigQuery sinks in Proj-1 and Proj-3.', rule_index=4,", ") ]) self.assertEqual(expected_violations, actual_violations) def test_folder_blacklist_violation(self): \"\"\"Tests violations are produced", "sinks.', rule_index=2, violation_type='LOG_SINK_VIOLATION', sink_destination=('bigquery.googleapis.com/projects/' 'my-audit-logs/datasets/folder_logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', sink_include_children=False, resource_data='__SINK_1__') ]) self.assertEqual(expected_violations,", "{ 'destination': 'bigquery.*', 'filter': '', 'include_children': '*' } rule_book.add_rule( {", "built correctly with a yaml file.\"\"\" rules_engine = self.get_engine_with_valid_rules() #", "include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.proj_2, raw_json='__SINK_1__' ), LogSink( sink_id='compute_logs_saver', destination=('bigquery.googleapis.com/projects/proj_2/' 'datasets/compute_logs'), sink_filter='resource.type=\"gce_instance\"',", "rule_name='Require Audit Log sinks in all projects.', rule_index=0, violation_type='LOG_SINK_VIOLATION', sink_destination=('^bigquery\\\\.googleapis\\\\.com\\\\/projects\\\\/'", "project 2', parent=self.folder_56, full_name='organization/234/folder/56/project/proj-2/', data='fake_project_data_4562') self.proj_3 = Project( 'proj-3', project_number=33445566,", "law or agreed to in writing, software # distributed under", "data='fake_project_data_4562') self.proj_3 = Project( 'proj-3', project_number=33445566, display_name='My project 3', parent=self.org_234,", "= [ LogSink( sink_id='non_audit_logs_to_bq', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/proj_2_logs'), sink_filter='logName:\"logs/non-cloudaudit.googleapis.com\"', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.proj_2,", "{ 'name': 'Valid rule', 'resource': [valid_resource], 'sink': valid_sink_spec, 'mode': 'whitelist'", "file.\"\"\" rules_local_path = get_datafile_path( __file__, 'log_sink_test_valid_rules.yaml') rules_engine = self.lsre.LogSinkRulesEngine( rules_file_path=rules_local_path)", "# Org needs an Audit Log sink, including children. log_sinks", "'type': 'bucket', 'applies_to': 'self', 'resource_ids': ['bucket-1'] }], 'sink': valid_sink_spec, 'mode':", "'mode': 'whitelist' }, 0) bad_rules = [ {}, { 'name':", "[ LogSink( sink_id='billing_logs', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/billing_logs'), sink_filter='', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.billing_acct_abcd, raw_json='__SINK_1__'", "'my-audit-logs/datasets/folder_logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', sink_include_children=False, resource_data='__SINK_1__') ]) self.assertEqual(expected_violations, actual_violations) def test_billing_account_with_whitelist_violations(self): \"\"\"Tests", "applies to type', 'resource': [{ 'type': 'billing_account', 'applies_to': 'children', 'resource_ids':", "'Bad applies to type', 'resource': [{ 'type': 'folder', 'applies_to': 'self_and_children',", "self.lsre.LogSinkRuleBook(global_configs=None) valid_resource = { 'type': 'organization', 'applies_to': 'children', 'resource_ids': ['1234']", "project_number=11223344, display_name='My project 1', parent=self.org_234, full_name='organization/234/project/proj-1/', data='fake_project_data_2341') self.proj_2 = Project(", "__file__, 'log_sink_test_invalid_rules.yaml') rules_engine = self.lsre.LogSinkRulesEngine( rules_file_path=rules_local_path) with self.assertRaises(InvalidRulesSchemaError): rules_engine.build_rule_book() def", "self.lsre = lsre self.lsre.LOGGER = mock.MagicMock() # Set up resources", "rules_file_path=rules_local_path) rules_engine.build_rule_book() return rules_engine def test_build_rule_book_from_local_yaml_file_works(self): \"\"\"Tests that a RuleBook", "'Bad resource type', 'resource': [{ 'type': 'bucket', 'applies_to': 'self', 'resource_ids':", "set([ lsre.Rule.RuleViolation( resource_name='234', resource_type='organization', resource_id='234', full_name='organization/234/', rule_name='Require an Org Level", "child_rule_resources.append(resource.name) expected_rule_resources = ['folders/56', 'organizations/234'] self.assertEqual(expected_rule_resources, sorted(child_rule_resources)) def test_build_rule_book_invalid_applies_to_fails(self): \"\"\"Tests", "def test_project_with_no_violations(self): \"\"\"Tests that no violations are produced for a", "Log sink, including children. log_sinks = [ LogSink( sink_id='sink_not_including_children', destination=('pubsub.googleapis.com/projects/proj-3/topics/'", "'resource': [valid_resource], 'sink': valid_sink_spec, 'mode': 'whitelist' }, 0) bad_rules =", "] actual_violations = rules_engine.find_violations( self.billing_acct_abcd, log_sinks) expected_violations = set([ lsre.Rule.RuleViolation(", "2018 The Forseti Security Authors. All rights reserved. # #", "raw_json='__SINK_1__' ), ] actual_violations = rules_engine.find_violations( self.billing_acct_abcd, log_sinks) self.assertEqual(set(), actual_violations)", "sink_destination='^.*$', sink_filter=('^logName\\\\:\\\\\"logs\\\\/' 'cloudaudit\\\\.googleapis\\\\.com\\\\\"$'), sink_include_children=True, resource_data='' ) ]) self.assertEqual(expected_violations, actual_violations) def", "are produced for non-whitelisted sinks.\"\"\" rules_engine = self.get_engine_with_valid_rules() # proj-3", "writer_identity='serviceAccount:<EMAIL>', parent=self.billing_acct_abcd, raw_json='__SINK_1__' ), ] actual_violations = rules_engine.find_violations( self.billing_acct_abcd, log_sinks)", "type', 'resource': [{ 'type': 'folder', 'applies_to': 'self_and_children', 'resource_ids': ['56'] }],", "[] for resource in rules_engine.rule_book.resource_rules_map['self']: self_rule_resources.append(resource.name) expected_rule_resources = [ 'billingAccounts/ABCD-1234',", "writer_identity=('serviceAccount:p12345-67890@' 'gcp-sa-logging.iam.gserviceaccount.com'), parent=self.proj_2, raw_json='__SINK_2__' ) ] actual_violations = rules_engine.find_violations( self.proj_2,", "rules. log_sinks = [ LogSink( sink_id='non_audit_logs_to_bq', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/proj_2_logs'), sink_filter='logName:\"logs/non-cloudaudit.googleapis.com\"', include_children=False,", "lsre.Rule.RuleViolation( resource_name='proj-2', resource_type='project', resource_id='proj-2', full_name='organization/234/folder/56/project/proj-2/', rule_name='Require Audit Log sinks in", ") ] actual_violations = rules_engine.find_violations( self.org_234, log_sinks) expected_violations = set([", "+-----------------------> proj-3 self.org_234 = Organization( '234', display_name='Organization 234', full_name='organization/234/', data='fake_org_data_234')", "correct project.\"\"\" rules_engine = self.get_engine_with_valid_rules() # proj-1 needs an Audit", "the LogSinkRulesEngine.\"\"\" import unittest import mock from tests.unittest_utils import ForsetiTestCase", "['bucket-1'] }], 'sink': valid_sink_spec, 'mode': 'whitelist' }, { 'name': 'Bad", "may obtain a copy of the License at # #", "sink_id='billing_logs', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/billing_logs'), sink_filter='', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.billing_acct_abcd, raw_json='__SINK_1__' ), ]", "sink_destination=('pubsub.googleapis.com/projects/proj-3/' 'topics/proj-audit-logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', sink_include_children=True, resource_data='__SINK_2__' ) ]) self.assertEqual(expected_violations, actual_violations) def", "} ] for rule in bad_rules: with self.assertRaises(InvalidRulesSchemaError): rule_book.add_rule(rule, 1)", "rules_engine = self.lsre.LogSinkRulesEngine( rules_file_path=rules_local_path) rules_engine.build_rule_book() return rules_engine def test_build_rule_book_from_local_yaml_file_works(self): \"\"\"Tests", "), LogSink( sink_id='compute_logs_saver', destination=('bigquery.googleapis.com/projects/proj_1/' 'datasets/compute_logs'), sink_filter='resource.type=\"gce_instance\"', include_children=False, writer_identity=('serviceAccount:<PASSWORD>@' 'gcp-sa-logging.iam.gserviceaccount.com'), parent=self.proj_1,", "import BillingAccount from google.cloud.forseti.common.gcp_type.folder import Folder from google.cloud.forseti.common.gcp_type.log_sink import LogSink", "from google.cloud.forseti.common.gcp_type.organization import Organization from google.cloud.forseti.common.gcp_type.project import Project from google.cloud.forseti.scanner.audit", "and a pubsub # sink, by folder-level rules. log_sinks =", "include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.folder_56, raw_json='__SINK_1__' ) ] actual_violations = rules_engine.find_violations( self.folder_56,", "| # | # org_234 +-----> folder_56 +-----> proj-2 #", "import Project from google.cloud.forseti.scanner.audit import log_sink_rules_engine as lsre from google.cloud.forseti.scanner.audit.errors", "for 5 difference resources and 'children' rules # for 2.", "LogSinkRulesEngine.\"\"\" def setUp(self): \"\"\"Set up GCP resources for tests.\"\"\" self.lsre", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "a valid rules file.\"\"\" rules_local_path = get_datafile_path( __file__, 'log_sink_test_valid_rules.yaml') rules_engine", "'datasets/compute_logs'), sink_filter='resource.type=\"gce_instance\"', include_children=False, writer_identity=('serviceAccount:<PASSWORD>@' 'gcp-sa-logging.iam.gserviceaccount.com'), parent=self.proj_1, raw_json='_SINK_2_' ) ] actual_violations", "{ 'name': 'Bad applies to type', 'resource': [{ 'type': 'folder',", "}], 'sink': valid_sink_spec, 'mode': 'whitelist' }, { 'name': 'Missing filter',", "= set([ lsre.Rule.RuleViolation( resource_name='projects/proj-3/sinks/audit_logs_to_pubsub', resource_type='sink', resource_id='audit_logs_to_pubsub', full_name='organization/234/project/proj-3/audit_logs_to_pubsub/', rule_name='Only allow BigQuery", "display_name='My project 1', parent=self.org_234, full_name='organization/234/project/proj-1/', data='fake_project_data_2341') self.proj_2 = Project( 'proj-2',", "may not use this file except in compliance with the", "with a valid rules file.\"\"\" rules_local_path = get_datafile_path( __file__, 'log_sink_test_valid_rules.yaml')", "'include_children': '*' }, 'mode': 'whitelist' }, { 'name': 'Bad include_children',", "# | # | # +-----------------------> proj-1 # | #", "] actual_violations = rules_engine.find_violations( self.billing_acct_abcd, log_sinks) self.assertEqual(set(), actual_violations) def test_org_with_no_violations(self):", "= Folder( '56', display_name='Folder 56', full_name='organization/234/folder/56/', data='fake_folder_data456456') self.proj_1 = Project(", "to type', 'resource': [{ 'type': 'folder', 'applies_to': 'self_and_children', 'resource_ids': ['56']", "] actual_violations = rules_engine.find_violations( self.proj_1, log_sinks) self.assertEqual(set(), actual_violations) def test_folder_with_no_violations(self):", "'bigquery.*', 'filter': '', 'include_children': '*' } rule_book.add_rule( { 'name': 'Valid", "sink_id='audit_logs_to_bq', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/proj_1_logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.proj_3, raw_json='__SINK_1__' ), LogSink(", "'mode': 'whitelist' }, { 'name': 'Bad applies to type', 'resource':", "log_sinks = [ LogSink( sink_id='audit_logs_to_bq', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/folder_logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=False, writer_identity='serviceAccount:<EMAIL>',", "'whitelist', 'sink': valid_sink_spec, }, { 'name': 'Mising sink', 'resource': [valid_resource],", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "sink_include_children=False, resource_data='__SINK_1__') ]) self.assertEqual(expected_violations, actual_violations) def test_org_missing_required_sinks(self): \"\"\"Tests violations are", "'destination': 'bigquery.*', 'filter': '', 'include_children': '*' } rule_book.add_rule( { 'name':", "with self.assertRaises(InvalidRulesSchemaError): rules_engine.build_rule_book() def test_project_with_no_violations(self): \"\"\"Tests that no violations are", "this file except in compliance with the License. # You", "parent=self.org_234, raw_json='__SINK_1__' ) ] actual_violations = rules_engine.find_violations( self.org_234, log_sinks) self.assertEqual(set(),", "GCP resources for tests.\"\"\" self.lsre = lsre self.lsre.LOGGER = mock.MagicMock()", "= rules_engine.find_violations( self.billing_acct_abcd, log_sinks) self.assertEqual(set(), actual_violations) def test_org_with_no_violations(self): \"\"\"Tests that", "sinks in all projects.', rule_index=0, violation_type='LOG_SINK_VIOLATION', sink_destination=('^bigquery\\\\.googleapis\\\\.com\\\\/projects\\\\/' 'my\\\\-audit\\\\-logs\\\\/datasets\\\\/.+$'), sink_filter=('^logName\\\\:\\\\\"logs\\\\/' 'cloudaudit\\\\.googleapis\\\\.com\\\\\"$'),", "non-whitelisted sinks.\"\"\" rules_engine = self.get_engine_with_valid_rules() # proj-3 can only have", "\"\"\"Tests violations are produced for billing account sinks.\"\"\" rules_engine =", "} rule_book.add_rule( { 'name': 'Valid rule', 'resource': [valid_resource], 'sink': valid_sink_spec,", "'Yes' }, 'mode': 'whitelist' } ] for rule in bad_rules:", "}], 'sink': valid_sink_spec, 'mode': 'whitelist' }, { 'name': 'Bad applies", "sink_destination='^pubsub\\\\.googleapis\\\\.com\\\\/.+$', sink_filter='^$', sink_include_children='*', resource_data='' ) ]) self.assertEqual(expected_violations, actual_violations) def test_project_whitelist_violation(self):", "correct billing acct.\"\"\" rules_engine = self.get_engine_with_valid_rules() log_sinks = [ LogSink(", "}, 'mode': 'whitelist' }, { 'name': 'Bad include_children', 'resource': [valid_resource],", "for blacklisted sinks.\"\"\" rules_engine = self.get_engine_with_valid_rules() # Rules disallow any", "allow Billing Account sinks to audit logs ' 'project.'), rule_index=6,", "rule in bad_rules: with self.assertRaises(InvalidRulesSchemaError): rule_book.add_rule(rule, 1) if __name__ ==", "'*', 'include_children': 'Yes' }, 'mode': 'whitelist' } ] for rule", "self.proj_2, log_sinks) expected_violations = set([ lsre.Rule.RuleViolation( resource_name='proj-2', resource_type='project', resource_id='proj-2', full_name='organization/234/folder/56/project/proj-2/',", "org missing required sinks.\"\"\" rules_engine = self.get_engine_with_valid_rules() # Org needs", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "self.folder_56 = Folder( '56', display_name='Folder 56', full_name='organization/234/folder/56/', data='fake_folder_data456456') self.proj_1 =", "include_children=False, writer_identity=('serviceAccount:<PASSWORD>@' 'gcp-sa-logging.iam.gserviceaccount.com'), parent=self.proj_1, raw_json='_SINK_2_' ) ] actual_violations = rules_engine.find_violations(", "= Project( 'proj-3', project_number=33445566, display_name='My project 3', parent=self.org_234, full_name='organization/234/project/proj-3/', data='fake_project_data_1233')", "needs an Audit Log sink, but to any destination. log_sinks", "any destination. log_sinks = [ LogSink( sink_id='audit_logs_to_pubsub', destination=('pubsub.googleapis.com/projects/proj-3/topics/' 'org-audit-logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"',", "sink_id='compute_logs_saver', destination=('bigquery.googleapis.com/projects/proj_1/' 'datasets/compute_logs'), sink_filter='resource.type=\"gce_instance\"', include_children=False, writer_identity=('serviceAccount:<PASSWORD>@' 'gcp-sa-logging.iam.gserviceaccount.com'), parent=self.proj_1, raw_json='_SINK_2_' )", "# # Licensed under the Apache License, Version 2.0 (the", "'applies_to': 'self', 'resource_ids': ['bucket-1'] }], 'sink': valid_sink_spec, 'mode': 'whitelist' },", "'resource_ids': ['1234'] } valid_sink_spec = { 'destination': 'bigquery.*', 'filter': '',", "rule_name='Disallow folder sinks.', rule_index=2, violation_type='LOG_SINK_VIOLATION', sink_destination=('bigquery.googleapis.com/projects/' 'my-audit-logs/datasets/folder_logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', sink_include_children=False, resource_data='__SINK_1__')", "['56'] }], 'sink': valid_sink_spec, 'mode': 'whitelist' }, { 'name': 'Bad", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "rule_index=6, violation_type='LOG_SINK_VIOLATION', sink_destination=('bigquery.googleapis.com/projects/' 'my-audit-logs/datasets/wrong_dataset'), sink_filter='', sink_include_children=False, resource_data='__SINK_1__') ]) self.assertEqual(expected_violations, actual_violations)", "[valid_resource], 'sink': valid_sink_spec, 'mode': 'whitelist' }, 0) bad_rules = [", "'Bad mode', 'resource': [valid_resource], 'sink': valid_sink_spec, 'mode': 'other', }, {", "that adding invalid rules raises exceptions.\"\"\" rule_book = self.lsre.LogSinkRuleBook(global_configs=None) valid_resource", "violation_type='LOG_SINK_VIOLATION', sink_destination=('pubsub.googleapis.com/projects/proj-3/' 'topics/proj-audit-logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', sink_include_children=True, resource_data='__SINK_2__' ) ]) self.assertEqual(expected_violations, actual_violations)", "= self.lsre.LogSinkRuleBook(global_configs=None) valid_resource = { 'type': 'organization', 'applies_to': 'children', 'resource_ids':", "valid_sink_spec, 'mode': 'whitelist' }, { 'name': 'Empty resource_ids', 'resource': [{", "'children', 'resource_ids': ['ABCD-1234'] }], 'sink': valid_sink_spec, 'mode': 'whitelist' }, {", "rules_engine = self.get_engine_with_valid_rules() # Creates 'self' rules for 5 difference", "organization.\"\"\" rules_engine = self.get_engine_with_valid_rules() # Org needs an Audit Log", "Organization from google.cloud.forseti.common.gcp_type.project import Project from google.cloud.forseti.scanner.audit import log_sink_rules_engine as", "rules_engine.build_rule_book() return rules_engine def test_build_rule_book_from_local_yaml_file_works(self): \"\"\"Tests that a RuleBook is", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "LogSink from google.cloud.forseti.common.gcp_type.organization import Organization from google.cloud.forseti.common.gcp_type.project import Project from", "parent=self.billing_acct_abcd, raw_json='__SINK_1__' ), ] actual_violations = rules_engine.find_violations( self.billing_acct_abcd, log_sinks) self.assertEqual(set(),", "exceptions.\"\"\" rule_book = self.lsre.LogSinkRuleBook(global_configs=None) valid_resource = { 'type': 'organization', 'applies_to':", "} valid_sink_spec = { 'destination': 'bigquery.*', 'filter': '', 'include_children': '*'", "projects.', rule_index=0, violation_type='LOG_SINK_VIOLATION', sink_destination=('^bigquery\\\\.googleapis\\\\.com\\\\/projects\\\\/' 'my\\\\-audit\\\\-logs\\\\/datasets\\\\/.+$'), sink_filter=('^logName\\\\:\\\\\"logs\\\\/' 'cloudaudit\\\\.googleapis\\\\.com\\\\\"$'), sink_include_children='*', resource_data='' ),", "test_folder_with_no_violations(self): \"\"\"Tests that no violations are produced for a correct", "expected_violations = set([ lsre.Rule.RuleViolation( resource_name='proj-2', resource_type='project', resource_id='proj-2', full_name='organization/234/folder/56/project/proj-2/', rule_name='Require Audit", "LogSink( sink_id='billing_logs', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/wrong_dataset'), sink_filter='', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.billing_acct_abcd, raw_json='__SINK_1__' ),", "sink_filter=('^logName\\\\:\\\\\"logs\\\\/' 'cloudaudit\\\\.googleapis\\\\.com\\\\\"$'), sink_include_children=True, resource_data='' ) ]) self.assertEqual(expected_violations, actual_violations) def test_add_invalid_rules(self):", "an org missing required sinks.\"\"\" rules_engine = self.get_engine_with_valid_rules() # Org", "in Proj-1 and Proj-3.', rule_index=4, violation_type='LOG_SINK_VIOLATION', sink_destination=('pubsub.googleapis.com/projects/proj-3/' 'topics/proj-audit-logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', sink_include_children=True,", "import unittest import mock from tests.unittest_utils import ForsetiTestCase from tests.unittest_utils", "that no violations are produced for a correct folder.\"\"\" rules_engine", "rights reserved. # # Licensed under the Apache License, Version", "] actual_violations = rules_engine.find_violations( self.proj_3, log_sinks) expected_violations = set([ lsre.Rule.RuleViolation(", "violation_type='LOG_SINK_VIOLATION', sink_destination=('bigquery.googleapis.com/projects/' 'my-audit-logs/datasets/folder_logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', sink_include_children=False, resource_data='__SINK_1__') ]) self.assertEqual(expected_violations, actual_violations) def", "sink_filter='', sink_include_children=False, resource_data='__SINK_1__') ]) self.assertEqual(expected_violations, actual_violations) def test_org_missing_required_sinks(self): \"\"\"Tests violations", "produced for project missing required sinks.\"\"\" rules_engine = self.get_engine_with_valid_rules() #", "include_children=True, writer_identity='serviceAccount:<EMAIL>', parent=self.proj_3, raw_json='__SINK_2__' ) ] actual_violations = rules_engine.find_violations( self.proj_3,", "data='fake_project_data_1233') def get_engine_with_valid_rules(self): \"\"\"Create a rule engine build with a", "file.\"\"\" rules_engine = self.get_engine_with_valid_rules() # Creates 'self' rules for 5", "Audit Log sink. log_sinks = [ LogSink( sink_id='audit_logs_to_bq', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/proj_1_logs'),", "resource in rules_engine.rule_book.resource_rules_map['children']: child_rule_resources.append(resource.name) expected_rule_resources = ['folders/56', 'organizations/234'] self.assertEqual(expected_rule_resources, sorted(child_rule_resources))", "def test_org_missing_required_sinks(self): \"\"\"Tests violations are produced for an org missing", "parent=self.folder_56, full_name='organization/234/folder/56/project/proj-2/', data='fake_project_data_4562') self.proj_3 = Project( 'proj-3', project_number=33445566, display_name='My project", "engine build with a valid rules file.\"\"\" rules_local_path = get_datafile_path(", "Resource', 'mode': 'whitelist', 'sink': valid_sink_spec, }, { 'name': 'Mising sink',", "violations are produced for blacklisted sinks.\"\"\" rules_engine = self.get_engine_with_valid_rules() #", "for an org missing required sinks.\"\"\" rules_engine = self.get_engine_with_valid_rules() #", "'children', 'resource_ids': ['1234'] } valid_sink_spec = { 'destination': 'bigquery.*', 'filter':", "parent=self.org_234, raw_json='__SINK_2__' ) ] actual_violations = rules_engine.find_violations( self.org_234, log_sinks) expected_violations", "from google.cloud.forseti.common.gcp_type.billing_account import BillingAccount from google.cloud.forseti.common.gcp_type.folder import Folder from google.cloud.forseti.common.gcp_type.log_sink", "from google.cloud.forseti.scanner.audit.errors import InvalidRulesSchemaError class LogSinkRulesEngineTest(ForsetiTestCase): \"\"\"Tests for the LogSinkRulesEngine.\"\"\"", "'*' } rule_book.add_rule( { 'name': 'Valid rule', 'resource': [valid_resource], 'sink':", "2, len(rules_engine.rule_book.resource_rules_map['children'])) self_rule_resources = [] for resource in rules_engine.rule_book.resource_rules_map['self']: self_rule_resources.append(resource.name)", "= get_datafile_path( __file__, 'log_sink_test_valid_rules.yaml') rules_engine = self.lsre.LogSinkRulesEngine( rules_file_path=rules_local_path) rules_engine.build_rule_book() return", ") ] actual_violations = rules_engine.find_violations( self.proj_3, log_sinks) expected_violations = set([", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "Audit Log sink, including children. log_sinks = [ LogSink( sink_id='sink_not_including_children',", "{ 'name': 'Empty resource_ids', 'resource': [{ 'type': 'project', 'applies_to': 'self',", "can only have BigQuery sinks. log_sinks = [ LogSink( sink_id='audit_logs_to_bq',", "1', parent=self.org_234, full_name='organization/234/project/proj-1/', data='fake_project_data_2341') self.proj_2 = Project( 'proj-2', project_number=223344, display_name='My", "'cloudaudit\\\\.googleapis\\\\.com\\\\\"$'), sink_include_children=True, resource_data='' ) ]) self.assertEqual(expected_violations, actual_violations) def test_add_invalid_rules(self): \"\"\"Tests", "{ 'destination': 'bigquery.*', 'filter': '*', 'include_children': 'Yes' }, 'mode': 'whitelist'", "rule_book = self.lsre.LogSinkRuleBook(global_configs=None) valid_resource = { 'type': 'organization', 'applies_to': 'children',", "required sinks.\"\"\" rules_engine = self.get_engine_with_valid_rules() # proj-2 needs an Audit", "= [ LogSink( sink_id='sink_not_including_children', destination=('pubsub.googleapis.com/projects/proj-3/topics/' 'org-audit-logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.org_234,", "'type': 'project', 'applies_to': 'self', 'resource_ids': [] }], 'sink': valid_sink_spec, 'mode':", "violations are produced for non-whitelisted sinks.\"\"\" rules_engine = self.get_engine_with_valid_rules() #", "log sink.', rule_index=1, violation_type='LOG_SINK_VIOLATION', sink_destination='^.*$', sink_filter=('^logName\\\\:\\\\\"logs\\\\/' 'cloudaudit\\\\.googleapis\\\\.com\\\\\"$'), sink_include_children=True, resource_data='' )", "import log_sink_rules_engine as lsre from google.cloud.forseti.scanner.audit.errors import InvalidRulesSchemaError class LogSinkRulesEngineTest(ForsetiTestCase):", "sink_id='audit_logs_to_bq', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/folder_logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.folder_56, raw_json='__SINK_1__' ) ]", "raises exceptions.\"\"\" rule_book = self.lsre.LogSinkRuleBook(global_configs=None) valid_resource = { 'type': 'organization',", "[ 'billingAccounts/ABCD-1234', 'folders/56', 'organizations/234', 'projects/proj-1', 'projects/proj-2', 'projects/proj-3'] self.assertEqual(expected_rule_resources, sorted(self_rule_resources)) child_rule_resources", "'datasets/compute_logs'), sink_filter='resource.type=\"gce_instance\"', include_children=False, writer_identity=('serviceAccount:p12345-67890@' 'gcp-sa-logging.iam.gserviceaccount.com'), parent=self.proj_2, raw_json='__SINK_2__' ) ] actual_violations", "or implied. # See the License for the specific language", "= self.get_engine_with_valid_rules() # proj-3 can only have BigQuery sinks. log_sinks", "parent=self.proj_1, raw_json='_SINK_1_' ), LogSink( sink_id='compute_logs_saver', destination=('bigquery.googleapis.com/projects/proj_1/' 'datasets/compute_logs'), sink_filter='resource.type=\"gce_instance\"', include_children=False, writer_identity=('serviceAccount:<PASSWORD>@'", "import Folder from google.cloud.forseti.common.gcp_type.log_sink import LogSink from google.cloud.forseti.common.gcp_type.organization import Organization", "a rule with invalid applies_to type cannot be created.\"\"\" rules_local_path", "rules_engine.find_violations( self.proj_2, log_sinks) expected_violations = set([ lsre.Rule.RuleViolation( resource_name='proj-2', resource_type='project', resource_id='proj-2',", "Org needs an Audit Log sink, including children. log_sinks =", "children. log_sinks = [ LogSink( sink_id='sink_not_including_children', destination=('pubsub.googleapis.com/projects/proj-3/topics/' 'org-audit-logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=False,", "include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.org_234, raw_json='__SINK_1__' ), LogSink( sink_id='sink_with_wrong_filter', destination=('pubsub.googleapis.com/projects/proj-3/topics/' 'org-more-logs'), sink_filter='logName:\"logs/otherapi.googleapis.com\"',", "'org-more-logs'), sink_filter='logName:\"logs/otherapi.googleapis.com\"', include_children=True, writer_identity='serviceAccount:<EMAIL>', parent=self.org_234, raw_json='__SINK_2__' ) ] actual_violations =", "0) bad_rules = [ {}, { 'name': 'Mising Resource', 'mode':", "sinks. log_sinks = [ LogSink( sink_id='audit_logs_to_bq', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/proj_1_logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=False,", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "for billing account sinks.\"\"\" rules_engine = self.get_engine_with_valid_rules() log_sinks = [", "Log sink. log_sinks = [ LogSink( sink_id='audit_logs_to_bq', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/proj_1_logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"',", "rules # for 2. self.assertEqual( 6, len(rules_engine.rule_book.resource_rules_map['self'])) self.assertEqual( 2, len(rules_engine.rule_book.resource_rules_map['children']))", "sink, including children. log_sinks = [ LogSink( sink_id='sink_not_including_children', destination=('pubsub.googleapis.com/projects/proj-3/topics/' 'org-audit-logs'),", "billing_acct_abcd # | # | # +-----------------------> proj-1 # |", "for a correct project.\"\"\" rules_engine = self.get_engine_with_valid_rules() # proj-1 needs", "for 2. self.assertEqual( 6, len(rules_engine.rule_book.resource_rules_map['self'])) self.assertEqual( 2, len(rules_engine.rule_book.resource_rules_map['children'])) self_rule_resources =", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "display_name='Folder 56', full_name='organization/234/folder/56/', data='fake_folder_data456456') self.proj_1 = Project( 'proj-1', project_number=11223344, display_name='My", "google.cloud.forseti.scanner.audit import log_sink_rules_engine as lsre from google.cloud.forseti.scanner.audit.errors import InvalidRulesSchemaError class", "['1234'] } valid_sink_spec = { 'destination': 'bigquery.*', 'filter': '', 'include_children':", "}, { 'name': 'Bad applies to type', 'resource': [{ 'type':", "= self.get_engine_with_valid_rules() # Rules disallow any folder-level LogSinks. actual_violations =", "}], 'sink': valid_sink_spec, 'mode': 'whitelist' }, { 'name': 'Empty resource_ids',", "google.cloud.forseti.common.gcp_type.billing_account import BillingAccount from google.cloud.forseti.common.gcp_type.folder import Folder from google.cloud.forseti.common.gcp_type.log_sink import", "tests.\"\"\" self.lsre = lsre self.lsre.LOGGER = mock.MagicMock() # Set up", "rules_engine.find_violations( self.billing_acct_abcd, log_sinks) expected_violations = set([ lsre.Rule.RuleViolation( resource_type='sink', resource_id='billing_logs', resource_name='billingAccounts/ABCD-1234/sinks/billing_logs',", "len(rules_engine.rule_book.resource_rules_map['children'])) self_rule_resources = [] for resource in rules_engine.rule_book.resource_rules_map['self']: self_rule_resources.append(resource.name) expected_rule_resources", "sink_include_children='*', resource_data='' ) ]) self.assertEqual(expected_violations, actual_violations) def test_project_whitelist_violation(self): \"\"\"Tests violations", "rule_book.add_rule( { 'name': 'Valid rule', 'resource': [valid_resource], 'sink': valid_sink_spec, 'mode':", "resource_id='audit_logs_to_pubsub', full_name='organization/234/project/proj-3/audit_logs_to_pubsub/', rule_name='Only allow BigQuery sinks in Proj-1 and Proj-3.',", "Log sinks in all projects.', rule_index=0, violation_type='LOG_SINK_VIOLATION', sink_destination=('^bigquery\\\\.googleapis\\\\.com\\\\/projects\\\\/' 'my\\\\-audit\\\\-logs\\\\/datasets\\\\/.+$'), sink_filter=('^logName\\\\:\\\\\"logs\\\\/'", "resources in the following hierarchy: # +-----> billing_acct_abcd # |", "include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.billing_acct_abcd, raw_json='__SINK_1__' ), ] actual_violations = rules_engine.find_violations( self.billing_acct_abcd,", "rules_engine = self.get_engine_with_valid_rules() # proj-2 needs an Audit Log sink,", "sink.', rule_index=1, violation_type='LOG_SINK_VIOLATION', sink_destination='^.*$', sink_filter=('^logName\\\\:\\\\\"logs\\\\/' 'cloudaudit\\\\.googleapis\\\\.com\\\\\"$'), sink_include_children=True, resource_data='' ) ])", "return rules_engine def test_build_rule_book_from_local_yaml_file_works(self): \"\"\"Tests that a RuleBook is built", "(the \"License\"); # you may not use this file except", "rules_engine = self.get_engine_with_valid_rules() # proj-1 needs an Audit Log sink.", "self.assertEqual(set(), actual_violations) def test_billing_account_with_no_violations(self): \"\"\"Tests that no violations are produced", "limitations under the License. \"\"\"Tests the LogSinkRulesEngine.\"\"\" import unittest import", "log_sinks) self.assertEqual(set(), actual_violations) def test_project_missing_required_sinks(self): \"\"\"Tests violations are produced for", "sink_id='compute_logs_saver', destination=('bigquery.googleapis.com/projects/proj_2/' 'datasets/compute_logs'), sink_filter='resource.type=\"gce_instance\"', include_children=False, writer_identity=('serviceAccount:p12345-67890@' 'gcp-sa-logging.iam.gserviceaccount.com'), parent=self.proj_2, raw_json='__SINK_2__' )", "# you may not use this file except in compliance", "resource_name='proj-2', resource_type='project', resource_id='proj-2', full_name='organization/234/folder/56/project/proj-2/', rule_name='Require a PubSub sink in folder-56", "projects.', rule_index=3, violation_type='LOG_SINK_VIOLATION', sink_destination='^pubsub\\\\.googleapis\\\\.com\\\\/.+$', sink_filter='^$', sink_include_children='*', resource_data='' ) ]) self.assertEqual(expected_violations,", "resource_name='234', resource_type='organization', resource_id='234', full_name='organization/234/', rule_name='Require an Org Level audit log", "= [ LogSink( sink_id='audit_logs_to_pubsub', destination=('pubsub.googleapis.com/projects/proj-3/topics/' 'org-audit-logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=True, writer_identity='serviceAccount:<EMAIL>', parent=self.org_234,", "following hierarchy: # +-----> billing_acct_abcd # | # | #", "actual_violations) def test_billing_account_with_no_violations(self): \"\"\"Tests that no violations are produced for", "missing required sinks.\"\"\" rules_engine = self.get_engine_with_valid_rules() # proj-2 needs an", "a rule engine build with a valid rules file.\"\"\" rules_local_path", "rules file.\"\"\" rules_local_path = get_datafile_path( __file__, 'log_sink_test_valid_rules.yaml') rules_engine = self.lsre.LogSinkRulesEngine(", "'mode': 'whitelist', 'sink': valid_sink_spec, }, { 'name': 'Mising sink', 'resource':", "# Creates 'self' rules for 5 difference resources and 'children'", "'Bad applies to type', 'resource': [{ 'type': 'billing_account', 'applies_to': 'children',", "rule_index=1, violation_type='LOG_SINK_VIOLATION', sink_destination='^.*$', sink_filter=('^logName\\\\:\\\\\"logs\\\\/' 'cloudaudit\\\\.googleapis\\\\.com\\\\\"$'), sink_include_children=True, resource_data='' ) ]) self.assertEqual(expected_violations,", "# org_234 +-----> folder_56 +-----> proj-2 # | # |", "sink, by folder-level rules. log_sinks = [ LogSink( sink_id='non_audit_logs_to_bq', destination=('bigquery.googleapis.com/projects/my-audit-logs/'", "= self.get_engine_with_valid_rules() # Org needs an Audit Log sink, but", "lsre.Rule.RuleViolation( resource_name='234', resource_type='organization', resource_id='234', full_name='organization/234/', rule_name='Require an Org Level audit", "}, { 'name': 'Empty resource_ids', 'resource': [{ 'type': 'project', 'applies_to':", "Account ABCD', full_name='organization/234/billingAccount/ABCD-1234/', data='fake_billing_account_data_abcd') self.folder_56 = Folder( '56', display_name='Folder 56',", "an Org Level audit log sink.', rule_index=1, violation_type='LOG_SINK_VIOLATION', sink_destination='^.*$', sink_filter=('^logName\\\\:\\\\\"logs\\\\/'", "destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/folder_logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.folder_56, raw_json='__SINK_1__' ) ] actual_violations", "log_sinks) self.assertEqual(set(), actual_violations) def test_folder_with_no_violations(self): \"\"\"Tests that no violations are", "resource_data='__SINK_1__') ]) self.assertEqual(expected_violations, actual_violations) def test_billing_account_with_whitelist_violations(self): \"\"\"Tests violations are produced", "LogSink( sink_id='audit_logs_to_pubsub', destination=('pubsub.googleapis.com/projects/proj-3/topics/' 'org-audit-logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=True, writer_identity='serviceAccount:<EMAIL>', parent=self.org_234, raw_json='__SINK_1__' )", "# # Unless required by applicable law or agreed to", "LogSink( sink_id='sink_with_wrong_filter', destination=('pubsub.googleapis.com/projects/proj-3/topics/' 'org-more-logs'), sink_filter='logName:\"logs/otherapi.googleapis.com\"', include_children=True, writer_identity='serviceAccount:<EMAIL>', parent=self.org_234, raw_json='__SINK_2__' )", "writer_identity='serviceAccount:<EMAIL>', parent=self.org_234, raw_json='__SINK_1__' ) ] actual_violations = rules_engine.find_violations( self.org_234, log_sinks)", "rule_name='Require a PubSub sink in folder-56 projects.', rule_index=3, violation_type='LOG_SINK_VIOLATION', sink_destination='^pubsub\\\\.googleapis\\\\.com\\\\/.+$',", "sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', sink_include_children=True, resource_data='__SINK_2__' ) ]) self.assertEqual(expected_violations, actual_violations) def test_folder_blacklist_violation(self): \"\"\"Tests", "'self' rules for 5 difference resources and 'children' rules #", "'organizations/234'] self.assertEqual(expected_rule_resources, sorted(child_rule_resources)) def test_build_rule_book_invalid_applies_to_fails(self): \"\"\"Tests that a rule with", "self.assertEqual( 6, len(rules_engine.rule_book.resource_rules_map['self'])) self.assertEqual( 2, len(rules_engine.rule_book.resource_rules_map['children'])) self_rule_resources = [] for", "# sink, by folder-level rules. log_sinks = [ LogSink( sink_id='non_audit_logs_to_bq',", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "{ 'name': 'Missing filter', 'resource': [valid_resource], 'sink': { 'destination': 'bigquery.*',", "lsre.Rule.RuleViolation( resource_name='projects/proj-3/sinks/audit_logs_to_pubsub', resource_type='sink', resource_id='audit_logs_to_pubsub', full_name='organization/234/project/proj-3/audit_logs_to_pubsub/', rule_name='Only allow BigQuery sinks in", "[ LogSink( sink_id='sink_not_including_children', destination=('pubsub.googleapis.com/projects/proj-3/topics/' 'org-audit-logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.org_234, raw_json='__SINK_1__'", "self.assertEqual(expected_violations, actual_violations) def test_folder_blacklist_violation(self): \"\"\"Tests violations are produced for blacklisted", "raw_json='__SINK_1__' ) ] actual_violations = rules_engine.find_violations( self.folder_56, log_sinks) expected_violations =", "Version 2.0 (the \"License\"); # you may not use this", "self.lsre.LogSinkRulesEngine( rules_file_path=rules_local_path) rules_engine.build_rule_book() return rules_engine def test_build_rule_book_from_local_yaml_file_works(self): \"\"\"Tests that a", "resources and 'children' rules # for 2. self.assertEqual( 6, len(rules_engine.rule_book.resource_rules_map['self']))", "= set([ lsre.Rule.RuleViolation( resource_type='sink', resource_id='billing_logs', resource_name='billingAccounts/ABCD-1234/sinks/billing_logs', full_name='organization/234/billingAccount/ABCD-1234/billing_logs/', rule_name=('Only allow Billing", "log_sink_rules_engine as lsre from google.cloud.forseti.scanner.audit.errors import InvalidRulesSchemaError class LogSinkRulesEngineTest(ForsetiTestCase): \"\"\"Tests", "'log_sink_test_invalid_rules.yaml') rules_engine = self.lsre.LogSinkRulesEngine( rules_file_path=rules_local_path) with self.assertRaises(InvalidRulesSchemaError): rules_engine.build_rule_book() def test_project_with_no_violations(self):", "\"\"\"Tests that no violations are produced for a correct billing", "[ LogSink( sink_id='audit_logs_to_bq', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/proj_1_logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.proj_1, raw_json='_SINK_1_'", "resource_data='' ) ]) self.assertEqual(expected_violations, actual_violations) def test_add_invalid_rules(self): \"\"\"Tests that adding", "up resources in the following hierarchy: # +-----> billing_acct_abcd #", "for rule in bad_rules: with self.assertRaises(InvalidRulesSchemaError): rule_book.add_rule(rule, 1) if __name__", "= set([ lsre.Rule.RuleViolation( resource_name='234', resource_type='organization', resource_id='234', full_name='organization/234/', rule_name='Require an Org", "google.cloud.forseti.scanner.audit.errors import InvalidRulesSchemaError class LogSinkRulesEngineTest(ForsetiTestCase): \"\"\"Tests for the LogSinkRulesEngine.\"\"\" def", "\"\"\"Tests violations are produced for non-whitelisted sinks.\"\"\" rules_engine = self.get_engine_with_valid_rules()", "full_name='organization/234/project/proj-3/', data='fake_project_data_1233') def get_engine_with_valid_rules(self): \"\"\"Create a rule engine build with", "self.assertEqual(set(), actual_violations) def test_project_missing_required_sinks(self): \"\"\"Tests violations are produced for project", "writer_identity=('serviceAccount:<PASSWORD>@' 'gcp-sa-logging.iam.gserviceaccount.com'), parent=self.proj_1, raw_json='_SINK_2_' ) ] actual_violations = rules_engine.find_violations( self.proj_1,", "self.folder_56, log_sinks) expected_violations = set([ lsre.Rule.RuleViolation( resource_name='folders/56/sinks/audit_logs_to_bq', resource_type='sink', resource_id='audit_logs_to_bq', full_name='organization/234/folder/56/audit_logs_to_bq/',", "'resource': [{ 'type': 'bucket', 'applies_to': 'self', 'resource_ids': ['bucket-1'] }], 'sink':", "] actual_violations = rules_engine.find_violations( self.proj_2, log_sinks) expected_violations = set([ lsre.Rule.RuleViolation(", "for resource in rules_engine.rule_book.resource_rules_map['children']: child_rule_resources.append(resource.name) expected_rule_resources = ['folders/56', 'organizations/234'] self.assertEqual(expected_rule_resources,", "are produced for a correct folder.\"\"\" rules_engine = self.get_engine_with_valid_rules() #", "unittest import mock from tests.unittest_utils import ForsetiTestCase from tests.unittest_utils import", "self.proj_1, log_sinks) self.assertEqual(set(), actual_violations) def test_folder_with_no_violations(self): \"\"\"Tests that no violations", "# Rules disallow any folder-level LogSinks. log_sinks = [ LogSink(", "produced for blacklisted sinks.\"\"\" rules_engine = self.get_engine_with_valid_rules() # Rules disallow", "expected_violations = set([ lsre.Rule.RuleViolation( resource_name='folders/56/sinks/audit_logs_to_bq', resource_type='sink', resource_id='audit_logs_to_bq', full_name='organization/234/folder/56/audit_logs_to_bq/', rule_name='Disallow folder", "violations are produced for a correct organization.\"\"\" rules_engine = self.get_engine_with_valid_rules()", "resource_type='sink', resource_id='audit_logs_to_bq', full_name='organization/234/folder/56/audit_logs_to_bq/', rule_name='Disallow folder sinks.', rule_index=2, violation_type='LOG_SINK_VIOLATION', sink_destination=('bigquery.googleapis.com/projects/' 'my-audit-logs/datasets/folder_logs'),", "RuleBook is built correctly with a yaml file.\"\"\" rules_engine =", "produced for billing account sinks.\"\"\" rules_engine = self.get_engine_with_valid_rules() log_sinks =", "rule_name=('Only allow Billing Account sinks to audit logs ' 'project.'),", "sink_filter='logName:\"logs/otherapi.googleapis.com\"', include_children=True, writer_identity='serviceAccount:<EMAIL>', parent=self.org_234, raw_json='__SINK_2__' ) ] actual_violations = rules_engine.find_violations(", "sink_filter='resource.type=\"gce_instance\"', include_children=False, writer_identity=('serviceAccount:p12345-67890@' 'gcp-sa-logging.iam.gserviceaccount.com'), parent=self.proj_2, raw_json='__SINK_2__' ) ] actual_violations =", "LogSinkRulesEngineTest(ForsetiTestCase): \"\"\"Tests for the LogSinkRulesEngine.\"\"\" def setUp(self): \"\"\"Set up GCP", "implied. # See the License for the specific language governing", "'bigquery.*', 'include_children': '*' }, 'mode': 'whitelist' }, { 'name': 'Bad", "'bigquery.*', 'filter': '*', 'include_children': 'Yes' }, 'mode': 'whitelist' } ]", "'whitelist' }, { 'name': 'Empty resource_ids', 'resource': [{ 'type': 'project',", "acct.\"\"\" rules_engine = self.get_engine_with_valid_rules() log_sinks = [ LogSink( sink_id='billing_logs', destination=('bigquery.googleapis.com/projects/my-audit-logs/'", "]) self.assertEqual(expected_violations, actual_violations) def test_folder_blacklist_violation(self): \"\"\"Tests violations are produced for", "under the Apache License, Version 2.0 (the \"License\"); # you", "rules_engine.find_violations( self.proj_1, log_sinks) self.assertEqual(set(), actual_violations) def test_folder_with_no_violations(self): \"\"\"Tests that no", "mock from tests.unittest_utils import ForsetiTestCase from tests.unittest_utils import get_datafile_path from", "allow BigQuery sinks in Proj-1 and Proj-3.', rule_index=4, violation_type='LOG_SINK_VIOLATION', sink_destination=('pubsub.googleapis.com/projects/proj-3/'", "rules_engine.find_violations( self.folder_56, log_sinks) expected_violations = set([ lsre.Rule.RuleViolation( resource_name='folders/56/sinks/audit_logs_to_bq', resource_type='sink', resource_id='audit_logs_to_bq',", "'self', 'resource_ids': [] }], 'sink': valid_sink_spec, 'mode': 'whitelist' }, {", "'applies_to': 'self_and_children', 'resource_ids': ['56'] }], 'sink': valid_sink_spec, 'mode': 'whitelist' },", "self.assertEqual(set(), actual_violations) def test_org_with_no_violations(self): \"\"\"Tests that no violations are produced", "Project( 'proj-1', project_number=11223344, display_name='My project 1', parent=self.org_234, full_name='organization/234/project/proj-1/', data='fake_project_data_2341') self.proj_2", "['folders/56', 'organizations/234'] self.assertEqual(expected_rule_resources, sorted(child_rule_resources)) def test_build_rule_book_invalid_applies_to_fails(self): \"\"\"Tests that a rule", "valid_sink_spec, 'mode': 'whitelist' }, 0) bad_rules = [ {}, {", "'whitelist' }, { 'name': 'Missing filter', 'resource': [valid_resource], 'sink': {", "}, 0) bad_rules = [ {}, { 'name': 'Mising Resource',", "), ] actual_violations = rules_engine.find_violations( self.billing_acct_abcd, log_sinks) expected_violations = set([", "{}, { 'name': 'Mising Resource', 'mode': 'whitelist', 'sink': valid_sink_spec, },", "'folders/56', 'organizations/234', 'projects/proj-1', 'projects/proj-2', 'projects/proj-3'] self.assertEqual(expected_rule_resources, sorted(self_rule_resources)) child_rule_resources = []", "'organizations/234', 'projects/proj-1', 'projects/proj-2', 'projects/proj-3'] self.assertEqual(expected_rule_resources, sorted(self_rule_resources)) child_rule_resources = [] for", "[ LogSink( sink_id='billing_logs', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/wrong_dataset'), sink_filter='', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.billing_acct_abcd, raw_json='__SINK_1__'", "'project', 'applies_to': 'self', 'resource_ids': [] }], 'sink': valid_sink_spec, 'mode': 'whitelist'", "in rules_engine.rule_book.resource_rules_map['self']: self_rule_resources.append(resource.name) expected_rule_resources = [ 'billingAccounts/ABCD-1234', 'folders/56', 'organizations/234', 'projects/proj-1',", "# proj-2 needs an Audit Log sink, by org-level rules,", "All rights reserved. # # Licensed under the Apache License,", "actual_violations) def test_add_invalid_rules(self): \"\"\"Tests that adding invalid rules raises exceptions.\"\"\"", "sink_filter=('^logName\\\\:\\\\\"logs\\\\/' 'cloudaudit\\\\.googleapis\\\\.com\\\\\"$'), sink_include_children='*', resource_data='' ), lsre.Rule.RuleViolation( resource_name='proj-2', resource_type='project', resource_id='proj-2', full_name='organization/234/folder/56/project/proj-2/',", "by applicable law or agreed to in writing, software #", "'ABCD-1234', display_name='Billing Account ABCD', full_name='organization/234/billingAccount/ABCD-1234/', data='fake_billing_account_data_abcd') self.folder_56 = Folder( '56',", "# Copyright 2018 The Forseti Security Authors. All rights reserved.", "self.get_engine_with_valid_rules() # proj-2 needs an Audit Log sink, by org-level", "rules_engine = self.get_engine_with_valid_rules() log_sinks = [ LogSink( sink_id='billing_logs', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/wrong_dataset'),", ") ]) self.assertEqual(expected_violations, actual_violations) def test_add_invalid_rules(self): \"\"\"Tests that adding invalid", "from tests.unittest_utils import get_datafile_path from google.cloud.forseti.common.gcp_type.billing_account import BillingAccount from google.cloud.forseti.common.gcp_type.folder", "for resource in rules_engine.rule_book.resource_rules_map['self']: self_rule_resources.append(resource.name) expected_rule_resources = [ 'billingAccounts/ABCD-1234', 'folders/56',", "self.assertEqual(expected_rule_resources, sorted(self_rule_resources)) child_rule_resources = [] for resource in rules_engine.rule_book.resource_rules_map['children']: child_rule_resources.append(resource.name)", "destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/proj_1_logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.proj_1, raw_json='_SINK_1_' ), LogSink( sink_id='compute_logs_saver',", "destination=('bigquery.googleapis.com/projects/proj_2/' 'datasets/compute_logs'), sink_filter='resource.type=\"gce_instance\"', include_children=False, writer_identity=('serviceAccount:p12345-67890@' 'gcp-sa-logging.iam.gserviceaccount.com'), parent=self.proj_2, raw_json='__SINK_2__' ) ]", "LogSink( sink_id='compute_logs_saver', destination=('bigquery.googleapis.com/projects/proj_2/' 'datasets/compute_logs'), sink_filter='resource.type=\"gce_instance\"', include_children=False, writer_identity=('serviceAccount:p12345-67890@' 'gcp-sa-logging.iam.gserviceaccount.com'), parent=self.proj_2, raw_json='__SINK_2__'", "sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.folder_56, raw_json='__SINK_1__' ) ] actual_violations = rules_engine.find_violations(", "test_org_with_no_violations(self): \"\"\"Tests that no violations are produced for a correct", "full_name='organization/234/folder/56/audit_logs_to_bq/', rule_name='Disallow folder sinks.', rule_index=2, violation_type='LOG_SINK_VIOLATION', sink_destination=('bigquery.googleapis.com/projects/' 'my-audit-logs/datasets/folder_logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', sink_include_children=False,", "sink_filter='logName:\"logs/non-cloudaudit.googleapis.com\"', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.proj_2, raw_json='__SINK_1__' ), LogSink( sink_id='compute_logs_saver', destination=('bigquery.googleapis.com/projects/proj_2/' 'datasets/compute_logs'),", "proj-3 can only have BigQuery sinks. log_sinks = [ LogSink(", "disallow any folder-level LogSinks. log_sinks = [ LogSink( sink_id='audit_logs_to_bq', destination=('bigquery.googleapis.com/projects/my-audit-logs/'", "under the License. \"\"\"Tests the LogSinkRulesEngine.\"\"\" import unittest import mock", "'my\\\\-audit\\\\-logs\\\\/datasets\\\\/.+$'), sink_filter=('^logName\\\\:\\\\\"logs\\\\/' 'cloudaudit\\\\.googleapis\\\\.com\\\\\"$'), sink_include_children='*', resource_data='' ), lsre.Rule.RuleViolation( resource_name='proj-2', resource_type='project', resource_id='proj-2',", "actual_violations) def test_org_missing_required_sinks(self): \"\"\"Tests violations are produced for an org", "= self.get_engine_with_valid_rules() log_sinks = [ LogSink( sink_id='billing_logs', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/wrong_dataset'), sink_filter='',", "writer_identity='serviceAccount:<EMAIL>', parent=self.org_234, raw_json='__SINK_2__' ) ] actual_violations = rules_engine.find_violations( self.org_234, log_sinks)", "an Audit Log sink, including children. log_sinks = [ LogSink(", "actual_violations = rules_engine.find_violations(self.folder_56, []) self.assertEqual(set(), actual_violations) def test_billing_account_with_no_violations(self): \"\"\"Tests that", "'self_and_children', 'resource_ids': ['56'] }], 'sink': valid_sink_spec, 'mode': 'whitelist' }, {", "that a rule with invalid applies_to type cannot be created.\"\"\"", "sink_include_children=False, resource_data='__SINK_1__') ]) self.assertEqual(expected_violations, actual_violations) def test_billing_account_with_whitelist_violations(self): \"\"\"Tests violations are", "sorted(child_rule_resources)) def test_build_rule_book_invalid_applies_to_fails(self): \"\"\"Tests that a rule with invalid applies_to", "resource in rules_engine.rule_book.resource_rules_map['self']: self_rule_resources.append(resource.name) expected_rule_resources = [ 'billingAccounts/ABCD-1234', 'folders/56', 'organizations/234',", "Authors. All rights reserved. # # Licensed under the Apache", "destination=('pubsub.googleapis.com/projects/proj-3/topics/' 'org-more-logs'), sink_filter='logName:\"logs/otherapi.googleapis.com\"', include_children=True, writer_identity='serviceAccount:<EMAIL>', parent=self.org_234, raw_json='__SINK_2__' ) ] actual_violations", "'name': 'Empty resource_ids', 'resource': [{ 'type': 'project', 'applies_to': 'self', 'resource_ids':", "[valid_resource], 'sink': { 'destination': 'bigquery.*', 'filter': '*', 'include_children': 'Yes' },", "governing permissions and # limitations under the License. \"\"\"Tests the", "self.assertRaises(InvalidRulesSchemaError): rules_engine.build_rule_book() def test_project_with_no_violations(self): \"\"\"Tests that no violations are produced", "to audit logs ' 'project.'), rule_index=6, violation_type='LOG_SINK_VIOLATION', sink_destination=('bigquery.googleapis.com/projects/' 'my-audit-logs/datasets/wrong_dataset'), sink_filter='',", ") ] actual_violations = rules_engine.find_violations( self.folder_56, log_sinks) expected_violations = set([", "= Organization( '234', display_name='Organization 234', full_name='organization/234/', data='fake_org_data_234') self.billing_acct_abcd = BillingAccount(", "= set([ lsre.Rule.RuleViolation( resource_name='proj-2', resource_type='project', resource_id='proj-2', full_name='organization/234/folder/56/project/proj-2/', rule_name='Require Audit Log", "mock.MagicMock() # Set up resources in the following hierarchy: #", "a correct organization.\"\"\" rules_engine = self.get_engine_with_valid_rules() # Org needs an", "yaml file.\"\"\" rules_engine = self.get_engine_with_valid_rules() # Creates 'self' rules for", "by org-level rules, and a pubsub # sink, by folder-level", "proj-2 # | # | # +-----------------------> proj-3 self.org_234 =", "import LogSink from google.cloud.forseti.common.gcp_type.organization import Organization from google.cloud.forseti.common.gcp_type.project import Project", "'234', display_name='Organization 234', full_name='organization/234/', data='fake_org_data_234') self.billing_acct_abcd = BillingAccount( 'ABCD-1234', display_name='Billing", "a pubsub # sink, by folder-level rules. log_sinks = [", "actual_violations = rules_engine.find_violations( self.proj_2, log_sinks) expected_violations = set([ lsre.Rule.RuleViolation( resource_name='proj-2',", "produced for a correct project.\"\"\" rules_engine = self.get_engine_with_valid_rules() # proj-1", "destination=('bigquery.googleapis.com/projects/proj_1/' 'datasets/compute_logs'), sink_filter='resource.type=\"gce_instance\"', include_children=False, writer_identity=('serviceAccount:<PASSWORD>@' 'gcp-sa-logging.iam.gserviceaccount.com'), parent=self.proj_1, raw_json='_SINK_2_' ) ]", "self.org_234, log_sinks) self.assertEqual(set(), actual_violations) def test_project_missing_required_sinks(self): \"\"\"Tests violations are produced", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "data='fake_billing_account_data_abcd') self.folder_56 = Folder( '56', display_name='Folder 56', full_name='organization/234/folder/56/', data='fake_folder_data456456') self.proj_1", "Unless required by applicable law or agreed to in writing,", "rules_engine = self.lsre.LogSinkRulesEngine( rules_file_path=rules_local_path) with self.assertRaises(InvalidRulesSchemaError): rules_engine.build_rule_book() def test_project_with_no_violations(self): \"\"\"Tests", "Security Authors. All rights reserved. # # Licensed under the", "self.get_engine_with_valid_rules() # Rules disallow any folder-level LogSinks. log_sinks = [", "# | # | # +-----------------------> proj-3 self.org_234 = Organization(", "'*' }, 'mode': 'whitelist' }, { 'name': 'Bad include_children', 'resource':", "LogSink( sink_id='billing_logs', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/billing_logs'), sink_filter='', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.billing_acct_abcd, raw_json='__SINK_1__' ),", "[valid_resource], 'sink': { 'destination': 'bigquery.*', 'include_children': '*' }, 'mode': 'whitelist'", "# +-----------------------> proj-1 # | # | # org_234 +----->", "hierarchy: # +-----> billing_acct_abcd # | # | # +----------------------->", "rule_index=3, violation_type='LOG_SINK_VIOLATION', sink_destination='^pubsub\\\\.googleapis\\\\.com\\\\/.+$', sink_filter='^$', sink_include_children='*', resource_data='' ) ]) self.assertEqual(expected_violations, actual_violations)", "'mode': 'whitelist', }, { 'name': 'Bad mode', 'resource': [valid_resource], 'sink':", "display_name='Organization 234', full_name='organization/234/', data='fake_org_data_234') self.billing_acct_abcd = BillingAccount( 'ABCD-1234', display_name='Billing Account", "cannot be created.\"\"\" rules_local_path = get_datafile_path( __file__, 'log_sink_test_invalid_rules.yaml') rules_engine =", "\"\"\"Tests that a rule with invalid applies_to type cannot be", "= self.get_engine_with_valid_rules() # Org needs an Audit Log sink, including", "LogSink( sink_id='audit_logs_to_bq', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/proj_1_logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.proj_1, raw_json='_SINK_1_' ),", "resource_id='proj-2', full_name='organization/234/folder/56/project/proj-2/', rule_name='Require a PubSub sink in folder-56 projects.', rule_index=3,", "Project( 'proj-2', project_number=223344, display_name='My project 2', parent=self.folder_56, full_name='organization/234/folder/56/project/proj-2/', data='fake_project_data_4562') self.proj_3", "the specific language governing permissions and # limitations under the", "sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.proj_1, raw_json='_SINK_1_' ), LogSink( sink_id='compute_logs_saver', destination=('bigquery.googleapis.com/projects/proj_1/' 'datasets/compute_logs'),", "56', full_name='organization/234/folder/56/', data='fake_folder_data456456') self.proj_1 = Project( 'proj-1', project_number=11223344, display_name='My project", "= rules_engine.find_violations( self.proj_3, log_sinks) expected_violations = set([ lsre.Rule.RuleViolation( resource_name='projects/proj-3/sinks/audit_logs_to_pubsub', resource_type='sink',", "'Missing filter', 'resource': [valid_resource], 'sink': { 'destination': 'bigquery.*', 'include_children': '*'", "lsre.Rule.RuleViolation( resource_name='proj-2', resource_type='project', resource_id='proj-2', full_name='organization/234/folder/56/project/proj-2/', rule_name='Require a PubSub sink in", "applicable law or agreed to in writing, software # distributed", "destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/wrong_dataset'), sink_filter='', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.billing_acct_abcd, raw_json='__SINK_1__' ), ] actual_violations", "resource_type='project', resource_id='proj-2', full_name='organization/234/folder/56/project/proj-2/', rule_name='Require a PubSub sink in folder-56 projects.',", "'', 'include_children': '*' } rule_book.add_rule( { 'name': 'Valid rule', 'resource':", "raw_json='__SINK_1__' ), LogSink( sink_id='sink_with_wrong_filter', destination=('pubsub.googleapis.com/projects/proj-3/topics/' 'org-more-logs'), sink_filter='logName:\"logs/otherapi.googleapis.com\"', include_children=True, writer_identity='serviceAccount:<EMAIL>', parent=self.org_234,", "sink_include_children=True, resource_data='' ) ]) self.assertEqual(expected_violations, actual_violations) def test_add_invalid_rules(self): \"\"\"Tests that", "'mode': 'whitelist' } ] for rule in bad_rules: with self.assertRaises(InvalidRulesSchemaError):", "]) self.assertEqual(expected_violations, actual_violations) def test_billing_account_with_whitelist_violations(self): \"\"\"Tests violations are produced for", "rules, and a pubsub # sink, by folder-level rules. log_sinks", "resource_type='project', resource_id='proj-2', full_name='organization/234/folder/56/project/proj-2/', rule_name='Require Audit Log sinks in all projects.',", "get_datafile_path from google.cloud.forseti.common.gcp_type.billing_account import BillingAccount from google.cloud.forseti.common.gcp_type.folder import Folder from", "no violations are produced for a correct project.\"\"\" rules_engine =", "'proj-audit-logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=True, writer_identity='serviceAccount:<EMAIL>', parent=self.proj_3, raw_json='__SINK_2__' ) ] actual_violations =", "= [ LogSink( sink_id='audit_logs_to_bq', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/proj_1_logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.proj_1,", "'billing_account', 'applies_to': 'children', 'resource_ids': ['ABCD-1234'] }], 'sink': valid_sink_spec, 'mode': 'whitelist'", "rules_engine.rule_book.resource_rules_map['children']: child_rule_resources.append(resource.name) expected_rule_resources = ['folders/56', 'organizations/234'] self.assertEqual(expected_rule_resources, sorted(child_rule_resources)) def test_build_rule_book_invalid_applies_to_fails(self):", "\"\"\"Tests that no violations are produced for a correct folder.\"\"\"", "raw_json='_SINK_2_' ) ] actual_violations = rules_engine.find_violations( self.proj_1, log_sinks) self.assertEqual(set(), actual_violations)", "test_project_missing_required_sinks(self): \"\"\"Tests violations are produced for project missing required sinks.\"\"\"", "expected_rule_resources = ['folders/56', 'organizations/234'] self.assertEqual(expected_rule_resources, sorted(child_rule_resources)) def test_build_rule_book_invalid_applies_to_fails(self): \"\"\"Tests that", "in writing, software # distributed under the License is distributed", "| # +-----------------------> proj-1 # | # | # org_234", "destination=('pubsub.googleapis.com/projects/proj-3/topics/' 'org-audit-logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=True, writer_identity='serviceAccount:<EMAIL>', parent=self.org_234, raw_json='__SINK_1__' ) ] actual_violations", "\"\"\"Tests violations are produced for an org missing required sinks.\"\"\"", "= rules_engine.find_violations( self.folder_56, log_sinks) expected_violations = set([ lsre.Rule.RuleViolation( resource_name='folders/56/sinks/audit_logs_to_bq', resource_type='sink',", "'name': 'Mising Resource', 'mode': 'whitelist', 'sink': valid_sink_spec, }, { 'name':", "destination=('pubsub.googleapis.com/projects/proj-3/topics/' 'org-audit-logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.org_234, raw_json='__SINK_1__' ), LogSink( sink_id='sink_with_wrong_filter',", "= Project( 'proj-1', project_number=11223344, display_name='My project 1', parent=self.org_234, full_name='organization/234/project/proj-1/', data='fake_project_data_2341')", "self.assertEqual( 2, len(rules_engine.rule_book.resource_rules_map['children'])) self_rule_resources = [] for resource in rules_engine.rule_book.resource_rules_map['self']:", "sink_id='audit_logs_to_bq', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/proj_1_logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.proj_1, raw_json='_SINK_1_' ), LogSink(", "'sink': valid_sink_spec, 'mode': 'whitelist' }, { 'name': 'Missing filter', 'resource':", "len(rules_engine.rule_book.resource_rules_map['self'])) self.assertEqual( 2, len(rules_engine.rule_book.resource_rules_map['children'])) self_rule_resources = [] for resource in", "License. \"\"\"Tests the LogSinkRulesEngine.\"\"\" import unittest import mock from tests.unittest_utils", "= [] for resource in rules_engine.rule_book.resource_rules_map['self']: self_rule_resources.append(resource.name) expected_rule_resources = [", "full_name='organization/234/billingAccount/ABCD-1234/', data='fake_billing_account_data_abcd') self.folder_56 = Folder( '56', display_name='Folder 56', full_name='organization/234/folder/56/', data='fake_folder_data456456')", "'Bad include_children', 'resource': [valid_resource], 'sink': { 'destination': 'bigquery.*', 'filter': '*',", "a PubSub sink in folder-56 projects.', rule_index=3, violation_type='LOG_SINK_VIOLATION', sink_destination='^pubsub\\\\.googleapis\\\\.com\\\\/.+$', sink_filter='^$',", "self.assertEqual(expected_violations, actual_violations) def test_add_invalid_rules(self): \"\"\"Tests that adding invalid rules raises", "log_sinks = [ LogSink( sink_id='audit_logs_to_bq', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/proj_1_logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=False, writer_identity='serviceAccount:<EMAIL>',", "required sinks.\"\"\" rules_engine = self.get_engine_with_valid_rules() # Org needs an Audit", "resource_name='billingAccounts/ABCD-1234/sinks/billing_logs', full_name='organization/234/billingAccount/ABCD-1234/billing_logs/', rule_name=('Only allow Billing Account sinks to audit logs", "writer_identity='serviceAccount:<EMAIL>', parent=self.proj_1, raw_json='_SINK_1_' ), LogSink( sink_id='compute_logs_saver', destination=('bigquery.googleapis.com/projects/proj_1/' 'datasets/compute_logs'), sink_filter='resource.type=\"gce_instance\"', include_children=False,", "'applies_to': 'children', 'resource_ids': ['1234'] } valid_sink_spec = { 'destination': 'bigquery.*',", "any folder-level LogSinks. actual_violations = rules_engine.find_violations(self.folder_56, []) self.assertEqual(set(), actual_violations) def", "valid_resource = { 'type': 'organization', 'applies_to': 'children', 'resource_ids': ['1234'] }", "rule', 'resource': [valid_resource], 'sink': valid_sink_spec, 'mode': 'whitelist' }, 0) bad_rules", "folder-56 projects.', rule_index=3, violation_type='LOG_SINK_VIOLATION', sink_destination='^pubsub\\\\.googleapis\\\\.com\\\\/.+$', sink_filter='^$', sink_include_children='*', resource_data='' ) ])", "= self.get_engine_with_valid_rules() # proj-1 needs an Audit Log sink. log_sinks", "violations are produced for project missing required sinks.\"\"\" rules_engine =", "[{ 'type': 'bucket', 'applies_to': 'self', 'resource_ids': ['bucket-1'] }], 'sink': valid_sink_spec,", "'resource_ids': [] }], 'sink': valid_sink_spec, 'mode': 'whitelist' }, { 'name':", "as lsre from google.cloud.forseti.scanner.audit.errors import InvalidRulesSchemaError class LogSinkRulesEngineTest(ForsetiTestCase): \"\"\"Tests for", "[] for resource in rules_engine.rule_book.resource_rules_map['children']: child_rule_resources.append(resource.name) expected_rule_resources = ['folders/56', 'organizations/234']", "= Project( 'proj-2', project_number=223344, display_name='My project 2', parent=self.folder_56, full_name='organization/234/folder/56/project/proj-2/', data='fake_project_data_4562')", ") ] actual_violations = rules_engine.find_violations( self.proj_2, log_sinks) expected_violations = set([", "' 'project.'), rule_index=6, violation_type='LOG_SINK_VIOLATION', sink_destination=('bigquery.googleapis.com/projects/' 'my-audit-logs/datasets/wrong_dataset'), sink_filter='', sink_include_children=False, resource_data='__SINK_1__') ])", "rule with invalid applies_to type cannot be created.\"\"\" rules_local_path =", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "Folder( '56', display_name='Folder 56', full_name='organization/234/folder/56/', data='fake_folder_data456456') self.proj_1 = Project( 'proj-1',", "sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.proj_3, raw_json='__SINK_1__' ), LogSink( sink_id='audit_logs_to_pubsub', destination=('pubsub.googleapis.com/projects/proj-3/topics/' 'proj-audit-logs'),", "parent=self.proj_3, raw_json='__SINK_1__' ), LogSink( sink_id='audit_logs_to_pubsub', destination=('pubsub.googleapis.com/projects/proj-3/topics/' 'proj-audit-logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=True, writer_identity='serviceAccount:<EMAIL>',", "License, Version 2.0 (the \"License\"); # you may not use", "are produced for a correct organization.\"\"\" rules_engine = self.get_engine_with_valid_rules() #", "rules_engine.build_rule_book() def test_project_with_no_violations(self): \"\"\"Tests that no violations are produced for", "# You may obtain a copy of the License at", "set([ lsre.Rule.RuleViolation( resource_name='projects/proj-3/sinks/audit_logs_to_pubsub', resource_type='sink', resource_id='audit_logs_to_pubsub', full_name='organization/234/project/proj-3/audit_logs_to_pubsub/', rule_name='Only allow BigQuery sinks", "{ 'name': 'Bad resource type', 'resource': [{ 'type': 'bucket', 'applies_to':", "import get_datafile_path from google.cloud.forseti.common.gcp_type.billing_account import BillingAccount from google.cloud.forseti.common.gcp_type.folder import Folder", "for a correct folder.\"\"\" rules_engine = self.get_engine_with_valid_rules() # Rules disallow", "'applies_to': 'self', 'resource_ids': [] }], 'sink': valid_sink_spec, 'mode': 'whitelist' },", "[{ 'type': 'folder', 'applies_to': 'self_and_children', 'resource_ids': ['56'] }], 'sink': valid_sink_spec,", "invalid applies_to type cannot be created.\"\"\" rules_local_path = get_datafile_path( __file__,", "sink_destination=('bigquery.googleapis.com/projects/' 'my-audit-logs/datasets/folder_logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', sink_include_children=False, resource_data='__SINK_1__') ]) self.assertEqual(expected_violations, actual_violations) def test_billing_account_with_whitelist_violations(self):", "org_234 +-----> folder_56 +-----> proj-2 # | # | #", "3', parent=self.org_234, full_name='organization/234/project/proj-3/', data='fake_project_data_1233') def get_engine_with_valid_rules(self): \"\"\"Create a rule engine", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "parent=self.proj_2, raw_json='__SINK_1__' ), LogSink( sink_id='compute_logs_saver', destination=('bigquery.googleapis.com/projects/proj_2/' 'datasets/compute_logs'), sink_filter='resource.type=\"gce_instance\"', include_children=False, writer_identity=('serviceAccount:p12345-67890@'", "build with a valid rules file.\"\"\" rules_local_path = get_datafile_path( __file__,", "), ] actual_violations = rules_engine.find_violations( self.billing_acct_abcd, log_sinks) self.assertEqual(set(), actual_violations) def", "expected_rule_resources = [ 'billingAccounts/ABCD-1234', 'folders/56', 'organizations/234', 'projects/proj-1', 'projects/proj-2', 'projects/proj-3'] self.assertEqual(expected_rule_resources,", "self.proj_1 = Project( 'proj-1', project_number=11223344, display_name='My project 1', parent=self.org_234, full_name='organization/234/project/proj-1/',", "produced for a correct organization.\"\"\" rules_engine = self.get_engine_with_valid_rules() # Org", "raw_json='__SINK_2__' ) ] actual_violations = rules_engine.find_violations( self.proj_3, log_sinks) expected_violations =", "'type': 'organization', 'applies_to': 'children', 'resource_ids': ['1234'] } valid_sink_spec = {", "'log_sink_test_valid_rules.yaml') rules_engine = self.lsre.LogSinkRulesEngine( rules_file_path=rules_local_path) rules_engine.build_rule_book() return rules_engine def test_build_rule_book_from_local_yaml_file_works(self):", "rules_engine.find_violations( self.org_234, log_sinks) expected_violations = set([ lsre.Rule.RuleViolation( resource_name='234', resource_type='organization', resource_id='234',", "sink, by org-level rules, and a pubsub # sink, by", "Audit Log sink, by org-level rules, and a pubsub #", "'name': 'Bad resource type', 'resource': [{ 'type': 'bucket', 'applies_to': 'self',", "a correct project.\"\"\" rules_engine = self.get_engine_with_valid_rules() # proj-1 needs an", "raw_json='__SINK_2__' ) ] actual_violations = rules_engine.find_violations( self.proj_2, log_sinks) expected_violations =", "logs ' 'project.'), rule_index=6, violation_type='LOG_SINK_VIOLATION', sink_destination=('bigquery.googleapis.com/projects/' 'my-audit-logs/datasets/wrong_dataset'), sink_filter='', sink_include_children=False, resource_data='__SINK_1__')", "[ {}, { 'name': 'Mising Resource', 'mode': 'whitelist', 'sink': valid_sink_spec,", "applies to type', 'resource': [{ 'type': 'folder', 'applies_to': 'self_and_children', 'resource_ids':", "for tests.\"\"\" self.lsre = lsre self.lsre.LOGGER = mock.MagicMock() # Set", "adding invalid rules raises exceptions.\"\"\" rule_book = self.lsre.LogSinkRuleBook(global_configs=None) valid_resource =", "'resource': [valid_resource], 'sink': valid_sink_spec, 'mode': 'other', }, { 'name': 'Bad", "full_name='organization/234/project/proj-1/', data='fake_project_data_2341') self.proj_2 = Project( 'proj-2', project_number=223344, display_name='My project 2',", "from google.cloud.forseti.common.gcp_type.folder import Folder from google.cloud.forseti.common.gcp_type.log_sink import LogSink from google.cloud.forseti.common.gcp_type.organization", "+-----------------------> proj-1 # | # | # org_234 +-----> folder_56", "[{ 'type': 'billing_account', 'applies_to': 'children', 'resource_ids': ['ABCD-1234'] }], 'sink': valid_sink_spec,", "the License for the specific language governing permissions and #", "set([ lsre.Rule.RuleViolation( resource_name='folders/56/sinks/audit_logs_to_bq', resource_type='sink', resource_id='audit_logs_to_bq', full_name='organization/234/folder/56/audit_logs_to_bq/', rule_name='Disallow folder sinks.', rule_index=2,", "Rules disallow any folder-level LogSinks. log_sinks = [ LogSink( sink_id='audit_logs_to_bq',", "def test_project_missing_required_sinks(self): \"\"\"Tests violations are produced for project missing required", "full_name='organization/234/folder/56/project/proj-2/', rule_name='Require Audit Log sinks in all projects.', rule_index=0, violation_type='LOG_SINK_VIOLATION',", "destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/proj_1_logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.proj_3, raw_json='__SINK_1__' ), LogSink( sink_id='audit_logs_to_pubsub',", "Apache License, Version 2.0 (the \"License\"); # you may not", "lsre self.lsre.LOGGER = mock.MagicMock() # Set up resources in the", "either express or implied. # See the License for the", "\"\"\"Tests that a RuleBook is built correctly with a yaml", "resource_id='proj-2', full_name='organization/234/folder/56/project/proj-2/', rule_name='Require Audit Log sinks in all projects.', rule_index=0,", "writer_identity='serviceAccount:<EMAIL>', parent=self.org_234, raw_json='__SINK_1__' ), LogSink( sink_id='sink_with_wrong_filter', destination=('pubsub.googleapis.com/projects/proj-3/topics/' 'org-more-logs'), sink_filter='logName:\"logs/otherapi.googleapis.com\"', include_children=True,", "= self.get_engine_with_valid_rules() log_sinks = [ LogSink( sink_id='billing_logs', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/billing_logs'), sink_filter='',", "audit log sink.', rule_index=1, violation_type='LOG_SINK_VIOLATION', sink_destination='^.*$', sink_filter=('^logName\\\\:\\\\\"logs\\\\/' 'cloudaudit\\\\.googleapis\\\\.com\\\\\"$'), sink_include_children=True, resource_data=''", "'sink': valid_sink_spec, 'mode': 'whitelist' }, { 'name': 'Empty resource_ids', 'resource':", "include_children', 'resource': [valid_resource], 'sink': { 'destination': 'bigquery.*', 'filter': '*', 'include_children':", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "[{ 'type': 'project', 'applies_to': 'self', 'resource_ids': [] }], 'sink': valid_sink_spec,", "include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.proj_1, raw_json='_SINK_1_' ), LogSink( sink_id='compute_logs_saver', destination=('bigquery.googleapis.com/projects/proj_1/' 'datasets/compute_logs'), sink_filter='resource.type=\"gce_instance\"',", "google.cloud.forseti.common.gcp_type.folder import Folder from google.cloud.forseti.common.gcp_type.log_sink import LogSink from google.cloud.forseti.common.gcp_type.organization import", "child_rule_resources = [] for resource in rules_engine.rule_book.resource_rules_map['children']: child_rule_resources.append(resource.name) expected_rule_resources =", "'name': 'Bad applies to type', 'resource': [{ 'type': 'folder', 'applies_to':", "'whitelist' } ] for rule in bad_rules: with self.assertRaises(InvalidRulesSchemaError): rule_book.add_rule(rule,", "Creates 'self' rules for 5 difference resources and 'children' rules", "missing required sinks.\"\"\" rules_engine = self.get_engine_with_valid_rules() # Org needs an", "'projects/proj-2', 'projects/proj-3'] self.assertEqual(expected_rule_resources, sorted(self_rule_resources)) child_rule_resources = [] for resource in", ") ] actual_violations = rules_engine.find_violations( self.proj_1, log_sinks) self.assertEqual(set(), actual_violations) def", "'resource': [{ 'type': 'project', 'applies_to': 'self', 'resource_ids': [] }], 'sink':", "setUp(self): \"\"\"Set up GCP resources for tests.\"\"\" self.lsre = lsre", "'sink': valid_sink_spec, 'mode': 'whitelist' }, { 'name': 'Bad applies to", "= ['folders/56', 'organizations/234'] self.assertEqual(expected_rule_resources, sorted(child_rule_resources)) def test_build_rule_book_invalid_applies_to_fails(self): \"\"\"Tests that a", "log_sinks = [ LogSink( sink_id='billing_logs', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/wrong_dataset'), sink_filter='', include_children=False, writer_identity='serviceAccount:<EMAIL>',", "= self.lsre.LogSinkRulesEngine( rules_file_path=rules_local_path) with self.assertRaises(InvalidRulesSchemaError): rules_engine.build_rule_book() def test_project_with_no_violations(self): \"\"\"Tests that", "full_name='organization/234/', data='fake_org_data_234') self.billing_acct_abcd = BillingAccount( 'ABCD-1234', display_name='Billing Account ABCD', full_name='organization/234/billingAccount/ABCD-1234/',", "'destination': 'bigquery.*', 'filter': '*', 'include_children': 'Yes' }, 'mode': 'whitelist' }", "type cannot be created.\"\"\" rules_local_path = get_datafile_path( __file__, 'log_sink_test_invalid_rules.yaml') rules_engine", "'sink': valid_sink_spec, }, { 'name': 'Mising sink', 'resource': [valid_resource], 'mode':", "rules_engine = self.get_engine_with_valid_rules() # Org needs an Audit Log sink,", "with invalid applies_to type cannot be created.\"\"\" rules_local_path = get_datafile_path(", "in all projects.', rule_index=0, violation_type='LOG_SINK_VIOLATION', sink_destination=('^bigquery\\\\.googleapis\\\\.com\\\\/projects\\\\/' 'my\\\\-audit\\\\-logs\\\\/datasets\\\\/.+$'), sink_filter=('^logName\\\\:\\\\\"logs\\\\/' 'cloudaudit\\\\.googleapis\\\\.com\\\\\"$'), sink_include_children='*',", "include_children=True, writer_identity='serviceAccount:<EMAIL>', parent=self.org_234, raw_json='__SINK_2__' ) ] actual_violations = rules_engine.find_violations( self.org_234,", "violation_type='LOG_SINK_VIOLATION', sink_destination='^.*$', sink_filter=('^logName\\\\:\\\\\"logs\\\\/' 'cloudaudit\\\\.googleapis\\\\.com\\\\\"$'), sink_include_children=True, resource_data='' ) ]) self.assertEqual(expected_violations, actual_violations)", "# for 2. self.assertEqual( 6, len(rules_engine.rule_book.resource_rules_map['self'])) self.assertEqual( 2, len(rules_engine.rule_book.resource_rules_map['children'])) self_rule_resources", "no violations are produced for a correct organization.\"\"\" rules_engine =", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "def test_folder_blacklist_violation(self): \"\"\"Tests violations are produced for blacklisted sinks.\"\"\" rules_engine", "actual_violations = rules_engine.find_violations( self.proj_1, log_sinks) self.assertEqual(set(), actual_violations) def test_folder_with_no_violations(self): \"\"\"Tests", "), LogSink( sink_id='sink_with_wrong_filter', destination=('pubsub.googleapis.com/projects/proj-3/topics/' 'org-more-logs'), sink_filter='logName:\"logs/otherapi.googleapis.com\"', include_children=True, writer_identity='serviceAccount:<EMAIL>', parent=self.org_234, raw_json='__SINK_2__'", "rule engine build with a valid rules file.\"\"\" rules_local_path =", "sink_include_children=True, resource_data='__SINK_2__' ) ]) self.assertEqual(expected_violations, actual_violations) def test_folder_blacklist_violation(self): \"\"\"Tests violations", "LogSink( sink_id='audit_logs_to_bq', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/folder_logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.folder_56, raw_json='__SINK_1__' )", "in folder-56 projects.', rule_index=3, violation_type='LOG_SINK_VIOLATION', sink_destination='^pubsub\\\\.googleapis\\\\.com\\\\/.+$', sink_filter='^$', sink_include_children='*', resource_data='' )", "Forseti Security Authors. All rights reserved. # # Licensed under", "folder-level rules. log_sinks = [ LogSink( sink_id='non_audit_logs_to_bq', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/proj_2_logs'), sink_filter='logName:\"logs/non-cloudaudit.googleapis.com\"',", "}, { 'name': 'Mising sink', 'resource': [valid_resource], 'mode': 'whitelist', },", "violations are produced for a correct folder.\"\"\" rules_engine = self.get_engine_with_valid_rules()", "sink_id='billing_logs', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/wrong_dataset'), sink_filter='', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.billing_acct_abcd, raw_json='__SINK_1__' ), ]", "), lsre.Rule.RuleViolation( resource_name='proj-2', resource_type='project', resource_id='proj-2', full_name='organization/234/folder/56/project/proj-2/', rule_name='Require a PubSub sink", "tests.unittest_utils import get_datafile_path from google.cloud.forseti.common.gcp_type.billing_account import BillingAccount from google.cloud.forseti.common.gcp_type.folder import", "# | # | # org_234 +-----> folder_56 +-----> proj-2", "Set up resources in the following hierarchy: # +-----> billing_acct_abcd", "'type': 'folder', 'applies_to': 'self_and_children', 'resource_ids': ['56'] }], 'sink': valid_sink_spec, 'mode':", "rules_engine = self.get_engine_with_valid_rules() log_sinks = [ LogSink( sink_id='billing_logs', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/billing_logs'),", "Project( 'proj-3', project_number=33445566, display_name='My project 3', parent=self.org_234, full_name='organization/234/project/proj-3/', data='fake_project_data_1233') def", "include_children=False, writer_identity=('serviceAccount:p12345-67890@' 'gcp-sa-logging.iam.gserviceaccount.com'), parent=self.proj_2, raw_json='__SINK_2__' ) ] actual_violations = rules_engine.find_violations(", "and 'children' rules # for 2. self.assertEqual( 6, len(rules_engine.rule_book.resource_rules_map['self'])) self.assertEqual(", "from google.cloud.forseti.scanner.audit import log_sink_rules_engine as lsre from google.cloud.forseti.scanner.audit.errors import InvalidRulesSchemaError", "folder.\"\"\" rules_engine = self.get_engine_with_valid_rules() # Rules disallow any folder-level LogSinks.", "the following hierarchy: # +-----> billing_acct_abcd # | # |", "] actual_violations = rules_engine.find_violations( self.folder_56, log_sinks) expected_violations = set([ lsre.Rule.RuleViolation(", "expected_violations = set([ lsre.Rule.RuleViolation( resource_type='sink', resource_id='billing_logs', resource_name='billingAccounts/ABCD-1234/sinks/billing_logs', full_name='organization/234/billingAccount/ABCD-1234/billing_logs/', rule_name=('Only allow", "\"License\"); # you may not use this file except in", "is built correctly with a yaml file.\"\"\" rules_engine = self.get_engine_with_valid_rules()", "project missing required sinks.\"\"\" rules_engine = self.get_engine_with_valid_rules() # proj-2 needs", "# | # org_234 +-----> folder_56 +-----> proj-2 # |", "| # | # +-----------------------> proj-1 # | # |", "rules_local_path = get_datafile_path( __file__, 'log_sink_test_valid_rules.yaml') rules_engine = self.lsre.LogSinkRulesEngine( rules_file_path=rules_local_path) rules_engine.build_rule_book()", "= self.get_engine_with_valid_rules() # Rules disallow any folder-level LogSinks. log_sinks =", "resource_data='__SINK_1__') ]) self.assertEqual(expected_violations, actual_violations) def test_org_missing_required_sinks(self): \"\"\"Tests violations are produced", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "log_sinks) expected_violations = set([ lsre.Rule.RuleViolation( resource_name='folders/56/sinks/audit_logs_to_bq', resource_type='sink', resource_id='audit_logs_to_bq', full_name='organization/234/folder/56/audit_logs_to_bq/', rule_name='Disallow", "'name': 'Mising sink', 'resource': [valid_resource], 'mode': 'whitelist', }, { 'name':", "5 difference resources and 'children' rules # for 2. self.assertEqual(", "mode', 'resource': [valid_resource], 'sink': valid_sink_spec, 'mode': 'other', }, { 'name':", "__file__, 'log_sink_test_valid_rules.yaml') rules_engine = self.lsre.LogSinkRulesEngine( rules_file_path=rules_local_path) rules_engine.build_rule_book() return rules_engine def", "# distributed under the License is distributed on an \"AS", "Log sink, but to any destination. log_sinks = [ LogSink(", "\"\"\"Tests that adding invalid rules raises exceptions.\"\"\" rule_book = self.lsre.LogSinkRuleBook(global_configs=None)", "but to any destination. log_sinks = [ LogSink( sink_id='audit_logs_to_pubsub', destination=('pubsub.googleapis.com/projects/proj-3/topics/'", "'org-audit-logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.org_234, raw_json='__SINK_1__' ), LogSink( sink_id='sink_with_wrong_filter', destination=('pubsub.googleapis.com/projects/proj-3/topics/'", "test_billing_account_with_no_violations(self): \"\"\"Tests that no violations are produced for a correct", "# Unless required by applicable law or agreed to in", "BillingAccount from google.cloud.forseti.common.gcp_type.folder import Folder from google.cloud.forseti.common.gcp_type.log_sink import LogSink from", "{ 'destination': 'bigquery.*', 'include_children': '*' }, 'mode': 'whitelist' }, {", "self.get_engine_with_valid_rules() log_sinks = [ LogSink( sink_id='billing_logs', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/billing_logs'), sink_filter='', include_children=False,", "project_number=223344, display_name='My project 2', parent=self.folder_56, full_name='organization/234/folder/56/project/proj-2/', data='fake_project_data_4562') self.proj_3 = Project(", "parent=self.org_234, full_name='organization/234/project/proj-3/', data='fake_project_data_1233') def get_engine_with_valid_rules(self): \"\"\"Create a rule engine build", "an Audit Log sink, but to any destination. log_sinks =", "resource_id='audit_logs_to_bq', full_name='organization/234/folder/56/audit_logs_to_bq/', rule_name='Disallow folder sinks.', rule_index=2, violation_type='LOG_SINK_VIOLATION', sink_destination=('bigquery.googleapis.com/projects/' 'my-audit-logs/datasets/folder_logs'), sink_filter='logName:\"logs/cloudaudit.googleapis.com\"',", "= rules_engine.find_violations( self.proj_1, log_sinks) self.assertEqual(set(), actual_violations) def test_folder_with_no_violations(self): \"\"\"Tests that", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "test_build_rule_book_invalid_applies_to_fails(self): \"\"\"Tests that a rule with invalid applies_to type cannot", "rules_engine.find_violations( self.org_234, log_sinks) self.assertEqual(set(), actual_violations) def test_project_missing_required_sinks(self): \"\"\"Tests violations are", "'name': 'Bad include_children', 'resource': [valid_resource], 'sink': { 'destination': 'bigquery.*', 'filter':", "def test_build_rule_book_invalid_applies_to_fails(self): \"\"\"Tests that a rule with invalid applies_to type", "'include_children': '*' } rule_book.add_rule( { 'name': 'Valid rule', 'resource': [valid_resource],", "'resource': [valid_resource], 'sink': { 'destination': 'bigquery.*', 'include_children': '*' }, 'mode':", "full_name='organization/234/folder/56/project/proj-2/', data='fake_project_data_4562') self.proj_3 = Project( 'proj-3', project_number=33445566, display_name='My project 3',", "You may obtain a copy of the License at #", "self.proj_3 = Project( 'proj-3', project_number=33445566, display_name='My project 3', parent=self.org_234, full_name='organization/234/project/proj-3/',", "applies_to type cannot be created.\"\"\" rules_local_path = get_datafile_path( __file__, 'log_sink_test_invalid_rules.yaml')", "sinks.\"\"\" rules_engine = self.get_engine_with_valid_rules() # Rules disallow any folder-level LogSinks.", "project 1', parent=self.org_234, full_name='organization/234/project/proj-1/', data='fake_project_data_2341') self.proj_2 = Project( 'proj-2', project_number=223344,", "actual_violations = rules_engine.find_violations( self.folder_56, log_sinks) expected_violations = set([ lsre.Rule.RuleViolation( resource_name='folders/56/sinks/audit_logs_to_bq',", "from google.cloud.forseti.common.gcp_type.project import Project from google.cloud.forseti.scanner.audit import log_sink_rules_engine as lsre", "LogSinkRulesEngine.\"\"\" import unittest import mock from tests.unittest_utils import ForsetiTestCase from", "import InvalidRulesSchemaError class LogSinkRulesEngineTest(ForsetiTestCase): \"\"\"Tests for the LogSinkRulesEngine.\"\"\" def setUp(self):", "are produced for an org missing required sinks.\"\"\" rules_engine =", "LogSink( sink_id='non_audit_logs_to_bq', destination=('bigquery.googleapis.com/projects/my-audit-logs/' 'datasets/proj_2_logs'), sink_filter='logName:\"logs/non-cloudaudit.googleapis.com\"', include_children=False, writer_identity='serviceAccount:<EMAIL>', parent=self.proj_2, raw_json='__SINK_1__' ),", "{ 'name': 'Mising Resource', 'mode': 'whitelist', 'sink': valid_sink_spec, }, {", "parent=self.org_234, raw_json='__SINK_1__' ), LogSink( sink_id='sink_with_wrong_filter', destination=('pubsub.googleapis.com/projects/proj-3/topics/' 'org-more-logs'), sink_filter='logName:\"logs/otherapi.googleapis.com\"', include_children=True, writer_identity='serviceAccount:<EMAIL>',", "class LogSinkRulesEngineTest(ForsetiTestCase): \"\"\"Tests for the LogSinkRulesEngine.\"\"\" def setUp(self): \"\"\"Set up", "]) self.assertEqual(expected_violations, actual_violations) def test_add_invalid_rules(self): \"\"\"Tests that adding invalid rules", "sinks.\"\"\" rules_engine = self.get_engine_with_valid_rules() # Org needs an Audit Log", "# | # +-----------------------> proj-1 # | # | #", "the Apache License, Version 2.0 (the \"License\"); # you may", "= mock.MagicMock() # Set up resources in the following hierarchy:", "rules_local_path = get_datafile_path( __file__, 'log_sink_test_invalid_rules.yaml') rules_engine = self.lsre.LogSinkRulesEngine( rules_file_path=rules_local_path) with", "lsre from google.cloud.forseti.scanner.audit.errors import InvalidRulesSchemaError class LogSinkRulesEngineTest(ForsetiTestCase): \"\"\"Tests for the", "sink_filter='logName:\"logs/cloudaudit.googleapis.com\"', include_children=True, writer_identity='serviceAccount:<EMAIL>', parent=self.org_234, raw_json='__SINK_1__' ) ] actual_violations = rules_engine.find_violations(", "for a correct organization.\"\"\" rules_engine = self.get_engine_with_valid_rules() # Org needs", "= [ 'billingAccounts/ABCD-1234', 'folders/56', 'organizations/234', 'projects/proj-1', 'projects/proj-2', 'projects/proj-3'] self.assertEqual(expected_rule_resources, sorted(self_rule_resources))", "), LogSink( sink_id='compute_logs_saver', destination=('bigquery.googleapis.com/projects/proj_2/' 'datasets/compute_logs'), sink_filter='resource.type=\"gce_instance\"', include_children=False, writer_identity=('serviceAccount:p12345-67890@' 'gcp-sa-logging.iam.gserviceaccount.com'), parent=self.proj_2,", "parent=self.proj_1, raw_json='_SINK_2_' ) ] actual_violations = rules_engine.find_violations( self.proj_1, log_sinks) self.assertEqual(set(),", "234', full_name='organization/234/', data='fake_org_data_234') self.billing_acct_abcd = BillingAccount( 'ABCD-1234', display_name='Billing Account ABCD',", "'folder', 'applies_to': 'self_and_children', 'resource_ids': ['56'] }], 'sink': valid_sink_spec, 'mode': 'whitelist'", "for the LogSinkRulesEngine.\"\"\" def setUp(self): \"\"\"Set up GCP resources for" ]
[ "cannot be performed\".format(code),None) except Exception as e: log.exception(f\"Db connection exception", "result: if value[\"active\"] == False: return post_error(\"Invalid Organization\", \"Organization is", "for active org record result = collections.find({\"code\": org_code}, {\"_id\": 0,", "if result.count()!=0: log.info(\"Deactivation request for org failed, {} active users", "return post_error(\"Invalid Organization\", \"Organization is currently inactive\", None) except Exception", "registered organization with the given Org Id\", None) for value", "Missing\", \"active not found\", None) code = str(org[\"code\"]).upper() active =", "import logging log = logging.getLogger('file') class OrgUtils: def __init__(self): pass", "the corresponding org is inactive. \"\"\" if \"code\" not in", "import USR_ORG_MONGO_COLLECTION, USR_MONGO_COLLECTION import db from models.response import post_error import", "registered and active on Anuvaad system. \"\"\" try: #connecting to", "\"\"\"UUID generation for org registeration\"\"\" return(uuid.uuid4().hex) @staticmethod def validate_org(org_code): \"\"\"Validating", "and active on Anuvaad system. \"\"\" try: #connecting to mongo", "org result = collections.find({\"orgID\": code,\"is_active\":True}) if result.count()!=0: log.info(\"Deactivation request for", "\"\"\" if \"code\" not in org or not org[\"code\"]: return", "if result.count() == 0: return post_error(\"Invalid Organization\", \"No such registered", "in {} hence this action cannot be performed\".format(code),None) except Exception", "connection exception\", \"An error occurred while connecting to the database:{}\".format(str(e)),", "config import USR_ORG_MONGO_COLLECTION, USR_MONGO_COLLECTION import db from models.response import post_error", "if \"code\" not in org or not org[\"code\"]: return post_error(\"Data", "found\", None) code = str(org[\"code\"]).upper() active = org[\"active\"] if not", "users in the corresponding org is inactive. \"\"\" if \"code\"", "is inactive. \"\"\" if \"code\" not in org or not", "0: return post_error(\"Invalid Organization\", \"No such registered organization with the", "def validate_org_upsert(i,org): \"\"\"Org validation on upsert deactivation of org allowed", "def validate_org(org_code): \"\"\"Validating Org Org should be registered and active", "be registered and active on Anuvaad system. \"\"\" try: #connecting", "return post_error(\"Data Missing\", \"active not found\", None) code = str(org[\"code\"]).upper()", "allowed only once all the users in the corresponding org", "org or not org[\"code\"]: return post_error(\"Data Missing\", \"code not found\",", "validate_org(org_code): \"\"\"Validating Org Org should be registered and active on", "= collections.find({\"orgID\": code,\"is_active\":True}) if result.count()!=0: log.info(\"Deactivation request for org failed,", "\"Organization is currently inactive\", None) except Exception as e: log.exception(f\"Db", "\"\"\"Org validation on upsert deactivation of org allowed only once", "all the users in the corresponding org is inactive. \"\"\"", "import post_error import logging log = logging.getLogger('file') class OrgUtils: def", "uuid from config import USR_ORG_MONGO_COLLECTION, USR_MONGO_COLLECTION import db from models.response", "USR_MONGO_COLLECTION import db from models.response import post_error import logging log", "exception\", \"An error occurred while connecting to the database:{}\".format(str(e)), None)", "isinstance(active,bool): return post_error(\"Invalid format\", \"active should be bool\", None), 400", "mongo instance/collection collections = db.get_db()[USR_MONGO_COLLECTION] #searching for active users in", "record result = collections.find({\"code\": org_code}, {\"_id\": 0, \"active\": 1}) if", "== False: return post_error(\"Invalid Organization\", \"Organization is currently inactive\", None)", "only once all the users in the corresponding org is", "Missing\", \"code not found\", None) if \"active\" not in org:", "= db.get_db()[USR_ORG_MONGO_COLLECTION] #searching for active org record result = collections.find({\"code\":", "active == False: try: #connecting to mongo instance/collection collections =", "Organization\", \"Organization is currently inactive\", None) except Exception as e:", "log.info(\"Deactivation request for org failed, {} active users with the", "result.count()!=0: log.info(\"Deactivation request for org failed, {} active users with", "connection exception : {e}\") return post_error(\"Database connection exception\", \"An error", "\"active\": 1}) if result.count() == 0: return post_error(\"Invalid Organization\", \"No", "post_error(\"Invalid Organization\", \"No such registered organization with the given Org", "as e: log.exception(f\"Db connection exception : {e}\") return post_error(\"Database connection", "result = collections.find({\"code\": org_code}, {\"_id\": 0, \"active\": 1}) if result.count()", "users with the orgID\".format(str(result.count()))) return post_error(\"Deactivation Failed\",\"There exist active users", "this action cannot be performed\".format(code),None) except Exception as e: log.exception(f\"Db", "validation on upsert deactivation of org allowed only once all", "post_error(\"Invalid Organization\", \"Organization is currently inactive\", None) except Exception as", "with the given Org Id\", None) for value in result:", "active users in {} hence this action cannot be performed\".format(code),None)", "None) for value in result: if value[\"active\"] == False: return", "collections = db.get_db()[USR_MONGO_COLLECTION] #searching for active users in the org", "active = org[\"active\"] if not isinstance(active,bool): return post_error(\"Invalid format\", \"active", "users in the org result = collections.find({\"orgID\": code,\"is_active\":True}) if result.count()!=0:", "not found\", None) code = str(org[\"code\"]).upper() active = org[\"active\"] if", "\"No such registered organization with the given Org Id\", None)", "post_error(\"Invalid format\", \"active should be bool\", None), 400 if active", "None), 400 if active == False: try: #connecting to mongo", "active users with the orgID\".format(str(result.count()))) return post_error(\"Deactivation Failed\",\"There exist active", "of org allowed only once all the users in the", "bool\", None), 400 if active == False: try: #connecting to", "def __init__(self): pass #orgId generation @staticmethod def generate_org_id(): \"\"\"UUID generation", "hence this action cannot be performed\".format(code),None) except Exception as e:", "not isinstance(active,bool): return post_error(\"Invalid format\", \"active should be bool\", None),", "try: #connecting to mongo instance/collection collections = db.get_db()[USR_ORG_MONGO_COLLECTION] #searching for", "found\", None) if \"active\" not in org: return post_error(\"Data Missing\",", "org is inactive. \"\"\" if \"code\" not in org or", "{} active users with the orgID\".format(str(result.count()))) return post_error(\"Deactivation Failed\",\"There exist", "be performed\".format(code),None) except Exception as e: log.exception(f\"Db connection exception :", "@staticmethod def validate_org(org_code): \"\"\"Validating Org Org should be registered and", "while connecting to the database:{}\".format(str(e)), None) @staticmethod def validate_org_upsert(i,org): \"\"\"Org", "return(uuid.uuid4().hex) @staticmethod def validate_org(org_code): \"\"\"Validating Org Org should be registered", "post_error import logging log = logging.getLogger('file') class OrgUtils: def __init__(self):", "{e}\") return post_error(\"Database connection exception\", \"An error occurred while connecting", "format\", \"active should be bool\", None), 400 if active ==", "org[\"code\"]: return post_error(\"Data Missing\", \"code not found\", None) if \"active\"", "is currently inactive\", None) except Exception as e: log.exception(f\"Db connection", "result.count() == 0: return post_error(\"Invalid Organization\", \"No such registered organization", "deactivation of org allowed only once all the users in", "#searching for active org record result = collections.find({\"code\": org_code}, {\"_id\":", "import uuid from config import USR_ORG_MONGO_COLLECTION, USR_MONGO_COLLECTION import db from", "collections.find({\"code\": org_code}, {\"_id\": 0, \"active\": 1}) if result.count() == 0:", "db.get_db()[USR_MONGO_COLLECTION] #searching for active users in the org result =", "if not isinstance(active,bool): return post_error(\"Invalid format\", \"active should be bool\",", "org failed, {} active users with the orgID\".format(str(result.count()))) return post_error(\"Deactivation", "not found\", None) if \"active\" not in org: return post_error(\"Data", "registeration\"\"\" return(uuid.uuid4().hex) @staticmethod def validate_org(org_code): \"\"\"Validating Org Org should be", "{} hence this action cannot be performed\".format(code),None) except Exception as", "from models.response import post_error import logging log = logging.getLogger('file') class", "such registered organization with the given Org Id\", None) for", "post_error(\"Data Missing\", \"code not found\", None) if \"active\" not in", "except Exception as e: log.exception(f\"Db connection exception : {e}\") return", "result = collections.find({\"orgID\": code,\"is_active\":True}) if result.count()!=0: log.info(\"Deactivation request for org", "db from models.response import post_error import logging log = logging.getLogger('file')", "database:{}\".format(str(e)), None) @staticmethod def validate_org_upsert(i,org): \"\"\"Org validation on upsert deactivation", "\"code not found\", None) if \"active\" not in org: return", "should be registered and active on Anuvaad system. \"\"\" try:", "= org[\"active\"] if not isinstance(active,bool): return post_error(\"Invalid format\", \"active should", "= logging.getLogger('file') class OrgUtils: def __init__(self): pass #orgId generation @staticmethod", "Org should be registered and active on Anuvaad system. \"\"\"", "return post_error(\"Invalid Organization\", \"No such registered organization with the given", "inactive. \"\"\" if \"code\" not in org or not org[\"code\"]:", "generation for org registeration\"\"\" return(uuid.uuid4().hex) @staticmethod def validate_org(org_code): \"\"\"Validating Org", "\"\"\"Validating Org Org should be registered and active on Anuvaad", "system. \"\"\" try: #connecting to mongo instance/collection collections = db.get_db()[USR_ORG_MONGO_COLLECTION]", "__init__(self): pass #orgId generation @staticmethod def generate_org_id(): \"\"\"UUID generation for", "None) if \"active\" not in org: return post_error(\"Data Missing\", \"active", "1}) if result.count() == 0: return post_error(\"Invalid Organization\", \"No such", "org[\"active\"] if not isinstance(active,bool): return post_error(\"Invalid format\", \"active should be", "#orgId generation @staticmethod def generate_org_id(): \"\"\"UUID generation for org registeration\"\"\"", "\"active\" not in org: return post_error(\"Data Missing\", \"active not found\",", "False: return post_error(\"Invalid Organization\", \"Organization is currently inactive\", None) except", "pass #orgId generation @staticmethod def generate_org_id(): \"\"\"UUID generation for org", "currently inactive\", None) except Exception as e: log.exception(f\"Db connection exception", "exception : {e}\") return post_error(\"Database connection exception\", \"An error occurred", "if active == False: try: #connecting to mongo instance/collection collections", "OrgUtils: def __init__(self): pass #orgId generation @staticmethod def generate_org_id(): \"\"\"UUID", "for org registeration\"\"\" return(uuid.uuid4().hex) @staticmethod def validate_org(org_code): \"\"\"Validating Org Org", "action cannot be performed\".format(code),None) except Exception as e: log.exception(f\"Db connection", "Org Org should be registered and active on Anuvaad system.", "\"\"\" try: #connecting to mongo instance/collection collections = db.get_db()[USR_ORG_MONGO_COLLECTION] #searching", "\"An error occurred while connecting to the database:{}\".format(str(e)), None) @staticmethod", "given Org Id\", None) for value in result: if value[\"active\"]", "return post_error(\"Data Missing\", \"code not found\", None) if \"active\" not", "logging.getLogger('file') class OrgUtils: def __init__(self): pass #orgId generation @staticmethod def", "the orgID\".format(str(result.count()))) return post_error(\"Deactivation Failed\",\"There exist active users in {}", "corresponding org is inactive. \"\"\" if \"code\" not in org", "not in org: return post_error(\"Data Missing\", \"active not found\", None)", "org registeration\"\"\" return(uuid.uuid4().hex) @staticmethod def validate_org(org_code): \"\"\"Validating Org Org should", "to mongo instance/collection collections = db.get_db()[USR_ORG_MONGO_COLLECTION] #searching for active org", "for active users in the org result = collections.find({\"orgID\": code,\"is_active\":True})", "collections = db.get_db()[USR_ORG_MONGO_COLLECTION] #searching for active org record result =", "False: try: #connecting to mongo instance/collection collections = db.get_db()[USR_MONGO_COLLECTION] #searching", "None) except Exception as e: log.exception(f\"Db connection exception : {e}\")", "in result: if value[\"active\"] == False: return post_error(\"Invalid Organization\", \"Organization", "org_code}, {\"_id\": 0, \"active\": 1}) if result.count() == 0: return", "validate_org_upsert(i,org): \"\"\"Org validation on upsert deactivation of org allowed only", "e: log.exception(f\"Db connection exception : {e}\") return post_error(\"Database connection exception\",", "@staticmethod def validate_org_upsert(i,org): \"\"\"Org validation on upsert deactivation of org", "USR_ORG_MONGO_COLLECTION, USR_MONGO_COLLECTION import db from models.response import post_error import logging", "\"code\" not in org or not org[\"code\"]: return post_error(\"Data Missing\",", "Organization\", \"No such registered organization with the given Org Id\",", "#connecting to mongo instance/collection collections = db.get_db()[USR_MONGO_COLLECTION] #searching for active", "post_error(\"Database connection exception\", \"An error occurred while connecting to the", "the users in the corresponding org is inactive. \"\"\" if", "== False: try: #connecting to mongo instance/collection collections = db.get_db()[USR_MONGO_COLLECTION]", "on upsert deactivation of org allowed only once all the", "active users in the org result = collections.find({\"orgID\": code,\"is_active\":True}) if", "logging log = logging.getLogger('file') class OrgUtils: def __init__(self): pass #orgId", "return post_error(\"Database connection exception\", \"An error occurred while connecting to", "occurred while connecting to the database:{}\".format(str(e)), None) @staticmethod def validate_org_upsert(i,org):", "to the database:{}\".format(str(e)), None) @staticmethod def validate_org_upsert(i,org): \"\"\"Org validation on", "the given Org Id\", None) for value in result: if", "Org Id\", None) for value in result: if value[\"active\"] ==", "post_error(\"Deactivation Failed\",\"There exist active users in {} hence this action", "#searching for active users in the org result = collections.find({\"orgID\":", "error occurred while connecting to the database:{}\".format(str(e)), None) @staticmethod def", "users in {} hence this action cannot be performed\".format(code),None) except", "0, \"active\": 1}) if result.count() == 0: return post_error(\"Invalid Organization\",", "the org result = collections.find({\"orgID\": code,\"is_active\":True}) if result.count()!=0: log.info(\"Deactivation request", "inactive\", None) except Exception as e: log.exception(f\"Db connection exception :", "post_error(\"Data Missing\", \"active not found\", None) code = str(org[\"code\"]).upper() active", "None) code = str(org[\"code\"]).upper() active = org[\"active\"] if not isinstance(active,bool):", "mongo instance/collection collections = db.get_db()[USR_ORG_MONGO_COLLECTION] #searching for active org record", "be bool\", None), 400 if active == False: try: #connecting", "log.exception(f\"Db connection exception : {e}\") return post_error(\"Database connection exception\", \"An", "= str(org[\"code\"]).upper() active = org[\"active\"] if not isinstance(active,bool): return post_error(\"Invalid", "on Anuvaad system. \"\"\" try: #connecting to mongo instance/collection collections", "not in org or not org[\"code\"]: return post_error(\"Data Missing\", \"code", "\"active not found\", None) code = str(org[\"code\"]).upper() active = org[\"active\"]", "generate_org_id(): \"\"\"UUID generation for org registeration\"\"\" return(uuid.uuid4().hex) @staticmethod def validate_org(org_code):", "active org record result = collections.find({\"code\": org_code}, {\"_id\": 0, \"active\":", "in org or not org[\"code\"]: return post_error(\"Data Missing\", \"code not", "organization with the given Org Id\", None) for value in", "org allowed only once all the users in the corresponding", "the database:{}\".format(str(e)), None) @staticmethod def validate_org_upsert(i,org): \"\"\"Org validation on upsert", "str(org[\"code\"]).upper() active = org[\"active\"] if not isinstance(active,bool): return post_error(\"Invalid format\",", "\"active should be bool\", None), 400 if active == False:", "if value[\"active\"] == False: return post_error(\"Invalid Organization\", \"Organization is currently", "models.response import post_error import logging log = logging.getLogger('file') class OrgUtils:", "{\"_id\": 0, \"active\": 1}) if result.count() == 0: return post_error(\"Invalid", "Id\", None) for value in result: if value[\"active\"] == False:", "400 if active == False: try: #connecting to mongo instance/collection", "if \"active\" not in org: return post_error(\"Data Missing\", \"active not", "instance/collection collections = db.get_db()[USR_MONGO_COLLECTION] #searching for active users in the", "once all the users in the corresponding org is inactive.", "orgID\".format(str(result.count()))) return post_error(\"Deactivation Failed\",\"There exist active users in {} hence", "Anuvaad system. \"\"\" try: #connecting to mongo instance/collection collections =", "active on Anuvaad system. \"\"\" try: #connecting to mongo instance/collection", "request for org failed, {} active users with the orgID\".format(str(result.count())))", "value[\"active\"] == False: return post_error(\"Invalid Organization\", \"Organization is currently inactive\",", "return post_error(\"Invalid format\", \"active should be bool\", None), 400 if", "should be bool\", None), 400 if active == False: try:", "for org failed, {} active users with the orgID\".format(str(result.count()))) return", "= collections.find({\"code\": org_code}, {\"_id\": 0, \"active\": 1}) if result.count() ==", "or not org[\"code\"]: return post_error(\"Data Missing\", \"code not found\", None)", "db.get_db()[USR_ORG_MONGO_COLLECTION] #searching for active org record result = collections.find({\"code\": org_code},", "class OrgUtils: def __init__(self): pass #orgId generation @staticmethod def generate_org_id():", "Exception as e: log.exception(f\"Db connection exception : {e}\") return post_error(\"Database", "connecting to the database:{}\".format(str(e)), None) @staticmethod def validate_org_upsert(i,org): \"\"\"Org validation", "code = str(org[\"code\"]).upper() active = org[\"active\"] if not isinstance(active,bool): return", "failed, {} active users with the orgID\".format(str(result.count()))) return post_error(\"Deactivation Failed\",\"There", "Failed\",\"There exist active users in {} hence this action cannot", "code,\"is_active\":True}) if result.count()!=0: log.info(\"Deactivation request for org failed, {} active", "exist active users in {} hence this action cannot be", "@staticmethod def generate_org_id(): \"\"\"UUID generation for org registeration\"\"\" return(uuid.uuid4().hex) @staticmethod", "performed\".format(code),None) except Exception as e: log.exception(f\"Db connection exception : {e}\")", "import db from models.response import post_error import logging log =", "to mongo instance/collection collections = db.get_db()[USR_MONGO_COLLECTION] #searching for active users", "not org[\"code\"]: return post_error(\"Data Missing\", \"code not found\", None) if", "from config import USR_ORG_MONGO_COLLECTION, USR_MONGO_COLLECTION import db from models.response import", "instance/collection collections = db.get_db()[USR_ORG_MONGO_COLLECTION] #searching for active org record result", "try: #connecting to mongo instance/collection collections = db.get_db()[USR_MONGO_COLLECTION] #searching for", "in the org result = collections.find({\"orgID\": code,\"is_active\":True}) if result.count()!=0: log.info(\"Deactivation", "collections.find({\"orgID\": code,\"is_active\":True}) if result.count()!=0: log.info(\"Deactivation request for org failed, {}", "with the orgID\".format(str(result.count()))) return post_error(\"Deactivation Failed\",\"There exist active users in", "None) @staticmethod def validate_org_upsert(i,org): \"\"\"Org validation on upsert deactivation of", "for value in result: if value[\"active\"] == False: return post_error(\"Invalid", "org: return post_error(\"Data Missing\", \"active not found\", None) code =", "in org: return post_error(\"Data Missing\", \"active not found\", None) code", "log = logging.getLogger('file') class OrgUtils: def __init__(self): pass #orgId generation", "def generate_org_id(): \"\"\"UUID generation for org registeration\"\"\" return(uuid.uuid4().hex) @staticmethod def", "org record result = collections.find({\"code\": org_code}, {\"_id\": 0, \"active\": 1})", "== 0: return post_error(\"Invalid Organization\", \"No such registered organization with", "in the corresponding org is inactive. \"\"\" if \"code\" not", "= db.get_db()[USR_MONGO_COLLECTION] #searching for active users in the org result", "value in result: if value[\"active\"] == False: return post_error(\"Invalid Organization\",", "return post_error(\"Deactivation Failed\",\"There exist active users in {} hence this", "upsert deactivation of org allowed only once all the users", "generation @staticmethod def generate_org_id(): \"\"\"UUID generation for org registeration\"\"\" return(uuid.uuid4().hex)", ": {e}\") return post_error(\"Database connection exception\", \"An error occurred while", "#connecting to mongo instance/collection collections = db.get_db()[USR_ORG_MONGO_COLLECTION] #searching for active" ]
[ "= ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=' + extdir, '-DPYTHON_INCLUDE_PATH=' + include_path, ] cfg =", "build_with_cuda = os.environ['DIFFVG_CUDA'] == '1' setup(name='diffvg', version='0.0.1', install_requires=[\"svgpathtools\"], description='Differentiable Vector", "+ \":\" + os.environ['PATH'] env_build[\"PATH\"] = \"/usr/local/cuda-10.1/bin\" + \":\" +", "platform.system() == \"Windows\": cmake_args += ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_{}={}'.format(cfg.upper(), extdir), '-DCMAKE_RUNTIME_OUTPUT_DIRECTORY_{}={}'.format(cfg.upper(), extdir)] if", "import install from distutils.sysconfig import get_config_var from distutils.version import LooseVersion", "get_paths() include_path = info['include'] cmake_args = ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=' + extdir, '-DPYTHON_INCLUDE_PATH='", "print('Error: PyTorch or Tensorflow must be installed. For Windows platform", "re import sys import platform import subprocess import importlib from", "None: packages.append('pydiffvg') import torch if torch.cuda.is_available(): build_with_cuda = True if", "import sys import platform import subprocess import importlib from sysconfig", "= True if len(packages) == 0: print('Error: PyTorch or Tensorflow", "+= ['-DDIFFVG_CUDA=0'] env = os.environ.copy() env['CXXFLAGS'] = '{} -DVERSION_INFO=\\\\\"{}\\\\\"'.format(env.get('CXXFLAGS', ''),", "build_ext from setuptools.command.install import install from distutils.sysconfig import get_config_var from", "extdir)] if sys.maxsize > 2 ** 32: cmake_args += ['-A',", "run(self): try: out = subprocess.check_output(['cmake', '--version']) except OSError: raise RuntimeError(\"CMake", "= info['include'] cmake_args = ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=' + extdir, '-DPYTHON_INCLUDE_PATH=' + include_path,", "\" + \", \".join(e.name for e in self.extensions)) super().run() def", "= \"/usr/bin/gcc-5\" env_build[\"CXX\"] = \"/usr/bin/g++-5\" env_build[\"CC\"] = \"/usr/bin/gcc-5\" env[\"PATH\"] =", "env = os.environ.copy() env['CXXFLAGS'] = '{} -DVERSION_INFO=\\\\\"{}\\\\\"'.format(env.get('CXXFLAGS', ''), self.distribution.get_version()) env_build", "build_args += ['--', '/m'] else: cmake_args += ['-DCMAKE_BUILD_TYPE=' + cfg]", "Build(build_ext): def run(self): try: out = subprocess.check_output(['cmake', '--version']) except OSError:", "else: cmake_args += ['-DDIFFVG_CUDA=0'] env = os.environ.copy() env['CXXFLAGS'] = '{}", "importlib from setuptools import setup, Extension from setuptools.command.build_ext import build_ext", "to build the following extensions: \" + \", \".join(e.name for", "supported.') exit() # Override build_with_cuda with environment variable if 'DIFFVG_CUDA'", "importlib.util.find_spec(\"tensorflow\") packages = [] build_with_cuda = False if torch_spec is", "and sys.platform != 'win32': packages.append('pydiffvg_tensorflow') if not build_with_cuda: import tensorflow", "= os.environ['DIFFVG_CUDA'] == '1' setup(name='diffvg', version='0.0.1', install_requires=[\"svgpathtools\"], description='Differentiable Vector Graphics',", "** 32: cmake_args += ['-A', 'x64'] build_args += ['--', '/m']", "+ os.environ['PATH'] if not os.path.exists(self.build_temp): os.makedirs(self.build_temp) subprocess.check_call(['cmake', ext.sourcedir] + cmake_args,", "or Tensorflow must be installed. For Windows platform only PyTorch", "extdir = os.path.abspath(os.path.dirname(self.get_ext_fullpath(ext.name))) info = get_paths() include_path = info['include'] cmake_args", "packages.append('pydiffvg_tensorflow') if not build_with_cuda: import tensorflow as tf if tf.test.is_gpu_available(cuda_only=True,", "= 'Debug' if self.debug else 'Release' build_args = ['--config', cfg]", "For Windows platform only PyTorch is supported.') exit() # Override", "if not os.path.exists(self.build_temp): os.makedirs(self.build_temp) subprocess.check_call(['cmake', ext.sourcedir] + cmake_args, cwd=self.build_temp, env=env)", "build_extension(self, ext): if isinstance(ext, CMakeExtension): extdir = os.path.abspath(os.path.dirname(self.get_ext_fullpath(ext.name))) info =", "def run(self): try: out = subprocess.check_output(['cmake', '--version']) except OSError: raise", "exit() # Override build_with_cuda with environment variable if 'DIFFVG_CUDA' in", "build the following extensions: \" + \", \".join(e.name for e", "\"Windows\": cmake_args += ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_{}={}'.format(cfg.upper(), extdir), '-DCMAKE_RUNTIME_OUTPUT_DIRECTORY_{}={}'.format(cfg.upper(), extdir)] if sys.maxsize >", "= True if tf_spec is not None and sys.platform !=", "env[\"PATH\"] = \"/usr/local/cuda-10.1/bin\" + \":\" + os.environ['PATH'] env_build[\"PATH\"] = \"/usr/local/cuda-10.1/bin\"", "['--', '/m'] else: cmake_args += ['-DCMAKE_BUILD_TYPE=' + cfg] build_args +=", "+ \":\" + os.environ['PATH'] if not os.path.exists(self.build_temp): os.makedirs(self.build_temp) subprocess.check_call(['cmake', ext.sourcedir]", "env_build[\"CXX\"] = \"/usr/bin/g++-5\" env_build[\"CC\"] = \"/usr/bin/gcc-5\" env[\"PATH\"] = \"/usr/local/cuda-10.1/bin\" +", "environment variable if 'DIFFVG_CUDA' in os.environ: build_with_cuda = os.environ['DIFFVG_CUDA'] ==", "+ os.environ['PATH'] env_build[\"PATH\"] = \"/usr/local/cuda-10.1/bin\" + \":\" + os.environ['PATH'] if", "subprocess import importlib from sysconfig import get_paths import importlib from", "Tensorflow must be installed. For Windows platform only PyTorch is", "self.debug else 'Release' build_args = ['--config', cfg] if platform.system() ==", "os.environ.copy() env['CXXFLAGS'] = '{} -DVERSION_INFO=\\\\\"{}\\\\\"'.format(env.get('CXXFLAGS', ''), self.distribution.get_version()) env_build = env", "if len(packages) == 0: print('Error: PyTorch or Tensorflow must be", "Extension from setuptools.command.build_ext import build_ext from setuptools.command.install import install from", "self.build_with_cuda = build_with_cuda class Build(build_ext): def run(self): try: out =", "'--version']) except OSError: raise RuntimeError(\"CMake must be installed to build", "= build_with_cuda class Build(build_ext): def run(self): try: out = subprocess.check_output(['cmake',", "not None and sys.platform != 'win32': packages.append('pydiffvg_tensorflow') if not build_with_cuda:", "'DIFFVG_CUDA' in os.environ: build_with_cuda = os.environ['DIFFVG_CUDA'] == '1' setup(name='diffvg', version='0.0.1',", "installed to build the following extensions: \" + \", \".join(e.name", "env=env_build) else: super().build_extension(ext) torch_spec = importlib.util.find_spec(\"torch\") tf_spec = importlib.util.find_spec(\"tensorflow\") packages", "else 'Release' build_args = ['--config', cfg] if platform.system() == \"Windows\":", "import LooseVersion class CMakeExtension(Extension): def __init__(self, name, sourcedir, build_with_cuda): Extension.__init__(self,", "= [] build_with_cuda = False if torch_spec is not None:", "subprocess.check_call(['cmake', ext.sourcedir] + cmake_args, cwd=self.build_temp, env=env) subprocess.check_call(['cmake', '--build', '.'] +", "'Debug' if self.debug else 'Release' build_args = ['--config', cfg] if", "CMakeExtension): extdir = os.path.abspath(os.path.dirname(self.get_ext_fullpath(ext.name))) info = get_paths() include_path = info['include']", "cmake_args += ['-DCMAKE_BUILD_TYPE=' + cfg] build_args += ['--', '-j8'] if", "= \"/usr/bin/g++-5\" env[\"CC\"] = \"/usr/bin/gcc-5\" env_build[\"CXX\"] = \"/usr/bin/g++-5\" env_build[\"CC\"] =", "= False if torch_spec is not None: packages.append('pydiffvg') import torch", "'.'] + build_args, cwd=self.build_temp, env=env_build) else: super().build_extension(ext) torch_spec = importlib.util.find_spec(\"torch\")", "sys.maxsize > 2 ** 32: cmake_args += ['-A', 'x64'] build_args", "build_with_cuda = False if torch_spec is not None: packages.append('pydiffvg') import", "import importlib from sysconfig import get_paths import importlib from setuptools", "cwd=self.build_temp, env=env_build) else: super().build_extension(ext) torch_spec = importlib.util.find_spec(\"torch\") tf_spec = importlib.util.find_spec(\"tensorflow\")", "env[\"CC\"] = \"/usr/bin/gcc-5\" env_build[\"CXX\"] = \"/usr/bin/g++-5\" env_build[\"CC\"] = \"/usr/bin/gcc-5\" env[\"PATH\"]", "True if tf_spec is not None and sys.platform != 'win32':", "+= ['--', '-j8'] if ext.build_with_cuda: cmake_args += ['-DDIFFVG_CUDA=1'] else: cmake_args", "if ext.build_with_cuda: cmake_args += ['-DDIFFVG_CUDA=1'] else: cmake_args += ['-DDIFFVG_CUDA=0'] env", "import get_paths import importlib from setuptools import setup, Extension from", "= importlib.util.find_spec(\"torch\") tf_spec = importlib.util.find_spec(\"tensorflow\") packages = [] build_with_cuda =", "\"/usr/local/cuda-10.1/bin\" + \":\" + os.environ['PATH'] if not os.path.exists(self.build_temp): os.makedirs(self.build_temp) subprocess.check_call(['cmake',", "not None: packages.append('pydiffvg') import torch if torch.cuda.is_available(): build_with_cuda = True", "if tf_spec is not None and sys.platform != 'win32': packages.append('pydiffvg_tensorflow')", "+= ['--', '/m'] else: cmake_args += ['-DCMAKE_BUILD_TYPE=' + cfg] build_args", "torch.cuda.is_available(): build_with_cuda = True if tf_spec is not None and", "ext): if isinstance(ext, CMakeExtension): extdir = os.path.abspath(os.path.dirname(self.get_ext_fullpath(ext.name))) info = get_paths()", "None and sys.platform != 'win32': packages.append('pydiffvg_tensorflow') if not build_with_cuda: import", "setup, Extension from setuptools.command.build_ext import build_ext from setuptools.command.install import install", "install from distutils.sysconfig import get_config_var from distutils.version import LooseVersion class", "build_with_cuda = True if tf_spec is not None and sys.platform", "import setup, Extension from setuptools.command.build_ext import build_ext from setuptools.command.install import", "cmake_args = ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=' + extdir, '-DPYTHON_INCLUDE_PATH=' + include_path, ] cfg", "build_with_cuda with environment variable if 'DIFFVG_CUDA' in os.environ: build_with_cuda =", "importlib.util.find_spec(\"torch\") tf_spec = importlib.util.find_spec(\"tensorflow\") packages = [] build_with_cuda = False", "info['include'] cmake_args = ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=' + extdir, '-DPYTHON_INCLUDE_PATH=' + include_path, ]", "tf.test.is_gpu_available(cuda_only=True, min_cuda_compute_capability=None): build_with_cuda = True if len(packages) == 0: print('Error:", "from setuptools.command.install import install from distutils.sysconfig import get_config_var from distutils.version", "build_args, cwd=self.build_temp, env=env_build) else: super().build_extension(ext) torch_spec = importlib.util.find_spec(\"torch\") tf_spec =", "from setuptools.command.build_ext import build_ext from setuptools.command.install import install from distutils.sysconfig", "= \"/usr/local/cuda-10.1/bin\" + \":\" + os.environ['PATH'] env_build[\"PATH\"] = \"/usr/local/cuda-10.1/bin\" +", "== 0: print('Error: PyTorch or Tensorflow must be installed. For", "tf_spec is not None and sys.platform != 'win32': packages.append('pydiffvg_tensorflow') if", "if platform.system() == \"Windows\": cmake_args += ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_{}={}'.format(cfg.upper(), extdir), '-DCMAKE_RUNTIME_OUTPUT_DIRECTORY_{}={}'.format(cfg.upper(), extdir)]", "''), self.distribution.get_version()) env_build = env env[\"CXX\"] = \"/usr/bin/g++-5\" env[\"CC\"] =", "> 2 ** 32: cmake_args += ['-A', 'x64'] build_args +=", "if torch.cuda.is_available(): build_with_cuda = True if tf_spec is not None", "os import re import sys import platform import subprocess import", "min_cuda_compute_capability=None): build_with_cuda = True if len(packages) == 0: print('Error: PyTorch", "ext.sourcedir] + cmake_args, cwd=self.build_temp, env=env) subprocess.check_call(['cmake', '--build', '.'] + build_args,", "not os.path.exists(self.build_temp): os.makedirs(self.build_temp) subprocess.check_call(['cmake', ext.sourcedir] + cmake_args, cwd=self.build_temp, env=env) subprocess.check_call(['cmake',", "build_with_cuda = True if len(packages) == 0: print('Error: PyTorch or", "+ build_args, cwd=self.build_temp, env=env_build) else: super().build_extension(ext) torch_spec = importlib.util.find_spec(\"torch\") tf_spec", "['--config', cfg] if platform.system() == \"Windows\": cmake_args += ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_{}={}'.format(cfg.upper(), extdir),", "tf_spec = importlib.util.find_spec(\"tensorflow\") packages = [] build_with_cuda = False if", "torch_spec is not None: packages.append('pydiffvg') import torch if torch.cuda.is_available(): build_with_cuda", "sys.platform != 'win32': packages.append('pydiffvg_tensorflow') if not build_with_cuda: import tensorflow as", "+ include_path, ] cfg = 'Debug' if self.debug else 'Release'", "be installed. For Windows platform only PyTorch is supported.') exit()", "= '{} -DVERSION_INFO=\\\\\"{}\\\\\"'.format(env.get('CXXFLAGS', ''), self.distribution.get_version()) env_build = env env[\"CXX\"] =", "from distutils.version import LooseVersion class CMakeExtension(Extension): def __init__(self, name, sourcedir,", "PyTorch or Tensorflow must be installed. For Windows platform only", "cmake_args += ['-DDIFFVG_CUDA=0'] env = os.environ.copy() env['CXXFLAGS'] = '{} -DVERSION_INFO=\\\\\"{}\\\\\"'.format(env.get('CXXFLAGS',", "out = subprocess.check_output(['cmake', '--version']) except OSError: raise RuntimeError(\"CMake must be", "import tensorflow as tf if tf.test.is_gpu_available(cuda_only=True, min_cuda_compute_capability=None): build_with_cuda = True", "import os import re import sys import platform import subprocess", "= get_paths() include_path = info['include'] cmake_args = ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=' + extdir,", "0: print('Error: PyTorch or Tensorflow must be installed. For Windows", "= os.path.abspath(sourcedir) self.build_with_cuda = build_with_cuda class Build(build_ext): def run(self): try:", "= ['--config', cfg] if platform.system() == \"Windows\": cmake_args += ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_{}={}'.format(cfg.upper(),", "include_path, ] cfg = 'Debug' if self.debug else 'Release' build_args", "if tf.test.is_gpu_available(cuda_only=True, min_cuda_compute_capability=None): build_with_cuda = True if len(packages) == 0:", "= importlib.util.find_spec(\"tensorflow\") packages = [] build_with_cuda = False if torch_spec", "extensions: \" + \", \".join(e.name for e in self.extensions)) super().run()", "Adapted from https://github.com/pybind/cmake_example/blob/master/setup.py import os import re import sys import", "ext.build_with_cuda: cmake_args += ['-DDIFFVG_CUDA=1'] else: cmake_args += ['-DDIFFVG_CUDA=0'] env =", "os.path.exists(self.build_temp): os.makedirs(self.build_temp) subprocess.check_call(['cmake', ext.sourcedir] + cmake_args, cwd=self.build_temp, env=env) subprocess.check_call(['cmake', '--build',", "following extensions: \" + \", \".join(e.name for e in self.extensions))", "env['CXXFLAGS'] = '{} -DVERSION_INFO=\\\\\"{}\\\\\"'.format(env.get('CXXFLAGS', ''), self.distribution.get_version()) env_build = env env[\"CXX\"]", "\"/usr/bin/gcc-5\" env_build[\"CXX\"] = \"/usr/bin/g++-5\" env_build[\"CC\"] = \"/usr/bin/gcc-5\" env[\"PATH\"] = \"/usr/local/cuda-10.1/bin\"", "def build_extension(self, ext): if isinstance(ext, CMakeExtension): extdir = os.path.abspath(os.path.dirname(self.get_ext_fullpath(ext.name))) info", "Extension.__init__(self, name, sources=[]) self.sourcedir = os.path.abspath(sourcedir) self.build_with_cuda = build_with_cuda class", "the following extensions: \" + \", \".join(e.name for e in", "os.path.abspath(os.path.dirname(self.get_ext_fullpath(ext.name))) info = get_paths() include_path = info['include'] cmake_args = ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY='", "= env env[\"CXX\"] = \"/usr/bin/g++-5\" env[\"CC\"] = \"/usr/bin/gcc-5\" env_build[\"CXX\"] =", "\", \".join(e.name for e in self.extensions)) super().run() def build_extension(self, ext):", "os.environ['PATH'] if not os.path.exists(self.build_temp): os.makedirs(self.build_temp) subprocess.check_call(['cmake', ext.sourcedir] + cmake_args, cwd=self.build_temp,", "not build_with_cuda: import tensorflow as tf if tf.test.is_gpu_available(cuda_only=True, min_cuda_compute_capability=None): build_with_cuda", "import subprocess import importlib from sysconfig import get_paths import importlib", "+= ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_{}={}'.format(cfg.upper(), extdir), '-DCMAKE_RUNTIME_OUTPUT_DIRECTORY_{}={}'.format(cfg.upper(), extdir)] if sys.maxsize > 2 **", "https://github.com/pybind/cmake_example/blob/master/setup.py import os import re import sys import platform import", "os.environ['PATH'] env_build[\"PATH\"] = \"/usr/local/cuda-10.1/bin\" + \":\" + os.environ['PATH'] if not", "\":\" + os.environ['PATH'] if not os.path.exists(self.build_temp): os.makedirs(self.build_temp) subprocess.check_call(['cmake', ext.sourcedir] +", "'win32': packages.append('pydiffvg_tensorflow') if not build_with_cuda: import tensorflow as tf if", "+= ['-DDIFFVG_CUDA=1'] else: cmake_args += ['-DDIFFVG_CUDA=0'] env = os.environ.copy() env['CXXFLAGS']", "['-DDIFFVG_CUDA=0'] env = os.environ.copy() env['CXXFLAGS'] = '{} -DVERSION_INFO=\\\\\"{}\\\\\"'.format(env.get('CXXFLAGS', ''), self.distribution.get_version())", "cmake_args, cwd=self.build_temp, env=env) subprocess.check_call(['cmake', '--build', '.'] + build_args, cwd=self.build_temp, env=env_build)", "Windows platform only PyTorch is supported.') exit() # Override build_with_cuda", "# Override build_with_cuda with environment variable if 'DIFFVG_CUDA' in os.environ:", "env_build[\"PATH\"] = \"/usr/local/cuda-10.1/bin\" + \":\" + os.environ['PATH'] if not os.path.exists(self.build_temp):", "description='Differentiable Vector Graphics', ext_modules=[CMakeExtension('diffvg', '', build_with_cuda)], cmdclass=dict(build_ext=Build, install=install), packages=packages, zip_safe=False)", "len(packages) == 0: print('Error: PyTorch or Tensorflow must be installed.", "sourcedir, build_with_cuda): Extension.__init__(self, name, sources=[]) self.sourcedir = os.path.abspath(sourcedir) self.build_with_cuda =", "is not None: packages.append('pydiffvg') import torch if torch.cuda.is_available(): build_with_cuda =", "['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=' + extdir, '-DPYTHON_INCLUDE_PATH=' + include_path, ] cfg = 'Debug'", "super().run() def build_extension(self, ext): if isinstance(ext, CMakeExtension): extdir = os.path.abspath(os.path.dirname(self.get_ext_fullpath(ext.name)))", "platform import subprocess import importlib from sysconfig import get_paths import", "setup(name='diffvg', version='0.0.1', install_requires=[\"svgpathtools\"], description='Differentiable Vector Graphics', ext_modules=[CMakeExtension('diffvg', '', build_with_cuda)], cmdclass=dict(build_ext=Build,", "importlib from sysconfig import get_paths import importlib from setuptools import", "import re import sys import platform import subprocess import importlib", "else: super().build_extension(ext) torch_spec = importlib.util.find_spec(\"torch\") tf_spec = importlib.util.find_spec(\"tensorflow\") packages =", "tf if tf.test.is_gpu_available(cuda_only=True, min_cuda_compute_capability=None): build_with_cuda = True if len(packages) ==", "from sysconfig import get_paths import importlib from setuptools import setup,", "in self.extensions)) super().run() def build_extension(self, ext): if isinstance(ext, CMakeExtension): extdir", "\".join(e.name for e in self.extensions)) super().run() def build_extension(self, ext): if", "cfg] build_args += ['--', '-j8'] if ext.build_with_cuda: cmake_args += ['-DDIFFVG_CUDA=1']", "+ extdir, '-DPYTHON_INCLUDE_PATH=' + include_path, ] cfg = 'Debug' if", "if isinstance(ext, CMakeExtension): extdir = os.path.abspath(os.path.dirname(self.get_ext_fullpath(ext.name))) info = get_paths() include_path", "PyTorch is supported.') exit() # Override build_with_cuda with environment variable", "!= 'win32': packages.append('pydiffvg_tensorflow') if not build_with_cuda: import tensorflow as tf", "['-DCMAKE_BUILD_TYPE=' + cfg] build_args += ['--', '-j8'] if ext.build_with_cuda: cmake_args", "as tf if tf.test.is_gpu_available(cuda_only=True, min_cuda_compute_capability=None): build_with_cuda = True if len(packages)", "build_args = ['--config', cfg] if platform.system() == \"Windows\": cmake_args +=", "'/m'] else: cmake_args += ['-DCMAKE_BUILD_TYPE=' + cfg] build_args += ['--',", "class Build(build_ext): def run(self): try: out = subprocess.check_output(['cmake', '--version']) except", "+ \", \".join(e.name for e in self.extensions)) super().run() def build_extension(self,", "env_build = env env[\"CXX\"] = \"/usr/bin/g++-5\" env[\"CC\"] = \"/usr/bin/gcc-5\" env_build[\"CXX\"]", "[] build_with_cuda = False if torch_spec is not None: packages.append('pydiffvg')", "class CMakeExtension(Extension): def __init__(self, name, sourcedir, build_with_cuda): Extension.__init__(self, name, sources=[])", "if sys.maxsize > 2 ** 32: cmake_args += ['-A', 'x64']", "sys import platform import subprocess import importlib from sysconfig import", "for e in self.extensions)) super().run() def build_extension(self, ext): if isinstance(ext,", "setuptools.command.install import install from distutils.sysconfig import get_config_var from distutils.version import", "os.environ['DIFFVG_CUDA'] == '1' setup(name='diffvg', version='0.0.1', install_requires=[\"svgpathtools\"], description='Differentiable Vector Graphics', ext_modules=[CMakeExtension('diffvg',", "= \"/usr/bin/g++-5\" env_build[\"CC\"] = \"/usr/bin/gcc-5\" env[\"PATH\"] = \"/usr/local/cuda-10.1/bin\" + \":\"", "must be installed to build the following extensions: \" +", "['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_{}={}'.format(cfg.upper(), extdir), '-DCMAKE_RUNTIME_OUTPUT_DIRECTORY_{}={}'.format(cfg.upper(), extdir)] if sys.maxsize > 2 ** 32:", "is supported.') exit() # Override build_with_cuda with environment variable if", "= os.path.abspath(os.path.dirname(self.get_ext_fullpath(ext.name))) info = get_paths() include_path = info['include'] cmake_args =", "sysconfig import get_paths import importlib from setuptools import setup, Extension", "os.path.abspath(sourcedir) self.build_with_cuda = build_with_cuda class Build(build_ext): def run(self): try: out", "extdir), '-DCMAKE_RUNTIME_OUTPUT_DIRECTORY_{}={}'.format(cfg.upper(), extdir)] if sys.maxsize > 2 ** 32: cmake_args", "'Release' build_args = ['--config', cfg] if platform.system() == \"Windows\": cmake_args", "\"/usr/bin/g++-5\" env_build[\"CC\"] = \"/usr/bin/gcc-5\" env[\"PATH\"] = \"/usr/local/cuda-10.1/bin\" + \":\" +", "Override build_with_cuda with environment variable if 'DIFFVG_CUDA' in os.environ: build_with_cuda", "else: cmake_args += ['-DCMAKE_BUILD_TYPE=' + cfg] build_args += ['--', '-j8']", "from https://github.com/pybind/cmake_example/blob/master/setup.py import os import re import sys import platform", "install_requires=[\"svgpathtools\"], description='Differentiable Vector Graphics', ext_modules=[CMakeExtension('diffvg', '', build_with_cuda)], cmdclass=dict(build_ext=Build, install=install), packages=packages,", "<reponame>AntonBiryukovUofC/diffvg # Adapted from https://github.com/pybind/cmake_example/blob/master/setup.py import os import re import", "version='0.0.1', install_requires=[\"svgpathtools\"], description='Differentiable Vector Graphics', ext_modules=[CMakeExtension('diffvg', '', build_with_cuda)], cmdclass=dict(build_ext=Build, install=install),", "['--', '-j8'] if ext.build_with_cuda: cmake_args += ['-DDIFFVG_CUDA=1'] else: cmake_args +=", "installed. For Windows platform only PyTorch is supported.') exit() #", "self.extensions)) super().run() def build_extension(self, ext): if isinstance(ext, CMakeExtension): extdir =", "os.environ: build_with_cuda = os.environ['DIFFVG_CUDA'] == '1' setup(name='diffvg', version='0.0.1', install_requires=[\"svgpathtools\"], description='Differentiable", "env env[\"CXX\"] = \"/usr/bin/g++-5\" env[\"CC\"] = \"/usr/bin/gcc-5\" env_build[\"CXX\"] = \"/usr/bin/g++-5\"", "import platform import subprocess import importlib from sysconfig import get_paths", "'x64'] build_args += ['--', '/m'] else: cmake_args += ['-DCMAKE_BUILD_TYPE=' +", "\"/usr/bin/g++-5\" env[\"CC\"] = \"/usr/bin/gcc-5\" env_build[\"CXX\"] = \"/usr/bin/g++-5\" env_build[\"CC\"] = \"/usr/bin/gcc-5\"", "e in self.extensions)) super().run() def build_extension(self, ext): if isinstance(ext, CMakeExtension):", "in os.environ: build_with_cuda = os.environ['DIFFVG_CUDA'] == '1' setup(name='diffvg', version='0.0.1', install_requires=[\"svgpathtools\"],", "== \"Windows\": cmake_args += ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_{}={}'.format(cfg.upper(), extdir), '-DCMAKE_RUNTIME_OUTPUT_DIRECTORY_{}={}'.format(cfg.upper(), extdir)] if sys.maxsize", "if torch_spec is not None: packages.append('pydiffvg') import torch if torch.cuda.is_available():", "'{} -DVERSION_INFO=\\\\\"{}\\\\\"'.format(env.get('CXXFLAGS', ''), self.distribution.get_version()) env_build = env env[\"CXX\"] = \"/usr/bin/g++-5\"", "cfg = 'Debug' if self.debug else 'Release' build_args = ['--config',", "self.distribution.get_version()) env_build = env env[\"CXX\"] = \"/usr/bin/g++-5\" env[\"CC\"] = \"/usr/bin/gcc-5\"", "only PyTorch is supported.') exit() # Override build_with_cuda with environment", "2 ** 32: cmake_args += ['-A', 'x64'] build_args += ['--',", "cfg] if platform.system() == \"Windows\": cmake_args += ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_{}={}'.format(cfg.upper(), extdir), '-DCMAKE_RUNTIME_OUTPUT_DIRECTORY_{}={}'.format(cfg.upper(),", "LooseVersion class CMakeExtension(Extension): def __init__(self, name, sourcedir, build_with_cuda): Extension.__init__(self, name,", "platform only PyTorch is supported.') exit() # Override build_with_cuda with", "'-DPYTHON_INCLUDE_PATH=' + include_path, ] cfg = 'Debug' if self.debug else", "be installed to build the following extensions: \" + \",", "setuptools.command.build_ext import build_ext from setuptools.command.install import install from distutils.sysconfig import", "cmake_args += ['-A', 'x64'] build_args += ['--', '/m'] else: cmake_args", "from setuptools import setup, Extension from setuptools.command.build_ext import build_ext from", "env=env) subprocess.check_call(['cmake', '--build', '.'] + build_args, cwd=self.build_temp, env=env_build) else: super().build_extension(ext)", "import build_ext from setuptools.command.install import install from distutils.sysconfig import get_config_var", "== '1' setup(name='diffvg', version='0.0.1', install_requires=[\"svgpathtools\"], description='Differentiable Vector Graphics', ext_modules=[CMakeExtension('diffvg', '',", "tensorflow as tf if tf.test.is_gpu_available(cuda_only=True, min_cuda_compute_capability=None): build_with_cuda = True if", "distutils.version import LooseVersion class CMakeExtension(Extension): def __init__(self, name, sourcedir, build_with_cuda):", "['-DDIFFVG_CUDA=1'] else: cmake_args += ['-DDIFFVG_CUDA=0'] env = os.environ.copy() env['CXXFLAGS'] =", "from distutils.sysconfig import get_config_var from distutils.version import LooseVersion class CMakeExtension(Extension):", "'-DCMAKE_RUNTIME_OUTPUT_DIRECTORY_{}={}'.format(cfg.upper(), extdir)] if sys.maxsize > 2 ** 32: cmake_args +=", "\":\" + os.environ['PATH'] env_build[\"PATH\"] = \"/usr/local/cuda-10.1/bin\" + \":\" + os.environ['PATH']", "torch if torch.cuda.is_available(): build_with_cuda = True if tf_spec is not", "cmake_args += ['-DDIFFVG_CUDA=1'] else: cmake_args += ['-DDIFFVG_CUDA=0'] env = os.environ.copy()", "name, sources=[]) self.sourcedir = os.path.abspath(sourcedir) self.build_with_cuda = build_with_cuda class Build(build_ext):", "build_with_cuda): Extension.__init__(self, name, sources=[]) self.sourcedir = os.path.abspath(sourcedir) self.build_with_cuda = build_with_cuda", "distutils.sysconfig import get_config_var from distutils.version import LooseVersion class CMakeExtension(Extension): def", "build_args += ['--', '-j8'] if ext.build_with_cuda: cmake_args += ['-DDIFFVG_CUDA=1'] else:", "is not None and sys.platform != 'win32': packages.append('pydiffvg_tensorflow') if not", "import torch if torch.cuda.is_available(): build_with_cuda = True if tf_spec is", "build_with_cuda class Build(build_ext): def run(self): try: out = subprocess.check_output(['cmake', '--version'])", "# Adapted from https://github.com/pybind/cmake_example/blob/master/setup.py import os import re import sys", "os.makedirs(self.build_temp) subprocess.check_call(['cmake', ext.sourcedir] + cmake_args, cwd=self.build_temp, env=env) subprocess.check_call(['cmake', '--build', '.']", "if self.debug else 'Release' build_args = ['--config', cfg] if platform.system()", "extdir, '-DPYTHON_INCLUDE_PATH=' + include_path, ] cfg = 'Debug' if self.debug", "include_path = info['include'] cmake_args = ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=' + extdir, '-DPYTHON_INCLUDE_PATH=' +", "+ cfg] build_args += ['--', '-j8'] if ext.build_with_cuda: cmake_args +=", "must be installed. For Windows platform only PyTorch is supported.')", "32: cmake_args += ['-A', 'x64'] build_args += ['--', '/m'] else:", "False if torch_spec is not None: packages.append('pydiffvg') import torch if", "= \"/usr/local/cuda-10.1/bin\" + \":\" + os.environ['PATH'] if not os.path.exists(self.build_temp): os.makedirs(self.build_temp)", "packages.append('pydiffvg') import torch if torch.cuda.is_available(): build_with_cuda = True if tf_spec", "subprocess.check_output(['cmake', '--version']) except OSError: raise RuntimeError(\"CMake must be installed to", "+= ['-A', 'x64'] build_args += ['--', '/m'] else: cmake_args +=", "torch_spec = importlib.util.find_spec(\"torch\") tf_spec = importlib.util.find_spec(\"tensorflow\") packages = [] build_with_cuda", "variable if 'DIFFVG_CUDA' in os.environ: build_with_cuda = os.environ['DIFFVG_CUDA'] == '1'", "-DVERSION_INFO=\\\\\"{}\\\\\"'.format(env.get('CXXFLAGS', ''), self.distribution.get_version()) env_build = env env[\"CXX\"] = \"/usr/bin/g++-5\" env[\"CC\"]", "CMakeExtension(Extension): def __init__(self, name, sourcedir, build_with_cuda): Extension.__init__(self, name, sources=[]) self.sourcedir", "= os.environ.copy() env['CXXFLAGS'] = '{} -DVERSION_INFO=\\\\\"{}\\\\\"'.format(env.get('CXXFLAGS', ''), self.distribution.get_version()) env_build =", "cwd=self.build_temp, env=env) subprocess.check_call(['cmake', '--build', '.'] + build_args, cwd=self.build_temp, env=env_build) else:", "subprocess.check_call(['cmake', '--build', '.'] + build_args, cwd=self.build_temp, env=env_build) else: super().build_extension(ext) torch_spec", "except OSError: raise RuntimeError(\"CMake must be installed to build the", "'--build', '.'] + build_args, cwd=self.build_temp, env=env_build) else: super().build_extension(ext) torch_spec =", "self.sourcedir = os.path.abspath(sourcedir) self.build_with_cuda = build_with_cuda class Build(build_ext): def run(self):", "env[\"CXX\"] = \"/usr/bin/g++-5\" env[\"CC\"] = \"/usr/bin/gcc-5\" env_build[\"CXX\"] = \"/usr/bin/g++-5\" env_build[\"CC\"]", "\"/usr/local/cuda-10.1/bin\" + \":\" + os.environ['PATH'] env_build[\"PATH\"] = \"/usr/local/cuda-10.1/bin\" + \":\"", "build_with_cuda: import tensorflow as tf if tf.test.is_gpu_available(cuda_only=True, min_cuda_compute_capability=None): build_with_cuda =", "isinstance(ext, CMakeExtension): extdir = os.path.abspath(os.path.dirname(self.get_ext_fullpath(ext.name))) info = get_paths() include_path =", "+= ['-DCMAKE_BUILD_TYPE=' + cfg] build_args += ['--', '-j8'] if ext.build_with_cuda:", "with environment variable if 'DIFFVG_CUDA' in os.environ: build_with_cuda = os.environ['DIFFVG_CUDA']", "\"/usr/bin/gcc-5\" env[\"PATH\"] = \"/usr/local/cuda-10.1/bin\" + \":\" + os.environ['PATH'] env_build[\"PATH\"] =", "super().build_extension(ext) torch_spec = importlib.util.find_spec(\"torch\") tf_spec = importlib.util.find_spec(\"tensorflow\") packages = []", "packages = [] build_with_cuda = False if torch_spec is not", "OSError: raise RuntimeError(\"CMake must be installed to build the following", "+ cmake_args, cwd=self.build_temp, env=env) subprocess.check_call(['cmake', '--build', '.'] + build_args, cwd=self.build_temp,", "setuptools import setup, Extension from setuptools.command.build_ext import build_ext from setuptools.command.install", "RuntimeError(\"CMake must be installed to build the following extensions: \"", "= \"/usr/bin/gcc-5\" env[\"PATH\"] = \"/usr/local/cuda-10.1/bin\" + \":\" + os.environ['PATH'] env_build[\"PATH\"]", "sources=[]) self.sourcedir = os.path.abspath(sourcedir) self.build_with_cuda = build_with_cuda class Build(build_ext): def", "env_build[\"CC\"] = \"/usr/bin/gcc-5\" env[\"PATH\"] = \"/usr/local/cuda-10.1/bin\" + \":\" + os.environ['PATH']", "info = get_paths() include_path = info['include'] cmake_args = ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=' +", "] cfg = 'Debug' if self.debug else 'Release' build_args =", "import get_config_var from distutils.version import LooseVersion class CMakeExtension(Extension): def __init__(self,", "cmake_args += ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_{}={}'.format(cfg.upper(), extdir), '-DCMAKE_RUNTIME_OUTPUT_DIRECTORY_{}={}'.format(cfg.upper(), extdir)] if sys.maxsize > 2", "get_config_var from distutils.version import LooseVersion class CMakeExtension(Extension): def __init__(self, name,", "__init__(self, name, sourcedir, build_with_cuda): Extension.__init__(self, name, sources=[]) self.sourcedir = os.path.abspath(sourcedir)", "= subprocess.check_output(['cmake', '--version']) except OSError: raise RuntimeError(\"CMake must be installed", "'-j8'] if ext.build_with_cuda: cmake_args += ['-DDIFFVG_CUDA=1'] else: cmake_args += ['-DDIFFVG_CUDA=0']", "def __init__(self, name, sourcedir, build_with_cuda): Extension.__init__(self, name, sources=[]) self.sourcedir =", "['-A', 'x64'] build_args += ['--', '/m'] else: cmake_args += ['-DCMAKE_BUILD_TYPE='", "'1' setup(name='diffvg', version='0.0.1', install_requires=[\"svgpathtools\"], description='Differentiable Vector Graphics', ext_modules=[CMakeExtension('diffvg', '', build_with_cuda)],", "if not build_with_cuda: import tensorflow as tf if tf.test.is_gpu_available(cuda_only=True, min_cuda_compute_capability=None):", "if 'DIFFVG_CUDA' in os.environ: build_with_cuda = os.environ['DIFFVG_CUDA'] == '1' setup(name='diffvg',", "get_paths import importlib from setuptools import setup, Extension from setuptools.command.build_ext", "name, sourcedir, build_with_cuda): Extension.__init__(self, name, sources=[]) self.sourcedir = os.path.abspath(sourcedir) self.build_with_cuda", "try: out = subprocess.check_output(['cmake', '--version']) except OSError: raise RuntimeError(\"CMake must", "raise RuntimeError(\"CMake must be installed to build the following extensions:", "True if len(packages) == 0: print('Error: PyTorch or Tensorflow must", "import importlib from setuptools import setup, Extension from setuptools.command.build_ext import" ]
[ "config[IMURegisters.NAVX_REG_WHOAMI] self.notify_sink._setBoardID(board_id) board_state = self.board_state board_state.cal_status = config[IMURegisters.NAVX_REG_CAL_STATUS] board_state.op_status =", "class _BoardState: op_status = 0 sensor_status = 0 cal_status =", "2465 (Kauaibots). Go Purple Wave! # # Open Source Software", "32768.0 ahrspos_update.quaternionZ = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_QUAT_Z_L-first_address)/ 32768.0 if displacement_registers: ahrspos_update.vel_x =", "IMURegisters.NAVX_REG_DISP_Z_I_L-first_address) self.notify_sink._setAHRSPosData(ahrspos_update, sensor_timestamp) else: self.notify_sink._setAHRSData(ahrspos_update, sensor_timestamp) board_state = self.board_state board_state.cal_status", "board_id.fw_ver_minor = config[IMURegisters.NAVX_REG_FW_VER_MINOR] board_id.type = config[IMURegisters.NAVX_REG_WHOAMI] self.notify_sink._setBoardID(board_id) board_state = self.board_state", "getCurrentData(self): first_address = IMURegisters.NAVX_REG_UPDATE_RATE_HZ displacement_registers = self.board_capabilities._isDisplacementSupported() # If firmware", "board_id.type = config[IMURegisters.NAVX_REG_WHOAMI] self.notify_sink._setBoardID(board_id) board_state = self.board_state board_state.cal_status = config[IMURegisters.NAVX_REG_CAL_STATUS]", "IMURegisters.NAVX_REG_UPDATE_RATE_HZ displacement_registers = self.board_capabilities._isDisplacementSupported() # If firmware supports displacement data,", "read_count = IMURegisters.NAVX_REG_QUAT_OFFSET_Z_H + 1 - first_address curr_data = self.io_provider.read(first_address,", "else: read_count = IMURegisters.NAVX_REG_QUAT_OFFSET_Z_H + 1 - first_address curr_data =", "(Kauaibots). Go Purple Wave! # # Open Source Software -", "= 0 unique_id = [0]*12 class _BoardState: op_status = 0", "AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_DISP_Y_I_L-first_address) ahrspos_update.disp_z = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_DISP_Z_I_L-first_address) self.notify_sink._setAHRSPosData(ahrspos_update, sensor_timestamp) else: self.notify_sink._setAHRSData(ahrspos_update,", "- first_address else: read_count = IMURegisters.NAVX_REG_QUAT_OFFSET_Z_H + 1 - first_address", "from the # 1/update_rate value to ensure samples are not", "IMURegisters.NAVX_REG_QUAT_Y_L-first_address)/ 32768.0 ahrspos_update.quaternionZ = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_QUAT_Z_L-first_address)/ 32768.0 if displacement_registers: ahrspos_update.vel_x", "from wpilib.timer import Timer import logging logger = logging.getLogger('navx') __all__", "_BoardId: type = 0 hw_rev = 0 fw_ver_major = 0", "potentially less accurate) calculations on this processor. if displacement_registers: read_count", "ahrspos_update.sensor_status = curr_data[IMURegisters.NAVX_REG_SENSOR_STATUS_L - first_address] ahrspos_update.yaw = AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_YAW_L-first_address) ahrspos_update.pitch", "zeroDisplacement(self): self.io_provider.write( IMURegisters.NAVX_REG_INTEGRATION_CTL, (AHRSProtocol.NAVX_INTEGRATION_CTL_RESET_DISP_X | AHRSProtocol.NAVX_INTEGRATION_CTL_RESET_DISP_Y | AHRSProtocol.NAVX_INTEGRATION_CTL_RESET_DISP_Z ) )", "& 0xFF) if update_rate > DELAY_OVERHEAD_SECONDS: update_rate -= DELAY_OVERHEAD_SECONDS logger.info(\"--", "raw_data_update.raw_accel_y = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_ACC_Y_L-first_address) raw_data_update.raw_accel_z = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_ACC_Z_L-first_address) raw_data_update.cal_mag_x =", "board_capabilities self.notify_sink = notify_sink self.raw_data_update = IMUProtocol.GyroUpdate() self.ahrspos_update = AHRSProtocol.AHRSPosUpdate()", "(rev %s)\", IMURegisters.model_type(self.board_id.type), self.board_id.hw_rev) logger.info(\"-- Firmware %s.%s\", self.board_id.fw_ver_major, self.board_id.fw_ver_minor) log_error", "similar (but potentially less accurate) calculations on this processor. if", "= AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_VEL_Y_I_L-first_address) ahrspos_update.vel_z = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_VEL_Z_I_L-first_address) ahrspos_update.disp_x = AHRSProtocol.decodeProtocol1616Float(curr_data,", "= ['RegisterIO'] IO_TIMEOUT_SECONDS = 1.0 DELAY_OVERHEAD_SECONDS = 0.004 class _BoardId:", "True # Calculate delay to match configured update rate #", "success = False Timer.delay(0.5) else: board_id = self.board_id board_id.hw_rev =", "fw_ver_major = 0 fw_ver_minor = 0 fw_revision = 0 unique_id", "self.update_count = 0 self.last_sensor_timestamp = 0 self._stop = False def", "_setBoardState, _yawResetComplete \"\"\" self.io_provider = io_provider self.update_rate_hz = update_rate_hz self.board_capabilities", "must be accompanied by the \\License.txt file # in the", "sensor_status = 0 cal_status = 0 selftest_status = 0 capability_flags", "0 cal_status = 0 selftest_status = 0 capability_flags = 0", "ahrspos_update.pitch = AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_PITCH_L-first_address) ahrspos_update.roll = AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_ROLL_L-first_address) ahrspos_update.compass_heading =", "following callable attributes: _setYawPitchRoll, _setAHRSData, _setAHRSPosData, _setRawData, _setBoardID, _setBoardState, _yawResetComplete", "_BoardId() self.last_update_time = 0 self.byte_count = 0 self.update_count = 0", "(%.4fs)\", self.update_rate_hz, update_rate) # IO Loop while not self._stop: if", "self.board_state.update_rate_hz != self.update_rate_hz: self.setUpdateRateHz(self.update_rate_hz) try: self.getCurrentData() except IOError: if log_error:", "the \\License.txt file # in the root directory of the", "= AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_GYRO_Y_L-first_address) raw_data_update.raw_gyro_z = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_GYRO_Z_L-first_address) raw_data_update.raw_accel_x = AHRSProtocol.decodeBinaryInt16(curr_data,", "logger.info(\"-- Board is %s (rev %s)\", IMURegisters.model_type(self.board_id.type), self.board_id.hw_rev) logger.info(\"-- Firmware", "the following callable attributes: _setYawPitchRoll, _setAHRSData, _setAHRSPosData, _setRawData, _setBoardID, _setBoardState,", "= AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_GYRO_X_L-first_address) raw_data_update.raw_gyro_y = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_GYRO_Y_L-first_address) raw_data_update.raw_gyro_z = AHRSProtocol.decodeBinaryInt16(curr_data,", "32768.0 if displacement_registers: ahrspos_update.vel_x = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_VEL_X_I_L-first_address) ahrspos_update.vel_y = AHRSProtocol.decodeProtocol1616Float(curr_data,", "<NAME> 2015. All Rights Reserved. # # Created in support", "= 0 while retry_count < 5 and not success: try:", "ahrspos_update.selftest_status = curr_data[IMURegisters.NAVX_REG_SELFTEST_STATUS - first_address] ahrspos_update.cal_status = curr_data[IMURegisters.NAVX_REG_CAL_STATUS] ahrspos_update.sensor_status =", "raw_data_update.raw_gyro_z = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_GYRO_Z_L-first_address) raw_data_update.raw_accel_x = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_ACC_X_L-first_address) raw_data_update.raw_accel_y =", "teams. Any # modifications to this code must be accompanied", "- first_address] ahrspos_update.yaw = AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_YAW_L-first_address) ahrspos_update.pitch = AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_PITCH_L-first_address)", "the following callable attributes: _isOmniMountSupported, _isBoardYawResetSupported, _isDisplacementSupported :param notify_sink: must", "= AHRSProtocol.decodeProtocolUnsignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_FUSED_HEADING_L-first_address) ahrspos_update.quaternionW = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_QUAT_W_L-first_address)/ 32768.0 ahrspos_update.quaternionX =", "(c) <NAME> 2015. All Rights Reserved. # # Created in", "# initial device configuration self.setUpdateRateHz(self.update_rate_hz) if not self.getConfiguration(): logger.warning(\"-- Did", "= self.io_provider.read(IMURegisters.NAVX_REG_WHOAMI, IMURegisters.NAVX_REG_SENSOR_STATUS_H+1) except IOError as e: logger.warning(\"Error reading configuration", "= 0 sensor_status = 0 cal_status = 0 selftest_status =", "accurate) calculations on this processor. if displacement_registers: read_count = IMURegisters.NAVX_REG_LAST", "= self.ahrspos_update ahrspos_update.op_status = curr_data[IMURegisters.NAVX_REG_OP_STATUS - first_address] ahrspos_update.selftest_status = curr_data[IMURegisters.NAVX_REG_SELFTEST_STATUS", "AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_DISP_X_I_L-first_address) ahrspos_update.disp_y = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_DISP_Y_I_L-first_address) ahrspos_update.disp_z = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_DISP_Z_I_L-first_address)", "code must be accompanied by the \\License.txt file # in", "not # dropped, esp. at higher update rates. update_rate =", "= curr_data[IMURegisters.NAVX_REG_CAL_STATUS-first_address] board_state.op_status = curr_data[IMURegisters.NAVX_REG_OP_STATUS-first_address] board_state.selftest_status = curr_data[IMURegisters.NAVX_REG_SELFTEST_STATUS-first_address] board_state.sensor_status =", "processor. if displacement_registers: read_count = IMURegisters.NAVX_REG_LAST + 1 - first_address", "If firmware supports displacement data, acquire it - otherwise implement", "= config[IMURegisters.NAVX_REG_CAL_STATUS] board_state.op_status = config[IMURegisters.NAVX_REG_OP_STATUS] board_state.selftest_status = config[IMURegisters.NAVX_REG_SELFTEST_STATUS] board_state.sensor_status =", "IMURegisters.NAVX_REG_DISP_Y_I_L-first_address) ahrspos_update.disp_z = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_DISP_Z_I_L-first_address) self.notify_sink._setAHRSPosData(ahrspos_update, sensor_timestamp) else: self.notify_sink._setAHRSData(ahrspos_update, sensor_timestamp)", "while retry_count < 5 and not success: try: config =", "IMUProtocol, IMURegisters from wpilib.timer import Timer import logging logger =", "IMURegisters.NAVX_REG_PITCH_L-first_address) ahrspos_update.roll = AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_ROLL_L-first_address) ahrspos_update.compass_heading = AHRSProtocol.decodeProtocolUnsignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_HEADING_L-first_address) ahrspos_update.mpu_temp_c", "AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_MAG_Y_L-first_address) raw_data_update.cal_mag_z = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_MAG_Z_L-first_address) raw_data_update.mpu_temp_c = ahrspos_update.mpu_temp self.notify_sink._setRawData(raw_data_update,", "c5e3a8a9b642 roborio/java/navx_frc/src/com/kauailabs/navx/frc/RegisterIO.java #---------------------------------------------------------------------------- # Copyright (c) <NAME> 2015. All Rights", "self.setUpdateRateHz(self.update_rate_hz) try: self.getCurrentData() except IOError: if log_error: logger.exception(\"Error getting data\")", "AHRSProtocol.decodeBinaryUint16(config,IMURegisters.NAVX_REG_SENSOR_STATUS_L) board_state.gyro_fsr_dps = AHRSProtocol.decodeBinaryUint16(config,IMURegisters.NAVX_REG_GYRO_FSR_DPS_L) board_state.accel_fsr_g = config[IMURegisters.NAVX_REG_ACCEL_FSR_G] board_state.update_rate_hz = config[IMURegisters.NAVX_REG_UPDATE_RATE_HZ]", "if displacement_registers: read_count = IMURegisters.NAVX_REG_LAST + 1 - first_address else:", "self.board_id.fw_ver_minor) log_error = True # Calculate delay to match configured", "exiting\") def getConfiguration(self): success = False retry_count = 0 while", "board_state.capability_flags= AHRSProtocol.decodeBinaryUint16(curr_data,IMURegisters.NAVX_REG_CAPABILITY_FLAGS_L-first_address) self.notify_sink._setBoardState(board_state) raw_data_update = self.raw_data_update raw_data_update.raw_gyro_x = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_GYRO_X_L-first_address)", "accel_fsr_g = 0 gyro_fsr_dps = 0 class RegisterIO: def __init__(self,", "= AHRSProtocol.decodeBinaryUint16(config,IMURegisters.NAVX_REG_SENSOR_STATUS_L) board_state.gyro_fsr_dps = AHRSProtocol.decodeBinaryUint16(config,IMURegisters.NAVX_REG_GYRO_FSR_DPS_L) board_state.accel_fsr_g = config[IMURegisters.NAVX_REG_ACCEL_FSR_G] board_state.update_rate_hz =", "if not self.getConfiguration(): logger.warning(\"-- Did not get configuration data\") else:", "0xFF) if update_rate > DELAY_OVERHEAD_SECONDS: update_rate -= DELAY_OVERHEAD_SECONDS logger.info(\"-- Update", "= curr_data[IMURegisters.NAVX_REG_SELFTEST_STATUS - first_address] ahrspos_update.cal_status = curr_data[IMURegisters.NAVX_REG_CAL_STATUS] ahrspos_update.sensor_status = curr_data[IMURegisters.NAVX_REG_SENSOR_STATUS_L", "True Timer.delay(update_rate) except Exception: logger.exception(\"Unhandled exception in NavX thread\") finally:", "AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_ACC_Z_L-first_address) raw_data_update.cal_mag_x = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_MAG_X_L-first_address) raw_data_update.cal_mag_y = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_MAG_Y_L-first_address)", "__init__(self, io_provider, update_rate_hz, notify_sink, board_capabilities): \"\"\" :param board_capabilities: must have", "sensor_timestamp == self.last_sensor_timestamp: return self.last_sensor_timestamp = sensor_timestamp ahrspos_update = self.ahrspos_update", "AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_QUAT_W_L-first_address)/ 32768.0 ahrspos_update.quaternionX = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_QUAT_X_L-first_address)/ 32768.0 ahrspos_update.quaternionY =", "AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_ACC_X_L-first_address) raw_data_update.raw_accel_y = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_ACC_Y_L-first_address) raw_data_update.raw_accel_z = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_ACC_Z_L-first_address)", "logger.info(\"NavX io thread starting\") try: self.io_provider.init() # initial device configuration", "%s.%s\", self.board_id.fw_ver_major, self.board_id.fw_ver_minor) log_error = True # Calculate delay to", "!= self.update_rate_hz: self.setUpdateRateHz(self.update_rate_hz) try: self.getCurrentData() except IOError: if log_error: logger.exception(\"Error", "= self.raw_data_update raw_data_update.raw_gyro_x = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_GYRO_X_L-first_address) raw_data_update.raw_gyro_y = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_GYRO_Y_L-first_address)", "not self.getConfiguration(): logger.warning(\"-- Did not get configuration data\") else: logger.info(\"--", "get configuration data\") else: logger.info(\"-- Board is %s (rev %s)\",", "= 0 accel_fsr_g = 0 gyro_fsr_dps = 0 class RegisterIO:", "ahrspos_update = self.ahrspos_update ahrspos_update.op_status = curr_data[IMURegisters.NAVX_REG_OP_STATUS - first_address] ahrspos_update.selftest_status =", "retry_count += 1 return success def getCurrentData(self): first_address = IMURegisters.NAVX_REG_UPDATE_RATE_HZ", "AHRSProtocol.decodeProtocolUnsignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_FUSED_HEADING_L-first_address) ahrspos_update.quaternionW = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_QUAT_W_L-first_address)/ 32768.0 ahrspos_update.quaternionX = AHRSProtocol.decodeBinaryInt16(curr_data,", "FRC teams. Any # modifications to this code must be", "attributes: _isOmniMountSupported, _isBoardYawResetSupported, _isDisplacementSupported :param notify_sink: must have the following", "Loop while not self._stop: if self.board_state.update_rate_hz != self.update_rate_hz: self.setUpdateRateHz(self.update_rate_hz) try:", "DELAY_OVERHEAD_SECONDS: update_rate -= DELAY_OVERHEAD_SECONDS logger.info(\"-- Update rate: %shz (%.4fs)\", self.update_rate_hz,", "= curr_data[IMURegisters.NAVX_REG_UPDATE_RATE_HZ-first_address] board_state.gyro_fsr_dps = AHRSProtocol.decodeBinaryUint16(curr_data,IMURegisters.NAVX_REG_GYRO_FSR_DPS_L) board_state.accel_fsr_g = curr_data[IMURegisters.NAVX_REG_ACCEL_FSR_G] board_state.capability_flags= AHRSProtocol.decodeBinaryUint16(curr_data,IMURegisters.NAVX_REG_CAPABILITY_FLAGS_L-first_address)", "the root directory of the project #---------------------------------------------------------------------------- from ._impl import", "0 fw_ver_minor = 0 fw_revision = 0 unique_id = [0]*12", "0 self.byte_count = 0 self.update_count = 0 self.last_sensor_timestamp = 0", "= self.board_id board_id.hw_rev = config[IMURegisters.NAVX_REG_HW_REV] board_id.fw_ver_major = config[IMURegisters.NAVX_REG_FW_VER_MAJOR] board_id.fw_ver_minor =", "have the following callable attributes: _setYawPitchRoll, _setAHRSData, _setAHRSPosData, _setRawData, _setBoardID,", "- first_address) ahrspos_update.fused_heading = AHRSProtocol.decodeProtocolUnsignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_FUSED_HEADING_L-first_address) ahrspos_update.quaternionW = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_QUAT_W_L-first_address)/", "self.getCurrentData() except IOError: if log_error: logger.exception(\"Error getting data\") log_error =", "[0]*12 class _BoardState: op_status = 0 sensor_status = 0 cal_status", "curr_data[IMURegisters.NAVX_REG_SENSOR_STATUS_L - first_address] ahrspos_update.yaw = AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_YAW_L-first_address) ahrspos_update.pitch = AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data,", "gyro_fsr_dps = 0 class RegisterIO: def __init__(self, io_provider, update_rate_hz, notify_sink,", "self.board_state = _BoardState() self.board_id = _BoardId() self.last_update_time = 0 self.byte_count", "0 update_rate_hz = 0 accel_fsr_g = 0 gyro_fsr_dps = 0", "IMURegisters.NAVX_REG_VEL_Z_I_L-first_address) ahrspos_update.disp_x = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_DISP_X_I_L-first_address) ahrspos_update.disp_y = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_DISP_Y_I_L-first_address) ahrspos_update.disp_z", "selftest_status = 0 capability_flags = 0 update_rate_hz = 0 accel_fsr_g", "update_rate_hz self.board_capabilities = board_capabilities self.notify_sink = notify_sink self.raw_data_update = IMUProtocol.GyroUpdate()", "IMURegisters.NAVX_REG_LINEAR_ACC_Z_L-first_address) ahrspos_update.altitude = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_ALTITUDE_D_L - first_address) ahrspos_update.baro_pressure = AHRSProtocol.decodeProtocol1616Float(curr_data,", "success: try: config = self.io_provider.read(IMURegisters.NAVX_REG_WHOAMI, IMURegisters.NAVX_REG_SENSOR_STATUS_H+1) except IOError as e:", "ahrspos_update.mpu_temp self.notify_sink._setRawData(raw_data_update, sensor_timestamp) self.last_update_time = Timer.getFPGATimestamp() self.byte_count += len(curr_data) self.update_count", "self.notify_sink._setBoardID(board_id) board_state = self.board_state board_state.cal_status = config[IMURegisters.NAVX_REG_CAL_STATUS] board_state.op_status = config[IMURegisters.NAVX_REG_OP_STATUS]", "AHRSProtocol.NAVX_INTEGRATION_CTL_RESET_YAW ) self.notify_sink._yawResetComplete() def zeroDisplacement(self): self.io_provider.write( IMURegisters.NAVX_REG_INTEGRATION_CTL, (AHRSProtocol.NAVX_INTEGRATION_CTL_RESET_DISP_X | AHRSProtocol.NAVX_INTEGRATION_CTL_RESET_DISP_Y", "Timer import logging logger = logging.getLogger('navx') __all__ = ['RegisterIO'] IO_TIMEOUT_SECONDS", "log_error = False else: log_error = True Timer.delay(update_rate) except Exception:", "thread\") finally: logger.info(\"NavX i/o thread exiting\") def getConfiguration(self): success =", "from ._impl import AHRSProtocol, IMUProtocol, IMURegisters from wpilib.timer import Timer", "= False retry_count = 0 while retry_count < 5 and", "= 0 self.update_count = 0 self.last_sensor_timestamp = 0 self._stop =", "AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_ROLL_L-first_address) ahrspos_update.compass_heading = AHRSProtocol.decodeProtocolUnsignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_HEADING_L-first_address) ahrspos_update.mpu_temp_c = AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_MPU_TEMP_C_L", "sensor_timestamp) board_state = self.board_state board_state.cal_status = curr_data[IMURegisters.NAVX_REG_CAL_STATUS-first_address] board_state.op_status = curr_data[IMURegisters.NAVX_REG_OP_STATUS-first_address]", "ahrspos_update.vel_y = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_VEL_Y_I_L-first_address) ahrspos_update.vel_z = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_VEL_Z_I_L-first_address) ahrspos_update.disp_x =", "self.io_provider.write(IMURegisters.NAVX_REG_UPDATE_RATE_HZ, update_rate_hz) def zeroYaw(self): self.io_provider.write( IMURegisters.NAVX_REG_INTEGRATION_CTL, AHRSProtocol.NAVX_INTEGRATION_CTL_RESET_YAW ) self.notify_sink._yawResetComplete() def", "NavX thread\") finally: logger.info(\"NavX i/o thread exiting\") def getConfiguration(self): success", "self._stop = False def stop(self): self._stop = True def shutdown(self):", "supports displacement data, acquire it - otherwise implement # similar", "= AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_ACC_X_L-first_address) raw_data_update.raw_accel_y = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_ACC_Y_L-first_address) raw_data_update.raw_accel_z = AHRSProtocol.decodeBinaryInt16(curr_data,", "e) success = False Timer.delay(0.5) else: board_id = self.board_id board_id.hw_rev", "import Timer import logging logger = logging.getLogger('navx') __all__ = ['RegisterIO']", "= False Timer.delay(0.5) else: board_id = self.board_id board_id.hw_rev = config[IMURegisters.NAVX_REG_HW_REV]", "return self.update_count def setUpdateRateHz(self, update_rate_hz): self.io_provider.write(IMURegisters.NAVX_REG_UPDATE_RATE_HZ, update_rate_hz) def zeroYaw(self): self.io_provider.write(", "config = self.io_provider.read(IMURegisters.NAVX_REG_WHOAMI, IMURegisters.NAVX_REG_SENSOR_STATUS_H+1) except IOError as e: logger.warning(\"Error reading", "= 0 hw_rev = 0 fw_ver_major = 0 fw_ver_minor =", "log_error = True Timer.delay(update_rate) except Exception: logger.exception(\"Unhandled exception in NavX", "IMURegisters.NAVX_REG_ACC_Y_L-first_address) raw_data_update.raw_accel_z = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_ACC_Z_L-first_address) raw_data_update.cal_mag_x = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_MAG_X_L-first_address) raw_data_update.cal_mag_y", "notify_sink, board_capabilities): \"\"\" :param board_capabilities: must have the following callable", "rate # Note: some additional time is removed from the", "self.board_id.hw_rev) logger.info(\"-- Firmware %s.%s\", self.board_id.fw_ver_major, self.board_id.fw_ver_minor) log_error = True #", "RegisterIO: def __init__(self, io_provider, update_rate_hz, notify_sink, board_capabilities): \"\"\" :param board_capabilities:", "self._stop: if self.board_state.update_rate_hz != self.update_rate_hz: self.setUpdateRateHz(self.update_rate_hz) try: self.getCurrentData() except IOError:", "IMURegisters.NAVX_REG_LAST + 1 - first_address else: read_count = IMURegisters.NAVX_REG_QUAT_OFFSET_Z_H +", "_BoardState: op_status = 0 sensor_status = 0 cal_status = 0", "# IO Loop while not self._stop: if self.board_state.update_rate_hz != self.update_rate_hz:", "0 unique_id = [0]*12 class _BoardState: op_status = 0 sensor_status", "0 fw_revision = 0 unique_id = [0]*12 class _BoardState: op_status", "= 0 gyro_fsr_dps = 0 class RegisterIO: def __init__(self, io_provider,", "except IOError: if log_error: logger.exception(\"Error getting data\") log_error = False", "= 0 capability_flags = 0 update_rate_hz = 0 accel_fsr_g =", "0.004 class _BoardId: type = 0 hw_rev = 0 fw_ver_major", "self.ahrspos_update ahrspos_update.op_status = curr_data[IMURegisters.NAVX_REG_OP_STATUS - first_address] ahrspos_update.selftest_status = curr_data[IMURegisters.NAVX_REG_SELFTEST_STATUS -", "- first_address) ahrspos_update.world_linear_accel_x = AHRSProtocol.decodeProtocolSignedThousandthsFloat(curr_data, IMURegisters.NAVX_REG_LINEAR_ACC_X_L-first_address) ahrspos_update.world_linear_accel_y = AHRSProtocol.decodeProtocolSignedThousandthsFloat(curr_data, IMURegisters.NAVX_REG_LINEAR_ACC_Y_L-first_address)", "IMURegisters.NAVX_REG_MAG_Z_L-first_address) raw_data_update.mpu_temp_c = ahrspos_update.mpu_temp self.notify_sink._setRawData(raw_data_update, sensor_timestamp) self.last_update_time = Timer.getFPGATimestamp() self.byte_count", "- first_address curr_data = self.io_provider.read(first_address, read_count) sensor_timestamp = AHRSProtocol.decodeBinaryUint32(curr_data, IMURegisters.NAVX_REG_TIMESTAMP_L_L-first_address)", "capability_flags = 0 update_rate_hz = 0 accel_fsr_g = 0 gyro_fsr_dps", "IMURegisters.NAVX_REG_HEADING_L-first_address) ahrspos_update.mpu_temp_c = AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_MPU_TEMP_C_L - first_address) ahrspos_update.world_linear_accel_x = AHRSProtocol.decodeProtocolSignedThousandthsFloat(curr_data,", "= config[IMURegisters.NAVX_REG_OP_STATUS] board_state.selftest_status = config[IMURegisters.NAVX_REG_SELFTEST_STATUS] board_state.sensor_status = AHRSProtocol.decodeBinaryUint16(config,IMURegisters.NAVX_REG_SENSOR_STATUS_L) board_state.gyro_fsr_dps =", "first_address else: read_count = IMURegisters.NAVX_REG_QUAT_OFFSET_Z_H + 1 - first_address curr_data", "IMURegisters.NAVX_REG_INTEGRATION_CTL, AHRSProtocol.NAVX_INTEGRATION_CTL_RESET_YAW ) self.notify_sink._yawResetComplete() def zeroDisplacement(self): self.io_provider.write( IMURegisters.NAVX_REG_INTEGRATION_CTL, (AHRSProtocol.NAVX_INTEGRATION_CTL_RESET_DISP_X |", "self.notify_sink._yawResetComplete() def zeroDisplacement(self): self.io_provider.write( IMURegisters.NAVX_REG_INTEGRATION_CTL, (AHRSProtocol.NAVX_INTEGRATION_CTL_RESET_DISP_X | AHRSProtocol.NAVX_INTEGRATION_CTL_RESET_DISP_Y | AHRSProtocol.NAVX_INTEGRATION_CTL_RESET_DISP_Z", "fw_revision = 0 unique_id = [0]*12 class _BoardState: op_status =", "IMURegisters.NAVX_REG_LINEAR_ACC_X_L-first_address) ahrspos_update.world_linear_accel_y = AHRSProtocol.decodeProtocolSignedThousandthsFloat(curr_data, IMURegisters.NAVX_REG_LINEAR_ACC_Y_L-first_address) ahrspos_update.world_linear_accel_z = AHRSProtocol.decodeProtocolSignedThousandthsFloat(curr_data, IMURegisters.NAVX_REG_LINEAR_ACC_Z_L-first_address) ahrspos_update.altitude", "AHRSProtocol.decodeProtocolSignedThousandthsFloat(curr_data, IMURegisters.NAVX_REG_LINEAR_ACC_X_L-first_address) ahrspos_update.world_linear_accel_y = AHRSProtocol.decodeProtocolSignedThousandthsFloat(curr_data, IMURegisters.NAVX_REG_LINEAR_ACC_Y_L-first_address) ahrspos_update.world_linear_accel_z = AHRSProtocol.decodeProtocolSignedThousandthsFloat(curr_data, IMURegisters.NAVX_REG_LINEAR_ACC_Z_L-first_address)", "to match configured update rate # Note: some additional time", "self.last_sensor_timestamp: return self.last_sensor_timestamp = sensor_timestamp ahrspos_update = self.ahrspos_update ahrspos_update.op_status =", "AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_DISP_Z_I_L-first_address) self.notify_sink._setAHRSPosData(ahrspos_update, sensor_timestamp) else: self.notify_sink._setAHRSData(ahrspos_update, sensor_timestamp) board_state = self.board_state", "DELAY_OVERHEAD_SECONDS logger.info(\"-- Update rate: %shz (%.4fs)\", self.update_rate_hz, update_rate) # IO", "= curr_data[IMURegisters.NAVX_REG_ACCEL_FSR_G] board_state.capability_flags= AHRSProtocol.decodeBinaryUint16(curr_data,IMURegisters.NAVX_REG_CAPABILITY_FLAGS_L-first_address) self.notify_sink._setBoardState(board_state) raw_data_update = self.raw_data_update raw_data_update.raw_gyro_x =", "- self.last_update_time return time_since_last_update <= IO_TIMEOUT_SECONDS def getByteCount(self): return self.byte_count", "_setRawData, _setBoardID, _setBoardState, _yawResetComplete \"\"\" self.io_provider = io_provider self.update_rate_hz =", "at higher update rates. update_rate = 1.0/(self.update_rate_hz & 0xFF) if", "self.last_update_time return time_since_last_update <= IO_TIMEOUT_SECONDS def getByteCount(self): return self.byte_count def", "sensor_timestamp ahrspos_update = self.ahrspos_update ahrspos_update.op_status = curr_data[IMURegisters.NAVX_REG_OP_STATUS - first_address] ahrspos_update.selftest_status", "IMURegisters.NAVX_REG_TIMESTAMP_L_L-first_address) if sensor_timestamp == self.last_sensor_timestamp: return self.last_sensor_timestamp = sensor_timestamp ahrspos_update", "# in the root directory of the project #---------------------------------------------------------------------------- from", "firmware supports displacement data, acquire it - otherwise implement #", "sensor_timestamp = AHRSProtocol.decodeBinaryUint32(curr_data, IMURegisters.NAVX_REG_TIMESTAMP_L_L-first_address) if sensor_timestamp == self.last_sensor_timestamp: return self.last_sensor_timestamp", "update_rate_hz = 0 accel_fsr_g = 0 gyro_fsr_dps = 0 class", "= AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_QUAT_W_L-first_address)/ 32768.0 ahrspos_update.quaternionX = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_QUAT_X_L-first_address)/ 32768.0 ahrspos_update.quaternionY", "else: logger.info(\"-- Board is %s (rev %s)\", IMURegisters.model_type(self.board_id.type), self.board_id.hw_rev) logger.info(\"--", "board_state.capability_flags = AHRSProtocol.decodeBinaryUint16(config,IMURegisters.NAVX_REG_CAPABILITY_FLAGS_L) self.notify_sink._setBoardState(board_state) success = True retry_count += 1", "the # 1/update_rate value to ensure samples are not #", "sensor_timestamp) else: self.notify_sink._setAHRSData(ahrspos_update, sensor_timestamp) board_state = self.board_state board_state.cal_status = curr_data[IMURegisters.NAVX_REG_CAL_STATUS-first_address]", "self.io_provider.write( IMURegisters.NAVX_REG_INTEGRATION_CTL, AHRSProtocol.NAVX_INTEGRATION_CTL_RESET_YAW ) self.notify_sink._yawResetComplete() def zeroDisplacement(self): self.io_provider.write( IMURegisters.NAVX_REG_INTEGRATION_CTL, (AHRSProtocol.NAVX_INTEGRATION_CTL_RESET_DISP_X", "def getCurrentData(self): first_address = IMURegisters.NAVX_REG_UPDATE_RATE_HZ displacement_registers = self.board_capabilities._isDisplacementSupported() # If", "= True retry_count += 1 return success def getCurrentData(self): first_address", "2015. All Rights Reserved. # # Created in support of", "= curr_data[IMURegisters.NAVX_REG_OP_STATUS - first_address] ahrspos_update.selftest_status = curr_data[IMURegisters.NAVX_REG_SELFTEST_STATUS - first_address] ahrspos_update.cal_status", "-= DELAY_OVERHEAD_SECONDS logger.info(\"-- Update rate: %shz (%.4fs)\", self.update_rate_hz, update_rate) #", "first_address] ahrspos_update.cal_status = curr_data[IMURegisters.NAVX_REG_CAL_STATUS] ahrspos_update.sensor_status = curr_data[IMURegisters.NAVX_REG_SENSOR_STATUS_L - first_address] ahrspos_update.yaw", "IO_TIMEOUT_SECONDS = 1.0 DELAY_OVERHEAD_SECONDS = 0.004 class _BoardId: type =", "Update rate: %shz (%.4fs)\", self.update_rate_hz, update_rate) # IO Loop while", "of Team 2465 (Kauaibots). Go Purple Wave! # # Open", "class RegisterIO: def __init__(self, io_provider, update_rate_hz, notify_sink, board_capabilities): \"\"\" :param", "= AHRSProtocol.decodeProtocolSignedThousandthsFloat(curr_data, IMURegisters.NAVX_REG_LINEAR_ACC_Z_L-first_address) ahrspos_update.altitude = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_ALTITUDE_D_L - first_address) ahrspos_update.baro_pressure", "def zeroYaw(self): self.io_provider.write( IMURegisters.NAVX_REG_INTEGRATION_CTL, AHRSProtocol.NAVX_INTEGRATION_CTL_RESET_YAW ) self.notify_sink._yawResetComplete() def zeroDisplacement(self): self.io_provider.write(", "io_provider, update_rate_hz, notify_sink, board_capabilities): \"\"\" :param board_capabilities: must have the", "= [0]*12 class _BoardState: op_status = 0 sensor_status = 0", "modifications to this code must be accompanied by the \\License.txt", "#---------------------------------------------------------------------------- from ._impl import AHRSProtocol, IMUProtocol, IMURegisters from wpilib.timer import", "ahrspos_update.world_linear_accel_x = AHRSProtocol.decodeProtocolSignedThousandthsFloat(curr_data, IMURegisters.NAVX_REG_LINEAR_ACC_X_L-first_address) ahrspos_update.world_linear_accel_y = AHRSProtocol.decodeProtocolSignedThousandthsFloat(curr_data, IMURegisters.NAVX_REG_LINEAR_ACC_Y_L-first_address) ahrspos_update.world_linear_accel_z =", "IMUProtocol.GyroUpdate() self.ahrspos_update = AHRSProtocol.AHRSPosUpdate() self.board_state = _BoardState() self.board_id = _BoardId()", "is removed from the # 1/update_rate value to ensure samples", "ahrspos_update.disp_z = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_DISP_Z_I_L-first_address) self.notify_sink._setAHRSPosData(ahrspos_update, sensor_timestamp) else: self.notify_sink._setAHRSData(ahrspos_update, sensor_timestamp) board_state", "board_state = self.board_state board_state.cal_status = config[IMURegisters.NAVX_REG_CAL_STATUS] board_state.op_status = config[IMURegisters.NAVX_REG_OP_STATUS] board_state.selftest_status", "self.io_provider.read(IMURegisters.NAVX_REG_WHOAMI, IMURegisters.NAVX_REG_SENSOR_STATUS_H+1) except IOError as e: logger.warning(\"Error reading configuration data,", "1 return success def getCurrentData(self): first_address = IMURegisters.NAVX_REG_UPDATE_RATE_HZ displacement_registers =", "IMURegisters.NAVX_REG_QUAT_Z_L-first_address)/ 32768.0 if displacement_registers: ahrspos_update.vel_x = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_VEL_X_I_L-first_address) ahrspos_update.vel_y =", "data\") log_error = False else: log_error = True Timer.delay(update_rate) except", "may be modified and shared by FRC teams. Any #", "board_state = self.board_state board_state.cal_status = curr_data[IMURegisters.NAVX_REG_CAL_STATUS-first_address] board_state.op_status = curr_data[IMURegisters.NAVX_REG_OP_STATUS-first_address] board_state.selftest_status", "= curr_data[IMURegisters.NAVX_REG_OP_STATUS-first_address] board_state.selftest_status = curr_data[IMURegisters.NAVX_REG_SELFTEST_STATUS-first_address] board_state.sensor_status = AHRSProtocol.decodeBinaryUint16(curr_data,IMURegisters.NAVX_REG_SENSOR_STATUS_L-first_address) board_state.update_rate_hz =", "getting data\") log_error = False else: log_error = True Timer.delay(update_rate)", "_isBoardYawResetSupported, _isDisplacementSupported :param notify_sink: must have the following callable attributes:", "= 0 self.byte_count = 0 self.update_count = 0 self.last_sensor_timestamp =", "roborio/java/navx_frc/src/com/kauailabs/navx/frc/RegisterIO.java #---------------------------------------------------------------------------- # Copyright (c) <NAME> 2015. All Rights Reserved.", "Software - may be modified and shared by FRC teams.", "= update_rate_hz self.board_capabilities = board_capabilities self.notify_sink = notify_sink self.raw_data_update =", "self.io_provider.read(first_address, read_count) sensor_timestamp = AHRSProtocol.decodeBinaryUint32(curr_data, IMURegisters.NAVX_REG_TIMESTAMP_L_L-first_address) if sensor_timestamp == self.last_sensor_timestamp:", "log_error: logger.exception(\"Error getting data\") log_error = False else: log_error =", "Reserved. # # Created in support of Team 2465 (Kauaibots).", "0 self._stop = False def stop(self): self._stop = True def", "removed from the # 1/update_rate value to ensure samples are", "try: self.getCurrentData() except IOError: if log_error: logger.exception(\"Error getting data\") log_error", "Exception: logger.exception(\"Unhandled exception in NavX thread\") finally: logger.info(\"NavX i/o thread", "self.board_capabilities._isDisplacementSupported() # If firmware supports displacement data, acquire it -", "board_id.fw_ver_major = config[IMURegisters.NAVX_REG_FW_VER_MAJOR] board_id.fw_ver_minor = config[IMURegisters.NAVX_REG_FW_VER_MINOR] board_id.type = config[IMURegisters.NAVX_REG_WHOAMI] self.notify_sink._setBoardID(board_id)", "io thread starting\") try: self.io_provider.init() # initial device configuration self.setUpdateRateHz(self.update_rate_hz)", "= logging.getLogger('navx') __all__ = ['RegisterIO'] IO_TIMEOUT_SECONDS = 1.0 DELAY_OVERHEAD_SECONDS =", "# 1/update_rate value to ensure samples are not # dropped,", "self.io_provider.shutdown() def run(self): logger.info(\"NavX io thread starting\") try: self.io_provider.init() #", "be modified and shared by FRC teams. Any # modifications", "= AHRSProtocol.AHRSPosUpdate() self.board_state = _BoardState() self.board_id = _BoardId() self.last_update_time =", "in NavX thread\") finally: logger.info(\"NavX i/o thread exiting\") def getConfiguration(self):", "IMURegisters.NAVX_REG_YAW_L-first_address) ahrspos_update.pitch = AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_PITCH_L-first_address) ahrspos_update.roll = AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_ROLL_L-first_address) ahrspos_update.compass_heading", "logger.info(\"-- Firmware %s.%s\", self.board_id.fw_ver_major, self.board_id.fw_ver_minor) log_error = True # Calculate", "= IMURegisters.NAVX_REG_LAST + 1 - first_address else: read_count = IMURegisters.NAVX_REG_QUAT_OFFSET_Z_H", "= config[IMURegisters.NAVX_REG_FW_VER_MAJOR] board_id.fw_ver_minor = config[IMURegisters.NAVX_REG_FW_VER_MINOR] board_id.type = config[IMURegisters.NAVX_REG_WHOAMI] self.notify_sink._setBoardID(board_id) board_state", "= self.board_state board_state.cal_status = config[IMURegisters.NAVX_REG_CAL_STATUS] board_state.op_status = config[IMURegisters.NAVX_REG_OP_STATUS] board_state.selftest_status =", "IO Loop while not self._stop: if self.board_state.update_rate_hz != self.update_rate_hz: self.setUpdateRateHz(self.update_rate_hz)", "log_error = True # Calculate delay to match configured update", "<= IO_TIMEOUT_SECONDS def getByteCount(self): return self.byte_count def getUpdateCount(self): return self.update_count", "curr_data[IMURegisters.NAVX_REG_ACCEL_FSR_G] board_state.capability_flags= AHRSProtocol.decodeBinaryUint16(curr_data,IMURegisters.NAVX_REG_CAPABILITY_FLAGS_L-first_address) self.notify_sink._setBoardState(board_state) raw_data_update = self.raw_data_update raw_data_update.raw_gyro_x = AHRSProtocol.decodeBinaryInt16(curr_data,", "IMURegisters.NAVX_REG_GYRO_Z_L-first_address) raw_data_update.raw_accel_x = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_ACC_X_L-first_address) raw_data_update.raw_accel_y = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_ACC_Y_L-first_address) raw_data_update.raw_accel_z", "return self.byte_count def getUpdateCount(self): return self.update_count def setUpdateRateHz(self, update_rate_hz): self.io_provider.write(IMURegisters.NAVX_REG_UPDATE_RATE_HZ,", "attributes: _setYawPitchRoll, _setAHRSData, _setAHRSPosData, _setRawData, _setBoardID, _setBoardState, _yawResetComplete \"\"\" self.io_provider", "ahrspos_update.altitude = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_ALTITUDE_D_L - first_address) ahrspos_update.baro_pressure = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_PRESSURE_DL", "board_state.update_rate_hz = curr_data[IMURegisters.NAVX_REG_UPDATE_RATE_HZ-first_address] board_state.gyro_fsr_dps = AHRSProtocol.decodeBinaryUint16(curr_data,IMURegisters.NAVX_REG_GYRO_FSR_DPS_L) board_state.accel_fsr_g = curr_data[IMURegisters.NAVX_REG_ACCEL_FSR_G] board_state.capability_flags=", "= self.io_provider.read(first_address, read_count) sensor_timestamp = AHRSProtocol.decodeBinaryUint32(curr_data, IMURegisters.NAVX_REG_TIMESTAMP_L_L-first_address) if sensor_timestamp ==", "= IMURegisters.NAVX_REG_QUAT_OFFSET_Z_H + 1 - first_address curr_data = self.io_provider.read(first_address, read_count)", "1.0 DELAY_OVERHEAD_SECONDS = 0.004 class _BoardId: type = 0 hw_rev", "retry_count < 5 and not success: try: config = self.io_provider.read(IMURegisters.NAVX_REG_WHOAMI,", "getByteCount(self): return self.byte_count def getUpdateCount(self): return self.update_count def setUpdateRateHz(self, update_rate_hz):", "IMURegisters.NAVX_REG_VEL_X_I_L-first_address) ahrspos_update.vel_y = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_VEL_Y_I_L-first_address) ahrspos_update.vel_z = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_VEL_Z_I_L-first_address) ahrspos_update.disp_x", "board_state.selftest_status = curr_data[IMURegisters.NAVX_REG_SELFTEST_STATUS-first_address] board_state.sensor_status = AHRSProtocol.decodeBinaryUint16(curr_data,IMURegisters.NAVX_REG_SENSOR_STATUS_L-first_address) board_state.update_rate_hz = curr_data[IMURegisters.NAVX_REG_UPDATE_RATE_HZ-first_address] board_state.gyro_fsr_dps", "self.byte_count += len(curr_data) self.update_count += 1 def isConnected(self): time_since_last_update =", "= 0 cal_status = 0 selftest_status = 0 capability_flags =", "AHRSProtocol, IMUProtocol, IMURegisters from wpilib.timer import Timer import logging logger", "1.0/(self.update_rate_hz & 0xFF) if update_rate > DELAY_OVERHEAD_SECONDS: update_rate -= DELAY_OVERHEAD_SECONDS", "if log_error: logger.exception(\"Error getting data\") log_error = False else: log_error", "ahrspos_update.quaternionZ = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_QUAT_Z_L-first_address)/ 32768.0 if displacement_registers: ahrspos_update.vel_x = AHRSProtocol.decodeProtocol1616Float(curr_data,", ":param board_capabilities: must have the following callable attributes: _isOmniMountSupported, _isBoardYawResetSupported,", "additional time is removed from the # 1/update_rate value to", "success = True retry_count += 1 return success def getCurrentData(self):", "raw_data_update.raw_accel_x = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_ACC_X_L-first_address) raw_data_update.raw_accel_y = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_ACC_Y_L-first_address) raw_data_update.raw_accel_z =", "update_rate = 1.0/(self.update_rate_hz & 0xFF) if update_rate > DELAY_OVERHEAD_SECONDS: update_rate", "(%s)\", e) success = False Timer.delay(0.5) else: board_id = self.board_id", "ahrspos_update.quaternionW = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_QUAT_W_L-first_address)/ 32768.0 ahrspos_update.quaternionX = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_QUAT_X_L-first_address)/ 32768.0", "IMURegisters.NAVX_REG_DISP_X_I_L-first_address) ahrspos_update.disp_y = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_DISP_Y_I_L-first_address) ahrspos_update.disp_z = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_DISP_Z_I_L-first_address) self.notify_sink._setAHRSPosData(ahrspos_update,", "True def shutdown(self): self.io_provider.shutdown() def run(self): logger.info(\"NavX io thread starting\")", "self.notify_sink._setAHRSData(ahrspos_update, sensor_timestamp) board_state = self.board_state board_state.cal_status = curr_data[IMURegisters.NAVX_REG_CAL_STATUS-first_address] board_state.op_status =", "= config[IMURegisters.NAVX_REG_HW_REV] board_id.fw_ver_major = config[IMURegisters.NAVX_REG_FW_VER_MAJOR] board_id.fw_ver_minor = config[IMURegisters.NAVX_REG_FW_VER_MINOR] board_id.type =", "otherwise implement # similar (but potentially less accurate) calculations on", "raw_data_update.cal_mag_x = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_MAG_X_L-first_address) raw_data_update.cal_mag_y = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_MAG_Y_L-first_address) raw_data_update.cal_mag_z =", "+= 1 def isConnected(self): time_since_last_update = Timer.getFPGATimestamp() - self.last_update_time return", "in support of Team 2465 (Kauaibots). Go Purple Wave! #", "to this code must be accompanied by the \\License.txt file", "Team 2465 (Kauaibots). Go Purple Wave! # # Open Source", "self._stop = True def shutdown(self): self.io_provider.shutdown() def run(self): logger.info(\"NavX io", "samples are not # dropped, esp. at higher update rates.", "# validated: 2017-02-19 DS c5e3a8a9b642 roborio/java/navx_frc/src/com/kauailabs/navx/frc/RegisterIO.java #---------------------------------------------------------------------------- # Copyright (c)", "AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_GYRO_Z_L-first_address) raw_data_update.raw_accel_x = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_ACC_X_L-first_address) raw_data_update.raw_accel_y = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_ACC_Y_L-first_address)", "ahrspos_update.vel_x = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_VEL_X_I_L-first_address) ahrspos_update.vel_y = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_VEL_Y_I_L-first_address) ahrspos_update.vel_z =", "ahrspos_update.world_linear_accel_z = AHRSProtocol.decodeProtocolSignedThousandthsFloat(curr_data, IMURegisters.NAVX_REG_LINEAR_ACC_Z_L-first_address) ahrspos_update.altitude = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_ALTITUDE_D_L - first_address)", "rate: %shz (%.4fs)\", self.update_rate_hz, update_rate) # IO Loop while not", "update rate # Note: some additional time is removed from", "else: board_id = self.board_id board_id.hw_rev = config[IMURegisters.NAVX_REG_HW_REV] board_id.fw_ver_major = config[IMURegisters.NAVX_REG_FW_VER_MAJOR]", "= 0 fw_ver_minor = 0 fw_revision = 0 unique_id =", "ahrspos_update.quaternionX = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_QUAT_X_L-first_address)/ 32768.0 ahrspos_update.quaternionY = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_QUAT_Y_L-first_address)/ 32768.0", "AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_ACC_Y_L-first_address) raw_data_update.raw_accel_z = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_ACC_Z_L-first_address) raw_data_update.cal_mag_x = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_MAG_X_L-first_address)", "AHRSProtocol.decodeProtocolSignedThousandthsFloat(curr_data, IMURegisters.NAVX_REG_LINEAR_ACC_Y_L-first_address) ahrspos_update.world_linear_accel_z = AHRSProtocol.decodeProtocolSignedThousandthsFloat(curr_data, IMURegisters.NAVX_REG_LINEAR_ACC_Z_L-first_address) ahrspos_update.altitude = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_ALTITUDE_D_L", "notify_sink: must have the following callable attributes: _setYawPitchRoll, _setAHRSData, _setAHRSPosData,", "self.setUpdateRateHz(self.update_rate_hz) if not self.getConfiguration(): logger.warning(\"-- Did not get configuration data\")", "ahrspos_update.fused_heading = AHRSProtocol.decodeProtocolUnsignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_FUSED_HEADING_L-first_address) ahrspos_update.quaternionW = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_QUAT_W_L-first_address)/ 32768.0 ahrspos_update.quaternionX", "shutdown(self): self.io_provider.shutdown() def run(self): logger.info(\"NavX io thread starting\") try: self.io_provider.init()", "not success: try: config = self.io_provider.read(IMURegisters.NAVX_REG_WHOAMI, IMURegisters.NAVX_REG_SENSOR_STATUS_H+1) except IOError as", "self.notify_sink = notify_sink self.raw_data_update = IMUProtocol.GyroUpdate() self.ahrspos_update = AHRSProtocol.AHRSPosUpdate() self.board_state", "return time_since_last_update <= IO_TIMEOUT_SECONDS def getByteCount(self): return self.byte_count def getUpdateCount(self):", "are not # dropped, esp. at higher update rates. update_rate", "= Timer.getFPGATimestamp() - self.last_update_time return time_since_last_update <= IO_TIMEOUT_SECONDS def getByteCount(self):", "try: config = self.io_provider.read(IMURegisters.NAVX_REG_WHOAMI, IMURegisters.NAVX_REG_SENSOR_STATUS_H+1) except IOError as e: logger.warning(\"Error", "curr_data[IMURegisters.NAVX_REG_CAL_STATUS] ahrspos_update.sensor_status = curr_data[IMURegisters.NAVX_REG_SENSOR_STATUS_L - first_address] ahrspos_update.yaw = AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_YAW_L-first_address)", "dropped, esp. at higher update rates. update_rate = 1.0/(self.update_rate_hz &", "time is removed from the # 1/update_rate value to ensure", "+= len(curr_data) self.update_count += 1 def isConnected(self): time_since_last_update = Timer.getFPGATimestamp()", "= AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_PRESSURE_DL - first_address) ahrspos_update.fused_heading = AHRSProtocol.decodeProtocolUnsignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_FUSED_HEADING_L-first_address) ahrspos_update.quaternionW", "= 0 class RegisterIO: def __init__(self, io_provider, update_rate_hz, notify_sink, board_capabilities):", "config[IMURegisters.NAVX_REG_UPDATE_RATE_HZ] board_state.capability_flags = AHRSProtocol.decodeBinaryUint16(config,IMURegisters.NAVX_REG_CAPABILITY_FLAGS_L) self.notify_sink._setBoardState(board_state) success = True retry_count +=", "and not success: try: config = self.io_provider.read(IMURegisters.NAVX_REG_WHOAMI, IMURegisters.NAVX_REG_SENSOR_STATUS_H+1) except IOError", "AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_VEL_Z_I_L-first_address) ahrspos_update.disp_x = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_DISP_X_I_L-first_address) ahrspos_update.disp_y = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_DISP_Y_I_L-first_address)", "self.update_count += 1 def isConnected(self): time_since_last_update = Timer.getFPGATimestamp() - self.last_update_time", "not get configuration data\") else: logger.info(\"-- Board is %s (rev", "implement # similar (but potentially less accurate) calculations on this", "higher update rates. update_rate = 1.0/(self.update_rate_hz & 0xFF) if update_rate", "raw_data_update.cal_mag_z = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_MAG_Z_L-first_address) raw_data_update.mpu_temp_c = ahrspos_update.mpu_temp self.notify_sink._setRawData(raw_data_update, sensor_timestamp) self.last_update_time", "self.board_id = _BoardId() self.last_update_time = 0 self.byte_count = 0 self.update_count", "if displacement_registers: ahrspos_update.vel_x = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_VEL_X_I_L-first_address) ahrspos_update.vel_y = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_VEL_Y_I_L-first_address)", "Wave! # # Open Source Software - may be modified", "def getByteCount(self): return self.byte_count def getUpdateCount(self): return self.update_count def setUpdateRateHz(self,", "Rights Reserved. # # Created in support of Team 2465", "import logging logger = logging.getLogger('navx') __all__ = ['RegisterIO'] IO_TIMEOUT_SECONDS =", "0 class RegisterIO: def __init__(self, io_provider, update_rate_hz, notify_sink, board_capabilities): \"\"\"", "0 accel_fsr_g = 0 gyro_fsr_dps = 0 class RegisterIO: def", "logging logger = logging.getLogger('navx') __all__ = ['RegisterIO'] IO_TIMEOUT_SECONDS = 1.0", "AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_ALTITUDE_D_L - first_address) ahrspos_update.baro_pressure = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_PRESSURE_DL - first_address)", "ahrspos_update.mpu_temp_c = AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_MPU_TEMP_C_L - first_address) ahrspos_update.world_linear_accel_x = AHRSProtocol.decodeProtocolSignedThousandthsFloat(curr_data, IMURegisters.NAVX_REG_LINEAR_ACC_X_L-first_address)", "config[IMURegisters.NAVX_REG_HW_REV] board_id.fw_ver_major = config[IMURegisters.NAVX_REG_FW_VER_MAJOR] board_id.fw_ver_minor = config[IMURegisters.NAVX_REG_FW_VER_MINOR] board_id.type = config[IMURegisters.NAVX_REG_WHOAMI]", "= Timer.getFPGATimestamp() self.byte_count += len(curr_data) self.update_count += 1 def isConnected(self):", "starting\") try: self.io_provider.init() # initial device configuration self.setUpdateRateHz(self.update_rate_hz) if not", "= config[IMURegisters.NAVX_REG_WHOAMI] self.notify_sink._setBoardID(board_id) board_state = self.board_state board_state.cal_status = config[IMURegisters.NAVX_REG_CAL_STATUS] board_state.op_status", "board_id = self.board_id board_id.hw_rev = config[IMURegisters.NAVX_REG_HW_REV] board_id.fw_ver_major = config[IMURegisters.NAVX_REG_FW_VER_MAJOR] board_id.fw_ver_minor", "= config[IMURegisters.NAVX_REG_FW_VER_MINOR] board_id.type = config[IMURegisters.NAVX_REG_WHOAMI] self.notify_sink._setBoardID(board_id) board_state = self.board_state board_state.cal_status", "< 5 and not success: try: config = self.io_provider.read(IMURegisters.NAVX_REG_WHOAMI, IMURegisters.NAVX_REG_SENSOR_STATUS_H+1)", "= AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_QUAT_Y_L-first_address)/ 32768.0 ahrspos_update.quaternionZ = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_QUAT_Z_L-first_address)/ 32768.0 if", "= AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_ACC_Y_L-first_address) raw_data_update.raw_accel_z = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_ACC_Z_L-first_address) raw_data_update.cal_mag_x = AHRSProtocol.decodeBinaryInt16(curr_data,", "0 hw_rev = 0 fw_ver_major = 0 fw_ver_minor = 0", "= AHRSProtocol.decodeProtocolSignedThousandthsFloat(curr_data, IMURegisters.NAVX_REG_LINEAR_ACC_Y_L-first_address) ahrspos_update.world_linear_accel_z = AHRSProtocol.decodeProtocolSignedThousandthsFloat(curr_data, IMURegisters.NAVX_REG_LINEAR_ACC_Z_L-first_address) ahrspos_update.altitude = AHRSProtocol.decodeProtocol1616Float(curr_data,", "calculations on this processor. if displacement_registers: read_count = IMURegisters.NAVX_REG_LAST +", "= AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_DISP_Y_I_L-first_address) ahrspos_update.disp_z = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_DISP_Z_I_L-first_address) self.notify_sink._setAHRSPosData(ahrspos_update, sensor_timestamp) else:", "= curr_data[IMURegisters.NAVX_REG_SELFTEST_STATUS-first_address] board_state.sensor_status = AHRSProtocol.decodeBinaryUint16(curr_data,IMURegisters.NAVX_REG_SENSOR_STATUS_L-first_address) board_state.update_rate_hz = curr_data[IMURegisters.NAVX_REG_UPDATE_RATE_HZ-first_address] board_state.gyro_fsr_dps =", "root directory of the project #---------------------------------------------------------------------------- from ._impl import AHRSProtocol,", "\"\"\" self.io_provider = io_provider self.update_rate_hz = update_rate_hz self.board_capabilities = board_capabilities", "1 - first_address else: read_count = IMURegisters.NAVX_REG_QUAT_OFFSET_Z_H + 1 -", "32768.0 ahrspos_update.quaternionX = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_QUAT_X_L-first_address)/ 32768.0 ahrspos_update.quaternionY = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_QUAT_Y_L-first_address)/", "self.board_id board_id.hw_rev = config[IMURegisters.NAVX_REG_HW_REV] board_id.fw_ver_major = config[IMURegisters.NAVX_REG_FW_VER_MAJOR] board_id.fw_ver_minor = config[IMURegisters.NAVX_REG_FW_VER_MINOR]", "displacement_registers: ahrspos_update.vel_x = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_VEL_X_I_L-first_address) ahrspos_update.vel_y = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_VEL_Y_I_L-first_address) ahrspos_update.vel_z", "following callable attributes: _isOmniMountSupported, _isBoardYawResetSupported, _isDisplacementSupported :param notify_sink: must have", "Go Purple Wave! # # Open Source Software - may", "def __init__(self, io_provider, update_rate_hz, notify_sink, board_capabilities): \"\"\" :param board_capabilities: must", "is %s (rev %s)\", IMURegisters.model_type(self.board_id.type), self.board_id.hw_rev) logger.info(\"-- Firmware %s.%s\", self.board_id.fw_ver_major,", "this code must be accompanied by the \\License.txt file #", "less accurate) calculations on this processor. if displacement_registers: read_count =", "AHRSProtocol.decodeBinaryUint32(curr_data, IMURegisters.NAVX_REG_TIMESTAMP_L_L-first_address) if sensor_timestamp == self.last_sensor_timestamp: return self.last_sensor_timestamp = sensor_timestamp", "= AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_DISP_Z_I_L-first_address) self.notify_sink._setAHRSPosData(ahrspos_update, sensor_timestamp) else: self.notify_sink._setAHRSData(ahrspos_update, sensor_timestamp) board_state =", "board_id.hw_rev = config[IMURegisters.NAVX_REG_HW_REV] board_id.fw_ver_major = config[IMURegisters.NAVX_REG_FW_VER_MAJOR] board_id.fw_ver_minor = config[IMURegisters.NAVX_REG_FW_VER_MINOR] board_id.type", "update_rate_hz, notify_sink, board_capabilities): \"\"\" :param board_capabilities: must have the following", "= io_provider self.update_rate_hz = update_rate_hz self.board_capabilities = board_capabilities self.notify_sink =", "= AHRSProtocol.decodeProtocolSignedThousandthsFloat(curr_data, IMURegisters.NAVX_REG_LINEAR_ACC_X_L-first_address) ahrspos_update.world_linear_accel_y = AHRSProtocol.decodeProtocolSignedThousandthsFloat(curr_data, IMURegisters.NAVX_REG_LINEAR_ACC_Y_L-first_address) ahrspos_update.world_linear_accel_z = AHRSProtocol.decodeProtocolSignedThousandthsFloat(curr_data,", "curr_data[IMURegisters.NAVX_REG_OP_STATUS-first_address] board_state.selftest_status = curr_data[IMURegisters.NAVX_REG_SELFTEST_STATUS-first_address] board_state.sensor_status = AHRSProtocol.decodeBinaryUint16(curr_data,IMURegisters.NAVX_REG_SENSOR_STATUS_L-first_address) board_state.update_rate_hz = curr_data[IMURegisters.NAVX_REG_UPDATE_RATE_HZ-first_address]", "the project #---------------------------------------------------------------------------- from ._impl import AHRSProtocol, IMUProtocol, IMURegisters from", "raw_data_update.cal_mag_y = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_MAG_Y_L-first_address) raw_data_update.cal_mag_z = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_MAG_Z_L-first_address) raw_data_update.mpu_temp_c =", "read_count = IMURegisters.NAVX_REG_LAST + 1 - first_address else: read_count =", "Any # modifications to this code must be accompanied by", "= AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_YAW_L-first_address) ahrspos_update.pitch = AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_PITCH_L-first_address) ahrspos_update.roll = AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data,", "self.update_rate_hz: self.setUpdateRateHz(self.update_rate_hz) try: self.getCurrentData() except IOError: if log_error: logger.exception(\"Error getting", "0 fw_ver_major = 0 fw_ver_minor = 0 fw_revision = 0", "board_state.op_status = config[IMURegisters.NAVX_REG_OP_STATUS] board_state.selftest_status = config[IMURegisters.NAVX_REG_SELFTEST_STATUS] board_state.sensor_status = AHRSProtocol.decodeBinaryUint16(config,IMURegisters.NAVX_REG_SENSOR_STATUS_L) board_state.gyro_fsr_dps", "raw_data_update.raw_accel_z = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_ACC_Z_L-first_address) raw_data_update.cal_mag_x = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_MAG_X_L-first_address) raw_data_update.cal_mag_y =", "= AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_VEL_Z_I_L-first_address) ahrspos_update.disp_x = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_DISP_X_I_L-first_address) ahrspos_update.disp_y = AHRSProtocol.decodeProtocol1616Float(curr_data,", "notify_sink self.raw_data_update = IMUProtocol.GyroUpdate() self.ahrspos_update = AHRSProtocol.AHRSPosUpdate() self.board_state = _BoardState()", "board_state.sensor_status = AHRSProtocol.decodeBinaryUint16(config,IMURegisters.NAVX_REG_SENSOR_STATUS_L) board_state.gyro_fsr_dps = AHRSProtocol.decodeBinaryUint16(config,IMURegisters.NAVX_REG_GYRO_FSR_DPS_L) board_state.accel_fsr_g = config[IMURegisters.NAVX_REG_ACCEL_FSR_G] board_state.update_rate_hz", "curr_data[IMURegisters.NAVX_REG_SELFTEST_STATUS - first_address] ahrspos_update.cal_status = curr_data[IMURegisters.NAVX_REG_CAL_STATUS] ahrspos_update.sensor_status = curr_data[IMURegisters.NAVX_REG_SENSOR_STATUS_L -", "(but potentially less accurate) calculations on this processor. if displacement_registers:", "= curr_data[IMURegisters.NAVX_REG_SENSOR_STATUS_L - first_address] ahrspos_update.yaw = AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_YAW_L-first_address) ahrspos_update.pitch =", "to ensure samples are not # dropped, esp. at higher", ") self.notify_sink._yawResetComplete() def zeroDisplacement(self): self.io_provider.write( IMURegisters.NAVX_REG_INTEGRATION_CTL, (AHRSProtocol.NAVX_INTEGRATION_CTL_RESET_DISP_X | AHRSProtocol.NAVX_INTEGRATION_CTL_RESET_DISP_Y |", "= notify_sink self.raw_data_update = IMUProtocol.GyroUpdate() self.ahrspos_update = AHRSProtocol.AHRSPosUpdate() self.board_state =", "first_address) ahrspos_update.fused_heading = AHRSProtocol.decodeProtocolUnsignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_FUSED_HEADING_L-first_address) ahrspos_update.quaternionW = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_QUAT_W_L-first_address)/ 32768.0", "Firmware %s.%s\", self.board_id.fw_ver_major, self.board_id.fw_ver_minor) log_error = True # Calculate delay", "time_since_last_update = Timer.getFPGATimestamp() - self.last_update_time return time_since_last_update <= IO_TIMEOUT_SECONDS def", "IMURegisters from wpilib.timer import Timer import logging logger = logging.getLogger('navx')", "first_address) ahrspos_update.world_linear_accel_x = AHRSProtocol.decodeProtocolSignedThousandthsFloat(curr_data, IMURegisters.NAVX_REG_LINEAR_ACC_X_L-first_address) ahrspos_update.world_linear_accel_y = AHRSProtocol.decodeProtocolSignedThousandthsFloat(curr_data, IMURegisters.NAVX_REG_LINEAR_ACC_Y_L-first_address) ahrspos_update.world_linear_accel_z", "AHRSProtocol.decodeBinaryUint16(config,IMURegisters.NAVX_REG_CAPABILITY_FLAGS_L) self.notify_sink._setBoardState(board_state) success = True retry_count += 1 return success", "All Rights Reserved. # # Created in support of Team", "AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_QUAT_X_L-first_address)/ 32768.0 ahrspos_update.quaternionY = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_QUAT_Y_L-first_address)/ 32768.0 ahrspos_update.quaternionZ =", "ahrspos_update.roll = AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_ROLL_L-first_address) ahrspos_update.compass_heading = AHRSProtocol.decodeProtocolUnsignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_HEADING_L-first_address) ahrspos_update.mpu_temp_c =", "cal_status = 0 selftest_status = 0 capability_flags = 0 update_rate_hz", "= _BoardId() self.last_update_time = 0 self.byte_count = 0 self.update_count =", "accompanied by the \\License.txt file # in the root directory", ":param notify_sink: must have the following callable attributes: _setYawPitchRoll, _setAHRSData,", "= AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_MAG_X_L-first_address) raw_data_update.cal_mag_y = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_MAG_Y_L-first_address) raw_data_update.cal_mag_z = AHRSProtocol.decodeBinaryInt16(curr_data,", "0 while retry_count < 5 and not success: try: config", "first_address curr_data = self.io_provider.read(first_address, read_count) sensor_timestamp = AHRSProtocol.decodeBinaryUint32(curr_data, IMURegisters.NAVX_REG_TIMESTAMP_L_L-first_address) if", "= True def shutdown(self): self.io_provider.shutdown() def run(self): logger.info(\"NavX io thread", "# Calculate delay to match configured update rate # Note:", "success = False retry_count = 0 while retry_count < 5", "AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_YAW_L-first_address) ahrspos_update.pitch = AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_PITCH_L-first_address) ahrspos_update.roll = AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_ROLL_L-first_address)", "logger.exception(\"Error getting data\") log_error = False else: log_error = True", "Did not get configuration data\") else: logger.info(\"-- Board is %s", "self.byte_count def getUpdateCount(self): return self.update_count def setUpdateRateHz(self, update_rate_hz): self.io_provider.write(IMURegisters.NAVX_REG_UPDATE_RATE_HZ, update_rate_hz)", "# If firmware supports displacement data, acquire it - otherwise", "= AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_ACC_Z_L-first_address) raw_data_update.cal_mag_x = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_MAG_X_L-first_address) raw_data_update.cal_mag_y = AHRSProtocol.decodeBinaryInt16(curr_data,", "Timer.delay(update_rate) except Exception: logger.exception(\"Unhandled exception in NavX thread\") finally: logger.info(\"NavX", "AHRSProtocol.decodeBinaryUint16(curr_data,IMURegisters.NAVX_REG_SENSOR_STATUS_L-first_address) board_state.update_rate_hz = curr_data[IMURegisters.NAVX_REG_UPDATE_RATE_HZ-first_address] board_state.gyro_fsr_dps = AHRSProtocol.decodeBinaryUint16(curr_data,IMURegisters.NAVX_REG_GYRO_FSR_DPS_L) board_state.accel_fsr_g = curr_data[IMURegisters.NAVX_REG_ACCEL_FSR_G]", "# Note: some additional time is removed from the #", "= ahrspos_update.mpu_temp self.notify_sink._setRawData(raw_data_update, sensor_timestamp) self.last_update_time = Timer.getFPGATimestamp() self.byte_count += len(curr_data)", "unique_id = [0]*12 class _BoardState: op_status = 0 sensor_status =", "AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_MPU_TEMP_C_L - first_address) ahrspos_update.world_linear_accel_x = AHRSProtocol.decodeProtocolSignedThousandthsFloat(curr_data, IMURegisters.NAVX_REG_LINEAR_ACC_X_L-first_address) ahrspos_update.world_linear_accel_y =", "sensor_timestamp) self.last_update_time = Timer.getFPGATimestamp() self.byte_count += len(curr_data) self.update_count += 1", "self.last_update_time = Timer.getFPGATimestamp() self.byte_count += len(curr_data) self.update_count += 1 def", "self.io_provider.init() # initial device configuration self.setUpdateRateHz(self.update_rate_hz) if not self.getConfiguration(): logger.warning(\"--", "Calculate delay to match configured update rate # Note: some", "- otherwise implement # similar (but potentially less accurate) calculations", "board_state.gyro_fsr_dps = AHRSProtocol.decodeBinaryUint16(config,IMURegisters.NAVX_REG_GYRO_FSR_DPS_L) board_state.accel_fsr_g = config[IMURegisters.NAVX_REG_ACCEL_FSR_G] board_state.update_rate_hz = config[IMURegisters.NAVX_REG_UPDATE_RATE_HZ] board_state.capability_flags", "value to ensure samples are not # dropped, esp. at", "self.board_state board_state.cal_status = curr_data[IMURegisters.NAVX_REG_CAL_STATUS-first_address] board_state.op_status = curr_data[IMURegisters.NAVX_REG_OP_STATUS-first_address] board_state.selftest_status = curr_data[IMURegisters.NAVX_REG_SELFTEST_STATUS-first_address]", "def isConnected(self): time_since_last_update = Timer.getFPGATimestamp() - self.last_update_time return time_since_last_update <=", "file # in the root directory of the project #----------------------------------------------------------------------------", "_isDisplacementSupported :param notify_sink: must have the following callable attributes: _setYawPitchRoll,", "\\License.txt file # in the root directory of the project", "IMURegisters.NAVX_REG_ROLL_L-first_address) ahrspos_update.compass_heading = AHRSProtocol.decodeProtocolUnsignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_HEADING_L-first_address) ahrspos_update.mpu_temp_c = AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_MPU_TEMP_C_L -", "AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_MAG_Z_L-first_address) raw_data_update.mpu_temp_c = ahrspos_update.mpu_temp self.notify_sink._setRawData(raw_data_update, sensor_timestamp) self.last_update_time = Timer.getFPGATimestamp()", "= AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_DISP_X_I_L-first_address) ahrspos_update.disp_y = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_DISP_Y_I_L-first_address) ahrspos_update.disp_z = AHRSProtocol.decodeProtocol1616Float(curr_data,", "AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_VEL_Y_I_L-first_address) ahrspos_update.vel_z = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_VEL_Z_I_L-first_address) ahrspos_update.disp_x = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_DISP_X_I_L-first_address)", "data, acquire it - otherwise implement # similar (but potentially", "AHRSProtocol.decodeBinaryUint16(config,IMURegisters.NAVX_REG_GYRO_FSR_DPS_L) board_state.accel_fsr_g = config[IMURegisters.NAVX_REG_ACCEL_FSR_G] board_state.update_rate_hz = config[IMURegisters.NAVX_REG_UPDATE_RATE_HZ] board_state.capability_flags = AHRSProtocol.decodeBinaryUint16(config,IMURegisters.NAVX_REG_CAPABILITY_FLAGS_L)", "= sensor_timestamp ahrspos_update = self.ahrspos_update ahrspos_update.op_status = curr_data[IMURegisters.NAVX_REG_OP_STATUS - first_address]", "data, retrying (%s)\", e) success = False Timer.delay(0.5) else: board_id", "as e: logger.warning(\"Error reading configuration data, retrying (%s)\", e) success", "thread starting\") try: self.io_provider.init() # initial device configuration self.setUpdateRateHz(self.update_rate_hz) if", "board_state.op_status = curr_data[IMURegisters.NAVX_REG_OP_STATUS-first_address] board_state.selftest_status = curr_data[IMURegisters.NAVX_REG_SELFTEST_STATUS-first_address] board_state.sensor_status = AHRSProtocol.decodeBinaryUint16(curr_data,IMURegisters.NAVX_REG_SENSOR_STATUS_L-first_address) board_state.update_rate_hz", "= 0 fw_ver_major = 0 fw_ver_minor = 0 fw_revision =", "callable attributes: _isOmniMountSupported, _isBoardYawResetSupported, _isDisplacementSupported :param notify_sink: must have the", "curr_data[IMURegisters.NAVX_REG_SELFTEST_STATUS-first_address] board_state.sensor_status = AHRSProtocol.decodeBinaryUint16(curr_data,IMURegisters.NAVX_REG_SENSOR_STATUS_L-first_address) board_state.update_rate_hz = curr_data[IMURegisters.NAVX_REG_UPDATE_RATE_HZ-first_address] board_state.gyro_fsr_dps = AHRSProtocol.decodeBinaryUint16(curr_data,IMURegisters.NAVX_REG_GYRO_FSR_DPS_L)", "= config[IMURegisters.NAVX_REG_ACCEL_FSR_G] board_state.update_rate_hz = config[IMURegisters.NAVX_REG_UPDATE_RATE_HZ] board_state.capability_flags = AHRSProtocol.decodeBinaryUint16(config,IMURegisters.NAVX_REG_CAPABILITY_FLAGS_L) self.notify_sink._setBoardState(board_state) success", "it - otherwise implement # similar (but potentially less accurate)", "curr_data[IMURegisters.NAVX_REG_UPDATE_RATE_HZ-first_address] board_state.gyro_fsr_dps = AHRSProtocol.decodeBinaryUint16(curr_data,IMURegisters.NAVX_REG_GYRO_FSR_DPS_L) board_state.accel_fsr_g = curr_data[IMURegisters.NAVX_REG_ACCEL_FSR_G] board_state.capability_flags= AHRSProtocol.decodeBinaryUint16(curr_data,IMURegisters.NAVX_REG_CAPABILITY_FLAGS_L-first_address) self.notify_sink._setBoardState(board_state)", "Copyright (c) <NAME> 2015. All Rights Reserved. # # Created", "try: self.io_provider.init() # initial device configuration self.setUpdateRateHz(self.update_rate_hz) if not self.getConfiguration():", "# similar (but potentially less accurate) calculations on this processor.", "_setBoardID, _setBoardState, _yawResetComplete \"\"\" self.io_provider = io_provider self.update_rate_hz = update_rate_hz", "data\") else: logger.info(\"-- Board is %s (rev %s)\", IMURegisters.model_type(self.board_id.type), self.board_id.hw_rev)", "configuration data, retrying (%s)\", e) success = False Timer.delay(0.5) else:", "0 self.update_count = 0 self.last_sensor_timestamp = 0 self._stop = False", "config[IMURegisters.NAVX_REG_OP_STATUS] board_state.selftest_status = config[IMURegisters.NAVX_REG_SELFTEST_STATUS] board_state.sensor_status = AHRSProtocol.decodeBinaryUint16(config,IMURegisters.NAVX_REG_SENSOR_STATUS_L) board_state.gyro_fsr_dps = AHRSProtocol.decodeBinaryUint16(config,IMURegisters.NAVX_REG_GYRO_FSR_DPS_L)", "acquire it - otherwise implement # similar (but potentially less", "and shared by FRC teams. Any # modifications to this", "update_rate) # IO Loop while not self._stop: if self.board_state.update_rate_hz !=", "= AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_ALTITUDE_D_L - first_address) ahrspos_update.baro_pressure = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_PRESSURE_DL -", "delay to match configured update rate # Note: some additional", "> DELAY_OVERHEAD_SECONDS: update_rate -= DELAY_OVERHEAD_SECONDS logger.info(\"-- Update rate: %shz (%.4fs)\",", "stop(self): self._stop = True def shutdown(self): self.io_provider.shutdown() def run(self): logger.info(\"NavX", "- may be modified and shared by FRC teams. Any", "self.notify_sink._setBoardState(board_state) raw_data_update = self.raw_data_update raw_data_update.raw_gyro_x = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_GYRO_X_L-first_address) raw_data_update.raw_gyro_y =", "curr_data[IMURegisters.NAVX_REG_CAL_STATUS-first_address] board_state.op_status = curr_data[IMURegisters.NAVX_REG_OP_STATUS-first_address] board_state.selftest_status = curr_data[IMURegisters.NAVX_REG_SELFTEST_STATUS-first_address] board_state.sensor_status = AHRSProtocol.decodeBinaryUint16(curr_data,IMURegisters.NAVX_REG_SENSOR_STATUS_L-first_address)", "= 1.0 DELAY_OVERHEAD_SECONDS = 0.004 class _BoardId: type = 0", "= 0 self.last_sensor_timestamp = 0 self._stop = False def stop(self):", "logger.exception(\"Unhandled exception in NavX thread\") finally: logger.info(\"NavX i/o thread exiting\")", "0 gyro_fsr_dps = 0 class RegisterIO: def __init__(self, io_provider, update_rate_hz,", "= False def stop(self): self._stop = True def shutdown(self): self.io_provider.shutdown()", "self.getConfiguration(): logger.warning(\"-- Did not get configuration data\") else: logger.info(\"-- Board", "by the \\License.txt file # in the root directory of", "ahrspos_update.quaternionY = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_QUAT_Y_L-first_address)/ 32768.0 ahrspos_update.quaternionZ = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_QUAT_Z_L-first_address)/ 32768.0", "__all__ = ['RegisterIO'] IO_TIMEOUT_SECONDS = 1.0 DELAY_OVERHEAD_SECONDS = 0.004 class", "self.raw_data_update = IMUProtocol.GyroUpdate() self.ahrspos_update = AHRSProtocol.AHRSPosUpdate() self.board_state = _BoardState() self.board_id", "first_address] ahrspos_update.selftest_status = curr_data[IMURegisters.NAVX_REG_SELFTEST_STATUS - first_address] ahrspos_update.cal_status = curr_data[IMURegisters.NAVX_REG_CAL_STATUS] ahrspos_update.sensor_status", "modified and shared by FRC teams. Any # modifications to", "board_state.cal_status = curr_data[IMURegisters.NAVX_REG_CAL_STATUS-first_address] board_state.op_status = curr_data[IMURegisters.NAVX_REG_OP_STATUS-first_address] board_state.selftest_status = curr_data[IMURegisters.NAVX_REG_SELFTEST_STATUS-first_address] board_state.sensor_status", "callable attributes: _setYawPitchRoll, _setAHRSData, _setAHRSPosData, _setRawData, _setBoardID, _setBoardState, _yawResetComplete \"\"\"", "len(curr_data) self.update_count += 1 def isConnected(self): time_since_last_update = Timer.getFPGATimestamp() -", "# Open Source Software - may be modified and shared", "= 0 fw_revision = 0 unique_id = [0]*12 class _BoardState:", "_yawResetComplete \"\"\" self.io_provider = io_provider self.update_rate_hz = update_rate_hz self.board_capabilities =", "IOError as e: logger.warning(\"Error reading configuration data, retrying (%s)\", e)", "AHRSProtocol.decodeBinaryUint16(curr_data,IMURegisters.NAVX_REG_GYRO_FSR_DPS_L) board_state.accel_fsr_g = curr_data[IMURegisters.NAVX_REG_ACCEL_FSR_G] board_state.capability_flags= AHRSProtocol.decodeBinaryUint16(curr_data,IMURegisters.NAVX_REG_CAPABILITY_FLAGS_L-first_address) self.notify_sink._setBoardState(board_state) raw_data_update = self.raw_data_update", "update_rate -= DELAY_OVERHEAD_SECONDS logger.info(\"-- Update rate: %shz (%.4fs)\", self.update_rate_hz, update_rate)", "self.board_capabilities = board_capabilities self.notify_sink = notify_sink self.raw_data_update = IMUProtocol.GyroUpdate() self.ahrspos_update", "IMURegisters.NAVX_REG_PRESSURE_DL - first_address) ahrspos_update.fused_heading = AHRSProtocol.decodeProtocolUnsignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_FUSED_HEADING_L-first_address) ahrspos_update.quaternionW = AHRSProtocol.decodeBinaryInt16(curr_data,", "['RegisterIO'] IO_TIMEOUT_SECONDS = 1.0 DELAY_OVERHEAD_SECONDS = 0.004 class _BoardId: type", "ahrspos_update.vel_z = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_VEL_Z_I_L-first_address) ahrspos_update.disp_x = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_DISP_X_I_L-first_address) ahrspos_update.disp_y =", "update_rate_hz): self.io_provider.write(IMURegisters.NAVX_REG_UPDATE_RATE_HZ, update_rate_hz) def zeroYaw(self): self.io_provider.write( IMURegisters.NAVX_REG_INTEGRATION_CTL, AHRSProtocol.NAVX_INTEGRATION_CTL_RESET_YAW ) self.notify_sink._yawResetComplete()", "Board is %s (rev %s)\", IMURegisters.model_type(self.board_id.type), self.board_id.hw_rev) logger.info(\"-- Firmware %s.%s\",", "reading configuration data, retrying (%s)\", e) success = False Timer.delay(0.5)", "first_address = IMURegisters.NAVX_REG_UPDATE_RATE_HZ displacement_registers = self.board_capabilities._isDisplacementSupported() # If firmware supports", "IMURegisters.NAVX_REG_GYRO_Y_L-first_address) raw_data_update.raw_gyro_z = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_GYRO_Z_L-first_address) raw_data_update.raw_accel_x = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_ACC_X_L-first_address) raw_data_update.raw_accel_y", "logger.warning(\"-- Did not get configuration data\") else: logger.info(\"-- Board is", "AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_MAG_X_L-first_address) raw_data_update.cal_mag_y = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_MAG_Y_L-first_address) raw_data_update.cal_mag_z = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_MAG_Z_L-first_address)", "IMURegisters.NAVX_REG_VEL_Y_I_L-first_address) ahrspos_update.vel_z = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_VEL_Z_I_L-first_address) ahrspos_update.disp_x = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_DISP_X_I_L-first_address) ahrspos_update.disp_y", "\"\"\" :param board_capabilities: must have the following callable attributes: _isOmniMountSupported,", "#---------------------------------------------------------------------------- # Copyright (c) <NAME> 2015. All Rights Reserved. #", "= config[IMURegisters.NAVX_REG_SELFTEST_STATUS] board_state.sensor_status = AHRSProtocol.decodeBinaryUint16(config,IMURegisters.NAVX_REG_SENSOR_STATUS_L) board_state.gyro_fsr_dps = AHRSProtocol.decodeBinaryUint16(config,IMURegisters.NAVX_REG_GYRO_FSR_DPS_L) board_state.accel_fsr_g =", "IMURegisters.NAVX_REG_LINEAR_ACC_Y_L-first_address) ahrspos_update.world_linear_accel_z = AHRSProtocol.decodeProtocolSignedThousandthsFloat(curr_data, IMURegisters.NAVX_REG_LINEAR_ACC_Z_L-first_address) ahrspos_update.altitude = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_ALTITUDE_D_L -", "IOError: if log_error: logger.exception(\"Error getting data\") log_error = False else:", "success def getCurrentData(self): first_address = IMURegisters.NAVX_REG_UPDATE_RATE_HZ displacement_registers = self.board_capabilities._isDisplacementSupported() #", "= self.board_state board_state.cal_status = curr_data[IMURegisters.NAVX_REG_CAL_STATUS-first_address] board_state.op_status = curr_data[IMURegisters.NAVX_REG_OP_STATUS-first_address] board_state.selftest_status =", "AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_GYRO_Y_L-first_address) raw_data_update.raw_gyro_z = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_GYRO_Z_L-first_address) raw_data_update.raw_accel_x = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_ACC_X_L-first_address)", "IMURegisters.NAVX_REG_MAG_Y_L-first_address) raw_data_update.cal_mag_z = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_MAG_Z_L-first_address) raw_data_update.mpu_temp_c = ahrspos_update.mpu_temp self.notify_sink._setRawData(raw_data_update, sensor_timestamp)", "ahrspos_update.cal_status = curr_data[IMURegisters.NAVX_REG_CAL_STATUS] ahrspos_update.sensor_status = curr_data[IMURegisters.NAVX_REG_SENSOR_STATUS_L - first_address] ahrspos_update.yaw =", "IMURegisters.model_type(self.board_id.type), self.board_id.hw_rev) logger.info(\"-- Firmware %s.%s\", self.board_id.fw_ver_major, self.board_id.fw_ver_minor) log_error = True", "wpilib.timer import Timer import logging logger = logging.getLogger('navx') __all__ =", "config[IMURegisters.NAVX_REG_FW_VER_MINOR] board_id.type = config[IMURegisters.NAVX_REG_WHOAMI] self.notify_sink._setBoardID(board_id) board_state = self.board_state board_state.cal_status =", "board_state.gyro_fsr_dps = AHRSProtocol.decodeBinaryUint16(curr_data,IMURegisters.NAVX_REG_GYRO_FSR_DPS_L) board_state.accel_fsr_g = curr_data[IMURegisters.NAVX_REG_ACCEL_FSR_G] board_state.capability_flags= AHRSProtocol.decodeBinaryUint16(curr_data,IMURegisters.NAVX_REG_CAPABILITY_FLAGS_L-first_address) self.notify_sink._setBoardState(board_state) raw_data_update", "be accompanied by the \\License.txt file # in the root", "if self.board_state.update_rate_hz != self.update_rate_hz: self.setUpdateRateHz(self.update_rate_hz) try: self.getCurrentData() except IOError: if", "board_state.accel_fsr_g = config[IMURegisters.NAVX_REG_ACCEL_FSR_G] board_state.update_rate_hz = config[IMURegisters.NAVX_REG_UPDATE_RATE_HZ] board_state.capability_flags = AHRSProtocol.decodeBinaryUint16(config,IMURegisters.NAVX_REG_CAPABILITY_FLAGS_L) self.notify_sink._setBoardState(board_state)", "AHRSProtocol.decodeBinaryUint16(curr_data,IMURegisters.NAVX_REG_CAPABILITY_FLAGS_L-first_address) self.notify_sink._setBoardState(board_state) raw_data_update = self.raw_data_update raw_data_update.raw_gyro_x = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_GYRO_X_L-first_address) raw_data_update.raw_gyro_y", "+ 1 - first_address else: read_count = IMURegisters.NAVX_REG_QUAT_OFFSET_Z_H + 1", "time_since_last_update <= IO_TIMEOUT_SECONDS def getByteCount(self): return self.byte_count def getUpdateCount(self): return", "hw_rev = 0 fw_ver_major = 0 fw_ver_minor = 0 fw_revision", "fw_ver_minor = 0 fw_revision = 0 unique_id = [0]*12 class", "# # Created in support of Team 2465 (Kauaibots). Go", "not self._stop: if self.board_state.update_rate_hz != self.update_rate_hz: self.setUpdateRateHz(self.update_rate_hz) try: self.getCurrentData() except", "thread exiting\") def getConfiguration(self): success = False retry_count = 0", "displacement data, acquire it - otherwise implement # similar (but", "first_address) ahrspos_update.baro_pressure = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_PRESSURE_DL - first_address) ahrspos_update.fused_heading = AHRSProtocol.decodeProtocolUnsignedHundredthsFloat(curr_data,", "match configured update rate # Note: some additional time is", "AHRSProtocol.AHRSPosUpdate() self.board_state = _BoardState() self.board_id = _BoardId() self.last_update_time = 0", "ahrspos_update.world_linear_accel_y = AHRSProtocol.decodeProtocolSignedThousandthsFloat(curr_data, IMURegisters.NAVX_REG_LINEAR_ACC_Y_L-first_address) ahrspos_update.world_linear_accel_z = AHRSProtocol.decodeProtocolSignedThousandthsFloat(curr_data, IMURegisters.NAVX_REG_LINEAR_ACC_Z_L-first_address) ahrspos_update.altitude =", "ahrspos_update.disp_y = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_DISP_Y_I_L-first_address) ahrspos_update.disp_z = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_DISP_Z_I_L-first_address) self.notify_sink._setAHRSPosData(ahrspos_update, sensor_timestamp)", "0 selftest_status = 0 capability_flags = 0 update_rate_hz = 0", "Timer.getFPGATimestamp() - self.last_update_time return time_since_last_update <= IO_TIMEOUT_SECONDS def getByteCount(self): return", "Purple Wave! # # Open Source Software - may be", "must have the following callable attributes: _isOmniMountSupported, _isBoardYawResetSupported, _isDisplacementSupported :param", "= AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_QUAT_X_L-first_address)/ 32768.0 ahrspos_update.quaternionY = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_QUAT_Y_L-first_address)/ 32768.0 ahrspos_update.quaternionZ", "Source Software - may be modified and shared by FRC", "AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_QUAT_Y_L-first_address)/ 32768.0 ahrspos_update.quaternionZ = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_QUAT_Z_L-first_address)/ 32768.0 if displacement_registers:", "finally: logger.info(\"NavX i/o thread exiting\") def getConfiguration(self): success = False", "raw_data_update.raw_gyro_x = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_GYRO_X_L-first_address) raw_data_update.raw_gyro_y = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_GYRO_Y_L-first_address) raw_data_update.raw_gyro_z =", "logger.warning(\"Error reading configuration data, retrying (%s)\", e) success = False", "IMURegisters.NAVX_REG_ACC_X_L-first_address) raw_data_update.raw_accel_y = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_ACC_Y_L-first_address) raw_data_update.raw_accel_z = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_ACC_Z_L-first_address) raw_data_update.cal_mag_x", "raw_data_update = self.raw_data_update raw_data_update.raw_gyro_x = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_GYRO_X_L-first_address) raw_data_update.raw_gyro_y = AHRSProtocol.decodeBinaryInt16(curr_data,", "zeroYaw(self): self.io_provider.write( IMURegisters.NAVX_REG_INTEGRATION_CTL, AHRSProtocol.NAVX_INTEGRATION_CTL_RESET_YAW ) self.notify_sink._yawResetComplete() def zeroDisplacement(self): self.io_provider.write( IMURegisters.NAVX_REG_INTEGRATION_CTL,", "configured update rate # Note: some additional time is removed", "i/o thread exiting\") def getConfiguration(self): success = False retry_count =", "1 def isConnected(self): time_since_last_update = Timer.getFPGATimestamp() - self.last_update_time return time_since_last_update", "self.notify_sink._setBoardState(board_state) success = True retry_count += 1 return success def", "AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_QUAT_Z_L-first_address)/ 32768.0 if displacement_registers: ahrspos_update.vel_x = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_VEL_X_I_L-first_address) ahrspos_update.vel_y", "self.last_sensor_timestamp = sensor_timestamp ahrspos_update = self.ahrspos_update ahrspos_update.op_status = curr_data[IMURegisters.NAVX_REG_OP_STATUS -", "raw_data_update.raw_gyro_y = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_GYRO_Y_L-first_address) raw_data_update.raw_gyro_z = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_GYRO_Z_L-first_address) raw_data_update.raw_accel_x =", "logging.getLogger('navx') __all__ = ['RegisterIO'] IO_TIMEOUT_SECONDS = 1.0 DELAY_OVERHEAD_SECONDS = 0.004", "%s (rev %s)\", IMURegisters.model_type(self.board_id.type), self.board_id.hw_rev) logger.info(\"-- Firmware %s.%s\", self.board_id.fw_ver_major, self.board_id.fw_ver_minor)", "io_provider self.update_rate_hz = update_rate_hz self.board_capabilities = board_capabilities self.notify_sink = notify_sink", "project #---------------------------------------------------------------------------- from ._impl import AHRSProtocol, IMUProtocol, IMURegisters from wpilib.timer", "displacement_registers: read_count = IMURegisters.NAVX_REG_LAST + 1 - first_address else: read_count", "return success def getCurrentData(self): first_address = IMURegisters.NAVX_REG_UPDATE_RATE_HZ displacement_registers = self.board_capabilities._isDisplacementSupported()", "_isOmniMountSupported, _isBoardYawResetSupported, _isDisplacementSupported :param notify_sink: must have the following callable", "def setUpdateRateHz(self, update_rate_hz): self.io_provider.write(IMURegisters.NAVX_REG_UPDATE_RATE_HZ, update_rate_hz) def zeroYaw(self): self.io_provider.write( IMURegisters.NAVX_REG_INTEGRATION_CTL, AHRSProtocol.NAVX_INTEGRATION_CTL_RESET_YAW", "AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_VEL_X_I_L-first_address) ahrspos_update.vel_y = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_VEL_Y_I_L-first_address) ahrspos_update.vel_z = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_VEL_Z_I_L-first_address)", "import AHRSProtocol, IMUProtocol, IMURegisters from wpilib.timer import Timer import logging", "def shutdown(self): self.io_provider.shutdown() def run(self): logger.info(\"NavX io thread starting\") try:", "rates. update_rate = 1.0/(self.update_rate_hz & 0xFF) if update_rate > DELAY_OVERHEAD_SECONDS:", "must have the following callable attributes: _setYawPitchRoll, _setAHRSData, _setAHRSPosData, _setRawData,", "DS c5e3a8a9b642 roborio/java/navx_frc/src/com/kauailabs/navx/frc/RegisterIO.java #---------------------------------------------------------------------------- # Copyright (c) <NAME> 2015. All", "if update_rate > DELAY_OVERHEAD_SECONDS: update_rate -= DELAY_OVERHEAD_SECONDS logger.info(\"-- Update rate:", "validated: 2017-02-19 DS c5e3a8a9b642 roborio/java/navx_frc/src/com/kauailabs/navx/frc/RegisterIO.java #---------------------------------------------------------------------------- # Copyright (c) <NAME>", "displacement_registers = self.board_capabilities._isDisplacementSupported() # If firmware supports displacement data, acquire", "AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_GYRO_X_L-first_address) raw_data_update.raw_gyro_y = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_GYRO_Y_L-first_address) raw_data_update.raw_gyro_z = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_GYRO_Z_L-first_address)", "_BoardState() self.board_id = _BoardId() self.last_update_time = 0 self.byte_count = 0", "IMURegisters.NAVX_REG_QUAT_X_L-first_address)/ 32768.0 ahrspos_update.quaternionY = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_QUAT_Y_L-first_address)/ 32768.0 ahrspos_update.quaternionZ = AHRSProtocol.decodeBinaryInt16(curr_data,", "False retry_count = 0 while retry_count < 5 and not", "support of Team 2465 (Kauaibots). Go Purple Wave! # #", "ahrspos_update.baro_pressure = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_PRESSURE_DL - first_address) ahrspos_update.fused_heading = AHRSProtocol.decodeProtocolUnsignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_FUSED_HEADING_L-first_address)", "device configuration self.setUpdateRateHz(self.update_rate_hz) if not self.getConfiguration(): logger.warning(\"-- Did not get", "Timer.getFPGATimestamp() self.byte_count += len(curr_data) self.update_count += 1 def isConnected(self): time_since_last_update", "getConfiguration(self): success = False retry_count = 0 while retry_count <", "else: log_error = True Timer.delay(update_rate) except Exception: logger.exception(\"Unhandled exception in", "IO_TIMEOUT_SECONDS def getByteCount(self): return self.byte_count def getUpdateCount(self): return self.update_count def", "- first_address] ahrspos_update.cal_status = curr_data[IMURegisters.NAVX_REG_CAL_STATUS] ahrspos_update.sensor_status = curr_data[IMURegisters.NAVX_REG_SENSOR_STATUS_L - first_address]", "= AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_PITCH_L-first_address) ahrspos_update.roll = AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_ROLL_L-first_address) ahrspos_update.compass_heading = AHRSProtocol.decodeProtocolUnsignedHundredthsFloat(curr_data,", "IMURegisters.NAVX_REG_QUAT_W_L-first_address)/ 32768.0 ahrspos_update.quaternionX = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_QUAT_X_L-first_address)/ 32768.0 ahrspos_update.quaternionY = AHRSProtocol.decodeBinaryInt16(curr_data,", "self.notify_sink._setRawData(raw_data_update, sensor_timestamp) self.last_update_time = Timer.getFPGATimestamp() self.byte_count += len(curr_data) self.update_count +=", "= AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_MAG_Z_L-first_address) raw_data_update.mpu_temp_c = ahrspos_update.mpu_temp self.notify_sink._setRawData(raw_data_update, sensor_timestamp) self.last_update_time =", "IMURegisters.NAVX_REG_GYRO_X_L-first_address) raw_data_update.raw_gyro_y = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_GYRO_Y_L-first_address) raw_data_update.raw_gyro_z = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_GYRO_Z_L-first_address) raw_data_update.raw_accel_x", "True retry_count += 1 return success def getCurrentData(self): first_address =", "False def stop(self): self._stop = True def shutdown(self): self.io_provider.shutdown() def", "= _BoardState() self.board_id = _BoardId() self.last_update_time = 0 self.byte_count =", "0 self.last_sensor_timestamp = 0 self._stop = False def stop(self): self._stop", "IMURegisters.NAVX_REG_SENSOR_STATUS_H+1) except IOError as e: logger.warning(\"Error reading configuration data, retrying", "self.last_update_time = 0 self.byte_count = 0 self.update_count = 0 self.last_sensor_timestamp", "= 0 self._stop = False def stop(self): self._stop = True", "= AHRSProtocol.decodeBinaryUint16(config,IMURegisters.NAVX_REG_CAPABILITY_FLAGS_L) self.notify_sink._setBoardState(board_state) success = True retry_count += 1 return", "# dropped, esp. at higher update rates. update_rate = 1.0/(self.update_rate_hz", "config[IMURegisters.NAVX_REG_FW_VER_MAJOR] board_id.fw_ver_minor = config[IMURegisters.NAVX_REG_FW_VER_MINOR] board_id.type = config[IMURegisters.NAVX_REG_WHOAMI] self.notify_sink._setBoardID(board_id) board_state =", "= AHRSProtocol.decodeProtocolUnsignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_HEADING_L-first_address) ahrspos_update.mpu_temp_c = AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_MPU_TEMP_C_L - first_address) ahrspos_update.world_linear_accel_x", "board_state.update_rate_hz = config[IMURegisters.NAVX_REG_UPDATE_RATE_HZ] board_state.capability_flags = AHRSProtocol.decodeBinaryUint16(config,IMURegisters.NAVX_REG_CAPABILITY_FLAGS_L) self.notify_sink._setBoardState(board_state) success = True", "run(self): logger.info(\"NavX io thread starting\") try: self.io_provider.init() # initial device", "else: self.notify_sink._setAHRSData(ahrspos_update, sensor_timestamp) board_state = self.board_state board_state.cal_status = curr_data[IMURegisters.NAVX_REG_CAL_STATUS-first_address] board_state.op_status", "= AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_QUAT_Z_L-first_address)/ 32768.0 if displacement_registers: ahrspos_update.vel_x = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_VEL_X_I_L-first_address)", "= AHRSProtocol.decodeBinaryUint16(curr_data,IMURegisters.NAVX_REG_SENSOR_STATUS_L-first_address) board_state.update_rate_hz = curr_data[IMURegisters.NAVX_REG_UPDATE_RATE_HZ-first_address] board_state.gyro_fsr_dps = AHRSProtocol.decodeBinaryUint16(curr_data,IMURegisters.NAVX_REG_GYRO_FSR_DPS_L) board_state.accel_fsr_g =", "False Timer.delay(0.5) else: board_id = self.board_id board_id.hw_rev = config[IMURegisters.NAVX_REG_HW_REV] board_id.fw_ver_major", "config[IMURegisters.NAVX_REG_CAL_STATUS] board_state.op_status = config[IMURegisters.NAVX_REG_OP_STATUS] board_state.selftest_status = config[IMURegisters.NAVX_REG_SELFTEST_STATUS] board_state.sensor_status = AHRSProtocol.decodeBinaryUint16(config,IMURegisters.NAVX_REG_SENSOR_STATUS_L)", "ahrspos_update.op_status = curr_data[IMURegisters.NAVX_REG_OP_STATUS - first_address] ahrspos_update.selftest_status = curr_data[IMURegisters.NAVX_REG_SELFTEST_STATUS - first_address]", "setUpdateRateHz(self, update_rate_hz): self.io_provider.write(IMURegisters.NAVX_REG_UPDATE_RATE_HZ, update_rate_hz) def zeroYaw(self): self.io_provider.write( IMURegisters.NAVX_REG_INTEGRATION_CTL, AHRSProtocol.NAVX_INTEGRATION_CTL_RESET_YAW )", "config[IMURegisters.NAVX_REG_SELFTEST_STATUS] board_state.sensor_status = AHRSProtocol.decodeBinaryUint16(config,IMURegisters.NAVX_REG_SENSOR_STATUS_L) board_state.gyro_fsr_dps = AHRSProtocol.decodeBinaryUint16(config,IMURegisters.NAVX_REG_GYRO_FSR_DPS_L) board_state.accel_fsr_g = config[IMURegisters.NAVX_REG_ACCEL_FSR_G]", "= board_capabilities self.notify_sink = notify_sink self.raw_data_update = IMUProtocol.GyroUpdate() self.ahrspos_update =", "curr_data[IMURegisters.NAVX_REG_OP_STATUS - first_address] ahrspos_update.selftest_status = curr_data[IMURegisters.NAVX_REG_SELFTEST_STATUS - first_address] ahrspos_update.cal_status =", "op_status = 0 sensor_status = 0 cal_status = 0 selftest_status", "= AHRSProtocol.decodeBinaryUint16(config,IMURegisters.NAVX_REG_GYRO_FSR_DPS_L) board_state.accel_fsr_g = config[IMURegisters.NAVX_REG_ACCEL_FSR_G] board_state.update_rate_hz = config[IMURegisters.NAVX_REG_UPDATE_RATE_HZ] board_state.capability_flags =", "directory of the project #---------------------------------------------------------------------------- from ._impl import AHRSProtocol, IMUProtocol,", "def run(self): logger.info(\"NavX io thread starting\") try: self.io_provider.init() # initial", "update rates. update_rate = 1.0/(self.update_rate_hz & 0xFF) if update_rate >", "AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_PRESSURE_DL - first_address) ahrspos_update.fused_heading = AHRSProtocol.decodeProtocolUnsignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_FUSED_HEADING_L-first_address) ahrspos_update.quaternionW =", "0 capability_flags = 0 update_rate_hz = 0 accel_fsr_g = 0", "board_state.cal_status = config[IMURegisters.NAVX_REG_CAL_STATUS] board_state.op_status = config[IMURegisters.NAVX_REG_OP_STATUS] board_state.selftest_status = config[IMURegisters.NAVX_REG_SELFTEST_STATUS] board_state.sensor_status", "= 0 selftest_status = 0 capability_flags = 0 update_rate_hz =", "2017-02-19 DS c5e3a8a9b642 roborio/java/navx_frc/src/com/kauailabs/navx/frc/RegisterIO.java #---------------------------------------------------------------------------- # Copyright (c) <NAME> 2015.", "= True Timer.delay(update_rate) except Exception: logger.exception(\"Unhandled exception in NavX thread\")", "def stop(self): self._stop = True def shutdown(self): self.io_provider.shutdown() def run(self):", "self.update_rate_hz, update_rate) # IO Loop while not self._stop: if self.board_state.update_rate_hz", "Created in support of Team 2465 (Kauaibots). Go Purple Wave!", "configuration self.setUpdateRateHz(self.update_rate_hz) if not self.getConfiguration(): logger.warning(\"-- Did not get configuration", "self.ahrspos_update = AHRSProtocol.AHRSPosUpdate() self.board_state = _BoardState() self.board_id = _BoardId() self.last_update_time", "ensure samples are not # dropped, esp. at higher update", "self.board_id.fw_ver_major, self.board_id.fw_ver_minor) log_error = True # Calculate delay to match", "IMURegisters.NAVX_REG_ALTITUDE_D_L - first_address) ahrspos_update.baro_pressure = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_PRESSURE_DL - first_address) ahrspos_update.fused_heading", "IMURegisters.NAVX_REG_QUAT_OFFSET_Z_H + 1 - first_address curr_data = self.io_provider.read(first_address, read_count) sensor_timestamp", "= True # Calculate delay to match configured update rate", "if sensor_timestamp == self.last_sensor_timestamp: return self.last_sensor_timestamp = sensor_timestamp ahrspos_update =", "by FRC teams. Any # modifications to this code must", "32768.0 ahrspos_update.quaternionY = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_QUAT_Y_L-first_address)/ 32768.0 ahrspos_update.quaternionZ = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_QUAT_Z_L-first_address)/", "self.notify_sink._setAHRSPosData(ahrspos_update, sensor_timestamp) else: self.notify_sink._setAHRSData(ahrspos_update, sensor_timestamp) board_state = self.board_state board_state.cal_status =", "ahrspos_update.compass_heading = AHRSProtocol.decodeProtocolUnsignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_HEADING_L-first_address) ahrspos_update.mpu_temp_c = AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_MPU_TEMP_C_L - first_address)", "Timer.delay(0.5) else: board_id = self.board_id board_id.hw_rev = config[IMURegisters.NAVX_REG_HW_REV] board_id.fw_ver_major =", "board_capabilities: must have the following callable attributes: _isOmniMountSupported, _isBoardYawResetSupported, _isDisplacementSupported", "# Copyright (c) <NAME> 2015. All Rights Reserved. # #", "# modifications to this code must be accompanied by the", "board_capabilities): \"\"\" :param board_capabilities: must have the following callable attributes:", "logger.info(\"NavX i/o thread exiting\") def getConfiguration(self): success = False retry_count", "= 0.004 class _BoardId: type = 0 hw_rev = 0", "e: logger.warning(\"Error reading configuration data, retrying (%s)\", e) success =", "some additional time is removed from the # 1/update_rate value", "of the project #---------------------------------------------------------------------------- from ._impl import AHRSProtocol, IMUProtocol, IMURegisters", "initial device configuration self.setUpdateRateHz(self.update_rate_hz) if not self.getConfiguration(): logger.warning(\"-- Did not", "1 - first_address curr_data = self.io_provider.read(first_address, read_count) sensor_timestamp = AHRSProtocol.decodeBinaryUint32(curr_data,", "= AHRSProtocol.decodeBinaryUint32(curr_data, IMURegisters.NAVX_REG_TIMESTAMP_L_L-first_address) if sensor_timestamp == self.last_sensor_timestamp: return self.last_sensor_timestamp =", "def getUpdateCount(self): return self.update_count def setUpdateRateHz(self, update_rate_hz): self.io_provider.write(IMURegisters.NAVX_REG_UPDATE_RATE_HZ, update_rate_hz) def", "= config[IMURegisters.NAVX_REG_UPDATE_RATE_HZ] board_state.capability_flags = AHRSProtocol.decodeBinaryUint16(config,IMURegisters.NAVX_REG_CAPABILITY_FLAGS_L) self.notify_sink._setBoardState(board_state) success = True retry_count", "= AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_GYRO_Z_L-first_address) raw_data_update.raw_accel_x = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_ACC_X_L-first_address) raw_data_update.raw_accel_y = AHRSProtocol.decodeBinaryInt16(curr_data,", "= AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_VEL_X_I_L-first_address) ahrspos_update.vel_y = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_VEL_Y_I_L-first_address) ahrspos_update.vel_z = AHRSProtocol.decodeProtocol1616Float(curr_data,", "config[IMURegisters.NAVX_REG_ACCEL_FSR_G] board_state.update_rate_hz = config[IMURegisters.NAVX_REG_UPDATE_RATE_HZ] board_state.capability_flags = AHRSProtocol.decodeBinaryUint16(config,IMURegisters.NAVX_REG_CAPABILITY_FLAGS_L) self.notify_sink._setBoardState(board_state) success =", "self.update_count def setUpdateRateHz(self, update_rate_hz): self.io_provider.write(IMURegisters.NAVX_REG_UPDATE_RATE_HZ, update_rate_hz) def zeroYaw(self): self.io_provider.write( IMURegisters.NAVX_REG_INTEGRATION_CTL,", "except IOError as e: logger.warning(\"Error reading configuration data, retrying (%s)\",", "+= 1 return success def getCurrentData(self): first_address = IMURegisters.NAVX_REG_UPDATE_RATE_HZ displacement_registers", "self.raw_data_update raw_data_update.raw_gyro_x = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_GYRO_X_L-first_address) raw_data_update.raw_gyro_y = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_GYRO_Y_L-first_address) raw_data_update.raw_gyro_z", "+ 1 - first_address curr_data = self.io_provider.read(first_address, read_count) sensor_timestamp =", "== self.last_sensor_timestamp: return self.last_sensor_timestamp = sensor_timestamp ahrspos_update = self.ahrspos_update ahrspos_update.op_status", "Note: some additional time is removed from the # 1/update_rate", "IMURegisters.NAVX_REG_MAG_X_L-first_address) raw_data_update.cal_mag_y = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_MAG_Y_L-first_address) raw_data_update.cal_mag_z = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_MAG_Z_L-first_address) raw_data_update.mpu_temp_c", "._impl import AHRSProtocol, IMUProtocol, IMURegisters from wpilib.timer import Timer import", "update_rate > DELAY_OVERHEAD_SECONDS: update_rate -= DELAY_OVERHEAD_SECONDS logger.info(\"-- Update rate: %shz", "_setAHRSData, _setAHRSPosData, _setRawData, _setBoardID, _setBoardState, _yawResetComplete \"\"\" self.io_provider = io_provider", "ahrspos_update.yaw = AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_YAW_L-first_address) ahrspos_update.pitch = AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_PITCH_L-first_address) ahrspos_update.roll =", "AHRSProtocol.decodeProtocolSignedThousandthsFloat(curr_data, IMURegisters.NAVX_REG_LINEAR_ACC_Z_L-first_address) ahrspos_update.altitude = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_ALTITUDE_D_L - first_address) ahrspos_update.baro_pressure =", "- first_address) ahrspos_update.baro_pressure = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_PRESSURE_DL - first_address) ahrspos_update.fused_heading =", "self.board_state board_state.cal_status = config[IMURegisters.NAVX_REG_CAL_STATUS] board_state.op_status = config[IMURegisters.NAVX_REG_OP_STATUS] board_state.selftest_status = config[IMURegisters.NAVX_REG_SELFTEST_STATUS]", "= IMURegisters.NAVX_REG_UPDATE_RATE_HZ displacement_registers = self.board_capabilities._isDisplacementSupported() # If firmware supports displacement", "self.byte_count = 0 self.update_count = 0 self.last_sensor_timestamp = 0 self._stop", "except Exception: logger.exception(\"Unhandled exception in NavX thread\") finally: logger.info(\"NavX i/o", "_setYawPitchRoll, _setAHRSData, _setAHRSPosData, _setRawData, _setBoardID, _setBoardState, _yawResetComplete \"\"\" self.io_provider =", "raw_data_update.mpu_temp_c = ahrspos_update.mpu_temp self.notify_sink._setRawData(raw_data_update, sensor_timestamp) self.last_update_time = Timer.getFPGATimestamp() self.byte_count +=", "DELAY_OVERHEAD_SECONDS = 0.004 class _BoardId: type = 0 hw_rev =", "= AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_ROLL_L-first_address) ahrspos_update.compass_heading = AHRSProtocol.decodeProtocolUnsignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_HEADING_L-first_address) ahrspos_update.mpu_temp_c = AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data,", "retry_count = 0 while retry_count < 5 and not success:", "0 sensor_status = 0 cal_status = 0 selftest_status = 0", "AHRSProtocol.decodeProtocolUnsignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_HEADING_L-first_address) ahrspos_update.mpu_temp_c = AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_MPU_TEMP_C_L - first_address) ahrspos_update.world_linear_accel_x =", "configuration data\") else: logger.info(\"-- Board is %s (rev %s)\", IMURegisters.model_type(self.board_id.type),", "in the root directory of the project #---------------------------------------------------------------------------- from ._impl", "have the following callable attributes: _isOmniMountSupported, _isBoardYawResetSupported, _isDisplacementSupported :param notify_sink:", "exception in NavX thread\") finally: logger.info(\"NavX i/o thread exiting\") def", "board_state.selftest_status = config[IMURegisters.NAVX_REG_SELFTEST_STATUS] board_state.sensor_status = AHRSProtocol.decodeBinaryUint16(config,IMURegisters.NAVX_REG_SENSOR_STATUS_L) board_state.gyro_fsr_dps = AHRSProtocol.decodeBinaryUint16(config,IMURegisters.NAVX_REG_GYRO_FSR_DPS_L) board_state.accel_fsr_g", "isConnected(self): time_since_last_update = Timer.getFPGATimestamp() - self.last_update_time return time_since_last_update <= IO_TIMEOUT_SECONDS", "curr_data = self.io_provider.read(first_address, read_count) sensor_timestamp = AHRSProtocol.decodeBinaryUint32(curr_data, IMURegisters.NAVX_REG_TIMESTAMP_L_L-first_address) if sensor_timestamp", "getUpdateCount(self): return self.update_count def setUpdateRateHz(self, update_rate_hz): self.io_provider.write(IMURegisters.NAVX_REG_UPDATE_RATE_HZ, update_rate_hz) def zeroYaw(self):", "_setAHRSPosData, _setRawData, _setBoardID, _setBoardState, _yawResetComplete \"\"\" self.io_provider = io_provider self.update_rate_hz", "= AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_MPU_TEMP_C_L - first_address) ahrspos_update.world_linear_accel_x = AHRSProtocol.decodeProtocolSignedThousandthsFloat(curr_data, IMURegisters.NAVX_REG_LINEAR_ACC_X_L-first_address) ahrspos_update.world_linear_accel_y", "retrying (%s)\", e) success = False Timer.delay(0.5) else: board_id =", "this processor. if displacement_registers: read_count = IMURegisters.NAVX_REG_LAST + 1 -", "first_address] ahrspos_update.yaw = AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_YAW_L-first_address) ahrspos_update.pitch = AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_PITCH_L-first_address) ahrspos_update.roll", "%shz (%.4fs)\", self.update_rate_hz, update_rate) # IO Loop while not self._stop:", "= False else: log_error = True Timer.delay(update_rate) except Exception: logger.exception(\"Unhandled", "= self.board_capabilities._isDisplacementSupported() # If firmware supports displacement data, acquire it", "%s)\", IMURegisters.model_type(self.board_id.type), self.board_id.hw_rev) logger.info(\"-- Firmware %s.%s\", self.board_id.fw_ver_major, self.board_id.fw_ver_minor) log_error =", "board_state.sensor_status = AHRSProtocol.decodeBinaryUint16(curr_data,IMURegisters.NAVX_REG_SENSOR_STATUS_L-first_address) board_state.update_rate_hz = curr_data[IMURegisters.NAVX_REG_UPDATE_RATE_HZ-first_address] board_state.gyro_fsr_dps = AHRSProtocol.decodeBinaryUint16(curr_data,IMURegisters.NAVX_REG_GYRO_FSR_DPS_L) board_state.accel_fsr_g", "logger.info(\"-- Update rate: %shz (%.4fs)\", self.update_rate_hz, update_rate) # IO Loop", "self.update_rate_hz = update_rate_hz self.board_capabilities = board_capabilities self.notify_sink = notify_sink self.raw_data_update", "AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_PITCH_L-first_address) ahrspos_update.roll = AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_ROLL_L-first_address) ahrspos_update.compass_heading = AHRSProtocol.decodeProtocolUnsignedHundredthsFloat(curr_data, IMURegisters.NAVX_REG_HEADING_L-first_address)", "= AHRSProtocol.decodeBinaryUint16(curr_data,IMURegisters.NAVX_REG_GYRO_FSR_DPS_L) board_state.accel_fsr_g = curr_data[IMURegisters.NAVX_REG_ACCEL_FSR_G] board_state.capability_flags= AHRSProtocol.decodeBinaryUint16(curr_data,IMURegisters.NAVX_REG_CAPABILITY_FLAGS_L-first_address) self.notify_sink._setBoardState(board_state) raw_data_update =", "= curr_data[IMURegisters.NAVX_REG_CAL_STATUS] ahrspos_update.sensor_status = curr_data[IMURegisters.NAVX_REG_SENSOR_STATUS_L - first_address] ahrspos_update.yaw = AHRSProtocol.decodeProtocolSignedHundredthsFloat(curr_data,", "update_rate_hz) def zeroYaw(self): self.io_provider.write( IMURegisters.NAVX_REG_INTEGRATION_CTL, AHRSProtocol.NAVX_INTEGRATION_CTL_RESET_YAW ) self.notify_sink._yawResetComplete() def zeroDisplacement(self):", "1/update_rate value to ensure samples are not # dropped, esp.", "IMURegisters.NAVX_REG_FUSED_HEADING_L-first_address) ahrspos_update.quaternionW = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_QUAT_W_L-first_address)/ 32768.0 ahrspos_update.quaternionX = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_QUAT_X_L-first_address)/", "# # Open Source Software - may be modified and", "self.last_sensor_timestamp = 0 self._stop = False def stop(self): self._stop =", "return self.last_sensor_timestamp = sensor_timestamp ahrspos_update = self.ahrspos_update ahrspos_update.op_status = curr_data[IMURegisters.NAVX_REG_OP_STATUS", "= AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_MAG_Y_L-first_address) raw_data_update.cal_mag_z = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_MAG_Z_L-first_address) raw_data_update.mpu_temp_c = ahrspos_update.mpu_temp", "def getConfiguration(self): success = False retry_count = 0 while retry_count", "# Created in support of Team 2465 (Kauaibots). Go Purple", "= 1.0/(self.update_rate_hz & 0xFF) if update_rate > DELAY_OVERHEAD_SECONDS: update_rate -=", "read_count) sensor_timestamp = AHRSProtocol.decodeBinaryUint32(curr_data, IMURegisters.NAVX_REG_TIMESTAMP_L_L-first_address) if sensor_timestamp == self.last_sensor_timestamp: return", "Open Source Software - may be modified and shared by", "self.io_provider = io_provider self.update_rate_hz = update_rate_hz self.board_capabilities = board_capabilities self.notify_sink", "False else: log_error = True Timer.delay(update_rate) except Exception: logger.exception(\"Unhandled exception", "IMURegisters.NAVX_REG_ACC_Z_L-first_address) raw_data_update.cal_mag_x = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_MAG_X_L-first_address) raw_data_update.cal_mag_y = AHRSProtocol.decodeBinaryInt16(curr_data, IMURegisters.NAVX_REG_MAG_Y_L-first_address) raw_data_update.cal_mag_z", "5 and not success: try: config = self.io_provider.read(IMURegisters.NAVX_REG_WHOAMI, IMURegisters.NAVX_REG_SENSOR_STATUS_H+1) except", "logger = logging.getLogger('navx') __all__ = ['RegisterIO'] IO_TIMEOUT_SECONDS = 1.0 DELAY_OVERHEAD_SECONDS", "board_state.accel_fsr_g = curr_data[IMURegisters.NAVX_REG_ACCEL_FSR_G] board_state.capability_flags= AHRSProtocol.decodeBinaryUint16(curr_data,IMURegisters.NAVX_REG_CAPABILITY_FLAGS_L-first_address) self.notify_sink._setBoardState(board_state) raw_data_update = self.raw_data_update raw_data_update.raw_gyro_x", "class _BoardId: type = 0 hw_rev = 0 fw_ver_major =", "- first_address] ahrspos_update.selftest_status = curr_data[IMURegisters.NAVX_REG_SELFTEST_STATUS - first_address] ahrspos_update.cal_status = curr_data[IMURegisters.NAVX_REG_CAL_STATUS]", "IMURegisters.NAVX_REG_MPU_TEMP_C_L - first_address) ahrspos_update.world_linear_accel_x = AHRSProtocol.decodeProtocolSignedThousandthsFloat(curr_data, IMURegisters.NAVX_REG_LINEAR_ACC_X_L-first_address) ahrspos_update.world_linear_accel_y = AHRSProtocol.decodeProtocolSignedThousandthsFloat(curr_data,", "def zeroDisplacement(self): self.io_provider.write( IMURegisters.NAVX_REG_INTEGRATION_CTL, (AHRSProtocol.NAVX_INTEGRATION_CTL_RESET_DISP_X | AHRSProtocol.NAVX_INTEGRATION_CTL_RESET_DISP_Y | AHRSProtocol.NAVX_INTEGRATION_CTL_RESET_DISP_Z )", "on this processor. if displacement_registers: read_count = IMURegisters.NAVX_REG_LAST + 1", "ahrspos_update.disp_x = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_DISP_X_I_L-first_address) ahrspos_update.disp_y = AHRSProtocol.decodeProtocol1616Float(curr_data, IMURegisters.NAVX_REG_DISP_Y_I_L-first_address) ahrspos_update.disp_z =", "shared by FRC teams. Any # modifications to this code", "while not self._stop: if self.board_state.update_rate_hz != self.update_rate_hz: self.setUpdateRateHz(self.update_rate_hz) try: self.getCurrentData()", "type = 0 hw_rev = 0 fw_ver_major = 0 fw_ver_minor", "= 0 update_rate_hz = 0 accel_fsr_g = 0 gyro_fsr_dps =", "= IMUProtocol.GyroUpdate() self.ahrspos_update = AHRSProtocol.AHRSPosUpdate() self.board_state = _BoardState() self.board_id =", "esp. at higher update rates. update_rate = 1.0/(self.update_rate_hz & 0xFF)" ]
[ "% ( 1, 2, 3, self.points-1, self.points) s += \"", "self.enabled_and_selected: if channel_number == 1: self.raw = np.frombuffer(w.header.raw_1, dtype=np.uint8) if", "def ds6000(self, w, channel_number): \"\"\"Interpret waveform for the Rigol DS6000", "self.y_offset = self.volt_offset if self.enabled_and_selected: if channel_number == 1: self.raw", "self.raw = np.frombuffer(w.header.raw_2, dtype=np.uint8) if channel_number == 3: self.raw =", "fformat % (number * scale, prefix) return s def _channel_bytes(channel_number,", "channel.volt_scale self.volt_offset = channel.volt_offset self.y_scale = channel.volt_scale self.y_offset = channel.volt_offset", "\" Channel %d:\\n\" % self.channel_number s += \" Coupling =", "None self.coupling = 'unknown' self.roll_stop = 0 self.time_offset = 0", "% self.points if self.enabled_and_selected: s += \" Count = [%9d,%9d,%9d", "offset = 4 - channel_number data = np.frombuffer(w.data.raw, dtype=np.uint8) raw_bytes", "if this channel is one of those chosen by user", "4 scope: string describing scope selected: string with channels chosen", "channel is one of those chosen by user chosen =", "self.time_scale = w.header.time_scale self.points = w.header.storage_depth self.firmware = w.header.firmware_version self.unit", "DS2000 series.\"\"\" self.time_offset = w.header.time_offset self.time_scale = w.header.time_scale self.points =", "series scopes.\"\"\" self.roll_stop = w.header.roll_stop if channel_number == 1: self.time_offset", "1000Z scopes. Waveform points are interleaved stored in memory when", "w.preheader.firmware_version self.probe = w.header.ch[channel_number-1].probe_value self.coupling = w.header.ch[channel_number-1].coupling.name.upper() self.y_scale = w.header.ch[channel_number-1].y_scale", "Channel Object. Args: w: Wfm object channel_number: 1, 2, 3,", "engineering_string(self.time_scale, 3) s += \" Offset = %10ss\\n\" % engineering_string(self.time_offset,", "chosen self.volt_scale = channel.volt_scale self.volt_offset = channel.volt_offset self.y_scale = channel.volt_scale", "\"\"\"Enumerated units for scopes without them.\"\"\" w = 0 a", "% n_digits s = fformat % (number * scale, prefix)", "and 1000E series scopes.\"\"\" self.roll_stop = w.header.roll_stop if channel_number ==", "s += \" Coupling = %8s\\n\" % self.coupling.rjust(7, ' ')", "= 1 self.volt_offset = 0 self.y_scale = 1 self.y_offset =", "1000E series scopes.\"\"\" self.roll_stop = w.header.roll_stop if channel_number == 1:", "channel_number) elif scope == 'wfm2000': self.ds2000(w, channel_number) elif scope ==", "\" Offset = %10sV\\n\" % engineering_string(self.volt_offset, 2) s += \"", "self.calc_times_and_volts() def ds1000z(self, w, channel_number): \"\"\"Interpret waveform for the Rigol", "self.y_offset = 0 self.volt_per_division = 1 self.probe_value = 1 self.inverted", "Class structure and methods for an oscilloscope channel. The idea", "1: self.raw = np.frombuffer(w.header.raw_1, dtype=np.uint8) if channel_number == 2: self.raw", "= w.header.points self.firmware = w.header.firmware_version self.coupling = w.header.ch[channel_number-1].coupling.name.upper() self.y_scale =", "channel if any([w.header.ch[i].enabled for i in range(channel_number-1)]): offset = 1", "signal voltages or the stringification method to describe a channel", "n_digits s = fformat % (number * scale, prefix) return", "= 1 v = 2 u = 3 def best_scale(number):", "s += \" Scale = %10sV/div\\n\" % engineering_string(self.volt_per_division, 2) s", "single structure that can be handled in a uniform and", "self.raw = np.frombuffer(w.header.raw_4, dtype=np.uint8) self.calc_times_and_volts() def ds4000(self, w, channel_number): \"\"\"Interpret", "dtype=np.uint8) self.calc_times_and_volts() def ds4000(self, w, channel_number): \"\"\"Interpret waveform for the", "1e6, 'µ' if absnr < 0.99999999: return 1e3, 'm' if", "channel_number self.waveform = w self.seconds_per_point = w.header.seconds_per_point self.firmware = 'unknown'", "w.header.ch[channel_number-1].coupling.name.upper() self.y_scale = -self.volt_scale self.y_offset = self.volt_offset if self.enabled_and_selected: if", "w.header.time_offset if channel_number == 1: if self.enabled_and_selected: self.points = len(w.data.ch1)", "% ( t[0], t[1], t[2], t[-2], t[-1]) v = [engineering_string(self.volts[i],", "This unweaves them. Args: channel_number: the number of enabled channels", "1: self.raw = np.array(w.header.raw_1, dtype=np.uint8) if channel_number == 2: self.raw", "self.calc_times_and_volts() def ds1000d(self, w, channel_number): \"\"\"Interpret waveform data for 1000CD", "s += \" Probe = %7gX\\n\" % self.probe_value s +=", "self.time_scale = w.header.time_scale self.points = w.header.points self.firmware = w.header.firmware_version self.coupling", "class Channel(): \"\"\"Base class for a single channel.\"\"\" def __init__(self,", "len(self.raw) self.calc_times_and_volts() def ds2000(self, w, channel_number): \"\"\"Interpret waveform for the", "self.coupling = 'unknown' self.roll_stop = 0 self.time_offset = 0 self.time_scale", "channel_number == 2: self.time_offset = w.header.ch2_time_offset self.time_scale = w.header.ch2_time_scale if", "best_scale(number) fformat = \"%%.%df %%s\" % n_digits s = fformat", "disable=too-many-statements \"\"\" Class structure and methods for an oscilloscope channel.", "channel_number == 3: self.raw = np.array(w.header.raw_3, dtype=np.uint8) if channel_number ==", "2) + \"V\" for i in [0, 1, 2, -2,", "( v[0], v[1], v[2], v[-2], v[-1]) return s def calc_times_and_volts(self):", "channel_number) def __str__(self): \"\"\"Describe this channel.\"\"\" s = \" Channel", "this channel.\"\"\" if self.enabled_and_selected: self.volts = self.y_scale * (127.0 -", "== 4: self.raw = np.frombuffer(w.header.raw_4, dtype=np.uint8) self.calc_times_and_volts() def ds4000(self, w,", "channel_number): \"\"\"Interpret waveform for the Rigol DS4000 series.\"\"\" self.time_offset =", "\"\"\"Interpret waveform for the Rigol DS4000 series.\"\"\" self.time_offset = w.header.time_offset", "np.frombuffer(w.data.ch2, dtype=np.uint8) self.calc_times_and_volts() def ds1000d(self, w, channel_number): \"\"\"Interpret waveform data", "ds4000(self, w, channel_number): \"\"\"Interpret waveform for the Rigol DS4000 series.\"\"\"", "= False self.volt_scale = 1 self.volt_offset = 0 self.y_scale =", "Rigol DS4000 series.\"\"\" self.time_offset = w.header.time_offset self.time_scale = w.header.time_scale self.points", "self.enabled_and_selected = channel.enabled and chosen self.volt_scale = channel.volt_scale self.volt_offset =", "ds1000e(self, w, channel_number): \"\"\"Interpret waveform data for 1000D and 1000E", "if self.enabled_and_selected: self.points = len(w.data.ch1) self.raw = np.frombuffer(w.data.ch1, dtype=np.uint8) elif", "that can be handled in a uniform and consistent manner.", "channel_number: 1, 2, 3, or 4 scope: string describing scope", "1: if self.enabled_and_selected: self.points = len(w.data.ch1) self.raw = np.frombuffer(w.data.ch1, dtype=np.uint8)", "self.time_offset = w.header.time_offset self.time_scale = w.header.time_scale self.points = w.header.storage_depth self.firmware", "number of enabled channels before this one w: original waveform", "i in range(channel_number-1)]): offset = 1 elif w.header.stride == 4:", "%10ss/div\\n\" % engineering_string(self.time_scale, 3) s += \" Offset = %10ss\\n\"", "3) + \"s\" for i in [0, 1, 2, -2,", "s def _channel_bytes(channel_number, w): \"\"\" Return right series of bytes", "scopes.\"\"\" self.time_scale = 1.0e-12 * w.header.time_scale self.time_offset = 1.0e-12 *", "(127.0 - self.raw) - self.y_offset h = self.points * self.seconds_per_point", "1, ' ' if absnr < 0.99999999e6: return 1e-3, 'k'", "units for scopes without them.\"\"\" w = 0 a =", "if channel_number == 2: self.raw = np.frombuffer(w.header.raw_2, dtype=np.uint8) if channel_number", "self.probe_value = channel.probe_value self.unit = channel.unit self.inverted = channel.inverted if", "w.header.roll_stop if channel_number == 1: self.time_offset = w.header.ch1_time_offset self.time_scale =", "prefix) return s def _channel_bytes(channel_number, w): \"\"\" Return right series", "\"\"\" from enum import Enum import numpy as np class", "self.y_scale = w.header.ch[channel_number-1].y_scale self.y_offset = w.header.ch[channel_number-1].y_offset if self.enabled_and_selected: self.raw =", "self.firmware = 'unknown' self.unit = UnitEnum.v self.points = 0 self.raw", "self.y_offset = channel.volt_offset self.volt_per_division = channel.volt_per_division self.probe_value = channel.probe_value self.unit", "= channel.inverted if scope == 'wfm1000c': self.ds1000c(w, channel_number) elif scope", "!= -1 if channel_number <= len(w.header.ch): channel = w.header.ch[channel_number-1] self.enabled", "object channel_number: 1, 2, 3, or 4 scope: string describing", "= %8s\\n\\n\" % self.inverted s += \" Time Base =", "self.roll_stop = w.header.roll_stop if channel_number == 1: self.time_offset = w.header.ch1_time_offset", "w.header.time_scale self.points = w.header.storage_depth self.firmware = w.header.firmware_version self.unit = UnitEnum(w.header.ch[channel_number-1].unit_actual)", "\" Probe = %7gX\\n\" % self.probe_value s += \" Inverted", "2 self.times = np.linspace(-h, h, self.points) + self.time_offset def ds1000c(self,", "self.ds1000d(w, channel_number) elif scope == 'wfm1000e': self.ds1000e(w, channel_number) elif scope", "numpy as np class UnitEnum(Enum): \"\"\"Enumerated units for scopes without", "if absnr < 0.99999999e3: return 1, ' ' if absnr", "\" Volts = [%9s,%9s,%9s ... %9s,%9s]\\n\" % ( v[0], v[1],", "-self.volt_scale self.y_offset = self.volt_offset if self.enabled_and_selected: if channel_number == 1:", "v = 2 u = 3 def best_scale(number): \"\"\"Scale and", "self.enabled_and_selected: self.points = len(w.data.ch1) self.raw = np.frombuffer(w.data.ch1, dtype=np.uint8) elif channel_number", "np.linspace(-h, h, self.points) + self.time_offset def ds1000c(self, w, channel_number): \"\"\"Interpret", "= np.frombuffer(w.header.raw_4, dtype=np.uint8) self.calc_times_and_volts() def ds4000(self, w, channel_number): \"\"\"Interpret waveform", "channel_number: the number of enabled channels before this one w:", "') s += \" Scale = %10sV/div\\n\" % engineering_string(self.volt_per_division, 2)", "self.points = len(w.data.ch2) self.raw = np.frombuffer(w.data.ch2, dtype=np.uint8) self.calc_times_and_volts() def ds1000e(self,", "def ds2000(self, w, channel_number): \"\"\"Interpret waveform for the Rigol DS2000", "w.header.ch[channel_number-1].unit if self.enabled_and_selected: if channel_number == 1: self.raw = np.array(w.header.raw_1,", "class UnitEnum(Enum): \"\"\"Enumerated units for scopes without them.\"\"\" w =", "and chosen self.volt_scale = channel.volt_scale self.volt_offset = channel.volt_offset self.y_scale =", "the Rigol DS4000 series.\"\"\" self.time_offset = w.header.time_offset self.time_scale = w.header.time_scale", "np class UnitEnum(Enum): \"\"\"Enumerated units for scopes without them.\"\"\" w", "(number * scale, prefix) return s def _channel_bytes(channel_number, w): \"\"\"", "1 self.y_offset = 0 self.volt_per_division = 1 self.probe_value = 1", "to collect all the relevant information from all the Rigol", "'wfm6000': self.ds6000(w, channel_number) def __str__(self): \"\"\"Describe this channel.\"\"\" s =", "1 v = 2 u = 3 def best_scale(number): \"\"\"Scale", "be handled in a uniform and consistent manner. Specifically this", "s = fformat % (number * scale, prefix) return s", "= \"CH %d\" % channel_number self.waveform = w self.seconds_per_point =", "can be handled in a uniform and consistent manner. Specifically", "The idea is to collect all the relevant information from", "Returns byte array for specified channel \"\"\" offset = 0", "the Rigol DS1000Z series.\"\"\" self.time_scale = w.header.time_scale self.time_offset = w.header.time_offset", "if channel_number == 3: self.raw = np.frombuffer(w.header.raw_3, dtype=np.uint8) if channel_number", "Delta = %10ss/point\\n\" % engineering_string(self.seconds_per_point, 3) s += \" Points", "a Channel Object. Args: w: Wfm object channel_number: 1, 2,", "memory when two or more channels are saved. This unweaves", "engineering_string(self.volt_per_division, 2) s += \" Offset = %10sV\\n\" % engineering_string(self.volt_offset,", "self.points = len(w.data.ch1) self.raw = np.frombuffer(w.data.ch1, dtype=np.uint8) if channel_number ==", "= w.preheader.firmware_version self.probe = w.header.ch[channel_number-1].probe_value self.coupling = w.header.ch[channel_number-1].coupling.name.upper() self.y_scale =", "w.header.firmware_version self.unit = UnitEnum(w.header.ch[channel_number-1].unit_actual) self.coupling = w.header.ch[channel_number-1].coupling.name.upper() self.y_scale = -self.volt_scale", "ds2000(self, w, channel_number): \"\"\"Interpret waveform for the Rigol DS2000 series.\"\"\"", "-1]] s += \" Times = [%9s,%9s,%9s ... %9s,%9s]\\n\" %", "#pylint: disable=too-many-return-statements #pylint: disable=too-many-statements \"\"\" Class structure and methods for", "of signal times channel.volts : numpy array of signal voltages", "enabled channels before this one w: original waveform object Returns", "= w self.seconds_per_point = w.header.seconds_per_point self.firmware = 'unknown' self.unit =", "the Rigol scope waveforms into a single structure that can", "method to describe a channel print(channel) \"\"\" from enum import", "channel print(channel) \"\"\" from enum import Enum import numpy as", "byte pattern CHx CHy # use odd bytes when this", "by user chosen = selected.find(str(channel_number)) != -1 if channel_number <=", "# byte pattern CHx CHy # use odd bytes when", "3, or 4 scope: string describing scope selected: string with", "[0, 1, 2, -2, -1]] s += \" Times =", "chosen by user chosen = selected.find(str(channel_number)) != -1 if channel_number", "self.points = len(w.data.ch2) self.raw = np.frombuffer(w.data.ch2, dtype=np.uint8) self.calc_times_and_volts() def ds1000d(self,", "DS6000 series.\"\"\" self.time_offset = w.header.time_offset self.time_scale = w.header.time_scale self.points =", "are interleaved stored in memory when two or more channels", "elif scope == 'wfm1000d': self.ds1000d(w, channel_number) elif scope == 'wfm1000e':", "self.firmware = w.header.firmware_version self.coupling = w.header.ch[channel_number-1].coupling.name.upper() self.unit = w.header.ch[channel_number-1].unit if", "a number with proper prefix.\"\"\" absnr = abs(number) if absnr", "False # determine if this channel is one of those", "' if absnr < 0.99999999e-9: return 1e12, 'p' if absnr", "1 self.enabled = False self.enabled_and_selected = False self.volt_scale = 1", "+= \" Inverted = %8s\\n\\n\" % self.inverted s += \"", "prefix = best_scale(number) fformat = \"%%.%df %%s\" % n_digits s", "-1 if channel_number <= len(w.header.ch): channel = w.header.ch[channel_number-1] self.enabled =", "channel_number) elif scope == 'wfm1000z': self.ds1000z(w, channel_number) elif scope ==", "= channel.volt_offset self.volt_per_division = channel.volt_per_division self.probe_value = channel.probe_value self.unit =", "absnr < 0.99999999: return 1e3, 'm' if absnr < 0.99999999e3:", "if channel_number == 2: if self.enabled_and_selected: self.points = len(w.data.ch2) self.raw", "self.volt_offset if self.enabled_and_selected: if channel_number == 1: self.raw = np.frombuffer(w.header.raw_1,", "by user Returns: Channel object \"\"\" self.channel_number = channel_number self.name", "Offset = %10ss\\n\" % engineering_string(self.time_offset, 3) s += \" Delta", "self.time_offset = 1.0e-12 * w.header.time_offset if channel_number == 1: if", "3: self.raw = np.array(w.header.raw_3, dtype=np.uint8) if channel_number == 4: self.raw", "= channel.enabled self.enabled_and_selected = channel.enabled and chosen self.volt_scale = channel.volt_scale", "waveform data for 1000D and 1000E series scopes.\"\"\" self.roll_stop =", "channel.inverted if scope == 'wfm1000c': self.ds1000c(w, channel_number) elif scope ==", "selected: string with channels chosen by user Returns: Channel object", "self.coupling.rjust(7, ' ') s += \" Scale = %10sV/div\\n\" %", "% engineering_string(self.time_offset, 3) s += \" Delta = %10ss/point\\n\" %", "w, channel_number): \"\"\"Interpret waveform for the Rigol DS1000Z series.\"\"\" self.time_scale", "def ds4000(self, w, channel_number): \"\"\"Interpret waveform for the Rigol DS4000", "= 2 u = 3 def best_scale(number): \"\"\"Scale and units", "stored in memory when two or more channels are saved.", "len(w.data.ch1) self.raw = np.frombuffer(w.data.ch1, dtype=np.uint8) if channel_number == 2: if", "1 elif w.header.stride == 4: # byte pattern CH4 CH3", "Coupling = %8s\\n\" % self.coupling.rjust(7, ' ') s += \"", "'wfm2000': self.ds2000(w, channel_number) elif scope == 'wfm4000': self.ds4000(w, channel_number) elif", "use channel.times : numpy array of signal times channel.volts :", "for the Rigol DS4000 series.\"\"\" self.time_offset = w.header.time_offset self.time_scale =", "+= \" Volts = [%9s,%9s,%9s ... %9s,%9s]\\n\" % ( v[0],", "channel_number <= len(w.header.ch): channel = w.header.ch[channel_number-1] self.enabled = channel.enabled self.enabled_and_selected", "self.y_offset = w.header.ch[channel_number-1].y_offset if self.enabled_and_selected: self.raw = _channel_bytes(channel_number, w) self.points", "_channel_bytes(channel_number, w): \"\"\" Return right series of bytes for a", "( 1, 2, 3, self.points-1, self.points) s += \" Raw", "in a uniform and consistent manner. Specifically this lets one", "- channel_number data = np.frombuffer(w.data.raw, dtype=np.uint8) raw_bytes = data[offset::w.header.stride] return", "if absnr < 0.99999999e-6: return 1e9, 'n' if absnr <", "w.header.seconds_per_point self.firmware = 'unknown' self.unit = UnitEnum.v self.points = 0", "channel_number) elif scope == 'wfm4000': self.ds4000(w, channel_number) elif scope ==", "= %8s\\n\" % self.coupling.rjust(7, ' ') s += \" Scale", "+= \" Count = [%9d,%9d,%9d ... %9d,%9d]\\n\" % ( 1,", "False self.volt_scale = 1 self.volt_offset = 0 self.y_scale = 1", "w.header.points self.stride = w.header.stride self.firmware = w.preheader.firmware_version self.probe = w.header.ch[channel_number-1].probe_value", "1.0e-12 * w.header.time_offset if channel_number == 1: if self.enabled_and_selected: self.points", "signal times channel.volts : numpy array of signal voltages or", "\"\"\" Initialize a Channel Object. Args: w: Wfm object channel_number:", "w self.seconds_per_point = w.header.seconds_per_point self.firmware = 'unknown' self.unit = UnitEnum.v", "= abs(number) if absnr == 0: return 1, ' '", "data for 1000CD series scopes.\"\"\" self.time_scale = 1.0e-12 * w.header.time_scale", "len(w.data.ch2) self.raw = np.frombuffer(w.data.ch2, dtype=np.uint8) self.calc_times_and_volts() def ds1000d(self, w, channel_number):", "channel_number == 1: self.raw = np.frombuffer(w.header.raw_1, dtype=np.uint8) if channel_number ==", "if self.enabled_and_selected: if channel_number == 1: self.raw = np.array(w.header.raw_1, dtype=np.uint8)", "= 1 self.inverted = False # determine if this channel", "= %10ss\\n\" % engineering_string(self.time_offset, 3) s += \" Delta =", "= channel.volt_scale self.volt_offset = channel.volt_offset self.y_scale = channel.volt_scale self.y_offset =", "one just use channel.times : numpy array of signal times", "= False self.enabled_and_selected = False self.volt_scale = 1 self.volt_offset =", "self.points = w.header.points self.stride = w.header.stride self.firmware = w.preheader.firmware_version self.probe", "self.unit = channel.unit self.inverted = channel.inverted if scope == 'wfm1000c':", "channel_number == 4: self.raw = np.frombuffer(w.header.raw_4, dtype=np.uint8) self.calc_times_and_volts() def ds4000(self,", "= w.header.seconds_per_point self.firmware = 'unknown' self.unit = UnitEnum.v self.points =", "in range(channel_number-1)]): offset = 1 elif w.header.stride == 4: #", "self.points = 0 self.raw = None self.volts = None self.times", "self.raw[1], self.raw[2], self.raw[-2], self.raw[-1]) t = [engineering_string(self.times[i], 3) + \"s\"", "channel_number) elif scope == 'wfm6000': self.ds6000(w, channel_number) def __str__(self): \"\"\"Describe", "# use odd bytes when this is the second enabled", "w.header.stride self.firmware = w.preheader.firmware_version self.probe = w.header.ch[channel_number-1].probe_value self.coupling = w.header.ch[channel_number-1].coupling.name.upper()", "w.header.stride == 4: # byte pattern CH4 CH3 CH2 CH1", "+= \" Probe = %7gX\\n\" % self.probe_value s += \"", "= w.header.ch1_time_offset self.time_scale = w.header.ch1_time_scale if self.enabled_and_selected: self.points = len(w.data.ch1)", "' ') s += \" Scale = %10sV/div\\n\" % engineering_string(self.volt_per_division,", "them.\"\"\" w = 0 a = 1 v = 2", "= [%9s,%9s,%9s ... %9s,%9s]\\n\" % ( v[0], v[1], v[2], v[-2],", "== 1: if self.enabled_and_selected: self.points = len(w.data.ch1) self.raw = np.frombuffer(w.data.ch1,", "w: original waveform object Returns byte array for specified channel", "in memory when two or more channels are saved. This", "data = np.frombuffer(w.data.raw, dtype=np.uint8) raw_bytes = data[offset::w.header.stride] return raw_bytes class", "1e-9, 'G' def engineering_string(number, n_digits): \"\"\"Format number with proper prefix.\"\"\"", "channel_number): \"\"\"Interpret waveform for the Rigol DS1000Z series.\"\"\" self.time_scale =", "self.time_scale = 1 self.enabled = False self.enabled_and_selected = False self.volt_scale", "i in [0, 1, 2, -2, -1]] s += \"", "Args: channel_number: the number of enabled channels before this one", "elif channel_number == 2: self.time_offset = w.header.ch2_time_offset self.time_scale = w.header.ch2_time_scale", "oscilloscope channel. The idea is to collect all the relevant", "= len(w.data.ch1) self.raw = np.frombuffer(w.data.ch1, dtype=np.uint8) if channel_number == 2:", "self.enabled = channel.enabled self.enabled_and_selected = channel.enabled and chosen self.volt_scale =", "dtype=np.uint8) raw_bytes = data[offset::w.header.stride] return raw_bytes class Channel(): \"\"\"Base class", "+= \" Points = %8d\\n\\n\" % self.points if self.enabled_and_selected: s", "string with channels chosen by user Returns: Channel object \"\"\"", "more channels are saved. This unweaves them. Args: channel_number: the", "elif scope == 'wfm6000': self.ds6000(w, channel_number) def __str__(self): \"\"\"Describe this", "waveform object Returns byte array for specified channel \"\"\" offset", "number with proper prefix.\"\"\" absnr = abs(number) if absnr ==", "= np.array(w.header.raw_3, dtype=np.uint8) if channel_number == 4: self.raw = np.array(w.header.raw_4,", "describe a channel print(channel) \"\"\" from enum import Enum import", "w, channel_number): \"\"\"Interpret waveform for the Rigol DS2000 series.\"\"\" self.time_offset", "= -self.volt_scale self.y_offset = self.volt_offset if self.enabled_and_selected: if channel_number ==", "or the stringification method to describe a channel print(channel) \"\"\"", "self.volt_offset = channel.volt_offset self.y_scale = channel.volt_scale self.y_offset = channel.volt_offset self.volt_per_division", "times channel.volts : numpy array of signal voltages or the", "absnr < 0.99999999e-9: return 1e12, 'p' if absnr < 0.99999999e-6:", "1e3, 'm' if absnr < 0.99999999e3: return 1, ' '", "range(channel_number-1)]): offset = 1 elif w.header.stride == 4: # byte", "2: self.time_offset = w.header.ch2_time_offset self.time_scale = w.header.ch2_time_scale if self.enabled_and_selected: self.points", "use odd bytes when this is the second enabled channel", "scope waveforms into a single structure that can be handled", "for i in [0, 1, 2, -2, -1]] s +=", "an oscilloscope channel. The idea is to collect all the", "'unknown' self.roll_stop = 0 self.time_offset = 0 self.time_scale = 1", "of those chosen by user chosen = selected.find(str(channel_number)) != -1", "\" Count = [%9d,%9d,%9d ... %9d,%9d]\\n\" % ( 1, 2,", "ds1000d(self, w, channel_number): \"\"\"Interpret waveform data for 1000CD series scopes.\"\"\"", "describing scope selected: string with channels chosen by user Returns:", "data for 1000D and 1000E series scopes.\"\"\" self.roll_stop = w.header.roll_stop", "len(w.data.ch2) self.raw = np.frombuffer(w.data.ch2, dtype=np.uint8) self.calc_times_and_volts() def ds1000z(self, w, channel_number):", "\"\"\"Interpret waveform for the Rigol DS1000Z series.\"\"\" self.time_scale = w.header.time_scale", "dtype=np.uint8) if channel_number == 2: self.raw = np.frombuffer(w.header.raw_2, dtype=np.uint8) if", "for a single channel.\"\"\" def __init__(self, w, channel_number, scope, selected='1234'):", "%10sV/div\\n\" % engineering_string(self.volt_per_division, 2) s += \" Offset = %10sV\\n\"", "[engineering_string(self.times[i], 3) + \"s\" for i in [0, 1, 2,", "self.time_scale = w.header.ch1_time_scale if self.enabled_and_selected: self.points = len(w.data.ch1) self.raw =", "self.enabled_and_selected: if channel_number == 1: self.raw = np.array(w.header.raw_1, dtype=np.uint8) if", "self.time_offset = w.header.ch1_time_offset self.time_scale = w.header.ch1_time_scale if self.enabled_and_selected: self.points =", "= w.header.time_scale self.points = w.header.points self.firmware = w.header.firmware_version self.coupling =", "t = [engineering_string(self.times[i], 3) + \"s\" for i in [0,", "pattern CHx CHy # use odd bytes when this is", "best_scale(number): \"\"\"Scale and units for a number with proper prefix.\"\"\"", "self.enabled_and_selected = False self.volt_scale = 1 self.volt_offset = 0 self.y_scale", "if absnr < 0.99999999e6: return 1e-3, 'k' if absnr <", "series scopes.\"\"\" self.time_scale = 1.0e-12 * w.header.time_scale self.time_offset = 1.0e-12", "w.header.storage_depth self.firmware = w.header.firmware_version self.unit = UnitEnum(w.header.ch[channel_number-1].unit_actual) self.coupling = w.header.ch[channel_number-1].coupling.name.upper()", "== 2: self.raw = np.array(w.header.raw_2, dtype=np.uint8) if channel_number == 3:", "n_digits): \"\"\"Format number with proper prefix.\"\"\" scale, prefix = best_scale(number)", "\"\"\" offset = 0 if w.header.stride == 2: # byte", "2: self.raw = np.array(w.header.raw_2, dtype=np.uint8) if channel_number == 3: self.raw", "s += \" Count = [%9d,%9d,%9d ... %9d,%9d]\\n\" % (", "absnr < 0.99999999e3: return 1, ' ' if absnr <", "= selected.find(str(channel_number)) != -1 if channel_number <= len(w.header.ch): channel =", "s += \" Inverted = %8s\\n\\n\" % self.inverted s +=", "self.time_offset = 0 self.time_scale = 1 self.enabled = False self.enabled_and_selected", "s += \" Delta = %10ss/point\\n\" % engineering_string(self.seconds_per_point, 3) s", "-2, -1]] s += \" Times = [%9s,%9s,%9s ... %9s,%9s]\\n\"", "self.firmware = w.header.firmware_version self.coupling = w.header.ch[channel_number-1].coupling.name.upper() self.y_scale = -self.volt_scale self.y_offset", "or more channels are saved. This unweaves them. Args: channel_number:", "channel = w.header.ch[channel_number-1] self.enabled = channel.enabled self.enabled_and_selected = channel.enabled and", "'µ' if absnr < 0.99999999: return 1e3, 'm' if absnr", "\"\"\"Format number with proper prefix.\"\"\" scale, prefix = best_scale(number) fformat", "== 3: self.raw = np.frombuffer(w.header.raw_3, dtype=np.uint8) if channel_number == 4:", "= [%9d,%9d,%9d ... %9d,%9d]\\n\" % ( self.raw[0], self.raw[1], self.raw[2], self.raw[-2],", "0 self.time_offset = 0 self.time_scale = 1 self.enabled = False", "dtype=np.uint8) if channel_number == 4: self.raw = np.frombuffer(w.header.raw_4, dtype=np.uint8) self.calc_times_and_volts()", "== 'wfm4000': self.ds4000(w, channel_number) elif scope == 'wfm6000': self.ds6000(w, channel_number)", "scopes. Waveform points are interleaved stored in memory when two", "= 0 self.time_scale = 1 self.enabled = False self.enabled_and_selected =", "0 self.time_scale = 1 self.enabled = False self.enabled_and_selected = False", "one of those chosen by user chosen = selected.find(str(channel_number)) !=", "= self.points * self.seconds_per_point / 2 self.times = np.linspace(-h, h,", "Rigol DS6000 series.\"\"\" self.time_offset = w.header.time_offset self.time_scale = w.header.time_scale self.points", "for i in range(channel_number-1)]): offset = 1 elif w.header.stride ==", "w.header.ch[channel_number-1].coupling.name.upper() self.y_scale = w.header.ch[channel_number-1].y_scale self.y_offset = w.header.ch[channel_number-1].y_offset if self.enabled_and_selected: self.raw", "self.channel_number s += \" Coupling = %8s\\n\" % self.coupling.rjust(7, '", "channel_number == 2: self.raw = np.array(w.header.raw_2, dtype=np.uint8) if channel_number ==", "specified channel \"\"\" offset = 0 if w.header.stride == 2:", "channel for 1000Z scopes. Waveform points are interleaved stored in", "Rigol DS1000Z series.\"\"\" self.time_scale = w.header.time_scale self.time_offset = w.header.time_offset self.points", "= np.array(w.header.raw_1, dtype=np.uint8) if channel_number == 2: self.raw = np.array(w.header.raw_2,", "the second enabled channel if any([w.header.ch[i].enabled for i in range(channel_number-1)]):", "self.points) s += \" Raw = [%9d,%9d,%9d ... %9d,%9d]\\n\" %", "return 1e-3, 'k' if absnr < 0.999999991e9: return 1e-6, 'M'", "user Returns: Channel object \"\"\" self.channel_number = channel_number self.name =", "ds1000z(self, w, channel_number): \"\"\"Interpret waveform for the Rigol DS1000Z series.\"\"\"", "dtype=np.uint8) self.calc_times_and_volts() def ds1000z(self, w, channel_number): \"\"\"Interpret waveform for the", "self.points = w.header.points self.firmware = w.header.firmware_version self.coupling = w.header.ch[channel_number-1].coupling.name.upper() self.y_scale", "channel.times : numpy array of signal times channel.volts : numpy", "v[0], v[1], v[2], v[-2], v[-1]) return s def calc_times_and_volts(self): \"\"\"Calculate", "proper prefix.\"\"\" absnr = abs(number) if absnr == 0: return", "% engineering_string(self.volt_per_division, 2) s += \" Offset = %10sV\\n\" %", "any([w.header.ch[i].enabled for i in range(channel_number-1)]): offset = 1 elif w.header.stride", "Object. Args: w: Wfm object channel_number: 1, 2, 3, or", "s def calc_times_and_volts(self): \"\"\"Calculate the times and voltages for this", "# determine if this channel is one of those chosen", "= np.frombuffer(w.data.ch1, dtype=np.uint8) if channel_number == 2: if self.enabled_and_selected: self.points", "\" Time Base = %10ss/div\\n\" % engineering_string(self.time_scale, 3) s +=", "manner. Specifically this lets one just use channel.times : numpy", "3, self.points-1, self.points) s += \" Raw = [%9d,%9d,%9d ...", "\"s\" for i in [0, 1, 2, -2, -1]] s", "idea is to collect all the relevant information from all", "__str__(self): \"\"\"Describe this channel.\"\"\" s = \" Channel %d:\\n\" %", "Channel object \"\"\" self.channel_number = channel_number self.name = \"CH %d\"", "% self.probe_value s += \" Inverted = %8s\\n\\n\" % self.inverted", "= w.header.time_scale self.time_offset = w.header.time_offset self.points = w.header.points self.stride =", "'wfm1000e': self.ds1000e(w, channel_number) elif scope == 'wfm1000z': self.ds1000z(w, channel_number) elif", "self.raw[0], self.raw[1], self.raw[2], self.raw[-2], self.raw[-1]) t = [engineering_string(self.times[i], 3) +", "Waveform points are interleaved stored in memory when two or", "when this is the second enabled channel if any([w.header.ch[i].enabled for", "the Rigol DS6000 series.\"\"\" self.time_offset = w.header.time_offset self.time_scale = w.header.time_scale", "\"\"\"Describe this channel.\"\"\" s = \" Channel %d:\\n\" % self.channel_number", "%7gX\\n\" % self.probe_value s += \" Inverted = %8s\\n\\n\" %", "is the second enabled channel if any([w.header.ch[i].enabled for i in", "points are interleaved stored in memory when two or more", "byte pattern CH4 CH3 CH2 CH1 offset = 4 -", "= _channel_bytes(channel_number, w) self.points = len(self.raw) self.calc_times_and_volts() def ds2000(self, w,", ": numpy array of signal times channel.volts : numpy array", "Channel(): \"\"\"Base class for a single channel.\"\"\" def __init__(self, w,", "channel_number) elif scope == 'wfm1000e': self.ds1000e(w, channel_number) elif scope ==", "a single channel.\"\"\" def __init__(self, w, channel_number, scope, selected='1234'): \"\"\"", "channel_number data = np.frombuffer(w.data.raw, dtype=np.uint8) raw_bytes = data[offset::w.header.stride] return raw_bytes", "+= \" Coupling = %8s\\n\" % self.coupling.rjust(7, ' ') s", "this is the second enabled channel if any([w.header.ch[i].enabled for i", "for a number with proper prefix.\"\"\" absnr = abs(number) if", "self.coupling = w.header.ch[channel_number-1].coupling.name.upper() self.unit = w.header.ch[channel_number-1].unit if self.enabled_and_selected: if channel_number", "Count = [%9d,%9d,%9d ... %9d,%9d]\\n\" % ( 1, 2, 3,", "= channel.probe_value self.unit = channel.unit self.inverted = channel.inverted if scope", "'unknown' self.unit = UnitEnum.v self.points = 0 self.raw = None", "self.unit = UnitEnum.v self.points = 0 self.raw = None self.volts", "s += \" Time Base = %10ss/div\\n\" % engineering_string(self.time_scale, 3)", "stringification method to describe a channel print(channel) \"\"\" from enum", "0.99999999e-6: return 1e9, 'n' if absnr < 0.99999999e-3: return 1e6,", "the stringification method to describe a channel print(channel) \"\"\" from", "= \" Channel %d:\\n\" % self.channel_number s += \" Coupling", "self.volts = self.y_scale * (127.0 - self.raw) - self.y_offset h", "1, 2, 3, or 4 scope: string describing scope selected:", "[%9s,%9s,%9s ... %9s,%9s]\\n\" % ( v[0], v[1], v[2], v[-2], v[-1])", "if channel_number == 1: self.raw = np.array(w.header.raw_1, dtype=np.uint8) if channel_number", "return 1e9, 'n' if absnr < 0.99999999e-3: return 1e6, 'µ'", "= None self.volts = None self.times = None self.coupling =", "voltages for this channel.\"\"\" if self.enabled_and_selected: self.volts = self.y_scale *", "self.y_scale * (127.0 - self.raw) - self.y_offset h = self.points", "number with proper prefix.\"\"\" scale, prefix = best_scale(number) fformat =", "np.frombuffer(w.header.raw_4, dtype=np.uint8) self.calc_times_and_volts() def ds6000(self, w, channel_number): \"\"\"Interpret waveform for", "% self.inverted s += \" Time Base = %10ss/div\\n\" %", "engineering_string(self.time_offset, 3) s += \" Delta = %10ss/point\\n\" % engineering_string(self.seconds_per_point,", "% engineering_string(self.time_scale, 3) s += \" Offset = %10ss\\n\" %", "if absnr < 0.99999999e-3: return 1e6, 'µ' if absnr <", "1, 2, -2, -1]] s += \" Volts = [%9s,%9s,%9s", "%%s\" % n_digits s = fformat % (number * scale,", "scope == 'wfm4000': self.ds4000(w, channel_number) elif scope == 'wfm6000': self.ds6000(w,", "= np.frombuffer(w.data.ch2, dtype=np.uint8) self.calc_times_and_volts() def ds1000d(self, w, channel_number): \"\"\"Interpret waveform", "self.time_offset = w.header.time_offset self.time_scale = w.header.time_scale self.points = w.header.points self.firmware", "self.stride = w.header.stride self.firmware = w.preheader.firmware_version self.probe = w.header.ch[channel_number-1].probe_value self.coupling", "self.points = w.header.storage_depth self.firmware = w.header.firmware_version self.unit = UnitEnum(w.header.ch[channel_number-1].unit_actual) self.coupling", "channel_number): \"\"\"Interpret waveform for the Rigol DS6000 series.\"\"\" self.time_offset =", "dtype=np.uint8) if channel_number == 2: if self.enabled_and_selected: self.points = len(w.data.ch2)", "self.raw = np.frombuffer(w.data.ch1, dtype=np.uint8) elif channel_number == 2: self.time_offset =", "2) s += \" Probe = %7gX\\n\" % self.probe_value s", "disable=too-many-return-statements #pylint: disable=too-many-statements \"\"\" Class structure and methods for an", "Returns: Channel object \"\"\" self.channel_number = channel_number self.name = \"CH", "' ' if absnr < 0.99999999e6: return 1e-3, 'k' if", "2 u = 3 def best_scale(number): \"\"\"Scale and units for", "proper prefix.\"\"\" scale, prefix = best_scale(number) fformat = \"%%.%df %%s\"", "0.99999999: return 1e3, 'm' if absnr < 0.99999999e3: return 1,", "\"V\" for i in [0, 1, 2, -2, -1]] s", "- self.y_offset h = self.points * self.seconds_per_point / 2 self.times", "= np.frombuffer(w.data.raw, dtype=np.uint8) raw_bytes = data[offset::w.header.stride] return raw_bytes class Channel():", "array of signal voltages or the stringification method to describe", "for the Rigol DS1000Z series.\"\"\" self.time_scale = w.header.time_scale self.time_offset =", "for the Rigol DS2000 series.\"\"\" self.time_offset = w.header.time_offset self.time_scale =", "CH4 CH3 CH2 CH1 offset = 4 - channel_number data", "2: self.raw = np.frombuffer(w.header.raw_2, dtype=np.uint8) if channel_number == 3: self.raw", "prefix.\"\"\" absnr = abs(number) if absnr == 0: return 1,", "[%9d,%9d,%9d ... %9d,%9d]\\n\" % ( self.raw[0], self.raw[1], self.raw[2], self.raw[-2], self.raw[-1])", "%8s\\n\" % self.coupling.rjust(7, ' ') s += \" Scale =", "= len(w.data.ch2) self.raw = np.frombuffer(w.data.ch2, dtype=np.uint8) self.calc_times_and_volts() def ds1000e(self, w,", "= w.header.storage_depth self.firmware = w.header.firmware_version self.unit = UnitEnum(w.header.ch[channel_number-1].unit_actual) self.coupling =", "= %10ss/point\\n\" % engineering_string(self.seconds_per_point, 3) s += \" Points =", "w): \"\"\" Return right series of bytes for a channel", "+ \"V\" for i in [0, 1, 2, -2, -1]]", "= w.header.ch[channel_number-1].coupling.name.upper() self.y_scale = w.header.ch[channel_number-1].y_scale self.y_offset = w.header.ch[channel_number-1].y_offset if self.enabled_and_selected:", "len(w.data.ch1) self.raw = np.frombuffer(w.data.ch1, dtype=np.uint8) elif channel_number == 2: self.time_offset", "dtype=np.uint8) if channel_number == 4: self.raw = np.array(w.header.raw_4, dtype=np.uint8) self.calc_times_and_volts()", "= 0 self.y_scale = 1 self.y_offset = 0 self.volt_per_division =", "raw_bytes class Channel(): \"\"\"Base class for a single channel.\"\"\" def", "w.header.ch1_time_offset self.time_scale = w.header.ch1_time_scale if self.enabled_and_selected: self.points = len(w.data.ch1) self.raw", "= fformat % (number * scale, prefix) return s def", "= 0 a = 1 v = 2 u =", "if w.header.stride == 2: # byte pattern CHx CHy #", "= 'unknown' self.roll_stop = 0 self.time_offset = 0 self.time_scale =", "%10ss/point\\n\" % engineering_string(self.seconds_per_point, 3) s += \" Points = %8d\\n\\n\"", "= w.header.time_offset self.time_scale = w.header.time_scale self.points = w.header.storage_depth self.firmware =", "this channel is one of those chosen by user chosen", "single channel.\"\"\" def __init__(self, w, channel_number, scope, selected='1234'): \"\"\" Initialize", "= None self.times = None self.coupling = 'unknown' self.roll_stop =", "= [engineering_string(self.volts[i], 2) + \"V\" for i in [0, 1,", "== 'wfm1000d': self.ds1000d(w, channel_number) elif scope == 'wfm1000e': self.ds1000e(w, channel_number)", "3) s += \" Delta = %10ss/point\\n\" % engineering_string(self.seconds_per_point, 3)", "methods for an oscilloscope channel. The idea is to collect", "import numpy as np class UnitEnum(Enum): \"\"\"Enumerated units for scopes", "CH2 CH1 offset = 4 - channel_number data = np.frombuffer(w.data.raw,", "'wfm1000d': self.ds1000d(w, channel_number) elif scope == 'wfm1000e': self.ds1000e(w, channel_number) elif", "self.points * self.seconds_per_point / 2 self.times = np.linspace(-h, h, self.points)", "self.channel_number = channel_number self.name = \"CH %d\" % channel_number self.waveform", "== 'wfm1000e': self.ds1000e(w, channel_number) elif scope == 'wfm1000z': self.ds1000z(w, channel_number)", "\"\"\"Calculate the times and voltages for this channel.\"\"\" if self.enabled_and_selected:", "== 2: if self.enabled_and_selected: self.points = len(w.data.ch2) self.raw = np.frombuffer(w.data.ch2,", "if channel_number == 1: self.time_offset = w.header.ch1_time_offset self.time_scale = w.header.ch1_time_scale", "channel_number == 1: self.time_offset = w.header.ch1_time_offset self.time_scale = w.header.ch1_time_scale if", "dtype=np.uint8) if channel_number == 3: self.raw = np.frombuffer(w.header.raw_3, dtype=np.uint8) if", "None self.volts = None self.times = None self.coupling = 'unknown'", "self.enabled_and_selected: self.raw = _channel_bytes(channel_number, w) self.points = len(self.raw) self.calc_times_and_volts() def", "enum import Enum import numpy as np class UnitEnum(Enum): \"\"\"Enumerated", "= w.header.ch1_time_scale if self.enabled_and_selected: self.points = len(w.data.ch1) self.raw = np.frombuffer(w.data.ch1,", "those chosen by user chosen = selected.find(str(channel_number)) != -1 if", "Scale = %10sV/div\\n\" % engineering_string(self.volt_per_division, 2) s += \" Offset", "np.array(w.header.raw_3, dtype=np.uint8) if channel_number == 4: self.raw = np.array(w.header.raw_4, dtype=np.uint8)", "self.coupling = w.header.ch[channel_number-1].coupling.name.upper() self.y_scale = w.header.ch[channel_number-1].y_scale self.y_offset = w.header.ch[channel_number-1].y_offset if", "1 self.volt_offset = 0 self.y_scale = 1 self.y_offset = 0", "self.unit = w.header.ch[channel_number-1].unit if self.enabled_and_selected: if channel_number == 1: self.raw", "if channel_number == 1: self.raw = np.frombuffer(w.header.raw_1, dtype=np.uint8) if channel_number", "channel. The idea is to collect all the relevant information", "+= \" Offset = %10ss\\n\" % engineering_string(self.time_offset, 3) s +=", "self.points-1, self.points) s += \" Raw = [%9d,%9d,%9d ... %9d,%9d]\\n\"", "len(w.header.ch): channel = w.header.ch[channel_number-1] self.enabled = channel.enabled self.enabled_and_selected = channel.enabled", "%9s,%9s]\\n\" % ( v[0], v[1], v[2], v[-2], v[-1]) return s", "= UnitEnum(w.header.ch[channel_number-1].unit_actual) self.coupling = w.header.ch[channel_number-1].coupling.name.upper() self.y_scale = -self.volt_scale self.y_offset =", "= 0 self.volt_per_division = 1 self.probe_value = 1 self.inverted =", "interleaved stored in memory when two or more channels are", "( self.raw[0], self.raw[1], self.raw[2], self.raw[-2], self.raw[-1]) t = [engineering_string(self.times[i], 3)", "w.header.firmware_version self.coupling = w.header.ch[channel_number-1].coupling.name.upper() self.y_scale = -self.volt_scale self.y_offset = self.volt_offset", "numpy array of signal voltages or the stringification method to", "string describing scope selected: string with channels chosen by user", "enabled channel if any([w.header.ch[i].enabled for i in range(channel_number-1)]): offset =", "s += \" Times = [%9s,%9s,%9s ... %9s,%9s]\\n\" % (", "= w.header.time_offset self.points = w.header.points self.stride = w.header.stride self.firmware =", "= w.header.ch[channel_number-1].coupling.name.upper() self.unit = w.header.ch[channel_number-1].unit if self.enabled_and_selected: if channel_number ==", "1, 2, 3, self.points-1, self.points) s += \" Raw =", "the Rigol DS2000 series.\"\"\" self.time_offset = w.header.time_offset self.time_scale = w.header.time_scale", "= 3 def best_scale(number): \"\"\"Scale and units for a number", "Channel %d:\\n\" % self.channel_number s += \" Coupling = %8s\\n\"", "Probe = %7gX\\n\" % self.probe_value s += \" Inverted =", "\" Delta = %10ss/point\\n\" % engineering_string(self.seconds_per_point, 3) s += \"", "0.99999999e-3: return 1e6, 'µ' if absnr < 0.99999999: return 1e3,", "def calc_times_and_volts(self): \"\"\"Calculate the times and voltages for this channel.\"\"\"", "voltages or the stringification method to describe a channel print(channel)", "== 2: # byte pattern CHx CHy # use odd", "object \"\"\" self.channel_number = channel_number self.name = \"CH %d\" %", "channel.enabled self.enabled_and_selected = channel.enabled and chosen self.volt_scale = channel.volt_scale self.volt_offset", "series of bytes for a channel for 1000Z scopes. Waveform", "series.\"\"\" self.time_scale = w.header.time_scale self.time_offset = w.header.time_offset self.points = w.header.points", "dtype=np.uint8) if channel_number == 3: self.raw = np.array(w.header.raw_3, dtype=np.uint8) if", "Return right series of bytes for a channel for 1000Z", "= 0 self.time_offset = 0 self.time_scale = 1 self.enabled =", "self.probe_value s += \" Inverted = %8s\\n\\n\" % self.inverted s", "two or more channels are saved. This unweaves them. Args:", "\" Coupling = %8s\\n\" % self.coupling.rjust(7, ' ') s +=", "self.enabled_and_selected: self.volts = self.y_scale * (127.0 - self.raw) - self.y_offset", "a channel print(channel) \"\"\" from enum import Enum import numpy", "4: # byte pattern CH4 CH3 CH2 CH1 offset =", "4 - channel_number data = np.frombuffer(w.data.raw, dtype=np.uint8) raw_bytes = data[offset::w.header.stride]", "calc_times_and_volts(self): \"\"\"Calculate the times and voltages for this channel.\"\"\" if", "if absnr == 0: return 1, ' ' if absnr", "= channel.enabled and chosen self.volt_scale = channel.volt_scale self.volt_offset = channel.volt_offset", "channel_number): \"\"\"Interpret waveform data for 1000CD series scopes.\"\"\" self.time_scale =", "CHy # use odd bytes when this is the second", "channel.enabled and chosen self.volt_scale = channel.volt_scale self.volt_offset = channel.volt_offset self.y_scale", "channel.volt_per_division self.probe_value = channel.probe_value self.unit = channel.unit self.inverted = channel.inverted", "= w.header.roll_stop if channel_number == 1: self.time_offset = w.header.ch1_time_offset self.time_scale", "dtype=np.uint8) elif channel_number == 2: self.time_offset = w.header.ch2_time_offset self.time_scale =", "== 1: self.raw = np.frombuffer(w.header.raw_1, dtype=np.uint8) if channel_number == 2:", "== 0: return 1, ' ' if absnr < 0.99999999e-9:", "as np class UnitEnum(Enum): \"\"\"Enumerated units for scopes without them.\"\"\"", "dtype=np.uint8) self.calc_times_and_volts() def ds6000(self, w, channel_number): \"\"\"Interpret waveform for the", "and consistent manner. Specifically this lets one just use channel.times", "% channel_number self.waveform = w self.seconds_per_point = w.header.seconds_per_point self.firmware =", "[engineering_string(self.volts[i], 2) + \"V\" for i in [0, 1, 2,", "offset = 0 if w.header.stride == 2: # byte pattern", "self.inverted = False # determine if this channel is one", "self.time_scale = w.header.ch2_time_scale if self.enabled_and_selected: self.points = len(w.data.ch2) self.raw =", "if channel_number == 2: self.raw = np.array(w.header.raw_2, dtype=np.uint8) if channel_number", "'G' def engineering_string(number, n_digits): \"\"\"Format number with proper prefix.\"\"\" scale,", "2, 3, self.points-1, self.points) s += \" Raw = [%9d,%9d,%9d", "Rigol DS2000 series.\"\"\" self.time_offset = w.header.time_offset self.time_scale = w.header.time_scale self.points", ": numpy array of signal voltages or the stringification method", "< 0.99999999: return 1e3, 'm' if absnr < 0.99999999e3: return", "s = \" Channel %d:\\n\" % self.channel_number s += \"", "v[-1]) return s def calc_times_and_volts(self): \"\"\"Calculate the times and voltages", "t[0], t[1], t[2], t[-2], t[-1]) v = [engineering_string(self.volts[i], 2) +", "self.raw = np.frombuffer(w.data.ch2, dtype=np.uint8) self.calc_times_and_volts() def ds1000e(self, w, channel_number): \"\"\"Interpret", "self.time_offset = w.header.ch2_time_offset self.time_scale = w.header.ch2_time_scale if self.enabled_and_selected: self.points =", "< 0.99999999e-6: return 1e9, 'n' if absnr < 0.99999999e-3: return", "= w.header.time_scale self.points = w.header.storage_depth self.firmware = w.header.firmware_version self.unit =", "... %9s,%9s]\\n\" % ( v[0], v[1], v[2], v[-2], v[-1]) return", "= channel_number self.name = \"CH %d\" % channel_number self.waveform =", "= data[offset::w.header.stride] return raw_bytes class Channel(): \"\"\"Base class for a", "offset = 1 elif w.header.stride == 4: # byte pattern", "= [engineering_string(self.times[i], 3) + \"s\" for i in [0, 1,", "0.99999999e-9: return 1e12, 'p' if absnr < 0.99999999e-6: return 1e9,", "raw_bytes = data[offset::w.header.stride] return raw_bytes class Channel(): \"\"\"Base class for", "scope == 'wfm1000e': self.ds1000e(w, channel_number) elif scope == 'wfm1000z': self.ds1000z(w,", "( t[0], t[1], t[2], t[-2], t[-1]) v = [engineering_string(self.volts[i], 2)", "= w.header.ch[channel_number-1].probe_value self.coupling = w.header.ch[channel_number-1].coupling.name.upper() self.y_scale = w.header.ch[channel_number-1].y_scale self.y_offset =", "w.header.ch[channel_number-1].y_offset if self.enabled_and_selected: self.raw = _channel_bytes(channel_number, w) self.points = len(self.raw)", "%8d\\n\\n\" % self.points if self.enabled_and_selected: s += \" Count =", "if channel_number == 1: if self.enabled_and_selected: self.points = len(w.data.ch1) self.raw", "a channel for 1000Z scopes. Waveform points are interleaved stored", "def engineering_string(number, n_digits): \"\"\"Format number with proper prefix.\"\"\" scale, prefix", "Raw = [%9d,%9d,%9d ... %9d,%9d]\\n\" % ( self.raw[0], self.raw[1], self.raw[2],", "= w.header.time_offset self.time_scale = w.header.time_scale self.points = w.header.points self.firmware =", "np.frombuffer(w.header.raw_2, dtype=np.uint8) if channel_number == 3: self.raw = np.frombuffer(w.header.raw_3, dtype=np.uint8)", "the relevant information from all the Rigol scope waveforms into", "w.header.ch[channel_number-1].y_scale self.y_offset = w.header.ch[channel_number-1].y_offset if self.enabled_and_selected: self.raw = _channel_bytes(channel_number, w)", "scopes without them.\"\"\" w = 0 a = 1 v", "2: # byte pattern CHx CHy # use odd bytes", "%d\" % channel_number self.waveform = w self.seconds_per_point = w.header.seconds_per_point self.firmware", "-2, -1]] s += \" Volts = [%9s,%9s,%9s ... %9s,%9s]\\n\"", "with proper prefix.\"\"\" scale, prefix = best_scale(number) fformat = \"%%.%df", "* (127.0 - self.raw) - self.y_offset h = self.points *", "numpy array of signal times channel.volts : numpy array of", "\" Scale = %10sV/div\\n\" % engineering_string(self.volt_per_division, 2) s += \"", "1, ' ' if absnr < 0.99999999e-9: return 1e12, 'p'", "if scope == 'wfm1000c': self.ds1000c(w, channel_number) elif scope == 'wfm1000d':", "w.header.ch[channel_number-1].probe_value self.coupling = w.header.ch[channel_number-1].coupling.name.upper() self.y_scale = w.header.ch[channel_number-1].y_scale self.y_offset = w.header.ch[channel_number-1].y_offset", "0.999999991e9: return 1e-6, 'M' return 1e-9, 'G' def engineering_string(number, n_digits):", "with channels chosen by user Returns: Channel object \"\"\" self.channel_number", "self.raw = np.frombuffer(w.data.ch1, dtype=np.uint8) if channel_number == 2: if self.enabled_and_selected:", "Inverted = %8s\\n\\n\" % self.inverted s += \" Time Base", "self.raw[2], self.raw[-2], self.raw[-1]) t = [engineering_string(self.times[i], 3) + \"s\" for", "self.enabled = False self.enabled_and_selected = False self.volt_scale = 1 self.volt_offset", "= np.frombuffer(w.header.raw_4, dtype=np.uint8) self.calc_times_and_volts() def ds6000(self, w, channel_number): \"\"\"Interpret waveform", "w.header.time_scale self.time_offset = w.header.time_offset self.points = w.header.points self.stride = w.header.stride", "= 1 self.probe_value = 1 self.inverted = False # determine", "without them.\"\"\" w = 0 a = 1 v =", "+= \" Offset = %10sV\\n\" % engineering_string(self.volt_offset, 2) s +=", "scope == 'wfm1000c': self.ds1000c(w, channel_number) elif scope == 'wfm1000d': self.ds1000d(w,", "before this one w: original waveform object Returns byte array", "+= \" Time Base = %10ss/div\\n\" % engineering_string(self.time_scale, 3) s", "% ( v[0], v[1], v[2], v[-2], v[-1]) return s def", "channels are saved. This unweaves them. Args: channel_number: the number", "for 1000D and 1000E series scopes.\"\"\" self.roll_stop = w.header.roll_stop if", "\"CH %d\" % channel_number self.waveform = w self.seconds_per_point = w.header.seconds_per_point", "self.waveform = w self.seconds_per_point = w.header.seconds_per_point self.firmware = 'unknown' self.unit", "Wfm object channel_number: 1, 2, 3, or 4 scope: string", "waveform for the Rigol DS6000 series.\"\"\" self.time_offset = w.header.time_offset self.time_scale", "dtype=np.uint8) if channel_number == 2: self.raw = np.array(w.header.raw_2, dtype=np.uint8) if", "the number of enabled channels before this one w: original", "self.inverted s += \" Time Base = %10ss/div\\n\" % engineering_string(self.time_scale,", "self.y_scale = channel.volt_scale self.y_offset = channel.volt_offset self.volt_per_division = channel.volt_per_division self.probe_value", "byte array for specified channel \"\"\" offset = 0 if", "channel_number == 2: self.raw = np.frombuffer(w.header.raw_2, dtype=np.uint8) if channel_number ==", "lets one just use channel.times : numpy array of signal", "and methods for an oscilloscope channel. The idea is to", "self.enabled_and_selected: self.points = len(w.data.ch1) self.raw = np.frombuffer(w.data.ch1, dtype=np.uint8) if channel_number", "= len(w.data.ch2) self.raw = np.frombuffer(w.data.ch2, dtype=np.uint8) self.calc_times_and_volts() def ds1000z(self, w,", "3) s += \" Offset = %10ss\\n\" % engineering_string(self.time_offset, 3)", "= %8d\\n\\n\" % self.points if self.enabled_and_selected: s += \" Count", "np.array(w.header.raw_1, dtype=np.uint8) if channel_number == 2: self.raw = np.array(w.header.raw_2, dtype=np.uint8)", "waveform data for 1000CD series scopes.\"\"\" self.time_scale = 1.0e-12 *", "a uniform and consistent manner. Specifically this lets one just", "\"\"\"Interpret waveform data for 1000CD series scopes.\"\"\" self.time_scale = 1.0e-12", "channel_number): \"\"\"Interpret waveform data for 1000D and 1000E series scopes.\"\"\"", "\"\"\"Interpret waveform for the Rigol DS2000 series.\"\"\" self.time_offset = w.header.time_offset", "s += \" Raw = [%9d,%9d,%9d ... %9d,%9d]\\n\" % (", "= 'unknown' self.unit = UnitEnum.v self.points = 0 self.raw =", "= 1 self.enabled = False self.enabled_and_selected = False self.volt_scale =", "if self.enabled_and_selected: s += \" Count = [%9d,%9d,%9d ... %9d,%9d]\\n\"", "= np.frombuffer(w.header.raw_3, dtype=np.uint8) if channel_number == 4: self.raw = np.frombuffer(w.header.raw_4,", "len(w.data.ch2) self.raw = np.frombuffer(w.data.ch2, dtype=np.uint8) self.calc_times_and_volts() def ds1000e(self, w, channel_number):", "if self.enabled_and_selected: self.points = len(w.data.ch2) self.raw = np.frombuffer(w.data.ch2, dtype=np.uint8) self.calc_times_and_volts()", "= 1.0e-12 * w.header.time_scale self.time_offset = 1.0e-12 * w.header.time_offset if", "are saved. This unweaves them. Args: channel_number: the number of", "%9d,%9d]\\n\" % ( self.raw[0], self.raw[1], self.raw[2], self.raw[-2], self.raw[-1]) t =", "'wfm4000': self.ds4000(w, channel_number) elif scope == 'wfm6000': self.ds6000(w, channel_number) def", "< 0.99999999e6: return 1e-3, 'k' if absnr < 0.999999991e9: return", "t[-2], t[-1]) v = [engineering_string(self.volts[i], 2) + \"V\" for i", "= self.y_scale * (127.0 - self.raw) - self.y_offset h =", "one w: original waveform object Returns byte array for specified", "0: return 1, ' ' if absnr < 0.99999999e-9: return", "with proper prefix.\"\"\" absnr = abs(number) if absnr == 0:", "pattern CH4 CH3 CH2 CH1 offset = 4 - channel_number", "elif scope == 'wfm2000': self.ds2000(w, channel_number) elif scope == 'wfm4000':", "chosen by user Returns: Channel object \"\"\" self.channel_number = channel_number", "= np.frombuffer(w.data.ch2, dtype=np.uint8) self.calc_times_and_volts() def ds1000e(self, w, channel_number): \"\"\"Interpret waveform", "def ds1000d(self, w, channel_number): \"\"\"Interpret waveform data for 1000CD series", "return 1e12, 'p' if absnr < 0.99999999e-6: return 1e9, 'n'", "v[1], v[2], v[-2], v[-1]) return s def calc_times_and_volts(self): \"\"\"Calculate the", "scope selected: string with channels chosen by user Returns: Channel", "import Enum import numpy as np class UnitEnum(Enum): \"\"\"Enumerated units", "waveform for the Rigol DS1000Z series.\"\"\" self.time_scale = w.header.time_scale self.time_offset", "\"\"\"Interpret waveform for the Rigol DS6000 series.\"\"\" self.time_offset = w.header.time_offset", "second enabled channel if any([w.header.ch[i].enabled for i in range(channel_number-1)]): offset", "3) s += \" Points = %8d\\n\\n\" % self.points if", "for this channel.\"\"\" if self.enabled_and_selected: self.volts = self.y_scale * (127.0", "def ds1000e(self, w, channel_number): \"\"\"Interpret waveform data for 1000D and", "\" Inverted = %8s\\n\\n\" % self.inverted s += \" Time", "= w.header.ch2_time_offset self.time_scale = w.header.ch2_time_scale if self.enabled_and_selected: self.points = len(w.data.ch2)", "= w.header.ch[channel_number-1].y_offset if self.enabled_and_selected: self.raw = _channel_bytes(channel_number, w) self.points =", "%10sV\\n\" % engineering_string(self.volt_offset, 2) s += \" Probe = %7gX\\n\"", "return 1, ' ' if absnr < 0.99999999e6: return 1e-3,", "1.0e-12 * w.header.time_scale self.time_offset = 1.0e-12 * w.header.time_offset if channel_number", "= 1 self.y_offset = 0 self.volt_per_division = 1 self.probe_value =", "return 1e-9, 'G' def engineering_string(number, n_digits): \"\"\"Format number with proper", "them. Args: channel_number: the number of enabled channels before this", "self.ds1000e(w, channel_number) elif scope == 'wfm1000z': self.ds1000z(w, channel_number) elif scope", "this channel.\"\"\" s = \" Channel %d:\\n\" % self.channel_number s", "np.frombuffer(w.data.raw, dtype=np.uint8) raw_bytes = data[offset::w.header.stride] return raw_bytes class Channel(): \"\"\"Base", "_channel_bytes(channel_number, w) self.points = len(self.raw) self.calc_times_and_volts() def ds2000(self, w, channel_number):", "+= \" Times = [%9s,%9s,%9s ... %9s,%9s]\\n\" % ( t[0],", "'wfm1000c': self.ds1000c(w, channel_number) elif scope == 'wfm1000d': self.ds1000d(w, channel_number) elif", "+ \"s\" for i in [0, 1, 2, -2, -1]]", "<= len(w.header.ch): channel = w.header.ch[channel_number-1] self.enabled = channel.enabled self.enabled_and_selected =", "w.header.ch1_time_scale if self.enabled_and_selected: self.points = len(w.data.ch1) self.raw = np.frombuffer(w.data.ch1, dtype=np.uint8)", "+ self.time_offset def ds1000c(self, w, channel_number): \"\"\"Interpret waveform data for", "self.probe_value = 1 self.inverted = False # determine if this", "self.name = \"CH %d\" % channel_number self.waveform = w self.seconds_per_point", "just use channel.times : numpy array of signal times channel.volts", "= [%9d,%9d,%9d ... %9d,%9d]\\n\" % ( 1, 2, 3, self.points-1,", "w = 0 a = 1 v = 2 u", "when two or more channels are saved. This unweaves them.", "Times = [%9s,%9s,%9s ... %9s,%9s]\\n\" % ( t[0], t[1], t[2],", "handled in a uniform and consistent manner. Specifically this lets", "= %10sV\\n\" % engineering_string(self.volt_offset, 2) s += \" Probe =", "structure and methods for an oscilloscope channel. The idea is", "np.frombuffer(w.header.raw_1, dtype=np.uint8) if channel_number == 2: self.raw = np.frombuffer(w.header.raw_2, dtype=np.uint8)", "h = self.points * self.seconds_per_point / 2 self.times = np.linspace(-h,", "if self.enabled_and_selected: self.raw = _channel_bytes(channel_number, w) self.points = len(self.raw) self.calc_times_and_volts()", "1e12, 'p' if absnr < 0.99999999e-6: return 1e9, 'n' if", "t[-1]) v = [engineering_string(self.volts[i], 2) + \"V\" for i in", "channel.volt_scale self.y_offset = channel.volt_offset self.volt_per_division = channel.volt_per_division self.probe_value = channel.probe_value", "#pylint: disable=too-many-instance-attributes #pylint: disable=too-many-return-statements #pylint: disable=too-many-statements \"\"\" Class structure and", "4: self.raw = np.frombuffer(w.header.raw_4, dtype=np.uint8) self.calc_times_and_volts() def ds6000(self, w, channel_number):", "= UnitEnum.v self.points = 0 self.raw = None self.volts =", "w.header.time_offset self.points = w.header.points self.stride = w.header.stride self.firmware = w.preheader.firmware_version", "[%9s,%9s,%9s ... %9s,%9s]\\n\" % ( t[0], t[1], t[2], t[-2], t[-1])", "is one of those chosen by user chosen = selected.find(str(channel_number))", "CH3 CH2 CH1 offset = 4 - channel_number data =", "= channel.volt_per_division self.probe_value = channel.probe_value self.unit = channel.unit self.inverted =", "v = [engineering_string(self.volts[i], 2) + \"V\" for i in [0,", "u = 3 def best_scale(number): \"\"\"Scale and units for a", "-1]] s += \" Volts = [%9s,%9s,%9s ... %9s,%9s]\\n\" %", "* w.header.time_offset if channel_number == 1: if self.enabled_and_selected: self.points =", "absnr = abs(number) if absnr == 0: return 1, '", "scope: string describing scope selected: string with channels chosen by", "= len(w.data.ch2) self.raw = np.frombuffer(w.data.ch2, dtype=np.uint8) self.calc_times_and_volts() def ds1000d(self, w,", "self.raw = np.frombuffer(w.header.raw_4, dtype=np.uint8) self.calc_times_and_volts() def ds6000(self, w, channel_number): \"\"\"Interpret", "self.calc_times_and_volts() def ds4000(self, w, channel_number): \"\"\"Interpret waveform for the Rigol", "\"\"\" Return right series of bytes for a channel for", "elif scope == 'wfm1000e': self.ds1000e(w, channel_number) elif scope == 'wfm1000z':", "fformat = \"%%.%df %%s\" % n_digits s = fformat %", "channel.\"\"\" s = \" Channel %d:\\n\" % self.channel_number s +=", "w, channel_number): \"\"\"Interpret waveform data for 1000CD series scopes.\"\"\" self.time_scale", "return 1e-6, 'M' return 1e-9, 'G' def engineering_string(number, n_digits): \"\"\"Format", "structure that can be handled in a uniform and consistent", "self.time_offset = w.header.time_offset self.points = w.header.points self.stride = w.header.stride self.firmware", "== 4: # byte pattern CH4 CH3 CH2 CH1 offset", "0 a = 1 v = 2 u = 3", "== 4: self.raw = np.frombuffer(w.header.raw_4, dtype=np.uint8) self.calc_times_and_volts() def ds6000(self, w,", "absnr < 0.99999999e6: return 1e-3, 'k' if absnr < 0.999999991e9:", "return s def _channel_bytes(channel_number, w): \"\"\" Return right series of", "#pylint: disable=invalid-name #pylint: disable=too-many-instance-attributes #pylint: disable=too-many-return-statements #pylint: disable=too-many-statements \"\"\" Class", "w.header.points self.firmware = w.header.firmware_version self.coupling = w.header.ch[channel_number-1].coupling.name.upper() self.y_scale = -self.volt_scale", "+= \" Raw = [%9d,%9d,%9d ... %9d,%9d]\\n\" % ( self.raw[0],", "%d:\\n\" % self.channel_number s += \" Coupling = %8s\\n\" %", "3 def best_scale(number): \"\"\"Scale and units for a number with", "% ( self.raw[0], self.raw[1], self.raw[2], self.raw[-2], self.raw[-1]) t = [engineering_string(self.times[i],", "< 0.99999999e-9: return 1e12, 'p' if absnr < 0.99999999e-6: return", "= %10sV/div\\n\" % engineering_string(self.volt_per_division, 2) s += \" Offset =", "scope == 'wfm1000z': self.ds1000z(w, channel_number) elif scope == 'wfm2000': self.ds2000(w,", "= w.header.points self.stride = w.header.stride self.firmware = w.preheader.firmware_version self.probe =", "elif scope == 'wfm1000z': self.ds1000z(w, channel_number) elif scope == 'wfm2000':", "for a channel for 1000Z scopes. Waveform points are interleaved", "def ds1000c(self, w, channel_number): \"\"\"Interpret waveform data for 1000CD series", "absnr < 0.999999991e9: return 1e-6, 'M' return 1e-9, 'G' def", "return 1, ' ' if absnr < 0.99999999e-9: return 1e12,", "is to collect all the relevant information from all the", "in [0, 1, 2, -2, -1]] s += \" Times", "channel_number): \"\"\"Interpret waveform for the Rigol DS2000 series.\"\"\" self.time_offset =", "s += \" Offset = %10ss\\n\" % engineering_string(self.time_offset, 3) s", "channel_number) elif scope == 'wfm1000d': self.ds1000d(w, channel_number) elif scope ==", "self.ds2000(w, channel_number) elif scope == 'wfm4000': self.ds4000(w, channel_number) elif scope", "np.array(w.header.raw_2, dtype=np.uint8) if channel_number == 3: self.raw = np.array(w.header.raw_3, dtype=np.uint8)", "= %10ss/div\\n\" % engineering_string(self.time_scale, 3) s += \" Offset =", "right series of bytes for a channel for 1000Z scopes.", "np.frombuffer(w.data.ch2, dtype=np.uint8) self.calc_times_and_volts() def ds1000z(self, w, channel_number): \"\"\"Interpret waveform for", "a single structure that can be handled in a uniform", "= np.frombuffer(w.header.raw_1, dtype=np.uint8) if channel_number == 2: self.raw = np.frombuffer(w.header.raw_2,", "= w.header.ch[channel_number-1].coupling.name.upper() self.y_scale = -self.volt_scale self.y_offset = self.volt_offset if self.enabled_and_selected:", "this one w: original waveform object Returns byte array for", "== 2: self.raw = np.frombuffer(w.header.raw_2, dtype=np.uint8) if channel_number == 3:", "1e-6, 'M' return 1e-9, 'G' def engineering_string(number, n_digits): \"\"\"Format number", "self.raw = np.frombuffer(w.data.ch2, dtype=np.uint8) self.calc_times_and_volts() def ds1000d(self, w, channel_number): \"\"\"Interpret", "self.ds6000(w, channel_number) def __str__(self): \"\"\"Describe this channel.\"\"\" s = \"", "= np.array(w.header.raw_2, dtype=np.uint8) if channel_number == 3: self.raw = np.array(w.header.raw_3,", "self.volt_scale = 1 self.volt_offset = 0 self.y_scale = 1 self.y_offset", "selected='1234'): \"\"\" Initialize a Channel Object. Args: w: Wfm object", "== 'wfm6000': self.ds6000(w, channel_number) def __str__(self): \"\"\"Describe this channel.\"\"\" s", "np.frombuffer(w.header.raw_3, dtype=np.uint8) if channel_number == 4: self.raw = np.frombuffer(w.header.raw_4, dtype=np.uint8)", "' ' if absnr < 0.99999999e-9: return 1e12, 'p' if", "self.raw[-2], self.raw[-1]) t = [engineering_string(self.times[i], 3) + \"s\" for i", "== 1: self.raw = np.array(w.header.raw_1, dtype=np.uint8) if channel_number == 2:", "series.\"\"\" self.time_offset = w.header.time_offset self.time_scale = w.header.time_scale self.points = w.header.points", "if absnr < 0.99999999e-9: return 1e12, 'p' if absnr <", "w.header.time_scale self.points = w.header.points self.firmware = w.header.firmware_version self.coupling = w.header.ch[channel_number-1].coupling.name.upper()", "0 self.raw = None self.volts = None self.times = None", "== 'wfm1000z': self.ds1000z(w, channel_number) elif scope == 'wfm2000': self.ds2000(w, channel_number)", "of signal voltages or the stringification method to describe a", "original waveform object Returns byte array for specified channel \"\"\"", "Base = %10ss/div\\n\" % engineering_string(self.time_scale, 3) s += \" Offset", "%9s,%9s]\\n\" % ( t[0], t[1], t[2], t[-2], t[-1]) v =", "def ds1000z(self, w, channel_number): \"\"\"Interpret waveform for the Rigol DS1000Z", "channel_number, scope, selected='1234'): \"\"\" Initialize a Channel Object. Args: w:", "self.firmware = w.preheader.firmware_version self.probe = w.header.ch[channel_number-1].probe_value self.coupling = w.header.ch[channel_number-1].coupling.name.upper() self.y_scale", "channel_number == 1: if self.enabled_and_selected: self.points = len(w.data.ch1) self.raw =", "engineering_string(self.volt_offset, 2) s += \" Probe = %7gX\\n\" % self.probe_value", "< 0.99999999e-3: return 1e6, 'µ' if absnr < 0.99999999: return", "False self.enabled_and_selected = False self.volt_scale = 1 self.volt_offset = 0", "= np.linspace(-h, h, self.points) + self.time_offset def ds1000c(self, w, channel_number):", "channel.volt_offset self.volt_per_division = channel.volt_per_division self.probe_value = channel.probe_value self.unit = channel.unit", "elif w.header.stride == 4: # byte pattern CH4 CH3 CH2", "= channel.volt_offset self.y_scale = channel.volt_scale self.y_offset = channel.volt_offset self.volt_per_division =", "uniform and consistent manner. Specifically this lets one just use", "times and voltages for this channel.\"\"\" if self.enabled_and_selected: self.volts =", "from enum import Enum import numpy as np class UnitEnum(Enum):", "if self.enabled_and_selected: self.volts = self.y_scale * (127.0 - self.raw) -", "Args: w: Wfm object channel_number: 1, 2, 3, or 4", "for 1000CD series scopes.\"\"\" self.time_scale = 1.0e-12 * w.header.time_scale self.time_offset", "odd bytes when this is the second enabled channel if", "0 self.volt_per_division = 1 self.probe_value = 1 self.inverted = False", "* self.seconds_per_point / 2 self.times = np.linspace(-h, h, self.points) +", "absnr < 0.99999999e-6: return 1e9, 'n' if absnr < 0.99999999e-3:", "self.volt_per_division = 1 self.probe_value = 1 self.inverted = False #", "self.points if self.enabled_and_selected: s += \" Count = [%9d,%9d,%9d ...", "'M' return 1e-9, 'G' def engineering_string(number, n_digits): \"\"\"Format number with", "= w.header.stride self.firmware = w.preheader.firmware_version self.probe = w.header.ch[channel_number-1].probe_value self.coupling =", "self.raw = _channel_bytes(channel_number, w) self.points = len(self.raw) self.calc_times_and_volts() def ds2000(self,", "from all the Rigol scope waveforms into a single structure", "information from all the Rigol scope waveforms into a single", "1e9, 'n' if absnr < 0.99999999e-3: return 1e6, 'µ' if", "= 1 elif w.header.stride == 4: # byte pattern CH4", "= w.header.ch[channel_number-1].y_scale self.y_offset = w.header.ch[channel_number-1].y_offset if self.enabled_and_selected: self.raw = _channel_bytes(channel_number,", "self.points = len(self.raw) self.calc_times_and_volts() def ds2000(self, w, channel_number): \"\"\"Interpret waveform", "= np.frombuffer(w.data.ch2, dtype=np.uint8) self.calc_times_and_volts() def ds1000z(self, w, channel_number): \"\"\"Interpret waveform", "= None self.coupling = 'unknown' self.roll_stop = 0 self.time_offset =", "= 0 if w.header.stride == 2: # byte pattern CHx", "self.enabled_and_selected: s += \" Count = [%9d,%9d,%9d ... %9d,%9d]\\n\" %", "self.raw = np.frombuffer(w.data.ch2, dtype=np.uint8) self.calc_times_and_volts() def ds1000z(self, w, channel_number): \"\"\"Interpret", "self.ds1000c(w, channel_number) elif scope == 'wfm1000d': self.ds1000d(w, channel_number) elif scope", "channel_number == 2: if self.enabled_and_selected: self.points = len(w.data.ch2) self.raw =", "= len(self.raw) self.calc_times_and_volts() def ds2000(self, w, channel_number): \"\"\"Interpret waveform for", "2, -2, -1]] s += \" Volts = [%9s,%9s,%9s ...", "channel.\"\"\" if self.enabled_and_selected: self.volts = self.y_scale * (127.0 - self.raw)", "v[-2], v[-1]) return s def calc_times_and_volts(self): \"\"\"Calculate the times and", "= 4 - channel_number data = np.frombuffer(w.data.raw, dtype=np.uint8) raw_bytes =", "1000D and 1000E series scopes.\"\"\" self.roll_stop = w.header.roll_stop if channel_number", "< 0.99999999e3: return 1, ' ' if absnr < 0.99999999e6:", "absnr == 0: return 1, ' ' if absnr <", "Time Base = %10ss/div\\n\" % engineering_string(self.time_scale, 3) s += \"", "self.volt_per_division = channel.volt_per_division self.probe_value = channel.probe_value self.unit = channel.unit self.inverted", "'m' if absnr < 0.99999999e3: return 1, ' ' if", "dtype=np.uint8) self.calc_times_and_volts() def ds1000d(self, w, channel_number): \"\"\"Interpret waveform data for", "self.calc_times_and_volts() def ds2000(self, w, channel_number): \"\"\"Interpret waveform for the Rigol", "series.\"\"\" self.time_offset = w.header.time_offset self.time_scale = w.header.time_scale self.points = w.header.storage_depth", "channel_number self.name = \"CH %d\" % channel_number self.waveform = w", "for an oscilloscope channel. The idea is to collect all", "= w.header.firmware_version self.coupling = w.header.ch[channel_number-1].coupling.name.upper() self.y_scale = -self.volt_scale self.y_offset =", "array for specified channel \"\"\" offset = 0 if w.header.stride", "= w.header.points self.firmware = w.header.firmware_version self.coupling = w.header.ch[channel_number-1].coupling.name.upper() self.unit =", "% engineering_string(self.volt_offset, 2) s += \" Probe = %7gX\\n\" %", "collect all the relevant information from all the Rigol scope", "# byte pattern CH4 CH3 CH2 CH1 offset = 4", "w.header.stride == 2: # byte pattern CHx CHy # use", "== 'wfm2000': self.ds2000(w, channel_number) elif scope == 'wfm4000': self.ds4000(w, channel_number)", "for scopes without them.\"\"\" w = 0 a = 1", "... %9d,%9d]\\n\" % ( self.raw[0], self.raw[1], self.raw[2], self.raw[-2], self.raw[-1]) t", "w, channel_number): \"\"\"Interpret waveform data for 1000D and 1000E series", "/ 2 self.times = np.linspace(-h, h, self.points) + self.time_offset def", "w.header.ch2_time_scale if self.enabled_and_selected: self.points = len(w.data.ch2) self.raw = np.frombuffer(w.data.ch2, dtype=np.uint8)", "self.y_scale = -self.volt_scale self.y_offset = self.volt_offset if self.enabled_and_selected: if channel_number", "return s def calc_times_and_volts(self): \"\"\"Calculate the times and voltages for", "= np.frombuffer(w.data.ch1, dtype=np.uint8) elif channel_number == 2: self.time_offset = w.header.ch2_time_offset", "w.header.time_offset self.time_scale = w.header.time_scale self.points = w.header.storage_depth self.firmware = w.header.firmware_version", "w.header.time_scale self.time_offset = 1.0e-12 * w.header.time_offset if channel_number == 1:", "channel.volt_offset self.y_scale = channel.volt_scale self.y_offset = channel.volt_offset self.volt_per_division = channel.volt_per_division", "np.frombuffer(w.header.raw_4, dtype=np.uint8) self.calc_times_and_volts() def ds4000(self, w, channel_number): \"\"\"Interpret waveform for", "self.time_offset def ds1000c(self, w, channel_number): \"\"\"Interpret waveform data for 1000CD", "= w.header.firmware_version self.coupling = w.header.ch[channel_number-1].coupling.name.upper() self.unit = w.header.ch[channel_number-1].unit if self.enabled_and_selected:", "if channel_number <= len(w.header.ch): channel = w.header.ch[channel_number-1] self.enabled = channel.enabled", "for the Rigol DS6000 series.\"\"\" self.time_offset = w.header.time_offset self.time_scale =", "the times and voltages for this channel.\"\"\" if self.enabled_and_selected: self.volts", "if absnr < 0.99999999: return 1e3, 'm' if absnr <", "1000CD series scopes.\"\"\" self.time_scale = 1.0e-12 * w.header.time_scale self.time_offset =", "to describe a channel print(channel) \"\"\" from enum import Enum", "chosen = selected.find(str(channel_number)) != -1 if channel_number <= len(w.header.ch): channel", "\" Offset = %10ss\\n\" % engineering_string(self.time_offset, 3) s += \"", "= False # determine if this channel is one of", "* scale, prefix) return s def _channel_bytes(channel_number, w): \"\"\" Return", "< 0.999999991e9: return 1e-6, 'M' return 1e-9, 'G' def engineering_string(number,", "all the Rigol scope waveforms into a single structure that", "\" Times = [%9s,%9s,%9s ... %9s,%9s]\\n\" % ( t[0], t[1],", "and voltages for this channel.\"\"\" if self.enabled_and_selected: self.volts = self.y_scale", "+= \" Scale = %10sV/div\\n\" % engineering_string(self.volt_per_division, 2) s +=", "self.roll_stop = 0 self.time_offset = 0 self.time_scale = 1 self.enabled", "self.unit = UnitEnum(w.header.ch[channel_number-1].unit_actual) self.coupling = w.header.ch[channel_number-1].coupling.name.upper() self.y_scale = -self.volt_scale self.y_offset", "bytes when this is the second enabled channel if any([w.header.ch[i].enabled", "scope == 'wfm2000': self.ds2000(w, channel_number) elif scope == 'wfm4000': self.ds4000(w,", "channels before this one w: original waveform object Returns byte", "1e-3, 'k' if absnr < 0.999999991e9: return 1e-6, 'M' return", "CHx CHy # use odd bytes when this is the", "\"\"\" Class structure and methods for an oscilloscope channel. The", "np.frombuffer(w.data.ch1, dtype=np.uint8) elif channel_number == 2: self.time_offset = w.header.ch2_time_offset self.time_scale", "__init__(self, w, channel_number, scope, selected='1234'): \"\"\" Initialize a Channel Object.", "Initialize a Channel Object. Args: w: Wfm object channel_number: 1,", "self.coupling = w.header.ch[channel_number-1].coupling.name.upper() self.y_scale = -self.volt_scale self.y_offset = self.volt_offset if", "w.header.firmware_version self.coupling = w.header.ch[channel_number-1].coupling.name.upper() self.unit = w.header.ch[channel_number-1].unit if self.enabled_and_selected: if", "if self.enabled_and_selected: self.points = len(w.data.ch1) self.raw = np.frombuffer(w.data.ch1, dtype=np.uint8) if", "= 0 self.raw = None self.volts = None self.times =", "elif scope == 'wfm4000': self.ds4000(w, channel_number) elif scope == 'wfm6000':", "bytes for a channel for 1000Z scopes. Waveform points are", "class for a single channel.\"\"\" def __init__(self, w, channel_number, scope,", "1 self.inverted = False # determine if this channel is", "engineering_string(number, n_digits): \"\"\"Format number with proper prefix.\"\"\" scale, prefix =", "[0, 1, 2, -2, -1]] s += \" Volts =", "Enum import numpy as np class UnitEnum(Enum): \"\"\"Enumerated units for", "== 'wfm1000c': self.ds1000c(w, channel_number) elif scope == 'wfm1000d': self.ds1000d(w, channel_number)", "w.header.ch[channel_number-1] self.enabled = channel.enabled self.enabled_and_selected = channel.enabled and chosen self.volt_scale", "%10ss\\n\" % engineering_string(self.time_offset, 3) s += \" Delta = %10ss/point\\n\"", "for 1000Z scopes. Waveform points are interleaved stored in memory", "unweaves them. Args: channel_number: the number of enabled channels before", "= len(w.data.ch1) self.raw = np.frombuffer(w.data.ch1, dtype=np.uint8) elif channel_number == 2:", "if channel_number == 4: self.raw = np.frombuffer(w.header.raw_4, dtype=np.uint8) self.calc_times_and_volts() def", "waveform for the Rigol DS4000 series.\"\"\" self.time_offset = w.header.time_offset self.time_scale", "if any([w.header.ch[i].enabled for i in range(channel_number-1)]): offset = 1 elif", "= w.header.firmware_version self.unit = UnitEnum(w.header.ch[channel_number-1].unit_actual) self.coupling = w.header.ch[channel_number-1].coupling.name.upper() self.y_scale =", "== 3: self.raw = np.array(w.header.raw_3, dtype=np.uint8) if channel_number == 4:", "for specified channel \"\"\" offset = 0 if w.header.stride ==", "... %9d,%9d]\\n\" % ( 1, 2, 3, self.points-1, self.points) s", "channel.probe_value self.unit = channel.unit self.inverted = channel.inverted if scope ==", "engineering_string(self.seconds_per_point, 3) s += \" Points = %8d\\n\\n\" % self.points", "1, 2, -2, -1]] s += \" Times = [%9s,%9s,%9s", "UnitEnum(Enum): \"\"\"Enumerated units for scopes without them.\"\"\" w = 0", "self.raw = np.frombuffer(w.header.raw_1, dtype=np.uint8) if channel_number == 2: self.raw =", "channel_number == 4: self.raw = np.frombuffer(w.header.raw_4, dtype=np.uint8) self.calc_times_and_volts() def ds6000(self,", "0.99999999e6: return 1e-3, 'k' if absnr < 0.999999991e9: return 1e-6,", "saved. This unweaves them. Args: channel_number: the number of enabled", "self.time_scale = w.header.time_scale self.time_offset = w.header.time_offset self.points = w.header.points self.stride", "UnitEnum.v self.points = 0 self.raw = None self.volts = None", "= self.volt_offset if self.enabled_and_selected: if channel_number == 1: self.raw =", "self.y_scale = 1 self.y_offset = 0 self.volt_per_division = 1 self.probe_value", "= np.frombuffer(w.header.raw_2, dtype=np.uint8) if channel_number == 3: self.raw = np.frombuffer(w.header.raw_3,", "print(channel) \"\"\" from enum import Enum import numpy as np", "DS1000Z series.\"\"\" self.time_scale = w.header.time_scale self.time_offset = w.header.time_offset self.points =", "abs(number) if absnr == 0: return 1, ' ' if", "t[1], t[2], t[-2], t[-1]) v = [engineering_string(self.volts[i], 2) + \"V\"", "[%9d,%9d,%9d ... %9d,%9d]\\n\" % ( 1, 2, 3, self.points-1, self.points)", "2) s += \" Offset = %10sV\\n\" % engineering_string(self.volt_offset, 2)", "self.points = len(w.data.ch1) self.raw = np.frombuffer(w.data.ch1, dtype=np.uint8) elif channel_number ==", "' if absnr < 0.99999999e6: return 1e-3, 'k' if absnr", "= [%9s,%9s,%9s ... %9s,%9s]\\n\" % ( t[0], t[1], t[2], t[-2],", "t[2], t[-2], t[-1]) v = [engineering_string(self.volts[i], 2) + \"V\" for", "DS4000 series.\"\"\" self.time_offset = w.header.time_offset self.time_scale = w.header.time_scale self.points =", "self.raw = np.array(w.header.raw_1, dtype=np.uint8) if channel_number == 2: self.raw =", "Offset = %10sV\\n\" % engineering_string(self.volt_offset, 2) s += \" Probe", "self.raw = None self.volts = None self.times = None self.coupling", "\" Raw = [%9d,%9d,%9d ... %9d,%9d]\\n\" % ( self.raw[0], self.raw[1],", "None self.times = None self.coupling = 'unknown' self.roll_stop = 0", "+= \" Delta = %10ss/point\\n\" % engineering_string(self.seconds_per_point, 3) s +=", "2: if self.enabled_and_selected: self.points = len(w.data.ch2) self.raw = np.frombuffer(w.data.ch2, dtype=np.uint8)", "0.99999999e3: return 1, ' ' if absnr < 0.99999999e6: return", "disable=too-many-instance-attributes #pylint: disable=too-many-return-statements #pylint: disable=too-many-statements \"\"\" Class structure and methods", "h, self.points) + self.time_offset def ds1000c(self, w, channel_number): \"\"\"Interpret waveform", "self.volt_scale = channel.volt_scale self.volt_offset = channel.volt_offset self.y_scale = channel.volt_scale self.y_offset", "scope == 'wfm1000d': self.ds1000d(w, channel_number) elif scope == 'wfm1000e': self.ds1000e(w,", "np.frombuffer(w.data.ch2, dtype=np.uint8) self.calc_times_and_volts() def ds1000e(self, w, channel_number): \"\"\"Interpret waveform data", "s += \" Offset = %10sV\\n\" % engineering_string(self.volt_offset, 2) s", "Points = %8d\\n\\n\" % self.points if self.enabled_and_selected: s += \"", "2, -2, -1]] s += \" Times = [%9s,%9s,%9s ...", "s += \" Points = %8d\\n\\n\" % self.points if self.enabled_and_selected:", "w) self.points = len(self.raw) self.calc_times_and_volts() def ds2000(self, w, channel_number): \"\"\"Interpret", "w, channel_number): \"\"\"Interpret waveform for the Rigol DS4000 series.\"\"\" self.time_offset", "self.points = w.header.points self.firmware = w.header.firmware_version self.coupling = w.header.ch[channel_number-1].coupling.name.upper() self.unit", "self.raw = np.array(w.header.raw_3, dtype=np.uint8) if channel_number == 4: self.raw =", "\" Points = %8d\\n\\n\" % self.points if self.enabled_and_selected: s +=", "w.header.ch2_time_offset self.time_scale = w.header.ch2_time_scale if self.enabled_and_selected: self.points = len(w.data.ch2) self.raw", "* w.header.time_scale self.time_offset = 1.0e-12 * w.header.time_offset if channel_number ==", "% self.coupling.rjust(7, ' ') s += \" Scale = %10sV/div\\n\"", "== 1: self.time_offset = w.header.ch1_time_offset self.time_scale = w.header.ch1_time_scale if self.enabled_and_selected:", "ds6000(self, w, channel_number): \"\"\"Interpret waveform for the Rigol DS6000 series.\"\"\"", "self.raw = np.array(w.header.raw_2, dtype=np.uint8) if channel_number == 3: self.raw =", "def best_scale(number): \"\"\"Scale and units for a number with proper", "user chosen = selected.find(str(channel_number)) != -1 if channel_number <= len(w.header.ch):", "dtype=np.uint8) self.calc_times_and_volts() def ds1000e(self, w, channel_number): \"\"\"Interpret waveform data for", "2, 3, or 4 scope: string describing scope selected: string", "self.y_offset h = self.points * self.seconds_per_point / 2 self.times =", "= channel.volt_scale self.y_offset = channel.volt_offset self.volt_per_division = channel.volt_per_division self.probe_value =", "3: self.raw = np.frombuffer(w.header.raw_3, dtype=np.uint8) if channel_number == 4: self.raw", "w.header.points self.firmware = w.header.firmware_version self.coupling = w.header.ch[channel_number-1].coupling.name.upper() self.unit = w.header.ch[channel_number-1].unit", "self.volts = None self.times = None self.coupling = 'unknown' self.roll_stop", "selected.find(str(channel_number)) != -1 if channel_number <= len(w.header.ch): channel = w.header.ch[channel_number-1]", "1: self.time_offset = w.header.ch1_time_offset self.time_scale = w.header.ch1_time_scale if self.enabled_and_selected: self.points", "= w.header.ch2_time_scale if self.enabled_and_selected: self.points = len(w.data.ch2) self.raw = np.frombuffer(w.data.ch2,", "channel.\"\"\" def __init__(self, w, channel_number, scope, selected='1234'): \"\"\" Initialize a", "self.points) + self.time_offset def ds1000c(self, w, channel_number): \"\"\"Interpret waveform data", "self.probe = w.header.ch[channel_number-1].probe_value self.coupling = w.header.ch[channel_number-1].coupling.name.upper() self.y_scale = w.header.ch[channel_number-1].y_scale self.y_offset", "Rigol scope waveforms into a single structure that can be", "'wfm1000z': self.ds1000z(w, channel_number) elif scope == 'wfm2000': self.ds2000(w, channel_number) elif", "- self.raw) - self.y_offset h = self.points * self.seconds_per_point /", "\"\"\"Scale and units for a number with proper prefix.\"\"\" absnr", "a = 1 v = 2 u = 3 def", "self.time_scale = 1.0e-12 * w.header.time_scale self.time_offset = 1.0e-12 * w.header.time_offset", "4: self.raw = np.frombuffer(w.header.raw_4, dtype=np.uint8) self.calc_times_and_volts() def ds4000(self, w, channel_number):", "return 1e3, 'm' if absnr < 0.99999999e3: return 1, '", "'k' if absnr < 0.999999991e9: return 1e-6, 'M' return 1e-9,", "return raw_bytes class Channel(): \"\"\"Base class for a single channel.\"\"\"", "def __init__(self, w, channel_number, scope, selected='1234'): \"\"\" Initialize a Channel", "channels chosen by user Returns: Channel object \"\"\" self.channel_number =", "self.raw) - self.y_offset h = self.points * self.seconds_per_point / 2", "def _channel_bytes(channel_number, w): \"\"\" Return right series of bytes for", "determine if this channel is one of those chosen by", "Volts = [%9s,%9s,%9s ... %9s,%9s]\\n\" % ( v[0], v[1], v[2],", "channel_number == 1: self.raw = np.array(w.header.raw_1, dtype=np.uint8) if channel_number ==", "\"\"\"Base class for a single channel.\"\"\" def __init__(self, w, channel_number,", "self.volt_offset = 0 self.y_scale = 1 self.y_offset = 0 self.volt_per_division", "consistent manner. Specifically this lets one just use channel.times :", "= %7gX\\n\" % self.probe_value s += \" Inverted = %8s\\n\\n\"", "self.firmware = w.header.firmware_version self.unit = UnitEnum(w.header.ch[channel_number-1].unit_actual) self.coupling = w.header.ch[channel_number-1].coupling.name.upper() self.y_scale", "units for a number with proper prefix.\"\"\" absnr = abs(number)", "v[2], v[-2], v[-1]) return s def calc_times_and_volts(self): \"\"\"Calculate the times", "= 1.0e-12 * w.header.time_offset if channel_number == 1: if self.enabled_and_selected:", "= w.header.ch[channel_number-1] self.enabled = channel.enabled self.enabled_and_selected = channel.enabled and chosen", "scale, prefix) return s def _channel_bytes(channel_number, w): \"\"\" Return right", "self.ds4000(w, channel_number) elif scope == 'wfm6000': self.ds6000(w, channel_number) def __str__(self):", "\"\"\"Interpret waveform data for 1000D and 1000E series scopes.\"\"\" self.roll_stop", "channel.volts : numpy array of signal voltages or the stringification", "in [0, 1, 2, -2, -1]] s += \" Volts", "disable=invalid-name #pylint: disable=too-many-instance-attributes #pylint: disable=too-many-return-statements #pylint: disable=too-many-statements \"\"\" Class structure", "== 2: self.time_offset = w.header.ch2_time_offset self.time_scale = w.header.ch2_time_scale if self.enabled_and_selected:", "scope, selected='1234'): \"\"\" Initialize a Channel Object. Args: w: Wfm", "self.seconds_per_point / 2 self.times = np.linspace(-h, h, self.points) + self.time_offset", "def __str__(self): \"\"\"Describe this channel.\"\"\" s = \" Channel %d:\\n\"", "waveform for the Rigol DS2000 series.\"\"\" self.time_offset = w.header.time_offset self.time_scale", "channel \"\"\" offset = 0 if w.header.stride == 2: #", "self.points = len(w.data.ch2) self.raw = np.frombuffer(w.data.ch2, dtype=np.uint8) self.calc_times_and_volts() def ds1000z(self,", "relevant information from all the Rigol scope waveforms into a", "0 if w.header.stride == 2: # byte pattern CHx CHy", "'n' if absnr < 0.99999999e-3: return 1e6, 'µ' if absnr", "channel_number == 3: self.raw = np.frombuffer(w.header.raw_3, dtype=np.uint8) if channel_number ==", "w.header.time_offset self.time_scale = w.header.time_scale self.points = w.header.points self.firmware = w.header.firmware_version", "and units for a number with proper prefix.\"\"\" absnr =", "s += \" Volts = [%9s,%9s,%9s ... %9s,%9s]\\n\" % (", "self.times = np.linspace(-h, h, self.points) + self.time_offset def ds1000c(self, w,", "object Returns byte array for specified channel \"\"\" offset =", "if absnr < 0.999999991e9: return 1e-6, 'M' return 1e-9, 'G'", "scope == 'wfm6000': self.ds6000(w, channel_number) def __str__(self): \"\"\"Describe this channel.\"\"\"", "self.times = None self.coupling = 'unknown' self.roll_stop = 0 self.time_offset", "%9d,%9d]\\n\" % ( 1, 2, 3, self.points-1, self.points) s +=", "w, channel_number, scope, selected='1234'): \"\"\" Initialize a Channel Object. Args:", "self.ds1000z(w, channel_number) elif scope == 'wfm2000': self.ds2000(w, channel_number) elif scope", "UnitEnum(w.header.ch[channel_number-1].unit_actual) self.coupling = w.header.ch[channel_number-1].coupling.name.upper() self.y_scale = -self.volt_scale self.y_offset = self.volt_offset", "... %9s,%9s]\\n\" % ( t[0], t[1], t[2], t[-2], t[-1]) v", "or 4 scope: string describing scope selected: string with channels", "'p' if absnr < 0.99999999e-6: return 1e9, 'n' if absnr", "%8s\\n\\n\" % self.inverted s += \" Time Base = %10ss/div\\n\"", "of bytes for a channel for 1000Z scopes. Waveform points", "of enabled channels before this one w: original waveform object", "% (number * scale, prefix) return s def _channel_bytes(channel_number, w):", "self.enabled_and_selected: self.points = len(w.data.ch2) self.raw = np.frombuffer(w.data.ch2, dtype=np.uint8) self.calc_times_and_volts() def", "waveforms into a single structure that can be handled in", "Specifically this lets one just use channel.times : numpy array", "prefix.\"\"\" scale, prefix = best_scale(number) fformat = \"%%.%df %%s\" %", "this lets one just use channel.times : numpy array of", "\"\"\" self.channel_number = channel_number self.name = \"CH %d\" % channel_number", "w: Wfm object channel_number: 1, 2, 3, or 4 scope:", "1 self.probe_value = 1 self.inverted = False # determine if", "into a single structure that can be handled in a", "data[offset::w.header.stride] return raw_bytes class Channel(): \"\"\"Base class for a single", "0 self.y_scale = 1 self.y_offset = 0 self.volt_per_division = 1", "ds1000c(self, w, channel_number): \"\"\"Interpret waveform data for 1000CD series scopes.\"\"\"", "np.frombuffer(w.data.ch1, dtype=np.uint8) if channel_number == 2: if self.enabled_and_selected: self.points =", "if channel_number == 3: self.raw = np.array(w.header.raw_3, dtype=np.uint8) if channel_number", "CH1 offset = 4 - channel_number data = np.frombuffer(w.data.raw, dtype=np.uint8)", "array of signal times channel.volts : numpy array of signal", "self.raw[-1]) t = [engineering_string(self.times[i], 3) + \"s\" for i in", "scale, prefix = best_scale(number) fformat = \"%%.%df %%s\" % n_digits", "#pylint: disable=too-many-statements \"\"\" Class structure and methods for an oscilloscope", "channel.unit self.inverted = channel.inverted if scope == 'wfm1000c': self.ds1000c(w, channel_number)", "self.inverted = channel.inverted if scope == 'wfm1000c': self.ds1000c(w, channel_number) elif", "self.calc_times_and_volts() def ds1000e(self, w, channel_number): \"\"\"Interpret waveform data for 1000D", "if self.enabled_and_selected: if channel_number == 1: self.raw = np.frombuffer(w.header.raw_1, dtype=np.uint8)", "return 1e6, 'µ' if absnr < 0.99999999: return 1e3, 'm'", "= w.header.ch[channel_number-1].unit if self.enabled_and_selected: if channel_number == 1: self.raw =", "% self.channel_number s += \" Coupling = %8s\\n\" % self.coupling.rjust(7,", "= channel.unit self.inverted = channel.inverted if scope == 'wfm1000c': self.ds1000c(w,", "\"%%.%df %%s\" % n_digits s = fformat % (number *", "all the relevant information from all the Rigol scope waveforms", "w, channel_number): \"\"\"Interpret waveform for the Rigol DS6000 series.\"\"\" self.time_offset", "scopes.\"\"\" self.roll_stop = w.header.roll_stop if channel_number == 1: self.time_offset =", "self.calc_times_and_volts() def ds6000(self, w, channel_number): \"\"\"Interpret waveform for the Rigol", "% engineering_string(self.seconds_per_point, 3) s += \" Points = %8d\\n\\n\" %", "self.raw = np.frombuffer(w.header.raw_3, dtype=np.uint8) if channel_number == 4: self.raw =", "self.seconds_per_point = w.header.seconds_per_point self.firmware = 'unknown' self.unit = UnitEnum.v self.points", "= best_scale(number) fformat = \"%%.%df %%s\" % n_digits s =", "absnr < 0.99999999e-3: return 1e6, 'µ' if absnr < 0.99999999:", "w.header.ch[channel_number-1].coupling.name.upper() self.unit = w.header.ch[channel_number-1].unit if self.enabled_and_selected: if channel_number == 1:", "= \"%%.%df %%s\" % n_digits s = fformat % (number" ]
[ "lr=0.0025, momentum=0.9, weight_decay=0.0001) #(1x2=2) total_epochs=24 evaluation = dict(classwise=True, interval=1, metric='bbox')", "4 GPUs #optimizer = dict(type='SGD', lr=0.0025, momentum=0.9, weight_decay=0.0001) #(1x2=2) total_epochs=24", "dict(classwise=True, interval=1, metric='bbox') work_dir = '/media/storage1/projects/WilLiCam/checkpoint_workdir/raubtierv2a/faster_rcnn_x101_64x4d_fpn_1x_raubtierv2a_nofreeze_4gpu' #http://download.openmmlab.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_x101_64x4d_fpn_1x_coco/faster_rcnn_x101_64x4d_fpn_1x_coco_20200204-833ee192.pth load_from = 'checkpoints/faster_rcnn_x101_64x4d_fpn_1x_coco_20200204-833ee192.pth'", "total_epochs=24 evaluation = dict(classwise=True, interval=1, metric='bbox') work_dir = '/media/storage1/projects/WilLiCam/checkpoint_workdir/raubtierv2a/faster_rcnn_x101_64x4d_fpn_1x_raubtierv2a_nofreeze_4gpu' #http://download.openmmlab.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_x101_64x4d_fpn_1x_coco/faster_rcnn_x101_64x4d_fpn_1x_coco_20200204-833ee192.pth", "roi_head=dict( bbox_head=dict( num_classes=3 ) ) ) dataset_type = 'COCODataset' classes", "('luchs', 'rotfuchs', 'wolf') data = dict( train=dict( img_prefix='raubtierv2a/train/', classes=classes, ann_file='raubtierv2a/train/_annotations.coco.json'),", "= dict( train=dict( img_prefix='raubtierv2a/train/', classes=classes, ann_file='raubtierv2a/train/_annotations.coco.json'), val=dict( img_prefix='raubtierv2a/valid/', classes=classes, ann_file='raubtierv2a/valid/_annotations.coco.json'),", "'COCODataset' classes = ('luchs', 'rotfuchs', 'wolf') data = dict( train=dict(", "dict( train=dict( img_prefix='raubtierv2a/train/', classes=classes, ann_file='raubtierv2a/train/_annotations.coco.json'), val=dict( img_prefix='raubtierv2a/valid/', classes=classes, ann_file='raubtierv2a/valid/_annotations.coco.json'), test=dict(", "model = dict( backbone=dict( num_stages=4, #frozen_stages=4 ), roi_head=dict( bbox_head=dict( num_classes=3", "= 'COCODataset' classes = ('luchs', 'rotfuchs', 'wolf') data = dict(", "ann_file='raubtierv2a/train/_annotations.coco.json'), val=dict( img_prefix='raubtierv2a/valid/', classes=classes, ann_file='raubtierv2a/valid/_annotations.coco.json'), test=dict( img_prefix='raubtierv2a/test/', classes=classes, ann_file='raubtierv2a/test/_annotations.coco.json')) #optimizer", "#optimizer = dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001) #original (8x2=16) optimizer =", "momentum=0.9, weight_decay=0.0001) #original (8x2=16) optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)", "classes=classes, ann_file='raubtierv2a/train/_annotations.coco.json'), val=dict( img_prefix='raubtierv2a/valid/', classes=classes, ann_file='raubtierv2a/valid/_annotations.coco.json'), test=dict( img_prefix='raubtierv2a/test/', classes=classes, ann_file='raubtierv2a/test/_annotations.coco.json'))", "ann_file='raubtierv2a/test/_annotations.coco.json')) #optimizer = dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001) #original (8x2=16) optimizer", "dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001) #original (8x2=16) optimizer = dict(type='SGD', lr=0.01,", "momentum=0.9, weight_decay=0.0001) #(4x2=8) 4 GPUs #optimizer = dict(type='SGD', lr=0.0025, momentum=0.9,", "classes=classes, ann_file='raubtierv2a/test/_annotations.coco.json')) #optimizer = dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001) #original (8x2=16)", "#original (8x2=16) optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001) #(4x2=8) 4", "= ('luchs', 'rotfuchs', 'wolf') data = dict( train=dict( img_prefix='raubtierv2a/train/', classes=classes,", "lr=0.02, momentum=0.9, weight_decay=0.0001) #original (8x2=16) optimizer = dict(type='SGD', lr=0.01, momentum=0.9,", "weight_decay=0.0001) #(1x2=2) total_epochs=24 evaluation = dict(classwise=True, interval=1, metric='bbox') work_dir =", "weight_decay=0.0001) #(4x2=8) 4 GPUs #optimizer = dict(type='SGD', lr=0.0025, momentum=0.9, weight_decay=0.0001)", "'../faster_rcnn/faster_rcnn_x101_64x4d_fpn_1x_coco.py' model = dict( backbone=dict( num_stages=4, #frozen_stages=4 ), roi_head=dict( bbox_head=dict(", "#frozen_stages=4 ), roi_head=dict( bbox_head=dict( num_classes=3 ) ) ) dataset_type =", "classes=classes, ann_file='raubtierv2a/valid/_annotations.coco.json'), test=dict( img_prefix='raubtierv2a/test/', classes=classes, ann_file='raubtierv2a/test/_annotations.coco.json')) #optimizer = dict(type='SGD', lr=0.02,", "img_prefix='raubtierv2a/valid/', classes=classes, ann_file='raubtierv2a/valid/_annotations.coco.json'), test=dict( img_prefix='raubtierv2a/test/', classes=classes, ann_file='raubtierv2a/test/_annotations.coco.json')) #optimizer = dict(type='SGD',", "#(4x2=8) 4 GPUs #optimizer = dict(type='SGD', lr=0.0025, momentum=0.9, weight_decay=0.0001) #(1x2=2)", "= dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001) #original (8x2=16) optimizer = dict(type='SGD',", "= dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001) #(4x2=8) 4 GPUs #optimizer =", "), roi_head=dict( bbox_head=dict( num_classes=3 ) ) ) dataset_type = 'COCODataset'", "'rotfuchs', 'wolf') data = dict( train=dict( img_prefix='raubtierv2a/train/', classes=classes, ann_file='raubtierv2a/train/_annotations.coco.json'), val=dict(", "(8x2=16) optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001) #(4x2=8) 4 GPUs", "lr=0.01, momentum=0.9, weight_decay=0.0001) #(4x2=8) 4 GPUs #optimizer = dict(type='SGD', lr=0.0025,", "GPUs #optimizer = dict(type='SGD', lr=0.0025, momentum=0.9, weight_decay=0.0001) #(1x2=2) total_epochs=24 evaluation", "#optimizer = dict(type='SGD', lr=0.0025, momentum=0.9, weight_decay=0.0001) #(1x2=2) total_epochs=24 evaluation =", "= '../faster_rcnn/faster_rcnn_x101_64x4d_fpn_1x_coco.py' model = dict( backbone=dict( num_stages=4, #frozen_stages=4 ), roi_head=dict(", ") ) ) dataset_type = 'COCODataset' classes = ('luchs', 'rotfuchs',", "val=dict( img_prefix='raubtierv2a/valid/', classes=classes, ann_file='raubtierv2a/valid/_annotations.coco.json'), test=dict( img_prefix='raubtierv2a/test/', classes=classes, ann_file='raubtierv2a/test/_annotations.coco.json')) #optimizer =", "img_prefix='raubtierv2a/test/', classes=classes, ann_file='raubtierv2a/test/_annotations.coco.json')) #optimizer = dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001) #original", "= dict( backbone=dict( num_stages=4, #frozen_stages=4 ), roi_head=dict( bbox_head=dict( num_classes=3 )", "weight_decay=0.0001) #original (8x2=16) optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001) #(4x2=8)", "data = dict( train=dict( img_prefix='raubtierv2a/train/', classes=classes, ann_file='raubtierv2a/train/_annotations.coco.json'), val=dict( img_prefix='raubtierv2a/valid/', classes=classes,", "img_prefix='raubtierv2a/train/', classes=classes, ann_file='raubtierv2a/train/_annotations.coco.json'), val=dict( img_prefix='raubtierv2a/valid/', classes=classes, ann_file='raubtierv2a/valid/_annotations.coco.json'), test=dict( img_prefix='raubtierv2a/test/', classes=classes,", "_base_ = '../faster_rcnn/faster_rcnn_x101_64x4d_fpn_1x_coco.py' model = dict( backbone=dict( num_stages=4, #frozen_stages=4 ),", "dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001) #(4x2=8) 4 GPUs #optimizer = dict(type='SGD',", "test=dict( img_prefix='raubtierv2a/test/', classes=classes, ann_file='raubtierv2a/test/_annotations.coco.json')) #optimizer = dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001)", "#(1x2=2) total_epochs=24 evaluation = dict(classwise=True, interval=1, metric='bbox') work_dir = '/media/storage1/projects/WilLiCam/checkpoint_workdir/raubtierv2a/faster_rcnn_x101_64x4d_fpn_1x_raubtierv2a_nofreeze_4gpu'", "= dict(classwise=True, interval=1, metric='bbox') work_dir = '/media/storage1/projects/WilLiCam/checkpoint_workdir/raubtierv2a/faster_rcnn_x101_64x4d_fpn_1x_raubtierv2a_nofreeze_4gpu' #http://download.openmmlab.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_x101_64x4d_fpn_1x_coco/faster_rcnn_x101_64x4d_fpn_1x_coco_20200204-833ee192.pth load_from =", "'wolf') data = dict( train=dict( img_prefix='raubtierv2a/train/', classes=classes, ann_file='raubtierv2a/train/_annotations.coco.json'), val=dict( img_prefix='raubtierv2a/valid/',", "dataset_type = 'COCODataset' classes = ('luchs', 'rotfuchs', 'wolf') data =", ") dataset_type = 'COCODataset' classes = ('luchs', 'rotfuchs', 'wolf') data", "bbox_head=dict( num_classes=3 ) ) ) dataset_type = 'COCODataset' classes =", ") ) dataset_type = 'COCODataset' classes = ('luchs', 'rotfuchs', 'wolf')", "num_stages=4, #frozen_stages=4 ), roi_head=dict( bbox_head=dict( num_classes=3 ) ) ) dataset_type", "dict( backbone=dict( num_stages=4, #frozen_stages=4 ), roi_head=dict( bbox_head=dict( num_classes=3 ) )", "= dict(type='SGD', lr=0.0025, momentum=0.9, weight_decay=0.0001) #(1x2=2) total_epochs=24 evaluation = dict(classwise=True,", "momentum=0.9, weight_decay=0.0001) #(1x2=2) total_epochs=24 evaluation = dict(classwise=True, interval=1, metric='bbox') work_dir", "classes = ('luchs', 'rotfuchs', 'wolf') data = dict( train=dict( img_prefix='raubtierv2a/train/',", "dict(type='SGD', lr=0.0025, momentum=0.9, weight_decay=0.0001) #(1x2=2) total_epochs=24 evaluation = dict(classwise=True, interval=1,", "backbone=dict( num_stages=4, #frozen_stages=4 ), roi_head=dict( bbox_head=dict( num_classes=3 ) ) )", "optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001) #(4x2=8) 4 GPUs #optimizer", "num_classes=3 ) ) ) dataset_type = 'COCODataset' classes = ('luchs',", "evaluation = dict(classwise=True, interval=1, metric='bbox') work_dir = '/media/storage1/projects/WilLiCam/checkpoint_workdir/raubtierv2a/faster_rcnn_x101_64x4d_fpn_1x_raubtierv2a_nofreeze_4gpu' #http://download.openmmlab.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_x101_64x4d_fpn_1x_coco/faster_rcnn_x101_64x4d_fpn_1x_coco_20200204-833ee192.pth load_from", "train=dict( img_prefix='raubtierv2a/train/', classes=classes, ann_file='raubtierv2a/train/_annotations.coco.json'), val=dict( img_prefix='raubtierv2a/valid/', classes=classes, ann_file='raubtierv2a/valid/_annotations.coco.json'), test=dict( img_prefix='raubtierv2a/test/',", "ann_file='raubtierv2a/valid/_annotations.coco.json'), test=dict( img_prefix='raubtierv2a/test/', classes=classes, ann_file='raubtierv2a/test/_annotations.coco.json')) #optimizer = dict(type='SGD', lr=0.02, momentum=0.9," ]
[ "from distutils.core import setup, Extension setup(name = 'qconf_py', version =", "'qconf_py', version = '1.2.2', ext_modules = [Extension('qconf_py', ['lib/python_qconf.cc'], include_dirs=['/usr/local/include/qconf'], extra_objects=['/usr/local/qconf/lib/libqconf.a']", "setup, Extension setup(name = 'qconf_py', version = '1.2.2', ext_modules =", "Extension setup(name = 'qconf_py', version = '1.2.2', ext_modules = [Extension('qconf_py',", "import setup, Extension setup(name = 'qconf_py', version = '1.2.2', ext_modules", "version = '1.2.2', ext_modules = [Extension('qconf_py', ['lib/python_qconf.cc'], include_dirs=['/usr/local/include/qconf'], extra_objects=['/usr/local/qconf/lib/libqconf.a'] )])", "= 'qconf_py', version = '1.2.2', ext_modules = [Extension('qconf_py', ['lib/python_qconf.cc'], include_dirs=['/usr/local/include/qconf'],", "<filename>driver/python/setup.py from distutils.core import setup, Extension setup(name = 'qconf_py', version", "setup(name = 'qconf_py', version = '1.2.2', ext_modules = [Extension('qconf_py', ['lib/python_qconf.cc'],", "distutils.core import setup, Extension setup(name = 'qconf_py', version = '1.2.2'," ]
[ "while h >= a: a = 2 ** i i", "0 t = True for j in range(1, i-1): c", "h >= a: a = 2 ** i i +=", "** i i += 1 s = 0 t =", "j in range(1, i-1): c += 2 ** j print(c)", "1 b = 1 c = 1 while h >=", "i = 1 a = 1 b = 1 c", "t = True for j in range(1, i-1): c +=", "= 1 c = 1 while h >= a: a", "= 1 b = 1 c = 1 while h", "= 1 while h >= a: a = 2 **", ">= a: a = 2 ** i i += 1", "1 while h >= a: a = 2 ** i", "= 0 t = True for j in range(1, i-1):", "int(input()) i = 1 a = 1 b = 1", "a: a = 2 ** i i += 1 s", "b = 1 c = 1 while h >= a:", "= int(input()) i = 1 a = 1 b =", "a = 2 ** i i += 1 s =", "i i += 1 s = 0 t = True", "1 s = 0 t = True for j in", "1 a = 1 b = 1 c = 1", "a = 1 b = 1 c = 1 while", "= True for j in range(1, i-1): c += 2", "2 ** i i += 1 s = 0 t", "s = 0 t = True for j in range(1,", "= 2 ** i i += 1 s = 0", "for j in range(1, i-1): c += 2 ** j", "c = 1 while h >= a: a = 2", "+= 1 s = 0 t = True for j", "True for j in range(1, i-1): c += 2 **", "1 c = 1 while h >= a: a =", "h = int(input()) i = 1 a = 1 b", "= 1 a = 1 b = 1 c =", "i += 1 s = 0 t = True for" ]
[ "SAMPLE_INDEX gopro: Optional[GoPro] = None return_code = 0 try: with", "\"battery_results.csv\" dump_results_as_csv(csv_location) if gopro is not None: gopro.close() console.print(\"Exiting...\") return", "code \"\"\" identifier, log_location, poll = parse_arguments() global logger logger", "initial values. bars = gopro.ble_status.batt_level.register_value_update().flatten percentage = gopro.ble_status.int_batt_per.register_value_update().flatten # Start", "last_percentage = initial_percentage last_bars = initial_bars while True: # Block", "default camera SSID. \\ If not used, first discovered GoPro", "5:05:45 PM \"\"\"Example to continuously read the battery (with no", "\"--poll\", type=int, help=\"Set to poll the battery at a given", "log_battery.py/Open GoPro, Version 2.0 (C) Copyright 2021 GoPro, Inc. (http://gopro.com/OpenGoPro).", "logger = logging.getLogger(__name__) console = Console() # rich consoler printer", "enable_wifi=False) as gopro: set_logging_level(logger, logging.ERROR) # # Setup notifications if", "dump_results_as_csv(csv_location) if gopro is not None: gopro.close() console.print(\"Exiting...\") return return_code", "# Otherwise, poll else: with console.status(\"[bold green]Polling the battery until", "of GoPro serial number, which is the last 4 digits", "store detailed log\", default=\"log_battery.log\", ) parser.add_argument( \"-p\", \"--poll\", type=int, help=\"Set", "[] def dump_results_as_csv(location: Path) -> None: \"\"\"Write all of the", "Path) -> None: \"\"\"Write all of the samples to a", "write to \"\"\" console.print(f\"Dumping results as CSV to {location}\") with", "logger = setup_logging(logger, log_location) global SAMPLE_INDEX gopro: Optional[GoPro] = None", "Copyright 2021 GoPro, Inc. (http://gopro.com/OpenGoPro). # This copyright was auto-generated", "set, battery level will be notified instead. Defaults to notifications.\",", "from rich.console import Console from open_gopro import GoPro from open_gopro.constants", "values. bars = gopro.ble_status.batt_level.register_value_update().flatten percentage = gopro.ble_status.int_batt_per.register_value_update().flatten # Start a", "battery level notifications threading.Thread( target=process_battery_notifications, args=(gopro, bars, percentage), daemon=True ).start()", "with console.status(\"[bold green]Polling the battery until it dies...\"): while True:", "percentage=last_percentage, bars=last_bars)) console.print(str(SAMPLES[-1])) SAMPLE_INDEX += 1 def main() -> int:", "int) -> None: \"\"\"Separate thread to continuously check for and", "poll else: with console.status(\"[bold green]Polling the battery until it dies...\"):", "return_code = 1 except KeyboardInterrupt: logger.warning(\"Received keyboard interrupt. Shutting down...\")", "to continuously read the battery (with no Wifi connection)\"\"\" import", "of the default camera SSID. \\ If not used, first", "notifications while True: time.sleep(1) # Otherwise, poll else: with console.status(\"[bold", "Optional[GoPro] = None return_code = 0 try: with GoPro(identifier, enable_wifi=False)", "{self.bars}, percentage: {self.percentage}\" SAMPLE_INDEX = 0 SAMPLES: List[Sample] = []", "data points if they have changed last_percentage = ( notification.data[StatusId.INT_BATT_PER]", "copyright was auto-generated on Wed, Sep 1, 2021 5:05:45 PM", "= Console() # rich consoler printer BarsType = Literal[0, 1,", "Literal[0, 1, 2, 3] @dataclass class Sample: \"\"\"Simple class to", "notifications.\", default=None, ) args = parser.parse_args() return args.identifier, args.log, args.poll", "as CSV to {location}\") with open(location, mode=\"w\") as f: w", "- initial_time).seconds, s.percentage, s.bars]) def process_battery_notifications(gopro: GoPro, initial_bars: BarsType, initial_percentage:", "bars=gopro.ble_status.batt_level.get_value().flatten, ) ) console.print(str(SAMPLES[-1])) SAMPLE_INDEX += 1 time.sleep(poll) except Exception", "return return_code # pylint: disable=lost-exception def parse_arguments() -> Tuple[str, Path,", "(http://gopro.com/OpenGoPro). # This copyright was auto-generated on Wed, Sep 1,", "bars: BarsType def __post_init__(self) -> None: self.time = datetime.now() def", "pathlib import Path from datetime import datetime from dataclasses import", "import dataclass from typing import Optional, Tuple, Literal, List from", "except KeyboardInterrupt: logger.warning(\"Received keyboard interrupt. Shutting down...\") finally: if len(SAMPLES)", "= parse_arguments() global logger logger = setup_logging(logger, log_location) global SAMPLE_INDEX", "to deal with battery level notifications while True: time.sleep(1) #", "dataclasses import dataclass from typing import Optional, Tuple, Literal, List", "+= 1 def main() -> int: \"\"\"Main program functionality Returns:", "interval. If not set, battery level will be notified instead.", "(s.time - initial_time).seconds, s.percentage, s.bars]) def process_battery_notifications(gopro: GoPro, initial_bars: BarsType,", "read the battery (either by polling or notifications).\" ) parser.add_argument(", "import datetime from dataclasses import dataclass from typing import Optional,", "\\ If not used, first discovered GoPro will be connected", "the battery at a given interval. If not set, battery", "was auto-generated on Wed, Sep 1, 2021 5:05:45 PM \"\"\"Example", "pylint: disable=missing-return-doc return f\"Index {self.index} @ time {self.time.strftime('%H:%M:%S')} --> bars:", "percentage = gopro.ble_status.int_batt_per.register_value_update().flatten # Start a thread to handle asynchronous", "time.sleep(poll) except Exception as e: # pylint: disable=broad-except logger.error(repr(e)) return_code", "bars, percentage), daemon=True ).start() with console.status(\"[bold green]Receiving battery notifications until", "in notification.data else last_bars ) # Append and print sample", "parser.add_argument( \"-i\", \"--identifier\", type=str, help=\"Last 4 digits of GoPro serial", "Enable notifications of the relevant battery statuses. Also store initial", "time.sleep(1) # Otherwise, poll else: with console.status(\"[bold green]Polling the battery", "Otherwise, poll else: with console.status(\"[bold green]Polling the battery until it", "with battery level notifications while True: time.sleep(1) # Otherwise, poll", "poll, this isn't used. Args: gopro (GoPro): instance to get", "to save log, path to VLC) \"\"\" parser = argparse.ArgumentParser(", "only and continuously read the battery (either by polling or", "initial_bars (BarsType): Initial bars level when notifications were enabled initial_percentage", "{self.index} @ time {self.time.strftime('%H:%M:%S')} --> bars: {self.bars}, percentage: {self.percentage}\" SAMPLE_INDEX", "for s in SAMPLES: w.writerow([s.index, (s.time - initial_time).seconds, s.percentage, s.bars])", "import Path from datetime import datetime from dataclasses import dataclass", "\"\"\" last_percentage = initial_percentage last_bars = initial_bars while True: #", "e: # pylint: disable=broad-except logger.error(repr(e)) return_code = 1 except KeyboardInterrupt:", "default=None, ) args = parser.parse_args() return args.identifier, args.log, args.poll if", "is the last 4 digits of the default camera SSID.", "get updates from initial_bars (BarsType): Initial bars level when notifications", "parse_arguments() global logger logger = setup_logging(logger, log_location) global SAMPLE_INDEX gopro:", "logging.ERROR) # # Setup notifications if we are not polling", "used, first discovered GoPro will be connected to\", default=None, )", "SAMPLE_INDEX += 1 time.sleep(poll) except Exception as e: # pylint:", "PM \"\"\"Example to continuously read the battery (with no Wifi", "import threading from pathlib import Path from datetime import datetime", "they have changed last_percentage = ( notification.data[StatusId.INT_BATT_PER] if StatusId.INT_BATT_PER in", "it dies...\"): while True: SAMPLES.append( Sample( index=SAMPLE_INDEX, percentage=gopro.ble_status.int_batt_per.get_value().flatten, bars=gopro.ble_status.batt_level.get_value().flatten, )", "discovered GoPro will be connected to\", default=None, ) parser.add_argument( \"-l\",", "SSID. \\ If not used, first discovered GoPro will be", "\"\"\" parser = argparse.ArgumentParser( description=\"Connect to the GoPro via BLE", "List from rich.console import Console from open_gopro import GoPro from", "description=\"Connect to the GoPro via BLE only and continuously read", "-> int: \"\"\"Main program functionality Returns: int: program return code", "initial_bars: BarsType, initial_percentage: int) -> None: \"\"\"Separate thread to continuously", "battery level will be notified instead. Defaults to notifications.\", default=None,", "\"\"\"Main program functionality Returns: int: program return code \"\"\" identifier,", "and continuously read the battery (either by polling or notifications).\"", "argparse.ArgumentParser( description=\"Connect to the GoPro via BLE only and continuously", "level will be notified instead. Defaults to notifications.\", default=None, )", "Setup notifications if we are not polling if poll is", "self.time = datetime.now() def __str__(self) -> str: # pylint: disable=missing-return-doc", "= 1 except KeyboardInterrupt: logger.warning(\"Received keyboard interrupt. Shutting down...\") finally:", "no Wifi connection)\"\"\" import csv import time import logging import", "and store battery notifications. If the CLI parameter was set", "in SAMPLES: w.writerow([s.index, (s.time - initial_time).seconds, s.percentage, s.bars]) def process_battery_notifications(gopro:", "( notification.data[StatusId.INT_BATT_PER] if StatusId.INT_BATT_PER in notification.data else last_percentage ) last_bars", "with console.status(\"[bold green]Receiving battery notifications until it dies...\"): # Sleep", "log_location, poll = parse_arguments() global logger logger = setup_logging(logger, log_location)", "BarsType = Literal[0, 1, 2, 3] @dataclass class Sample: \"\"\"Simple", "the CLI parameter was set to poll, this isn't used.", "GoPro via BLE only and continuously read the battery (either", "= ( notification.data[StatusId.BATT_LEVEL] if StatusId.BATT_LEVEL in notification.data else last_bars )", "as f: w = csv.writer(f, delimiter=\",\", quotechar='\"', quoting=csv.QUOTE_MINIMAL) w.writerow([\"index\", \"time\",", "delimiter=\",\", quotechar='\"', quoting=csv.QUOTE_MINIMAL) w.writerow([\"index\", \"time\", \"percentage\", \"bars\"]) initial_time = SAMPLES[0].time", "parser.parse_args() return args.identifier, args.log, args.poll if __name__ == \"__main__\": main()", "StatusId from open_gopro.util import setup_logging, set_logging_level logger = logging.getLogger(__name__) console", "notifications were enabled initial_percentage (int): Initial percentage when notifications were", "gopro.ble_status.int_batt_per.register_value_update().flatten # Start a thread to handle asynchronous battery level", "save log, path to VLC) \"\"\" parser = argparse.ArgumentParser( description=\"Connect", "digits of GoPro serial number, which is the last 4", "set to poll, this isn't used. Args: gopro (GoPro): instance", "Append and print sample global SAMPLE_INDEX SAMPLES.append(Sample(index=SAMPLE_INDEX, percentage=last_percentage, bars=last_bars)) console.print(str(SAMPLES[-1]))", "1, 2, 3] @dataclass class Sample: \"\"\"Simple class to store", "VLC) \"\"\" parser = argparse.ArgumentParser( description=\"Connect to the GoPro via", "class to store battery samples\"\"\" index: int percentage: int bars:", "bars=last_bars)) console.print(str(SAMPLES[-1])) SAMPLE_INDEX += 1 def main() -> int: \"\"\"Main", "SAMPLES: List[Sample] = [] def dump_results_as_csv(location: Path) -> None: \"\"\"Write", "None: gopro.close() console.print(\"Exiting...\") return return_code # pylint: disable=lost-exception def parse_arguments()", "open(location, mode=\"w\") as f: w = csv.writer(f, delimiter=\",\", quotechar='\"', quoting=csv.QUOTE_MINIMAL)", "we receive an update notification = gopro.get_update() # Update data", "def __post_init__(self) -> None: self.time = datetime.now() def __str__(self) ->", "if gopro is not None: gopro.close() console.print(\"Exiting...\") return return_code #", "(with no Wifi connection)\"\"\" import csv import time import logging", "Sep 1, 2021 5:05:45 PM \"\"\"Example to continuously read the", "int: \"\"\"Main program functionality Returns: int: program return code \"\"\"", "battery (with no Wifi connection)\"\"\" import csv import time import", "import Optional, Tuple, Literal, List from rich.console import Console from", "\"bars\"]) initial_time = SAMPLES[0].time for s in SAMPLES: w.writerow([s.index, (s.time", "import logging import argparse import threading from pathlib import Path", "1 time.sleep(poll) except Exception as e: # pylint: disable=broad-except logger.error(repr(e))", "= gopro.ble_status.batt_level.register_value_update().flatten percentage = gopro.ble_status.int_batt_per.register_value_update().flatten # Start a thread to", "0 SAMPLES: List[Sample] = [] def dump_results_as_csv(location: Path) -> None:", "@dataclass class Sample: \"\"\"Simple class to store battery samples\"\"\" index:", "battery statuses. Also store initial values. bars = gopro.ble_status.batt_level.register_value_update().flatten percentage", "Path(log_location.parent) / \"battery_results.csv\" dump_results_as_csv(csv_location) if gopro is not None: gopro.close()", "\"--log\", type=Path, help=\"Location to store detailed log\", default=\"log_battery.log\", ) parser.add_argument(", "\"-i\", \"--identifier\", type=str, help=\"Last 4 digits of GoPro serial number,", "\"-l\", \"--log\", type=Path, help=\"Location to store detailed log\", default=\"log_battery.log\", )", "digits of the default camera SSID. \\ If not used,", "SAMPLE_INDEX = 0 SAMPLES: List[Sample] = [] def dump_results_as_csv(location: Path)", "target=process_battery_notifications, args=(gopro, bars, percentage), daemon=True ).start() with console.status(\"[bold green]Receiving battery", "2, 3] @dataclass class Sample: \"\"\"Simple class to store battery", "Optional, Tuple, Literal, List from rich.console import Console from open_gopro", "import Console from open_gopro import GoPro from open_gopro.constants import StatusId", "set_logging_level(logger, logging.ERROR) # # Setup notifications if we are not", "instead. Defaults to notifications.\", default=None, ) args = parser.parse_args() return", "Defaults to notifications.\", default=None, ) args = parser.parse_args() return args.identifier,", "quoting=csv.QUOTE_MINIMAL) w.writerow([\"index\", \"time\", \"percentage\", \"bars\"]) initial_time = SAMPLES[0].time for s", "store battery samples\"\"\" index: int percentage: int bars: BarsType def", "Update data points if they have changed last_percentage = (", "type=str, help=\"Last 4 digits of GoPro serial number, which is", "check for and store battery notifications. If the CLI parameter", "is not None: gopro.close() console.print(\"Exiting...\") return return_code # pylint: disable=lost-exception", "percentage=gopro.ble_status.int_batt_per.get_value().flatten, bars=gopro.ble_status.batt_level.get_value().flatten, ) ) console.print(str(SAMPLES[-1])) SAMPLE_INDEX += 1 time.sleep(poll) except", "bars = gopro.ble_status.batt_level.register_value_update().flatten percentage = gopro.ble_status.int_batt_per.register_value_update().flatten # Start a thread", "notification.data else last_bars ) # Append and print sample global", "battery until it dies...\"): while True: SAMPLES.append( Sample( index=SAMPLE_INDEX, percentage=gopro.ble_status.int_batt_per.get_value().flatten,", "to a csv file Args: location (Path): File to write", "will be connected to\", default=None, ) parser.add_argument( \"-l\", \"--log\", type=Path,", "(BarsType): Initial bars level when notifications were enabled initial_percentage (int):", "= 0 try: with GoPro(identifier, enable_wifi=False) as gopro: set_logging_level(logger, logging.ERROR)", "process_battery_notifications(gopro: GoPro, initial_bars: BarsType, initial_percentage: int) -> None: \"\"\"Separate thread", "not set, battery level will be notified instead. Defaults to", "args=(gopro, bars, percentage), daemon=True ).start() with console.status(\"[bold green]Receiving battery notifications", "pylint: disable=lost-exception def parse_arguments() -> Tuple[str, Path, Optional[int]]: \"\"\"Parse command", "# Start a thread to handle asynchronous battery level notifications", "level notifications threading.Thread( target=process_battery_notifications, args=(gopro, bars, percentage), daemon=True ).start() with", "from datetime import datetime from dataclasses import dataclass from typing", "last_bars ) # Append and print sample global SAMPLE_INDEX SAMPLES.append(Sample(index=SAMPLE_INDEX,", "the battery (with no Wifi connection)\"\"\" import csv import time", "notifications. If the CLI parameter was set to poll, this", "when notifications were enabled initial_percentage (int): Initial percentage when notifications", "Inc. (http://gopro.com/OpenGoPro). # This copyright was auto-generated on Wed, Sep", "Args: location (Path): File to write to \"\"\" console.print(f\"Dumping results", "class Sample: \"\"\"Simple class to store battery samples\"\"\" index: int", "csv.writer(f, delimiter=\",\", quotechar='\"', quoting=csv.QUOTE_MINIMAL) w.writerow([\"index\", \"time\", \"percentage\", \"bars\"]) initial_time =", "SAMPLES[0].time for s in SAMPLES: w.writerow([s.index, (s.time - initial_time).seconds, s.percentage,", "Initial bars level when notifications were enabled initial_percentage (int): Initial", "deal with battery level notifications while True: time.sleep(1) # Otherwise,", "allowing notification handler thread to deal with battery level notifications", "path to save log, path to VLC) \"\"\" parser =", "until it dies...\"): while True: SAMPLES.append( Sample( index=SAMPLE_INDEX, percentage=gopro.ble_status.int_batt_per.get_value().flatten, bars=gopro.ble_status.batt_level.get_value().flatten,", "poll = parse_arguments() global logger logger = setup_logging(logger, log_location) global", "an update notification = gopro.get_update() # Update data points if", "the relevant battery statuses. Also store initial values. bars =", "global SAMPLE_INDEX gopro: Optional[GoPro] = None return_code = 0 try:", "return_code # pylint: disable=lost-exception def parse_arguments() -> Tuple[str, Path, Optional[int]]:", "Tuple[str, Path, Optional[int]]: \"\"\"Parse command line arguments Returns: Tuple[str, Path,", "command line arguments Returns: Tuple[str, Path, Path]: (identifier, path to", "notifications were enabled \"\"\" last_percentage = initial_percentage last_bars = initial_bars", "True: time.sleep(1) # Otherwise, poll else: with console.status(\"[bold green]Polling the", "connected to\", default=None, ) parser.add_argument( \"-l\", \"--log\", type=Path, help=\"Location to", "GoPro, initial_bars: BarsType, initial_percentage: int) -> None: \"\"\"Separate thread to", "identifier, log_location, poll = parse_arguments() global logger logger = setup_logging(logger,", "continuously read the battery (with no Wifi connection)\"\"\" import csv", "asynchronous battery level notifications threading.Thread( target=process_battery_notifications, args=(gopro, bars, percentage), daemon=True", "= gopro.ble_status.int_batt_per.register_value_update().flatten # Start a thread to handle asynchronous battery", "GoPro, Version 2.0 (C) Copyright 2021 GoPro, Inc. (http://gopro.com/OpenGoPro). #", "import argparse import threading from pathlib import Path from datetime", "read the battery (with no Wifi connection)\"\"\" import csv import", "SAMPLES.append(Sample(index=SAMPLE_INDEX, percentage=last_percentage, bars=last_bars)) console.print(str(SAMPLES[-1])) SAMPLE_INDEX += 1 def main() ->", "return_code = 0 try: with GoPro(identifier, enable_wifi=False) as gopro: set_logging_level(logger,", "in notification.data else last_percentage ) last_bars = ( notification.data[StatusId.BATT_LEVEL] if", "<filename>demos/python/sdk_wireless_camera_control/open_gopro/demos/log_battery.py<gh_stars>100-1000 # log_battery.py/Open GoPro, Version 2.0 (C) Copyright 2021 GoPro,", "to poll the battery at a given interval. If not", "was set to poll, this isn't used. Args: gopro (GoPro):", "else last_percentage ) last_bars = ( notification.data[StatusId.BATT_LEVEL] if StatusId.BATT_LEVEL in", "datetime from dataclasses import dataclass from typing import Optional, Tuple,", "logging.getLogger(__name__) console = Console() # rich consoler printer BarsType =", "are not polling if poll is None: console.print(\"Configuring battery notifications...\")", "battery samples\"\"\" index: int percentage: int bars: BarsType def __post_init__(self)", "notifications...\") # Enable notifications of the relevant battery statuses. Also", "console.print(\"Exiting...\") return return_code # pylint: disable=lost-exception def parse_arguments() -> Tuple[str,", "from open_gopro.util import setup_logging, set_logging_level logger = logging.getLogger(__name__) console =", ") args = parser.parse_args() return args.identifier, args.log, args.poll if __name__", "camera SSID. \\ If not used, first discovered GoPro will", "None: console.print(\"Configuring battery notifications...\") # Enable notifications of the relevant", "functionality Returns: int: program return code \"\"\" identifier, log_location, poll", "f\"Index {self.index} @ time {self.time.strftime('%H:%M:%S')} --> bars: {self.bars}, percentage: {self.percentage}\"", "relevant battery statuses. Also store initial values. bars = gopro.ble_status.batt_level.register_value_update().flatten", "Path]: (identifier, path to save log, path to VLC) \"\"\"", "\"\"\" identifier, log_location, poll = parse_arguments() global logger logger =", "if we are not polling if poll is None: console.print(\"Configuring", "Sample( index=SAMPLE_INDEX, percentage=gopro.ble_status.int_batt_per.get_value().flatten, bars=gopro.ble_status.batt_level.get_value().flatten, ) ) console.print(str(SAMPLES[-1])) SAMPLE_INDEX += 1", "__str__(self) -> str: # pylint: disable=missing-return-doc return f\"Index {self.index} @", "while True: SAMPLES.append( Sample( index=SAMPLE_INDEX, percentage=gopro.ble_status.int_batt_per.get_value().flatten, bars=gopro.ble_status.batt_level.get_value().flatten, ) ) console.print(str(SAMPLES[-1]))", "Returns: Tuple[str, Path, Path]: (identifier, path to save log, path", "gopro.close() console.print(\"Exiting...\") return return_code # pylint: disable=lost-exception def parse_arguments() ->", "initial_percentage: int) -> None: \"\"\"Separate thread to continuously check for", "{self.time.strftime('%H:%M:%S')} --> bars: {self.bars}, percentage: {self.percentage}\" SAMPLE_INDEX = 0 SAMPLES:", "SAMPLE_INDEX SAMPLES.append(Sample(index=SAMPLE_INDEX, percentage=last_percentage, bars=last_bars)) console.print(str(SAMPLES[-1])) SAMPLE_INDEX += 1 def main()", "\"\"\"Write all of the samples to a csv file Args:", ") parser.add_argument( \"-p\", \"--poll\", type=int, help=\"Set to poll the battery", "battery at a given interval. If not set, battery level", "be connected to\", default=None, ) parser.add_argument( \"-l\", \"--log\", type=Path, help=\"Location", "import setup_logging, set_logging_level logger = logging.getLogger(__name__) console = Console() #", "a csv file Args: location (Path): File to write to", "type=int, help=\"Set to poll the battery at a given interval.", "\"--identifier\", type=str, help=\"Last 4 digits of GoPro serial number, which", "SAMPLES: w.writerow([s.index, (s.time - initial_time).seconds, s.percentage, s.bars]) def process_battery_notifications(gopro: GoPro,", "samples to a csv file Args: location (Path): File to", "dataclass from typing import Optional, Tuple, Literal, List from rich.console", "while True: # Block until we receive an update notification", ").start() with console.status(\"[bold green]Receiving battery notifications until it dies...\"): #", "disable=lost-exception def parse_arguments() -> Tuple[str, Path, Optional[int]]: \"\"\"Parse command line", "to write to \"\"\" console.print(f\"Dumping results as CSV to {location}\")", "dump_results_as_csv(location: Path) -> None: \"\"\"Write all of the samples to", "enabled initial_percentage (int): Initial percentage when notifications were enabled \"\"\"", "File to write to \"\"\" console.print(f\"Dumping results as CSV to", "datetime.now() def __str__(self) -> str: # pylint: disable=missing-return-doc return f\"Index", "4 digits of GoPro serial number, which is the last", "List[Sample] = [] def dump_results_as_csv(location: Path) -> None: \"\"\"Write all", "gopro: Optional[GoPro] = None return_code = 0 try: with GoPro(identifier,", "percentage: int bars: BarsType def __post_init__(self) -> None: self.time =", "Version 2.0 (C) Copyright 2021 GoPro, Inc. (http://gopro.com/OpenGoPro). # This", "csv import time import logging import argparse import threading from", "None: \"\"\"Write all of the samples to a csv file", "log_location) global SAMPLE_INDEX gopro: Optional[GoPro] = None return_code = 0", "\"\"\" console.print(f\"Dumping results as CSV to {location}\") with open(location, mode=\"w\")", "# Append and print sample global SAMPLE_INDEX SAMPLES.append(Sample(index=SAMPLE_INDEX, percentage=last_percentage, bars=last_bars))", "thread to continuously check for and store battery notifications. If", "as gopro: set_logging_level(logger, logging.ERROR) # # Setup notifications if we", "= csv.writer(f, delimiter=\",\", quotechar='\"', quoting=csv.QUOTE_MINIMAL) w.writerow([\"index\", \"time\", \"percentage\", \"bars\"]) initial_time", "as e: # pylint: disable=broad-except logger.error(repr(e)) return_code = 1 except", "file Args: location (Path): File to write to \"\"\" console.print(f\"Dumping", "setup_logging(logger, log_location) global SAMPLE_INDEX gopro: Optional[GoPro] = None return_code =", "console.print(str(SAMPLES[-1])) SAMPLE_INDEX += 1 def main() -> int: \"\"\"Main program", "def parse_arguments() -> Tuple[str, Path, Optional[int]]: \"\"\"Parse command line arguments", "{location}\") with open(location, mode=\"w\") as f: w = csv.writer(f, delimiter=\",\",", "else last_bars ) # Append and print sample global SAMPLE_INDEX", "we are not polling if poll is None: console.print(\"Configuring battery", "printer BarsType = Literal[0, 1, 2, 3] @dataclass class Sample:", "notifications if we are not polling if poll is None:", "= initial_percentage last_bars = initial_bars while True: # Block until", "Sleep forever, allowing notification handler thread to deal with battery", "1 except KeyboardInterrupt: logger.warning(\"Received keyboard interrupt. Shutting down...\") finally: if", "logger.error(repr(e)) return_code = 1 except KeyboardInterrupt: logger.warning(\"Received keyboard interrupt. Shutting", "last_percentage = ( notification.data[StatusId.INT_BATT_PER] if StatusId.INT_BATT_PER in notification.data else last_percentage", "Args: gopro (GoPro): instance to get updates from initial_bars (BarsType):", ") # Append and print sample global SAMPLE_INDEX SAMPLES.append(Sample(index=SAMPLE_INDEX, percentage=last_percentage,", "import GoPro from open_gopro.constants import StatusId from open_gopro.util import setup_logging,", "None return_code = 0 try: with GoPro(identifier, enable_wifi=False) as gopro:", "continuously read the battery (either by polling or notifications).\" )", "def dump_results_as_csv(location: Path) -> None: \"\"\"Write all of the samples", "from open_gopro.constants import StatusId from open_gopro.util import setup_logging, set_logging_level logger", "w = csv.writer(f, delimiter=\",\", quotechar='\"', quoting=csv.QUOTE_MINIMAL) w.writerow([\"index\", \"time\", \"percentage\", \"bars\"])", "it dies...\"): # Sleep forever, allowing notification handler thread to", "console = Console() # rich consoler printer BarsType = Literal[0,", "until it dies...\"): # Sleep forever, allowing notification handler thread", "= 0 SAMPLES: List[Sample] = [] def dump_results_as_csv(location: Path) ->", "(int): Initial percentage when notifications were enabled \"\"\" last_percentage =", "csv file Args: location (Path): File to write to \"\"\"", "len(SAMPLES) > 0: csv_location = Path(log_location.parent) / \"battery_results.csv\" dump_results_as_csv(csv_location) if", "# # Setup notifications if we are not polling if", "first discovered GoPro will be connected to\", default=None, ) parser.add_argument(", "gopro.get_update() # Update data points if they have changed last_percentage", "gopro is not None: gopro.close() console.print(\"Exiting...\") return return_code # pylint:", "open_gopro.util import setup_logging, set_logging_level logger = logging.getLogger(__name__) console = Console()", "try: with GoPro(identifier, enable_wifi=False) as gopro: set_logging_level(logger, logging.ERROR) # #", "Tuple, Literal, List from rich.console import Console from open_gopro import", "# pylint: disable=missing-return-doc return f\"Index {self.index} @ time {self.time.strftime('%H:%M:%S')} -->", ") ) console.print(str(SAMPLES[-1])) SAMPLE_INDEX += 1 time.sleep(poll) except Exception as", "0: csv_location = Path(log_location.parent) / \"battery_results.csv\" dump_results_as_csv(csv_location) if gopro is", "int percentage: int bars: BarsType def __post_init__(self) -> None: self.time", "w.writerow([\"index\", \"time\", \"percentage\", \"bars\"]) initial_time = SAMPLES[0].time for s in", "to store battery samples\"\"\" index: int percentage: int bars: BarsType", "to the GoPro via BLE only and continuously read the", "notification = gopro.get_update() # Update data points if they have", "last 4 digits of the default camera SSID. \\ If", "this isn't used. Args: gopro (GoPro): instance to get updates", "= argparse.ArgumentParser( description=\"Connect to the GoPro via BLE only and", "# pylint: disable=lost-exception def parse_arguments() -> Tuple[str, Path, Optional[int]]: \"\"\"Parse", "initial_percentage last_bars = initial_bars while True: # Block until we", "Path from datetime import datetime from dataclasses import dataclass from", "open_gopro.constants import StatusId from open_gopro.util import setup_logging, set_logging_level logger =", "= ( notification.data[StatusId.INT_BATT_PER] if StatusId.INT_BATT_PER in notification.data else last_percentage )", "\"time\", \"percentage\", \"bars\"]) initial_time = SAMPLES[0].time for s in SAMPLES:", "with GoPro(identifier, enable_wifi=False) as gopro: set_logging_level(logger, logging.ERROR) # # Setup", "\"\"\"Separate thread to continuously check for and store battery notifications.", "# This copyright was auto-generated on Wed, Sep 1, 2021", "percentage), daemon=True ).start() with console.status(\"[bold green]Receiving battery notifications until it", "the battery (either by polling or notifications).\" ) parser.add_argument( \"-i\",", "last_bars = ( notification.data[StatusId.BATT_LEVEL] if StatusId.BATT_LEVEL in notification.data else last_bars", "main() -> int: \"\"\"Main program functionality Returns: int: program return", "Sample: \"\"\"Simple class to store battery samples\"\"\" index: int percentage:", "program functionality Returns: int: program return code \"\"\" identifier, log_location,", "notifications until it dies...\"): # Sleep forever, allowing notification handler", "connection)\"\"\" import csv import time import logging import argparse import", "Wifi connection)\"\"\" import csv import time import logging import argparse", "-> Tuple[str, Path, Optional[int]]: \"\"\"Parse command line arguments Returns: Tuple[str,", "global SAMPLE_INDEX SAMPLES.append(Sample(index=SAMPLE_INDEX, percentage=last_percentage, bars=last_bars)) console.print(str(SAMPLES[-1])) SAMPLE_INDEX += 1 def", "= datetime.now() def __str__(self) -> str: # pylint: disable=missing-return-doc return", "2021 5:05:45 PM \"\"\"Example to continuously read the battery (with", "StatusId.INT_BATT_PER in notification.data else last_percentage ) last_bars = ( notification.data[StatusId.BATT_LEVEL]", "log, path to VLC) \"\"\" parser = argparse.ArgumentParser( description=\"Connect to", "--> bars: {self.bars}, percentage: {self.percentage}\" SAMPLE_INDEX = 0 SAMPLES: List[Sample]", "pylint: disable=broad-except logger.error(repr(e)) return_code = 1 except KeyboardInterrupt: logger.warning(\"Received keyboard", "consoler printer BarsType = Literal[0, 1, 2, 3] @dataclass class", "to store detailed log\", default=\"log_battery.log\", ) parser.add_argument( \"-p\", \"--poll\", type=int,", "parse_arguments() -> Tuple[str, Path, Optional[int]]: \"\"\"Parse command line arguments Returns:", "notification.data[StatusId.BATT_LEVEL] if StatusId.BATT_LEVEL in notification.data else last_bars ) # Append", "console.print(f\"Dumping results as CSV to {location}\") with open(location, mode=\"w\") as", "will be notified instead. Defaults to notifications.\", default=None, ) args", "polling if poll is None: console.print(\"Configuring battery notifications...\") # Enable", "on Wed, Sep 1, 2021 5:05:45 PM \"\"\"Example to continuously", "args = parser.parse_args() return args.identifier, args.log, args.poll if __name__ ==", "results as CSV to {location}\") with open(location, mode=\"w\") as f:", "True: # Block until we receive an update notification =", "statuses. Also store initial values. bars = gopro.ble_status.batt_level.register_value_update().flatten percentage =", "to handle asynchronous battery level notifications threading.Thread( target=process_battery_notifications, args=(gopro, bars,", "instance to get updates from initial_bars (BarsType): Initial bars level", "Path, Optional[int]]: \"\"\"Parse command line arguments Returns: Tuple[str, Path, Path]:", "if StatusId.INT_BATT_PER in notification.data else last_percentage ) last_bars = (", "typing import Optional, Tuple, Literal, List from rich.console import Console", "Block until we receive an update notification = gopro.get_update() #", "if StatusId.BATT_LEVEL in notification.data else last_bars ) # Append and", "Also store initial values. bars = gopro.ble_status.batt_level.register_value_update().flatten percentage = gopro.ble_status.int_batt_per.register_value_update().flatten", "except Exception as e: # pylint: disable=broad-except logger.error(repr(e)) return_code =", "BLE only and continuously read the battery (either by polling", "GoPro, Inc. (http://gopro.com/OpenGoPro). # This copyright was auto-generated on Wed,", "( notification.data[StatusId.BATT_LEVEL] if StatusId.BATT_LEVEL in notification.data else last_bars ) #", "disable=missing-return-doc return f\"Index {self.index} @ time {self.time.strftime('%H:%M:%S')} --> bars: {self.bars},", "index: int percentage: int bars: BarsType def __post_init__(self) -> None:", "number, which is the last 4 digits of the default", "battery notifications...\") # Enable notifications of the relevant battery statuses.", "> 0: csv_location = Path(log_location.parent) / \"battery_results.csv\" dump_results_as_csv(csv_location) if gopro", "handler thread to deal with battery level notifications while True:", "# Enable notifications of the relevant battery statuses. Also store", "the default camera SSID. \\ If not used, first discovered", "def process_battery_notifications(gopro: GoPro, initial_bars: BarsType, initial_percentage: int) -> None: \"\"\"Separate", "mode=\"w\") as f: w = csv.writer(f, delimiter=\",\", quotechar='\"', quoting=csv.QUOTE_MINIMAL) w.writerow([\"index\",", "detailed log\", default=\"log_battery.log\", ) parser.add_argument( \"-p\", \"--poll\", type=int, help=\"Set to", "GoPro will be connected to\", default=None, ) parser.add_argument( \"-l\", \"--log\",", "/ \"battery_results.csv\" dump_results_as_csv(csv_location) if gopro is not None: gopro.close() console.print(\"Exiting...\")", "gopro: set_logging_level(logger, logging.ERROR) # # Setup notifications if we are", "to get updates from initial_bars (BarsType): Initial bars level when", "parser.add_argument( \"-p\", \"--poll\", type=int, help=\"Set to poll the battery at", "green]Polling the battery until it dies...\"): while True: SAMPLES.append( Sample(", "None: self.time = datetime.now() def __str__(self) -> str: # pylint:", "quotechar='\"', quoting=csv.QUOTE_MINIMAL) w.writerow([\"index\", \"time\", \"percentage\", \"bars\"]) initial_time = SAMPLES[0].time for", "path to VLC) \"\"\" parser = argparse.ArgumentParser( description=\"Connect to the", "points if they have changed last_percentage = ( notification.data[StatusId.INT_BATT_PER] if", "which is the last 4 digits of the default camera", "(Path): File to write to \"\"\" console.print(f\"Dumping results as CSV", "polling or notifications).\" ) parser.add_argument( \"-i\", \"--identifier\", type=str, help=\"Last 4", "help=\"Last 4 digits of GoPro serial number, which is the", "by polling or notifications).\" ) parser.add_argument( \"-i\", \"--identifier\", type=str, help=\"Last", "poll the battery at a given interval. If not set,", "type=Path, help=\"Location to store detailed log\", default=\"log_battery.log\", ) parser.add_argument( \"-p\",", "when notifications were enabled \"\"\" last_percentage = initial_percentage last_bars =", "\"-p\", \"--poll\", type=int, help=\"Set to poll the battery at a", "Optional[int]]: \"\"\"Parse command line arguments Returns: Tuple[str, Path, Path]: (identifier,", "notification handler thread to deal with battery level notifications while", "If not used, first discovered GoPro will be connected to\",", "dies...\"): # Sleep forever, allowing notification handler thread to deal", "given interval. If not set, battery level will be notified", "2021 GoPro, Inc. (http://gopro.com/OpenGoPro). # This copyright was auto-generated on", "a thread to handle asynchronous battery level notifications threading.Thread( target=process_battery_notifications,", "# Setup notifications if we are not polling if poll", "notified instead. Defaults to notifications.\", default=None, ) args = parser.parse_args()", "default=None, ) parser.add_argument( \"-l\", \"--log\", type=Path, help=\"Location to store detailed", "from initial_bars (BarsType): Initial bars level when notifications were enabled", "\"\"\"Example to continuously read the battery (with no Wifi connection)\"\"\"", "if poll is None: console.print(\"Configuring battery notifications...\") # Enable notifications", "\"\"\"Parse command line arguments Returns: Tuple[str, Path, Path]: (identifier, path", "dies...\"): while True: SAMPLES.append( Sample( index=SAMPLE_INDEX, percentage=gopro.ble_status.int_batt_per.get_value().flatten, bars=gopro.ble_status.batt_level.get_value().flatten, ) )", "to notifications.\", default=None, ) args = parser.parse_args() return args.identifier, args.log,", "to VLC) \"\"\" parser = argparse.ArgumentParser( description=\"Connect to the GoPro", "# rich consoler printer BarsType = Literal[0, 1, 2, 3]", "threading from pathlib import Path from datetime import datetime from", "Start a thread to handle asynchronous battery level notifications threading.Thread(", "for and store battery notifications. If the CLI parameter was", "is None: console.print(\"Configuring battery notifications...\") # Enable notifications of the", "1 def main() -> int: \"\"\"Main program functionality Returns: int:", "program return code \"\"\" identifier, log_location, poll = parse_arguments() global", "initial_percentage (int): Initial percentage when notifications were enabled \"\"\" last_percentage", "from pathlib import Path from datetime import datetime from dataclasses", "update notification = gopro.get_update() # Update data points if they", "not polling if poll is None: console.print(\"Configuring battery notifications...\") #", "datetime import datetime from dataclasses import dataclass from typing import", "GoPro(identifier, enable_wifi=False) as gopro: set_logging_level(logger, logging.ERROR) # # Setup notifications", "w.writerow([s.index, (s.time - initial_time).seconds, s.percentage, s.bars]) def process_battery_notifications(gopro: GoPro, initial_bars:", "= Literal[0, 1, 2, 3] @dataclass class Sample: \"\"\"Simple class", "finally: if len(SAMPLES) > 0: csv_location = Path(log_location.parent) / \"battery_results.csv\"", "auto-generated on Wed, Sep 1, 2021 5:05:45 PM \"\"\"Example to", "def main() -> int: \"\"\"Main program functionality Returns: int: program", "Console from open_gopro import GoPro from open_gopro.constants import StatusId from", "None: \"\"\"Separate thread to continuously check for and store battery", "+= 1 time.sleep(poll) except Exception as e: # pylint: disable=broad-except", "notification.data else last_percentage ) last_bars = ( notification.data[StatusId.BATT_LEVEL] if StatusId.BATT_LEVEL", "forever, allowing notification handler thread to deal with battery level", "notifications of the relevant battery statuses. Also store initial values.", "-> str: # pylint: disable=missing-return-doc return f\"Index {self.index} @ time", "the battery until it dies...\"): while True: SAMPLES.append( Sample( index=SAMPLE_INDEX,", "KeyboardInterrupt: logger.warning(\"Received keyboard interrupt. Shutting down...\") finally: if len(SAMPLES) >", "a given interval. If not set, battery level will be", "time {self.time.strftime('%H:%M:%S')} --> bars: {self.bars}, percentage: {self.percentage}\" SAMPLE_INDEX = 0", "to poll, this isn't used. Args: gopro (GoPro): instance to", "default=\"log_battery.log\", ) parser.add_argument( \"-p\", \"--poll\", type=int, help=\"Set to poll the", "3] @dataclass class Sample: \"\"\"Simple class to store battery samples\"\"\"", "SAMPLES.append( Sample( index=SAMPLE_INDEX, percentage=gopro.ble_status.int_batt_per.get_value().flatten, bars=gopro.ble_status.batt_level.get_value().flatten, ) ) console.print(str(SAMPLES[-1])) SAMPLE_INDEX +=", ") parser.add_argument( \"-i\", \"--identifier\", type=str, help=\"Last 4 digits of GoPro", "log\", default=\"log_battery.log\", ) parser.add_argument( \"-p\", \"--poll\", type=int, help=\"Set to poll", "Initial percentage when notifications were enabled \"\"\" last_percentage = initial_percentage", "with open(location, mode=\"w\") as f: w = csv.writer(f, delimiter=\",\", quotechar='\"',", "samples\"\"\" index: int percentage: int bars: BarsType def __post_init__(self) ->", "logging import argparse import threading from pathlib import Path from", "__post_init__(self) -> None: self.time = datetime.now() def __str__(self) -> str:", "(GoPro): instance to get updates from initial_bars (BarsType): Initial bars", "console.status(\"[bold green]Receiving battery notifications until it dies...\"): # Sleep forever,", "CSV to {location}\") with open(location, mode=\"w\") as f: w =", "help=\"Set to poll the battery at a given interval. If", "return code \"\"\" identifier, log_location, poll = parse_arguments() global logger", "the GoPro via BLE only and continuously read the battery", "def __str__(self) -> str: # pylint: disable=missing-return-doc return f\"Index {self.index}", "int bars: BarsType def __post_init__(self) -> None: self.time = datetime.now()", "last_percentage ) last_bars = ( notification.data[StatusId.BATT_LEVEL] if StatusId.BATT_LEVEL in notification.data", "handle asynchronous battery level notifications threading.Thread( target=process_battery_notifications, args=(gopro, bars, percentage),", "continuously check for and store battery notifications. If the CLI", "were enabled \"\"\" last_percentage = initial_percentage last_bars = initial_bars while", "= Path(log_location.parent) / \"battery_results.csv\" dump_results_as_csv(csv_location) if gopro is not None:", "serial number, which is the last 4 digits of the", "logger logger = setup_logging(logger, log_location) global SAMPLE_INDEX gopro: Optional[GoPro] =", "from open_gopro import GoPro from open_gopro.constants import StatusId from open_gopro.util", "print sample global SAMPLE_INDEX SAMPLES.append(Sample(index=SAMPLE_INDEX, percentage=last_percentage, bars=last_bars)) console.print(str(SAMPLES[-1])) SAMPLE_INDEX +=", "4 digits of the default camera SSID. \\ If not", "battery level notifications while True: time.sleep(1) # Otherwise, poll else:", "threading.Thread( target=process_battery_notifications, args=(gopro, bars, percentage), daemon=True ).start() with console.status(\"[bold green]Receiving", "-> None: \"\"\"Separate thread to continuously check for and store", "= parser.parse_args() return args.identifier, args.log, args.poll if __name__ == \"__main__\":", "Exception as e: # pylint: disable=broad-except logger.error(repr(e)) return_code = 1", "percentage: {self.percentage}\" SAMPLE_INDEX = 0 SAMPLES: List[Sample] = [] def", "# Block until we receive an update notification = gopro.get_update()", "level notifications while True: time.sleep(1) # Otherwise, poll else: with", "console.status(\"[bold green]Polling the battery until it dies...\"): while True: SAMPLES.append(", "receive an update notification = gopro.get_update() # Update data points", "down...\") finally: if len(SAMPLES) > 0: csv_location = Path(log_location.parent) /", "at a given interval. If not set, battery level will", "time import logging import argparse import threading from pathlib import", "If not set, battery level will be notified instead. Defaults", "gopro (GoPro): instance to get updates from initial_bars (BarsType): Initial", "gopro.ble_status.batt_level.register_value_update().flatten percentage = gopro.ble_status.int_batt_per.register_value_update().flatten # Start a thread to handle", ") console.print(str(SAMPLES[-1])) SAMPLE_INDEX += 1 time.sleep(poll) except Exception as e:", "\"\"\"Simple class to store battery samples\"\"\" index: int percentage: int", "until we receive an update notification = gopro.get_update() # Update", "percentage when notifications were enabled \"\"\" last_percentage = initial_percentage last_bars", "were enabled initial_percentage (int): Initial percentage when notifications were enabled", "csv_location = Path(log_location.parent) / \"battery_results.csv\" dump_results_as_csv(csv_location) if gopro is not", "level when notifications were enabled initial_percentage (int): Initial percentage when", "(either by polling or notifications).\" ) parser.add_argument( \"-i\", \"--identifier\", type=str,", "rich.console import Console from open_gopro import GoPro from open_gopro.constants import", "# log_battery.py/Open GoPro, Version 2.0 (C) Copyright 2021 GoPro, Inc.", "= None return_code = 0 try: with GoPro(identifier, enable_wifi=False) as", "-> None: self.time = datetime.now() def __str__(self) -> str: #", "If the CLI parameter was set to poll, this isn't", "not None: gopro.close() console.print(\"Exiting...\") return return_code # pylint: disable=lost-exception def", "thread to handle asynchronous battery level notifications threading.Thread( target=process_battery_notifications, args=(gopro,", "help=\"Location to store detailed log\", default=\"log_battery.log\", ) parser.add_argument( \"-p\", \"--poll\",", "# Update data points if they have changed last_percentage =", "(C) Copyright 2021 GoPro, Inc. (http://gopro.com/OpenGoPro). # This copyright was", "location (Path): File to write to \"\"\" console.print(f\"Dumping results as", "disable=broad-except logger.error(repr(e)) return_code = 1 except KeyboardInterrupt: logger.warning(\"Received keyboard interrupt.", "# pylint: disable=broad-except logger.error(repr(e)) return_code = 1 except KeyboardInterrupt: logger.warning(\"Received", "s.bars]) def process_battery_notifications(gopro: GoPro, initial_bars: BarsType, initial_percentage: int) -> None:", "open_gopro import GoPro from open_gopro.constants import StatusId from open_gopro.util import", "else: with console.status(\"[bold green]Polling the battery until it dies...\"): while", "enabled \"\"\" last_percentage = initial_percentage last_bars = initial_bars while True:", "s.percentage, s.bars]) def process_battery_notifications(gopro: GoPro, initial_bars: BarsType, initial_percentage: int) ->", "Returns: int: program return code \"\"\" identifier, log_location, poll =", "initial_time).seconds, s.percentage, s.bars]) def process_battery_notifications(gopro: GoPro, initial_bars: BarsType, initial_percentage: int)", "StatusId.BATT_LEVEL in notification.data else last_bars ) # Append and print", "parser.add_argument( \"-l\", \"--log\", type=Path, help=\"Location to store detailed log\", default=\"log_battery.log\",", "battery notifications. If the CLI parameter was set to poll,", "logger.warning(\"Received keyboard interrupt. Shutting down...\") finally: if len(SAMPLES) > 0:", "to\", default=None, ) parser.add_argument( \"-l\", \"--log\", type=Path, help=\"Location to store", "return f\"Index {self.index} @ time {self.time.strftime('%H:%M:%S')} --> bars: {self.bars}, percentage:", "\"percentage\", \"bars\"]) initial_time = SAMPLES[0].time for s in SAMPLES: w.writerow([s.index,", "setup_logging, set_logging_level logger = logging.getLogger(__name__) console = Console() # rich", "be notified instead. Defaults to notifications.\", default=None, ) args =", "This copyright was auto-generated on Wed, Sep 1, 2021 5:05:45", "True: SAMPLES.append( Sample( index=SAMPLE_INDEX, percentage=gopro.ble_status.int_batt_per.get_value().flatten, bars=gopro.ble_status.batt_level.get_value().flatten, ) ) console.print(str(SAMPLES[-1])) SAMPLE_INDEX", "of the samples to a csv file Args: location (Path):", "initial_bars while True: # Block until we receive an update", "sample global SAMPLE_INDEX SAMPLES.append(Sample(index=SAMPLE_INDEX, percentage=last_percentage, bars=last_bars)) console.print(str(SAMPLES[-1])) SAMPLE_INDEX += 1", "1, 2021 5:05:45 PM \"\"\"Example to continuously read the battery", "parameter was set to poll, this isn't used. Args: gopro", "console.print(str(SAMPLES[-1])) SAMPLE_INDEX += 1 time.sleep(poll) except Exception as e: #", "from typing import Optional, Tuple, Literal, List from rich.console import", "line arguments Returns: Tuple[str, Path, Path]: (identifier, path to save", "2.0 (C) Copyright 2021 GoPro, Inc. (http://gopro.com/OpenGoPro). # This copyright", "and print sample global SAMPLE_INDEX SAMPLES.append(Sample(index=SAMPLE_INDEX, percentage=last_percentage, bars=last_bars)) console.print(str(SAMPLES[-1])) SAMPLE_INDEX", ") parser.add_argument( \"-l\", \"--log\", type=Path, help=\"Location to store detailed log\",", "to {location}\") with open(location, mode=\"w\") as f: w = csv.writer(f,", "CLI parameter was set to poll, this isn't used. Args:", "have changed last_percentage = ( notification.data[StatusId.INT_BATT_PER] if StatusId.INT_BATT_PER in notification.data", "@ time {self.time.strftime('%H:%M:%S')} --> bars: {self.bars}, percentage: {self.percentage}\" SAMPLE_INDEX =", "console.print(\"Configuring battery notifications...\") # Enable notifications of the relevant battery", "or notifications).\" ) parser.add_argument( \"-i\", \"--identifier\", type=str, help=\"Last 4 digits", "last_bars = initial_bars while True: # Block until we receive", "= SAMPLES[0].time for s in SAMPLES: w.writerow([s.index, (s.time - initial_time).seconds,", "store battery notifications. If the CLI parameter was set to", "of the relevant battery statuses. Also store initial values. bars", "parser = argparse.ArgumentParser( description=\"Connect to the GoPro via BLE only", "int: program return code \"\"\" identifier, log_location, poll = parse_arguments()", "Tuple[str, Path, Path]: (identifier, path to save log, path to", "not used, first discovered GoPro will be connected to\", default=None,", "argparse import threading from pathlib import Path from datetime import", "import csv import time import logging import argparse import threading", "all of the samples to a csv file Args: location", "= logging.getLogger(__name__) console = Console() # rich consoler printer BarsType", "0 try: with GoPro(identifier, enable_wifi=False) as gopro: set_logging_level(logger, logging.ERROR) #", "to \"\"\" console.print(f\"Dumping results as CSV to {location}\") with open(location,", "f: w = csv.writer(f, delimiter=\",\", quotechar='\"', quoting=csv.QUOTE_MINIMAL) w.writerow([\"index\", \"time\", \"percentage\",", "to continuously check for and store battery notifications. If the", "Path, Path]: (identifier, path to save log, path to VLC)", "from dataclasses import dataclass from typing import Optional, Tuple, Literal,", "via BLE only and continuously read the battery (either by", "updates from initial_bars (BarsType): Initial bars level when notifications were", "keyboard interrupt. Shutting down...\") finally: if len(SAMPLES) > 0: csv_location", "battery (either by polling or notifications).\" ) parser.add_argument( \"-i\", \"--identifier\",", "import StatusId from open_gopro.util import setup_logging, set_logging_level logger = logging.getLogger(__name__)", "set_logging_level logger = logging.getLogger(__name__) console = Console() # rich consoler", "s in SAMPLES: w.writerow([s.index, (s.time - initial_time).seconds, s.percentage, s.bars]) def", "interrupt. Shutting down...\") finally: if len(SAMPLES) > 0: csv_location =", "global logger logger = setup_logging(logger, log_location) global SAMPLE_INDEX gopro: Optional[GoPro]", "GoPro serial number, which is the last 4 digits of", "rich consoler printer BarsType = Literal[0, 1, 2, 3] @dataclass", "BarsType, initial_percentage: int) -> None: \"\"\"Separate thread to continuously check", "while True: time.sleep(1) # Otherwise, poll else: with console.status(\"[bold green]Polling", "Wed, Sep 1, 2021 5:05:45 PM \"\"\"Example to continuously read", "bars: {self.bars}, percentage: {self.percentage}\" SAMPLE_INDEX = 0 SAMPLES: List[Sample] =", "thread to deal with battery level notifications while True: time.sleep(1)", "notification.data[StatusId.INT_BATT_PER] if StatusId.INT_BATT_PER in notification.data else last_percentage ) last_bars =", "the last 4 digits of the default camera SSID. \\", "notifications).\" ) parser.add_argument( \"-i\", \"--identifier\", type=str, help=\"Last 4 digits of", "Shutting down...\") finally: if len(SAMPLES) > 0: csv_location = Path(log_location.parent)", "battery notifications until it dies...\"): # Sleep forever, allowing notification", "BarsType def __post_init__(self) -> None: self.time = datetime.now() def __str__(self)", "= setup_logging(logger, log_location) global SAMPLE_INDEX gopro: Optional[GoPro] = None return_code", ") last_bars = ( notification.data[StatusId.BATT_LEVEL] if StatusId.BATT_LEVEL in notification.data else", "if they have changed last_percentage = ( notification.data[StatusId.INT_BATT_PER] if StatusId.INT_BATT_PER", "index=SAMPLE_INDEX, percentage=gopro.ble_status.int_batt_per.get_value().flatten, bars=gopro.ble_status.batt_level.get_value().flatten, ) ) console.print(str(SAMPLES[-1])) SAMPLE_INDEX += 1 time.sleep(poll)", "str: # pylint: disable=missing-return-doc return f\"Index {self.index} @ time {self.time.strftime('%H:%M:%S')}", "= initial_bars while True: # Block until we receive an", "poll is None: console.print(\"Configuring battery notifications...\") # Enable notifications of", "Console() # rich consoler printer BarsType = Literal[0, 1, 2,", "store initial values. bars = gopro.ble_status.batt_level.register_value_update().flatten percentage = gopro.ble_status.int_batt_per.register_value_update().flatten #", "import time import logging import argparse import threading from pathlib", "used. Args: gopro (GoPro): instance to get updates from initial_bars", "SAMPLE_INDEX += 1 def main() -> int: \"\"\"Main program functionality", "daemon=True ).start() with console.status(\"[bold green]Receiving battery notifications until it dies...\"):", "bars level when notifications were enabled initial_percentage (int): Initial percentage", "the samples to a csv file Args: location (Path): File", "{self.percentage}\" SAMPLE_INDEX = 0 SAMPLES: List[Sample] = [] def dump_results_as_csv(location:", "-> None: \"\"\"Write all of the samples to a csv", "initial_time = SAMPLES[0].time for s in SAMPLES: w.writerow([s.index, (s.time -", "notifications threading.Thread( target=process_battery_notifications, args=(gopro, bars, percentage), daemon=True ).start() with console.status(\"[bold", "Literal, List from rich.console import Console from open_gopro import GoPro", "= gopro.get_update() # Update data points if they have changed", "= [] def dump_results_as_csv(location: Path) -> None: \"\"\"Write all of", "changed last_percentage = ( notification.data[StatusId.INT_BATT_PER] if StatusId.INT_BATT_PER in notification.data else", "isn't used. Args: gopro (GoPro): instance to get updates from", "if len(SAMPLES) > 0: csv_location = Path(log_location.parent) / \"battery_results.csv\" dump_results_as_csv(csv_location)", "(identifier, path to save log, path to VLC) \"\"\" parser", "arguments Returns: Tuple[str, Path, Path]: (identifier, path to save log,", "green]Receiving battery notifications until it dies...\"): # Sleep forever, allowing", "# Sleep forever, allowing notification handler thread to deal with", "GoPro from open_gopro.constants import StatusId from open_gopro.util import setup_logging, set_logging_level" ]
[ "# These are not the droids you are looking for.", "<reponame>mcroydon/django-tumbleweed<filename>tumbleweed/models.py # These are not the droids you are looking" ]
[ "(not ors.contentProvider.content_provider_id): return cpid = ors.contentProvider.content_provider_id # validation requires URL", "= [x[\"origin_server_id\"] for x in self.client.onev.ListAll(\"OriginServer\")] for ors in OriginServer.objects.all():", "HpcLibrary): provides=[OriginServer] requested_interval=0 def __init__(self, **args): SyncStep.__init__(self, **args) HpcLibrary.__init__(self) def", "from observer.syncstep import SyncStep from core.models import Service from hpc.models", "x in self.client.onev.ListAll(\"OriginServer\")] for ors in OriginServer.objects.all(): if (ors.origin_server_id is", "found on CMI\" % ors.origin_server_id) ors.origin_server_id=None ors.save() result = True", "(ors.origin_server_id not in all_ors_ids): # we have an origin server", "# validation requires URL start with http:// url = ors.url", "import sys import base64 from django.db.models import F, Q from", "an origin server ID, but it doesn't exist in the", "os import sys import base64 from django.db.models import F, Q", "true if something changed result=False # sanity check to make", "sys import base64 from django.db.models import F, Q from xos.config", "util.logger import Logger, logging # hpclibrary will be in steps/..", "Logger, logging # hpclibrary will be in steps/.. parentdir =", "SyncStep.__init__(self, **args) HpcLibrary.__init__(self) def fetch_pending(self, deleted): #self.consistency_check() return SyncStep.fetch_pending(self, deleted)", "have an origin server ID, but it doesn't exist in", "server %s\" % str(ors)) if (not ors.contentProvider) or (not ors.contentProvider.content_provider_id):", "not url.startswith(\"http://\"): url = \"http://\" + url ors_dict = {\"authenticated_content\":", "it via onev. url = url[7:] self.client.cob.UpdateContent(ors.origin_server_id, {\"url\": url}) ors.silent", "not found on CMI\" % ors.origin_server_id) ors.origin_server_id=None ors.save() result =", "if not url.startswith(\"http://\"): url = \"http://\" + url ors_dict =", "it doesn't exist in the CMI # something went wrong", "= True return result def sync_record(self, ors): logger.info(\"sync'ing origin server", "all_ors_ids): # we have an origin server ID, but it", "and (ors.origin_server_id not in all_ors_ids): # we have an origin", "server %s was not found on CMI\" % ors.origin_server_id) ors.origin_server_id=None", "% ors.origin_server_id) ors.origin_server_id=None ors.save() result = True return result def", "logging # hpclibrary will be in steps/.. parentdir = os.path.join(os.path.dirname(__file__),\"..\")", "server ID, but it doesn't exist in the CMI #", "Q from xos.config import Config from observer.syncstep import SyncStep from", "from util.logger import Logger, logging # hpclibrary will be in", "if (not ors.contentProvider) or (not ors.contentProvider.content_provider_id): return cpid = ors.contentProvider.content_provider_id", "def consistency_check(self): # set to true if something changed result=False", "import Service from hpc.models import ServiceProvider, ContentProvider, CDNPrefix, OriginServer from", "hpc.models import ServiceProvider, ContentProvider, CDNPrefix, OriginServer from util.logger import Logger,", "if (ors.origin_server_id is not None) and (ors.origin_server_id not in all_ors_ids):", "ors.authenticated, \"zone_redirects\": ors.redirects, \"content_provider_id\": cpid, \"url\": url, \"service_type\": \"HyperCache\", \"caching_type\":", "them all_ors_ids = [x[\"origin_server_id\"] for x in self.client.onev.ListAll(\"OriginServer\")] for ors", "ors): logger.info(\"sync'ing origin server %s\" % str(ors)) if (not ors.contentProvider)", "or (not ors.contentProvider.content_provider_id): return cpid = ors.contentProvider.content_provider_id # validation requires", "import Logger, logging # hpclibrary will be in steps/.. parentdir", "steps/.. parentdir = os.path.join(os.path.dirname(__file__),\"..\") sys.path.insert(0,parentdir) from hpclib import HpcLibrary logger", "in steps/.. parentdir = os.path.join(os.path.dirname(__file__),\"..\") sys.path.insert(0,parentdir) from hpclib import HpcLibrary", "ors.contentProvider.content_provider_id # validation requires URL start with http:// url =", "ors.origin_server_id = id else: self.client.onev.Update(\"OriginServer\", ors.origin_server_id, ors_dict) # ... something", "return result def sync_record(self, ors): logger.info(\"sync'ing origin server %s\" %", "return SyncStep.fetch_pending(self, deleted) def consistency_check(self): # set to true if", "consistency_check(self): # set to true if something changed result=False #", "on CMI\" % ors.origin_server_id) ors.origin_server_id=None ors.save() result = True return", "sure our PS objects have CMI objects behind them all_ors_ids", "return cpid = ors.contentProvider.content_provider_id # validation requires URL start with", "\"content_provider_id\": cpid, \"url\": url, \"service_type\": \"HyperCache\", \"caching_type\": \"Optimistic\", \"description\": ors.description}", "\"Optimistic\", \"description\": ors.description} #print os_dict if not ors.origin_server_id: id =", "ors.origin_server_id, ors_dict) # ... something breaks (analytics) if the URL", "change it in cob after we added it via onev.", "changed result=False # sanity check to make sure our PS", "behind them all_ors_ids = [x[\"origin_server_id\"] for x in self.client.onev.ListAll(\"OriginServer\")] for", "the CMI # something went wrong # start over logger.info(\"origin", "ors.origin_server_id: id = self.client.onev.Create(\"OriginServer\", ors_dict) ors.origin_server_id = id else: self.client.onev.Update(\"OriginServer\",", "breaks (analytics) if the URL starts with http://, so we", "self.client.onev.Create(\"OriginServer\", ors_dict) ors.origin_server_id = id else: self.client.onev.Update(\"OriginServer\", ors.origin_server_id, ors_dict) #", "url = ors.url if not url.startswith(\"http://\"): url = \"http://\" +", "OriginServer from util.logger import Logger, logging # hpclibrary will be", "ors.save() def delete_record(self, m): if m.origin_server_id is not None: self.client.onev.Delete(\"OriginServer\",", "sys.path.insert(0,parentdir) from hpclib import HpcLibrary logger = Logger(level=logging.INFO) class SyncOriginServer(SyncStep,", "objects behind them all_ors_ids = [x[\"origin_server_id\"] for x in self.client.onev.ListAll(\"OriginServer\")]", "after we added it via onev. url = url[7:] self.client.cob.UpdateContent(ors.origin_server_id,", "HpcLibrary logger = Logger(level=logging.INFO) class SyncOriginServer(SyncStep, HpcLibrary): provides=[OriginServer] requested_interval=0 def", "= self.client.onev.Create(\"OriginServer\", ors_dict) ors.origin_server_id = id else: self.client.onev.Update(\"OriginServer\", ors.origin_server_id, ors_dict)", "# change it in cob after we added it via", "for ors in OriginServer.objects.all(): if (ors.origin_server_id is not None) and", "over logger.info(\"origin server %s was not found on CMI\" %", "ContentProvider, CDNPrefix, OriginServer from util.logger import Logger, logging # hpclibrary", "None) and (ors.origin_server_id not in all_ors_ids): # we have an", "cpid, \"url\": url, \"service_type\": \"HyperCache\", \"caching_type\": \"Optimistic\", \"description\": ors.description} #print", "ors.description} #print os_dict if not ors.origin_server_id: id = self.client.onev.Create(\"OriginServer\", ors_dict)", "cpid = ors.contentProvider.content_provider_id # validation requires URL start with http://", "{\"url\": url}) ors.silent = True ors.save() def delete_record(self, m): if", "result def sync_record(self, ors): logger.info(\"sync'ing origin server %s\" % str(ors))", "+ url ors_dict = {\"authenticated_content\": ors.authenticated, \"zone_redirects\": ors.redirects, \"content_provider_id\": cpid,", "logger = Logger(level=logging.INFO) class SyncOriginServer(SyncStep, HpcLibrary): provides=[OriginServer] requested_interval=0 def __init__(self,", "\"service_type\": \"HyperCache\", \"caching_type\": \"Optimistic\", \"description\": ors.description} #print os_dict if not", "validation requires URL start with http:// url = ors.url if", "wrong # start over logger.info(\"origin server %s was not found", "import os import sys import base64 from django.db.models import F,", "os_dict if not ors.origin_server_id: id = self.client.onev.Create(\"OriginServer\", ors_dict) ors.origin_server_id =", "be in steps/.. parentdir = os.path.join(os.path.dirname(__file__),\"..\") sys.path.insert(0,parentdir) from hpclib import", "str(ors)) if (not ors.contentProvider) or (not ors.contentProvider.content_provider_id): return cpid =", "sync_record(self, ors): logger.info(\"sync'ing origin server %s\" % str(ors)) if (not", "import HpcLibrary logger = Logger(level=logging.INFO) class SyncOriginServer(SyncStep, HpcLibrary): provides=[OriginServer] requested_interval=0", "= url[7:] self.client.cob.UpdateContent(ors.origin_server_id, {\"url\": url}) ors.silent = True ors.save() def", "[x[\"origin_server_id\"] for x in self.client.onev.ListAll(\"OriginServer\")] for ors in OriginServer.objects.all(): if", "URL start with http:// url = ors.url if not url.startswith(\"http://\"):", "the URL starts with http://, so we # change it", "check to make sure our PS objects have CMI objects", "onev. url = url[7:] self.client.cob.UpdateContent(ors.origin_server_id, {\"url\": url}) ors.silent = True", "(not ors.contentProvider) or (not ors.contentProvider.content_provider_id): return cpid = ors.contentProvider.content_provider_id #", "(analytics) if the URL starts with http://, so we #", "was not found on CMI\" % ors.origin_server_id) ors.origin_server_id=None ors.save() result", "deleted) def consistency_check(self): # set to true if something changed", "# start over logger.info(\"origin server %s was not found on", "id = self.client.onev.Create(\"OriginServer\", ors_dict) ors.origin_server_id = id else: self.client.onev.Update(\"OriginServer\", ors.origin_server_id,", "else: self.client.onev.Update(\"OriginServer\", ors.origin_server_id, ors_dict) # ... something breaks (analytics) if", "went wrong # start over logger.info(\"origin server %s was not", "\"description\": ors.description} #print os_dict if not ors.origin_server_id: id = self.client.onev.Create(\"OriginServer\",", "not None) and (ors.origin_server_id not in all_ors_ids): # we have", "something breaks (analytics) if the URL starts with http://, so", "logger.info(\"origin server %s was not found on CMI\" % ors.origin_server_id)", "hpclibrary will be in steps/.. parentdir = os.path.join(os.path.dirname(__file__),\"..\") sys.path.insert(0,parentdir) from", "ors.origin_server_id=None ors.save() result = True return result def sync_record(self, ors):", "\"caching_type\": \"Optimistic\", \"description\": ors.description} #print os_dict if not ors.origin_server_id: id", "something changed result=False # sanity check to make sure our", "def delete_record(self, m): if m.origin_server_id is not None: self.client.onev.Delete(\"OriginServer\", m.origin_server_id)", "# sanity check to make sure our PS objects have", "CMI objects behind them all_ors_ids = [x[\"origin_server_id\"] for x in", "{\"authenticated_content\": ors.authenticated, \"zone_redirects\": ors.redirects, \"content_provider_id\": cpid, \"url\": url, \"service_type\": \"HyperCache\",", "= os.path.join(os.path.dirname(__file__),\"..\") sys.path.insert(0,parentdir) from hpclib import HpcLibrary logger = Logger(level=logging.INFO)", "fetch_pending(self, deleted): #self.consistency_check() return SyncStep.fetch_pending(self, deleted) def consistency_check(self): # set", "from hpc.models import ServiceProvider, ContentProvider, CDNPrefix, OriginServer from util.logger import", "SyncStep.fetch_pending(self, deleted) def consistency_check(self): # set to true if something", "OriginServer.objects.all(): if (ors.origin_server_id is not None) and (ors.origin_server_id not in", "__init__(self, **args): SyncStep.__init__(self, **args) HpcLibrary.__init__(self) def fetch_pending(self, deleted): #self.consistency_check() return", "= id else: self.client.onev.Update(\"OriginServer\", ors.origin_server_id, ors_dict) # ... something breaks", "#self.consistency_check() return SyncStep.fetch_pending(self, deleted) def consistency_check(self): # set to true", "from django.db.models import F, Q from xos.config import Config from", "True return result def sync_record(self, ors): logger.info(\"sync'ing origin server %s\"", "ors.contentProvider) or (not ors.contentProvider.content_provider_id): return cpid = ors.contentProvider.content_provider_id # validation", "hpclib import HpcLibrary logger = Logger(level=logging.INFO) class SyncOriginServer(SyncStep, HpcLibrary): provides=[OriginServer]", "we # change it in cob after we added it", "url ors_dict = {\"authenticated_content\": ors.authenticated, \"zone_redirects\": ors.redirects, \"content_provider_id\": cpid, \"url\":", "url.startswith(\"http://\"): url = \"http://\" + url ors_dict = {\"authenticated_content\": ors.authenticated,", "**args): SyncStep.__init__(self, **args) HpcLibrary.__init__(self) def fetch_pending(self, deleted): #self.consistency_check() return SyncStep.fetch_pending(self,", "provides=[OriginServer] requested_interval=0 def __init__(self, **args): SyncStep.__init__(self, **args) HpcLibrary.__init__(self) def fetch_pending(self,", "ors.save() result = True return result def sync_record(self, ors): logger.info(\"sync'ing", "True ors.save() def delete_record(self, m): if m.origin_server_id is not None:", "ors_dict) ors.origin_server_id = id else: self.client.onev.Update(\"OriginServer\", ors.origin_server_id, ors_dict) # ...", "Logger(level=logging.INFO) class SyncOriginServer(SyncStep, HpcLibrary): provides=[OriginServer] requested_interval=0 def __init__(self, **args): SyncStep.__init__(self,", "ors.silent = True ors.save() def delete_record(self, m): if m.origin_server_id is", "url}) ors.silent = True ors.save() def delete_record(self, m): if m.origin_server_id", "if not ors.origin_server_id: id = self.client.onev.Create(\"OriginServer\", ors_dict) ors.origin_server_id = id", "objects have CMI objects behind them all_ors_ids = [x[\"origin_server_id\"] for", "not ors.origin_server_id: id = self.client.onev.Create(\"OriginServer\", ors_dict) ors.origin_server_id = id else:", "import Config from observer.syncstep import SyncStep from core.models import Service", "Config from observer.syncstep import SyncStep from core.models import Service from", "django.db.models import F, Q from xos.config import Config from observer.syncstep", "SyncOriginServer(SyncStep, HpcLibrary): provides=[OriginServer] requested_interval=0 def __init__(self, **args): SyncStep.__init__(self, **args) HpcLibrary.__init__(self)", "from hpclib import HpcLibrary logger = Logger(level=logging.INFO) class SyncOriginServer(SyncStep, HpcLibrary):", "# we have an origin server ID, but it doesn't", "# ... something breaks (analytics) if the URL starts with", "def sync_record(self, ors): logger.info(\"sync'ing origin server %s\" % str(ors)) if", "CMI # something went wrong # start over logger.info(\"origin server", "is not None) and (ors.origin_server_id not in all_ors_ids): # we", "... something breaks (analytics) if the URL starts with http://,", "via onev. url = url[7:] self.client.cob.UpdateContent(ors.origin_server_id, {\"url\": url}) ors.silent =", "deleted): #self.consistency_check() return SyncStep.fetch_pending(self, deleted) def consistency_check(self): # set to", "ors_dict) # ... something breaks (analytics) if the URL starts", "origin server %s\" % str(ors)) if (not ors.contentProvider) or (not", "xos.config import Config from observer.syncstep import SyncStep from core.models import", "ServiceProvider, ContentProvider, CDNPrefix, OriginServer from util.logger import Logger, logging #", "PS objects have CMI objects behind them all_ors_ids = [x[\"origin_server_id\"]", "= ors.url if not url.startswith(\"http://\"): url = \"http://\" + url", "import F, Q from xos.config import Config from observer.syncstep import", "self.client.onev.Update(\"OriginServer\", ors.origin_server_id, ors_dict) # ... something breaks (analytics) if the", "class SyncOriginServer(SyncStep, HpcLibrary): provides=[OriginServer] requested_interval=0 def __init__(self, **args): SyncStep.__init__(self, **args)", "URL starts with http://, so we # change it in", "if something changed result=False # sanity check to make sure", "for x in self.client.onev.ListAll(\"OriginServer\")] for ors in OriginServer.objects.all(): if (ors.origin_server_id", "requires URL start with http:// url = ors.url if not", "so we # change it in cob after we added", "added it via onev. url = url[7:] self.client.cob.UpdateContent(ors.origin_server_id, {\"url\": url})", "from core.models import Service from hpc.models import ServiceProvider, ContentProvider, CDNPrefix,", "(ors.origin_server_id is not None) and (ors.origin_server_id not in all_ors_ids): #", "http://, so we # change it in cob after we", "in the CMI # something went wrong # start over", "start with http:// url = ors.url if not url.startswith(\"http://\"): url", "with http:// url = ors.url if not url.startswith(\"http://\"): url =", "in cob after we added it via onev. url =", "import SyncStep from core.models import Service from hpc.models import ServiceProvider,", "core.models import Service from hpc.models import ServiceProvider, ContentProvider, CDNPrefix, OriginServer", "**args) HpcLibrary.__init__(self) def fetch_pending(self, deleted): #self.consistency_check() return SyncStep.fetch_pending(self, deleted) def", "in self.client.onev.ListAll(\"OriginServer\")] for ors in OriginServer.objects.all(): if (ors.origin_server_id is not", "= {\"authenticated_content\": ors.authenticated, \"zone_redirects\": ors.redirects, \"content_provider_id\": cpid, \"url\": url, \"service_type\":", "not in all_ors_ids): # we have an origin server ID,", "Service from hpc.models import ServiceProvider, ContentProvider, CDNPrefix, OriginServer from util.logger", "\"http://\" + url ors_dict = {\"authenticated_content\": ors.authenticated, \"zone_redirects\": ors.redirects, \"content_provider_id\":", "# set to true if something changed result=False # sanity", "we have an origin server ID, but it doesn't exist", "if the URL starts with http://, so we # change", "self.client.cob.UpdateContent(ors.origin_server_id, {\"url\": url}) ors.silent = True ors.save() def delete_record(self, m):", "requested_interval=0 def __init__(self, **args): SyncStep.__init__(self, **args) HpcLibrary.__init__(self) def fetch_pending(self, deleted):", "= ors.contentProvider.content_provider_id # validation requires URL start with http:// url", "= Logger(level=logging.INFO) class SyncOriginServer(SyncStep, HpcLibrary): provides=[OriginServer] requested_interval=0 def __init__(self, **args):", "start over logger.info(\"origin server %s was not found on CMI\"", "= \"http://\" + url ors_dict = {\"authenticated_content\": ors.authenticated, \"zone_redirects\": ors.redirects,", "os.path.join(os.path.dirname(__file__),\"..\") sys.path.insert(0,parentdir) from hpclib import HpcLibrary logger = Logger(level=logging.INFO) class", "origin server ID, but it doesn't exist in the CMI", "url = \"http://\" + url ors_dict = {\"authenticated_content\": ors.authenticated, \"zone_redirects\":", "# something went wrong # start over logger.info(\"origin server %s", "ors.origin_server_id) ors.origin_server_id=None ors.save() result = True return result def sync_record(self,", "%s\" % str(ors)) if (not ors.contentProvider) or (not ors.contentProvider.content_provider_id): return", "import base64 from django.db.models import F, Q from xos.config import", "self.client.onev.ListAll(\"OriginServer\")] for ors in OriginServer.objects.all(): if (ors.origin_server_id is not None)", "# hpclibrary will be in steps/.. parentdir = os.path.join(os.path.dirname(__file__),\"..\") sys.path.insert(0,parentdir)", "ors.url if not url.startswith(\"http://\"): url = \"http://\" + url ors_dict", "SyncStep from core.models import Service from hpc.models import ServiceProvider, ContentProvider,", "\"url\": url, \"service_type\": \"HyperCache\", \"caching_type\": \"Optimistic\", \"description\": ors.description} #print os_dict", "make sure our PS objects have CMI objects behind them", "in all_ors_ids): # we have an origin server ID, but", "ors.contentProvider.content_provider_id): return cpid = ors.contentProvider.content_provider_id # validation requires URL start", "ors_dict = {\"authenticated_content\": ors.authenticated, \"zone_redirects\": ors.redirects, \"content_provider_id\": cpid, \"url\": url,", "url, \"service_type\": \"HyperCache\", \"caching_type\": \"Optimistic\", \"description\": ors.description} #print os_dict if", "will be in steps/.. parentdir = os.path.join(os.path.dirname(__file__),\"..\") sys.path.insert(0,parentdir) from hpclib", "exist in the CMI # something went wrong # start", "but it doesn't exist in the CMI # something went", "#print os_dict if not ors.origin_server_id: id = self.client.onev.Create(\"OriginServer\", ors_dict) ors.origin_server_id", "url[7:] self.client.cob.UpdateContent(ors.origin_server_id, {\"url\": url}) ors.silent = True ors.save() def delete_record(self,", "ors in OriginServer.objects.all(): if (ors.origin_server_id is not None) and (ors.origin_server_id", "with http://, so we # change it in cob after", "import ServiceProvider, ContentProvider, CDNPrefix, OriginServer from util.logger import Logger, logging", "http:// url = ors.url if not url.startswith(\"http://\"): url = \"http://\"", "our PS objects have CMI objects behind them all_ors_ids =", "ors.redirects, \"content_provider_id\": cpid, \"url\": url, \"service_type\": \"HyperCache\", \"caching_type\": \"Optimistic\", \"description\":", "url = url[7:] self.client.cob.UpdateContent(ors.origin_server_id, {\"url\": url}) ors.silent = True ors.save()", "we added it via onev. url = url[7:] self.client.cob.UpdateContent(ors.origin_server_id, {\"url\":", "CDNPrefix, OriginServer from util.logger import Logger, logging # hpclibrary will", "base64 from django.db.models import F, Q from xos.config import Config", "from xos.config import Config from observer.syncstep import SyncStep from core.models", "% str(ors)) if (not ors.contentProvider) or (not ors.contentProvider.content_provider_id): return cpid", "id else: self.client.onev.Update(\"OriginServer\", ors.origin_server_id, ors_dict) # ... something breaks (analytics)", "parentdir = os.path.join(os.path.dirname(__file__),\"..\") sys.path.insert(0,parentdir) from hpclib import HpcLibrary logger =", "CMI\" % ors.origin_server_id) ors.origin_server_id=None ors.save() result = True return result", "\"zone_redirects\": ors.redirects, \"content_provider_id\": cpid, \"url\": url, \"service_type\": \"HyperCache\", \"caching_type\": \"Optimistic\",", "logger.info(\"sync'ing origin server %s\" % str(ors)) if (not ors.contentProvider) or", "observer.syncstep import SyncStep from core.models import Service from hpc.models import", "result=False # sanity check to make sure our PS objects", "sanity check to make sure our PS objects have CMI", "ID, but it doesn't exist in the CMI # something", "have CMI objects behind them all_ors_ids = [x[\"origin_server_id\"] for x", "something went wrong # start over logger.info(\"origin server %s was", "starts with http://, so we # change it in cob", "def __init__(self, **args): SyncStep.__init__(self, **args) HpcLibrary.__init__(self) def fetch_pending(self, deleted): #self.consistency_check()", "set to true if something changed result=False # sanity check", "in OriginServer.objects.all(): if (ors.origin_server_id is not None) and (ors.origin_server_id not", "def fetch_pending(self, deleted): #self.consistency_check() return SyncStep.fetch_pending(self, deleted) def consistency_check(self): #", "= True ors.save() def delete_record(self, m): if m.origin_server_id is not", "doesn't exist in the CMI # something went wrong #", "%s was not found on CMI\" % ors.origin_server_id) ors.origin_server_id=None ors.save()", "HpcLibrary.__init__(self) def fetch_pending(self, deleted): #self.consistency_check() return SyncStep.fetch_pending(self, deleted) def consistency_check(self):", "\"HyperCache\", \"caching_type\": \"Optimistic\", \"description\": ors.description} #print os_dict if not ors.origin_server_id:", "F, Q from xos.config import Config from observer.syncstep import SyncStep", "to make sure our PS objects have CMI objects behind", "result = True return result def sync_record(self, ors): logger.info(\"sync'ing origin", "it in cob after we added it via onev. url", "to true if something changed result=False # sanity check to", "all_ors_ids = [x[\"origin_server_id\"] for x in self.client.onev.ListAll(\"OriginServer\")] for ors in", "cob after we added it via onev. url = url[7:]" ]
[ "def tranform(r, g, b): tmp = b b = g", "= tmp r = r // 2 return r, g,", "tuple(tranform(*pixel) for pixel in input_pixels) im.putdata(output_pixels) im.save('green-flames.png') if __name__ ==", "im = Image.open('blue-flames.jpg') input_pixels = im.getdata() output_pixels = tuple(tranform(*pixel) for", "= im.getdata() output_pixels = tuple(tranform(*pixel) for pixel in input_pixels) im.putdata(output_pixels)", "= r // 2 return r, g, b def main():", "b def main(): im = Image.open('blue-flames.jpg') input_pixels = im.getdata() output_pixels", "main(): im = Image.open('blue-flames.jpg') input_pixels = im.getdata() output_pixels = tuple(tranform(*pixel)", "= g // 2 g = tmp r = r", "for pixel in input_pixels) im.putdata(output_pixels) im.save('green-flames.png') if __name__ == '__main__':", "b): tmp = b b = g // 2 g", "tranform(r, g, b): tmp = b b = g //", "Image def tranform(r, g, b): tmp = b b =", "def main(): im = Image.open('blue-flames.jpg') input_pixels = im.getdata() output_pixels =", "r = r // 2 return r, g, b def", "tmp r = r // 2 return r, g, b", "= b b = g // 2 g = tmp", "PIL import Image def tranform(r, g, b): tmp = b", "return r, g, b def main(): im = Image.open('blue-flames.jpg') input_pixels", "g, b def main(): im = Image.open('blue-flames.jpg') input_pixels = im.getdata()", "2 return r, g, b def main(): im = Image.open('blue-flames.jpg')", "Image.open('blue-flames.jpg') input_pixels = im.getdata() output_pixels = tuple(tranform(*pixel) for pixel in", "= Image.open('blue-flames.jpg') input_pixels = im.getdata() output_pixels = tuple(tranform(*pixel) for pixel", "// 2 g = tmp r = r // 2", "// 2 return r, g, b def main(): im =", "output_pixels = tuple(tranform(*pixel) for pixel in input_pixels) im.putdata(output_pixels) im.save('green-flames.png') if", "g // 2 g = tmp r = r //", "r, g, b def main(): im = Image.open('blue-flames.jpg') input_pixels =", "python3 from PIL import Image def tranform(r, g, b): tmp", "#!/usr/bin/env python3 from PIL import Image def tranform(r, g, b):", "2 g = tmp r = r // 2 return", "tmp = b b = g // 2 g =", "import Image def tranform(r, g, b): tmp = b b", "g = tmp r = r // 2 return r,", "g, b): tmp = b b = g // 2", "r // 2 return r, g, b def main(): im", "= tuple(tranform(*pixel) for pixel in input_pixels) im.putdata(output_pixels) im.save('green-flames.png') if __name__", "input_pixels = im.getdata() output_pixels = tuple(tranform(*pixel) for pixel in input_pixels)", "b = g // 2 g = tmp r =", "b b = g // 2 g = tmp r", "from PIL import Image def tranform(r, g, b): tmp =", "pixel in input_pixels) im.putdata(output_pixels) im.save('green-flames.png') if __name__ == '__main__': main()", "im.getdata() output_pixels = tuple(tranform(*pixel) for pixel in input_pixels) im.putdata(output_pixels) im.save('green-flames.png')" ]
[ "swig2_ext.i $ g++ -Wall -O2 -I/usr/include/python2.3 -fPIC -I. -c \\", "method from C++ using weave.inline \"\"\" a = swig2_ext.A() b", "using weave.inline \"\"\" a = swig2_ext.A() b = swig2_ext.foo() #", "refers to SWIG versions >= 1.3. To run this example", "-O2 -I/usr/include/python2.3 -fPIC -I. -c \\ -o swig2_ext_wrap.os swig2_ext_wrap.cxx $", "like this:: $ swig -c++ -python -I. -o swig2_ext_wrap.cxx swig2_ext.i", "b->f(); \"\"\" weave.inline(code, ['a', 'b'], include_dirs=['.'], headers=['\"swig2_ext.h\"'], verbose=1) if __name__", "SWIG versions >= 1.3. To run this example you must", "to do something like this:: $ swig -c++ -python -I.", "need to do something like this:: $ swig -c++ -python", "wrapped library import swig2_ext import scipy.weave as weave from scipy.weave", "SWIG2 support works fine whether SWIG_COBJECT_TYPES are used or not.", "from scipy.weave import swig2_spec, converters # SWIG2 support is not", "our SWIG2 wrapped library import swig2_ext import scipy.weave as weave", "of converters. converters.default.insert(0, swig2_spec.swig2_converter()) def test(): \"\"\"Instantiate the SWIG wrapped", "converters # SWIG2 support is not enabled by default. We", "this you need to do something like this:: $ swig", "do something like this:: $ swig -c++ -python -I. -o", "use weave.inline on SWIG2 wrapped objects. SWIG2 refers to SWIG", "-o swig2_ext_wrap.cxx swig2_ext.i $ g++ -Wall -O2 -I/usr/include/python2.3 -fPIC -I.", "swig2_ext.h are included in the same directory that contains this", "BSD Style. \"\"\" # Import our SWIG2 wrapped library import", "called swig2_ext. To do this you need to do something", "example you must build the trivial SWIG2 extension called swig2_ext.", "-I. -c \\ -o swig2_ext_wrap.os swig2_ext_wrap.cxx $ g++ -shared -o", "do this by adding the # swig2 converter to the", "wrapped object and then call its method from C++ using", "\"\"\"Simple example to show how to use weave.inline on SWIG2", "# SWIG2 support is not enabled by default. We do", "\"\"\"Instantiate the SWIG wrapped object and then call its method", "= swig2_ext.A() b = swig2_ext.foo() # This will be an", "library import swig2_ext import scipy.weave as weave from scipy.weave import", "-python -I. -o swig2_ext_wrap.cxx swig2_ext.i $ g++ -Wall -O2 -I/usr/include/python2.3", "The files swig2_ext.i and swig2_ext.h are included in the same", "or not. Author: <NAME> Copyright (c) 2004, <NAME> License: BSD", "converters.default.insert(0, swig2_spec.swig2_converter()) def test(): \"\"\"Instantiate the SWIG wrapped object and", "file. Note that weave's SWIG2 support works fine whether SWIG_COBJECT_TYPES", "its method from C++ using weave.inline \"\"\" a = swig2_ext.A()", "\"\"\"a->f(); b->f(); \"\"\" weave.inline(code, ['a', 'b'], include_dirs=['.'], headers=['\"swig2_ext.h\"'], verbose=1) if", "will be an APtr instance. b.thisown = 1 # Prevent", "fine whether SWIG_COBJECT_TYPES are used or not. Author: <NAME> Copyright", "show how to use weave.inline on SWIG2 wrapped objects. SWIG2", "-Wall -O2 -I/usr/include/python2.3 -fPIC -I. -c \\ -o swig2_ext_wrap.os swig2_ext_wrap.cxx", "then call its method from C++ using weave.inline \"\"\" a", "default. We do this by adding the # swig2 converter", "list of converters. converters.default.insert(0, swig2_spec.swig2_converter()) def test(): \"\"\"Instantiate the SWIG", "adding the # swig2 converter to the default list of", "enabled by default. We do this by adding the #", "by default. We do this by adding the # swig2", "swig2_ext.i and swig2_ext.h are included in the same directory that", "call its method from C++ using weave.inline \"\"\" a =", "weave's SWIG2 support works fine whether SWIG_COBJECT_TYPES are used or", "and then call its method from C++ using weave.inline \"\"\"", "versions >= 1.3. To run this example you must build", "used or not. Author: <NAME> Copyright (c) 2004, <NAME> License:", "# Import our SWIG2 wrapped library import swig2_ext import scipy.weave", "g++ -Wall -O2 -I/usr/include/python2.3 -fPIC -I. -c \\ -o swig2_ext_wrap.os", "= \"\"\"a->f(); b->f(); \"\"\" weave.inline(code, ['a', 'b'], include_dirs=['.'], headers=['\"swig2_ext.h\"'], verbose=1)", "-o _swig2_ext.so swig2_ext_wrap.os \\ -L/usr/lib/python2.3/config The files swig2_ext.i and swig2_ext.h", "from C++ using weave.inline \"\"\" a = swig2_ext.A() b =", "weave from scipy.weave import swig2_spec, converters # SWIG2 support is", "SWIG_COBJECT_TYPES are used or not. Author: <NAME> Copyright (c) 2004,", "converters. converters.default.insert(0, swig2_spec.swig2_converter()) def test(): \"\"\"Instantiate the SWIG wrapped object", "are used or not. Author: <NAME> Copyright (c) 2004, <NAME>", "2004, <NAME> License: BSD Style. \"\"\" # Import our SWIG2", "def test(): \"\"\"Instantiate the SWIG wrapped object and then call", "Author: <NAME> Copyright (c) 2004, <NAME> License: BSD Style. \"\"\"", "Prevent memory leaks. code = \"\"\"a->f(); b->f(); \"\"\" weave.inline(code, ['a',", "SWIG2 wrapped library import swig2_ext import scipy.weave as weave from", "on SWIG2 wrapped objects. SWIG2 refers to SWIG versions >=", "swig2_spec, converters # SWIG2 support is not enabled by default.", "by adding the # swig2 converter to the default list", "support is not enabled by default. We do this by", "that contains this file. Note that weave's SWIG2 support works", "run this example you must build the trivial SWIG2 extension", "do this you need to do something like this:: $", "<NAME> Copyright (c) 2004, <NAME> License: BSD Style. \"\"\" #", "extension called swig2_ext. To do this you need to do", "to use weave.inline on SWIG2 wrapped objects. SWIG2 refers to", "-I/usr/include/python2.3 -fPIC -I. -c \\ -o swig2_ext_wrap.os swig2_ext_wrap.cxx $ g++", "same directory that contains this file. Note that weave's SWIG2", "scipy.weave import swig2_spec, converters # SWIG2 support is not enabled", "= 1 # Prevent memory leaks. code = \"\"\"a->f(); b->f();", "directory that contains this file. Note that weave's SWIG2 support", "# Prevent memory leaks. code = \"\"\"a->f(); b->f(); \"\"\" weave.inline(code,", "\"\"\" a = swig2_ext.A() b = swig2_ext.foo() # This will", "Copyright (c) 2004, <NAME> License: BSD Style. \"\"\" # Import", "must build the trivial SWIG2 extension called swig2_ext. To do", "To run this example you must build the trivial SWIG2", "are included in the same directory that contains this file.", "instance. b.thisown = 1 # Prevent memory leaks. code =", "contains this file. Note that weave's SWIG2 support works fine", "be an APtr instance. b.thisown = 1 # Prevent memory", "g++ -shared -o _swig2_ext.so swig2_ext_wrap.os \\ -L/usr/lib/python2.3/config The files swig2_ext.i", "Import our SWIG2 wrapped library import swig2_ext import scipy.weave as", "b = swig2_ext.foo() # This will be an APtr instance.", "this:: $ swig -c++ -python -I. -o swig2_ext_wrap.cxx swig2_ext.i $", "this example you must build the trivial SWIG2 extension called", "License: BSD Style. \"\"\" # Import our SWIG2 wrapped library", "= swig2_ext.foo() # This will be an APtr instance. b.thisown", "b.thisown = 1 # Prevent memory leaks. code = \"\"\"a->f();", "swig2_ext_wrap.cxx swig2_ext.i $ g++ -Wall -O2 -I/usr/include/python2.3 -fPIC -I. -c", "files swig2_ext.i and swig2_ext.h are included in the same directory", "APtr instance. b.thisown = 1 # Prevent memory leaks. code", "trivial SWIG2 extension called swig2_ext. To do this you need", "leaks. code = \"\"\"a->f(); b->f(); \"\"\" weave.inline(code, ['a', 'b'], include_dirs=['.'],", "SWIG2 extension called swig2_ext. To do this you need to", "1.3. To run this example you must build the trivial", "To do this you need to do something like this::", "C++ using weave.inline \"\"\" a = swig2_ext.A() b = swig2_ext.foo()", "included in the same directory that contains this file. Note", "works fine whether SWIG_COBJECT_TYPES are used or not. Author: <NAME>", "objects. SWIG2 refers to SWIG versions >= 1.3. To run", "Style. \"\"\" # Import our SWIG2 wrapped library import swig2_ext", "\\ -o swig2_ext_wrap.os swig2_ext_wrap.cxx $ g++ -shared -o _swig2_ext.so swig2_ext_wrap.os", "_swig2_ext.so swig2_ext_wrap.os \\ -L/usr/lib/python2.3/config The files swig2_ext.i and swig2_ext.h are", "weave.inline \"\"\" a = swig2_ext.A() b = swig2_ext.foo() # This", "and swig2_ext.h are included in the same directory that contains", "this by adding the # swig2 converter to the default", "$ g++ -Wall -O2 -I/usr/include/python2.3 -fPIC -I. -c \\ -o", "swig2_ext_wrap.os \\ -L/usr/lib/python2.3/config The files swig2_ext.i and swig2_ext.h are included", "to SWIG versions >= 1.3. To run this example you", "support works fine whether SWIG_COBJECT_TYPES are used or not. Author:", "test(): \"\"\"Instantiate the SWIG wrapped object and then call its", "swig2_ext.A() b = swig2_ext.foo() # This will be an APtr", "code = \"\"\"a->f(); b->f(); \"\"\" weave.inline(code, ['a', 'b'], include_dirs=['.'], headers=['\"swig2_ext.h\"'],", "wrapped objects. SWIG2 refers to SWIG versions >= 1.3. To", "-I. -o swig2_ext_wrap.cxx swig2_ext.i $ g++ -Wall -O2 -I/usr/include/python2.3 -fPIC", "(c) 2004, <NAME> License: BSD Style. \"\"\" # Import our", "weave.inline(code, ['a', 'b'], include_dirs=['.'], headers=['\"swig2_ext.h\"'], verbose=1) if __name__ == \"__main__\":", "example to show how to use weave.inline on SWIG2 wrapped", "swig -c++ -python -I. -o swig2_ext_wrap.cxx swig2_ext.i $ g++ -Wall", "you need to do something like this:: $ swig -c++", "that weave's SWIG2 support works fine whether SWIG_COBJECT_TYPES are used", "the # swig2 converter to the default list of converters.", "-L/usr/lib/python2.3/config The files swig2_ext.i and swig2_ext.h are included in the", "\\ -L/usr/lib/python2.3/config The files swig2_ext.i and swig2_ext.h are included in", "import scipy.weave as weave from scipy.weave import swig2_spec, converters #", "the trivial SWIG2 extension called swig2_ext. To do this you", "1 # Prevent memory leaks. code = \"\"\"a->f(); b->f(); \"\"\"", "swig2_ext. To do this you need to do something like", "# This will be an APtr instance. b.thisown = 1", "the default list of converters. converters.default.insert(0, swig2_spec.swig2_converter()) def test(): \"\"\"Instantiate", "-fPIC -I. -c \\ -o swig2_ext_wrap.os swig2_ext_wrap.cxx $ g++ -shared", "the same directory that contains this file. Note that weave's", "converter to the default list of converters. converters.default.insert(0, swig2_spec.swig2_converter()) def", "something like this:: $ swig -c++ -python -I. -o swig2_ext_wrap.cxx", "object and then call its method from C++ using weave.inline", "this file. Note that weave's SWIG2 support works fine whether", "$ g++ -shared -o _swig2_ext.so swig2_ext_wrap.os \\ -L/usr/lib/python2.3/config The files", "$ swig -c++ -python -I. -o swig2_ext_wrap.cxx swig2_ext.i $ g++", "to show how to use weave.inline on SWIG2 wrapped objects.", "not. Author: <NAME> Copyright (c) 2004, <NAME> License: BSD Style.", "a = swig2_ext.A() b = swig2_ext.foo() # This will be", "This will be an APtr instance. b.thisown = 1 #", "SWIG2 wrapped objects. SWIG2 refers to SWIG versions >= 1.3.", "swig2_ext_wrap.os swig2_ext_wrap.cxx $ g++ -shared -o _swig2_ext.so swig2_ext_wrap.os \\ -L/usr/lib/python2.3/config", "SWIG2 refers to SWIG versions >= 1.3. To run this", "how to use weave.inline on SWIG2 wrapped objects. SWIG2 refers", "in the same directory that contains this file. Note that", "an APtr instance. b.thisown = 1 # Prevent memory leaks.", "the SWIG wrapped object and then call its method from", "['a', 'b'], include_dirs=['.'], headers=['\"swig2_ext.h\"'], verbose=1) if __name__ == \"__main__\": test()", "Note that weave's SWIG2 support works fine whether SWIG_COBJECT_TYPES are", "import swig2_spec, converters # SWIG2 support is not enabled by", "import swig2_ext import scipy.weave as weave from scipy.weave import swig2_spec,", ">= 1.3. To run this example you must build the", "build the trivial SWIG2 extension called swig2_ext. To do this", "-shared -o _swig2_ext.so swig2_ext_wrap.os \\ -L/usr/lib/python2.3/config The files swig2_ext.i and", "swig2_ext import scipy.weave as weave from scipy.weave import swig2_spec, converters", "swig2_ext.foo() # This will be an APtr instance. b.thisown =", "you must build the trivial SWIG2 extension called swig2_ext. To", "SWIG wrapped object and then call its method from C++", "swig2 converter to the default list of converters. converters.default.insert(0, swig2_spec.swig2_converter())", "weave.inline on SWIG2 wrapped objects. SWIG2 refers to SWIG versions", "<reponame>lesserwhirls/scipy-cwt<filename>scipy/weave/examples/swig2_example.py \"\"\"Simple example to show how to use weave.inline on", "whether SWIG_COBJECT_TYPES are used or not. Author: <NAME> Copyright (c)", "as weave from scipy.weave import swig2_spec, converters # SWIG2 support", "is not enabled by default. We do this by adding", "swig2_spec.swig2_converter()) def test(): \"\"\"Instantiate the SWIG wrapped object and then", "\"\"\" weave.inline(code, ['a', 'b'], include_dirs=['.'], headers=['\"swig2_ext.h\"'], verbose=1) if __name__ ==", "\"\"\" # Import our SWIG2 wrapped library import swig2_ext import", "memory leaks. code = \"\"\"a->f(); b->f(); \"\"\" weave.inline(code, ['a', 'b'],", "-c++ -python -I. -o swig2_ext_wrap.cxx swig2_ext.i $ g++ -Wall -O2", "<NAME> License: BSD Style. \"\"\" # Import our SWIG2 wrapped", "-c \\ -o swig2_ext_wrap.os swig2_ext_wrap.cxx $ g++ -shared -o _swig2_ext.so", "to the default list of converters. converters.default.insert(0, swig2_spec.swig2_converter()) def test():", "not enabled by default. We do this by adding the", "We do this by adding the # swig2 converter to", "swig2_ext_wrap.cxx $ g++ -shared -o _swig2_ext.so swig2_ext_wrap.os \\ -L/usr/lib/python2.3/config The", "# swig2 converter to the default list of converters. converters.default.insert(0,", "SWIG2 support is not enabled by default. We do this", "scipy.weave as weave from scipy.weave import swig2_spec, converters # SWIG2", "default list of converters. converters.default.insert(0, swig2_spec.swig2_converter()) def test(): \"\"\"Instantiate the", "-o swig2_ext_wrap.os swig2_ext_wrap.cxx $ g++ -shared -o _swig2_ext.so swig2_ext_wrap.os \\" ]
[ "== ['E']: return ['Exp'] + args[1] if p < 0:", "if isinstance(s, WLSymbol): if s.name == 'E': return 'E' else:", "res1 else: return res + e else: if len(args) ==", "else: f = str(exp.head) args = list(map(parse, exp.args)) res =", "+ args[1] if p < 0: res = [\"Inv\"] p", "else: return s.name[7:] def parse(exp): symbol = parseGlobalSymbol(exp) if symbol:", ":= 1/zzz\") f = wlexpr(str(Func(exp))) getfreeVars = wlexpr(\"Reduce`FreeVariables\") freeVariables =", "parse(exp): symbol = parseGlobalSymbol(exp) if symbol: return [symbol] else: f", "elif len(args) >= 2: res = [f] + args[0] +", "return res if __name__ == \"__main__\": exp = sys.argv[1:] if", "+ args[1] args = args[2:] for arg in args: res", "args = list(map(parse, exp.args)) res = [] if (f ==", "+ e return res + res1 else: return res +", "== 'E': return 'E' else: return s.name[7:] def parse(exp): symbol", "arg return res def simplify(exp): with WolframLanguageSession() as session: session.evaluate(\"Inv[zzz_]", "res if __name__ == \"__main__\": exp = sys.argv[1:] if exp", "import * def parseGlobalSymbol(s): if isinstance(s, numbers.Number): return s if", "+ res1 else: return res + e else: if len(args)", "res def simplify(exp): with WolframLanguageSession() as session: session.evaluate(\"Inv[zzz_] := 1/zzz\")", "[\"Times\"] + e + e while p > 0: p", "isinstance(s, numbers.Number): return s if isinstance(s, WLSymbol): if s.name ==", ">= 2: res = [f] + args[0] + args[1] args", "\"Power\"): res1 = [] p = args[1][0] e = args[0]", "__name__ == \"__main__\": exp = sys.argv[1:] if exp == []:", "= [\"Times\"] + res1 + e return res + res1", "return ['Exp'] + args[1] if p < 0: res =", "numbers.Number): return s if isinstance(s, WLSymbol): if s.name == 'E':", "s if isinstance(s, WLSymbol): if s.name == 'E': return 'E'", "= wlexpr(str(Func(exp))) getfreeVars = wlexpr(\"Reduce`FreeVariables\") freeVariables = session.evaluate(getfreeVars(f)) ass =", "isinstance(s, WLSymbol): if s.name == 'E': return 'E' else: return", "if s.name == 'E': return 'E' else: return s.name[7:] def", "= [] p = args[1][0] e = args[0] if e", "- 1 res1 = [\"Times\"] + res1 + e return", "= [\"Times\"] + e + e while p > 0:", "p < 0: res = [\"Inv\"] p = -p if", "if len(args) == 1: return [f] + args[0] elif len(args)", "args[1] args = args[2:] for arg in args: res =", "sys.argv[1:] if exp == []: exp = [\"Sin\", \"x\"] res", "session: session.evaluate(\"Inv[zzz_] := 1/zzz\") f = wlexpr(str(Func(exp))) getfreeVars = wlexpr(\"Reduce`FreeVariables\")", "list(map(parse, exp.args)) res = [] if (f == \"Power\"): res1", "+ args[0] elif len(args) >= 2: res = [f] +", "with WolframLanguageSession() as session: session.evaluate(\"Inv[zzz_] := 1/zzz\") f = wlexpr(str(Func(exp)))", "= parse(wmres) return res if __name__ == \"__main__\": exp =", "as session: session.evaluate(\"Inv[zzz_] := 1/zzz\") f = wlexpr(str(Func(exp))) getfreeVars =", "for arg in args: res = [f] + res +", "> 0: p = p - 1 res1 = [\"Times\"]", "print(wmres) res = parse(wmres) return res if __name__ == \"__main__\":", "= [] if (f == \"Power\"): res1 = [] p", ">= 2: p = p - 2 res1 = [\"Times\"]", "= wlexpr(\"Reduce`FreeVariables\") freeVariables = session.evaluate(getfreeVars(f)) ass = wl.Element(wl.Alternatives(freeVariables), wl.Reals) wmres", "[f] + args[0] + args[1] args = args[2:] for arg", "1/zzz\") f = wlexpr(str(Func(exp))) getfreeVars = wlexpr(\"Reduce`FreeVariables\") freeVariables = session.evaluate(getfreeVars(f))", "wl.Element(wl.Alternatives(freeVariables), wl.Reals) wmres = session.evaluate(wl.FullSimplify(f,ass)) print(wmres) res = parse(wmres) return", "from wolframclient.language.expression import WLSymbol from nnDiff import * def parseGlobalSymbol(s):", "if p >= 2: p = p - 2 res1", "WLSymbol from nnDiff import * def parseGlobalSymbol(s): if isinstance(s, numbers.Number):", "simplify(exp): with WolframLanguageSession() as session: session.evaluate(\"Inv[zzz_] := 1/zzz\") f =", "2: res = [f] + args[0] + args[1] args =", "WLSymbol): if s.name == 'E': return 'E' else: return s.name[7:]", "exp = sys.argv[1:] if exp == []: exp = [\"Sin\",", "< 0: res = [\"Inv\"] p = -p if p", "p = args[1][0] e = args[0] if e == ['E']:", "p - 2 res1 = [\"Times\"] + e + e", "e = args[0] if e == ['E']: return ['Exp'] +", "p = p - 2 res1 = [\"Times\"] + e", "= p - 1 res1 = [\"Times\"] + res1 +", "* def parseGlobalSymbol(s): if isinstance(s, numbers.Number): return s if isinstance(s,", "return [symbol] else: f = str(exp.head) args = list(map(parse, exp.args))", "wl.Reals) wmres = session.evaluate(wl.FullSimplify(f,ass)) print(wmres) res = parse(wmres) return res", "if exp == []: exp = [\"Sin\", \"x\"] res =", "session.evaluate(\"Inv[zzz_] := 1/zzz\") f = wlexpr(str(Func(exp))) getfreeVars = wlexpr(\"Reduce`FreeVariables\") freeVariables", "exp.args)) res = [] if (f == \"Power\"): res1 =", "return s if isinstance(s, WLSymbol): if s.name == 'E': return", "args[0] + args[1] args = args[2:] for arg in args:", "[]: exp = [\"Sin\", \"x\"] res = map(str,simplify(exp)) print(' '.join(res),", "<filename>src/simplify.py from wolframclient.language.expression import WLSymbol from nnDiff import * def", "s.name == 'E': return 'E' else: return s.name[7:] def parse(exp):", "p - 1 res1 = [\"Times\"] + res1 + e", "if e == ['E']: return ['Exp'] + args[1] if p", "return s.name[7:] def parse(exp): symbol = parseGlobalSymbol(exp) if symbol: return", "return res + res1 else: return res + e else:", "= args[0] if e == ['E']: return ['Exp'] + args[1]", "args[0] if e == ['E']: return ['Exp'] + args[1] if", "wmres = session.evaluate(wl.FullSimplify(f,ass)) print(wmres) res = parse(wmres) return res if", "return 'E' else: return s.name[7:] def parse(exp): symbol = parseGlobalSymbol(exp)", "+ e else: if len(args) == 1: return [f] +", "res = [\"Inv\"] p = -p if p >= 2:", "res1 = [\"Times\"] + res1 + e return res +", "= args[1][0] e = args[0] if e == ['E']: return", "session.evaluate(getfreeVars(f)) ass = wl.Element(wl.Alternatives(freeVariables), wl.Reals) wmres = session.evaluate(wl.FullSimplify(f,ass)) print(wmres) res", "[f] + args[0] elif len(args) >= 2: res = [f]", "== \"Power\"): res1 = [] p = args[1][0] e =", "in args: res = [f] + res + arg return", "if symbol: return [symbol] else: f = str(exp.head) args =", "+ e while p > 0: p = p -", "res + res1 else: return res + e else: if", "def parse(exp): symbol = parseGlobalSymbol(exp) if symbol: return [symbol] else:", "1 res1 = [\"Times\"] + res1 + e return res", "1: return [f] + args[0] elif len(args) >= 2: res", "res = parse(wmres) return res if __name__ == \"__main__\": exp", "res1 + e return res + res1 else: return res", "parseGlobalSymbol(exp) if symbol: return [symbol] else: f = str(exp.head) args", "args = args[2:] for arg in args: res = [f]", "== 1: return [f] + args[0] elif len(args) >= 2:", "symbol = parseGlobalSymbol(exp) if symbol: return [symbol] else: f =", "p = -p if p >= 2: p = p", "res = [f] + args[0] + args[1] args = args[2:]", "parseGlobalSymbol(s): if isinstance(s, numbers.Number): return s if isinstance(s, WLSymbol): if", "= session.evaluate(getfreeVars(f)) ass = wl.Element(wl.Alternatives(freeVariables), wl.Reals) wmres = session.evaluate(wl.FullSimplify(f,ass)) print(wmres)", "session.evaluate(wl.FullSimplify(f,ass)) print(wmres) res = parse(wmres) return res if __name__ ==", "['E']: return ['Exp'] + args[1] if p < 0: res", "2: p = p - 2 res1 = [\"Times\"] +", "nnDiff import * def parseGlobalSymbol(s): if isinstance(s, numbers.Number): return s", "getfreeVars = wlexpr(\"Reduce`FreeVariables\") freeVariables = session.evaluate(getfreeVars(f)) ass = wl.Element(wl.Alternatives(freeVariables), wl.Reals)", "+ args[0] + args[1] args = args[2:] for arg in", "wolframclient.language.expression import WLSymbol from nnDiff import * def parseGlobalSymbol(s): if", "arg in args: res = [f] + res + arg", "e == ['E']: return ['Exp'] + args[1] if p <", "+ arg return res def simplify(exp): with WolframLanguageSession() as session:", "p >= 2: p = p - 2 res1 =", "- 2 res1 = [\"Times\"] + e + e while", "import WLSymbol from nnDiff import * def parseGlobalSymbol(s): if isinstance(s,", "= p - 2 res1 = [\"Times\"] + e +", "else: return res + e else: if len(args) == 1:", "args[0] elif len(args) >= 2: res = [f] + args[0]", "= [f] + res + arg return res def simplify(exp):", "res + arg return res def simplify(exp): with WolframLanguageSession() as", "exp = [\"Sin\", \"x\"] res = map(str,simplify(exp)) print(' '.join(res), file=sys.stderr)", "2 res1 = [\"Times\"] + e + e while p", "res1 = [] p = args[1][0] e = args[0] if", "if isinstance(s, numbers.Number): return s if isinstance(s, WLSymbol): if s.name", "freeVariables = session.evaluate(getfreeVars(f)) ass = wl.Element(wl.Alternatives(freeVariables), wl.Reals) wmres = session.evaluate(wl.FullSimplify(f,ass))", "= [f] + args[0] + args[1] args = args[2:] for", "[symbol] else: f = str(exp.head) args = list(map(parse, exp.args)) res", "res = [] if (f == \"Power\"): res1 = []", "[] if (f == \"Power\"): res1 = [] p =", "[\"Times\"] + res1 + e return res + res1 else:", "== \"__main__\": exp = sys.argv[1:] if exp == []: exp", "def parseGlobalSymbol(s): if isinstance(s, numbers.Number): return s if isinstance(s, WLSymbol):", "if (f == \"Power\"): res1 = [] p = args[1][0]", "def simplify(exp): with WolframLanguageSession() as session: session.evaluate(\"Inv[zzz_] := 1/zzz\") f", "== []: exp = [\"Sin\", \"x\"] res = map(str,simplify(exp)) print('", "0: res = [\"Inv\"] p = -p if p >=", "args[2:] for arg in args: res = [f] + res", "= sys.argv[1:] if exp == []: exp = [\"Sin\", \"x\"]", "= session.evaluate(wl.FullSimplify(f,ass)) print(wmres) res = parse(wmres) return res if __name__", "= list(map(parse, exp.args)) res = [] if (f == \"Power\"):", "= args[2:] for arg in args: res = [f] +", "\"__main__\": exp = sys.argv[1:] if exp == []: exp =", "return res def simplify(exp): with WolframLanguageSession() as session: session.evaluate(\"Inv[zzz_] :=", "str(exp.head) args = list(map(parse, exp.args)) res = [] if (f", "exp == []: exp = [\"Sin\", \"x\"] res = map(str,simplify(exp))", "if p < 0: res = [\"Inv\"] p = -p", "from nnDiff import * def parseGlobalSymbol(s): if isinstance(s, numbers.Number): return", "symbol: return [symbol] else: f = str(exp.head) args = list(map(parse,", "+ res1 + e return res + res1 else: return", "else: if len(args) == 1: return [f] + args[0] elif", "WolframLanguageSession() as session: session.evaluate(\"Inv[zzz_] := 1/zzz\") f = wlexpr(str(Func(exp))) getfreeVars", "wlexpr(str(Func(exp))) getfreeVars = wlexpr(\"Reduce`FreeVariables\") freeVariables = session.evaluate(getfreeVars(f)) ass = wl.Element(wl.Alternatives(freeVariables),", "[f] + res + arg return res def simplify(exp): with", "= [\"Inv\"] p = -p if p >= 2: p", "(f == \"Power\"): res1 = [] p = args[1][0] e", "+ e + e while p > 0: p =", "e + e while p > 0: p = p", "while p > 0: p = p - 1 res1", "= -p if p >= 2: p = p -", "res = [f] + res + arg return res def", "'E' else: return s.name[7:] def parse(exp): symbol = parseGlobalSymbol(exp) if", "if __name__ == \"__main__\": exp = sys.argv[1:] if exp ==", "e while p > 0: p = p - 1", "wlexpr(\"Reduce`FreeVariables\") freeVariables = session.evaluate(getfreeVars(f)) ass = wl.Element(wl.Alternatives(freeVariables), wl.Reals) wmres =", "parse(wmres) return res if __name__ == \"__main__\": exp = sys.argv[1:]", "e else: if len(args) == 1: return [f] + args[0]", "len(args) == 1: return [f] + args[0] elif len(args) >=", "res1 = [\"Times\"] + e + e while p >", "res + e else: if len(args) == 1: return [f]", "f = wlexpr(str(Func(exp))) getfreeVars = wlexpr(\"Reduce`FreeVariables\") freeVariables = session.evaluate(getfreeVars(f)) ass", "= wl.Element(wl.Alternatives(freeVariables), wl.Reals) wmres = session.evaluate(wl.FullSimplify(f,ass)) print(wmres) res = parse(wmres)", "len(args) >= 2: res = [f] + args[0] + args[1]", "f = str(exp.head) args = list(map(parse, exp.args)) res = []", "+ res + arg return res def simplify(exp): with WolframLanguageSession()", "0: p = p - 1 res1 = [\"Times\"] +", "p > 0: p = p - 1 res1 =", "ass = wl.Element(wl.Alternatives(freeVariables), wl.Reals) wmres = session.evaluate(wl.FullSimplify(f,ass)) print(wmres) res =", "return [f] + args[0] elif len(args) >= 2: res =", "[\"Inv\"] p = -p if p >= 2: p =", "args[1] if p < 0: res = [\"Inv\"] p =", "s.name[7:] def parse(exp): symbol = parseGlobalSymbol(exp) if symbol: return [symbol]", "['Exp'] + args[1] if p < 0: res = [\"Inv\"]", "-p if p >= 2: p = p - 2", "return res + e else: if len(args) == 1: return", "p = p - 1 res1 = [\"Times\"] + res1", "= str(exp.head) args = list(map(parse, exp.args)) res = [] if", "'E': return 'E' else: return s.name[7:] def parse(exp): symbol =", "[] p = args[1][0] e = args[0] if e ==", "args: res = [f] + res + arg return res", "= parseGlobalSymbol(exp) if symbol: return [symbol] else: f = str(exp.head)", "args[1][0] e = args[0] if e == ['E']: return ['Exp']", "e return res + res1 else: return res + e" ]
[ "packages=['firetv'], install_requires=['pycryptodome', 'rsa', 'adb-homeassistant', 'pure-python-adb-homeassistant'], extras_require={ 'firetv-server': ['Flask>=0.10.1', 'PyYAML>=3.12'] },", "[ 'firetv-server = firetv.__main__:main' ] }, classifiers=[ 'License :: OSI", "an Amazon Fire TV device via ADB over a network.',", "network.', url='https://github.com/happyleavesaoc/python-firetv/', license='MIT', author='happyleaves', author_email='<EMAIL>', packages=['firetv'], install_requires=['pycryptodome', 'rsa', 'adb-homeassistant', 'pure-python-adb-homeassistant'],", "MIT License', 'Operating System :: OS Independent', 'Programming Language ::", "= firetv.__main__:main' ] }, classifiers=[ 'License :: OSI Approved ::", "License', 'Operating System :: OS Independent', 'Programming Language :: Python", "Fire TV device via ADB over a network.', url='https://github.com/happyleavesaoc/python-firetv/', license='MIT',", "'License :: OSI Approved :: MIT License', 'Operating System ::", "'Programming Language :: Python :: 2', 'Programming Language :: Python", "TV device via ADB over a network.', url='https://github.com/happyleavesaoc/python-firetv/', license='MIT', author='happyleaves',", "url='https://github.com/happyleavesaoc/python-firetv/', license='MIT', author='happyleaves', author_email='<EMAIL>', packages=['firetv'], install_requires=['pycryptodome', 'rsa', 'adb-homeassistant', 'pure-python-adb-homeassistant'], extras_require={", ":: OSI Approved :: MIT License', 'Operating System :: OS", "}, entry_points={ 'console_scripts': [ 'firetv-server = firetv.__main__:main' ] }, classifiers=[", ":: 2', 'Programming Language :: Python :: 3' ] )", "}, classifiers=[ 'License :: OSI Approved :: MIT License', 'Operating", "Python :: 2', 'Programming Language :: Python :: 3' ]", "author_email='<EMAIL>', packages=['firetv'], install_requires=['pycryptodome', 'rsa', 'adb-homeassistant', 'pure-python-adb-homeassistant'], extras_require={ 'firetv-server': ['Flask>=0.10.1', 'PyYAML>=3.12']", "firetv.__main__:main' ] }, classifiers=[ 'License :: OSI Approved :: MIT", "'pure-python-adb-homeassistant'], extras_require={ 'firetv-server': ['Flask>=0.10.1', 'PyYAML>=3.12'] }, entry_points={ 'console_scripts': [ 'firetv-server", "'console_scripts': [ 'firetv-server = firetv.__main__:main' ] }, classifiers=[ 'License ::", "setup( name='firetv', version='1.0.7', description='Communicate with an Amazon Fire TV device", "via ADB over a network.', url='https://github.com/happyleavesaoc/python-firetv/', license='MIT', author='happyleaves', author_email='<EMAIL>', packages=['firetv'],", "setuptools import setup setup( name='firetv', version='1.0.7', description='Communicate with an Amazon", "entry_points={ 'console_scripts': [ 'firetv-server = firetv.__main__:main' ] }, classifiers=[ 'License", "'rsa', 'adb-homeassistant', 'pure-python-adb-homeassistant'], extras_require={ 'firetv-server': ['Flask>=0.10.1', 'PyYAML>=3.12'] }, entry_points={ 'console_scripts':", ":: MIT License', 'Operating System :: OS Independent', 'Programming Language", "'adb-homeassistant', 'pure-python-adb-homeassistant'], extras_require={ 'firetv-server': ['Flask>=0.10.1', 'PyYAML>=3.12'] }, entry_points={ 'console_scripts': [", "license='MIT', author='happyleaves', author_email='<EMAIL>', packages=['firetv'], install_requires=['pycryptodome', 'rsa', 'adb-homeassistant', 'pure-python-adb-homeassistant'], extras_require={ 'firetv-server':", "from setuptools import setup setup( name='firetv', version='1.0.7', description='Communicate with an", ":: Python :: 2', 'Programming Language :: Python :: 3'", "import setup setup( name='firetv', version='1.0.7', description='Communicate with an Amazon Fire", "a network.', url='https://github.com/happyleavesaoc/python-firetv/', license='MIT', author='happyleaves', author_email='<EMAIL>', packages=['firetv'], install_requires=['pycryptodome', 'rsa', 'adb-homeassistant',", "over a network.', url='https://github.com/happyleavesaoc/python-firetv/', license='MIT', author='happyleaves', author_email='<EMAIL>', packages=['firetv'], install_requires=['pycryptodome', 'rsa',", "description='Communicate with an Amazon Fire TV device via ADB over", "OSI Approved :: MIT License', 'Operating System :: OS Independent',", "] }, classifiers=[ 'License :: OSI Approved :: MIT License',", "version='1.0.7', description='Communicate with an Amazon Fire TV device via ADB", "Approved :: MIT License', 'Operating System :: OS Independent', 'Programming", "OS Independent', 'Programming Language :: Python :: 2', 'Programming Language", "'firetv-server': ['Flask>=0.10.1', 'PyYAML>=3.12'] }, entry_points={ 'console_scripts': [ 'firetv-server = firetv.__main__:main'", "extras_require={ 'firetv-server': ['Flask>=0.10.1', 'PyYAML>=3.12'] }, entry_points={ 'console_scripts': [ 'firetv-server =", "Independent', 'Programming Language :: Python :: 2', 'Programming Language ::", "Amazon Fire TV device via ADB over a network.', url='https://github.com/happyleavesaoc/python-firetv/',", "install_requires=['pycryptodome', 'rsa', 'adb-homeassistant', 'pure-python-adb-homeassistant'], extras_require={ 'firetv-server': ['Flask>=0.10.1', 'PyYAML>=3.12'] }, entry_points={", "with an Amazon Fire TV device via ADB over a", "'firetv-server = firetv.__main__:main' ] }, classifiers=[ 'License :: OSI Approved", "'Operating System :: OS Independent', 'Programming Language :: Python ::", "setup setup( name='firetv', version='1.0.7', description='Communicate with an Amazon Fire TV", "author='happyleaves', author_email='<EMAIL>', packages=['firetv'], install_requires=['pycryptodome', 'rsa', 'adb-homeassistant', 'pure-python-adb-homeassistant'], extras_require={ 'firetv-server': ['Flask>=0.10.1',", "classifiers=[ 'License :: OSI Approved :: MIT License', 'Operating System", "System :: OS Independent', 'Programming Language :: Python :: 2',", "'PyYAML>=3.12'] }, entry_points={ 'console_scripts': [ 'firetv-server = firetv.__main__:main' ] },", "device via ADB over a network.', url='https://github.com/happyleavesaoc/python-firetv/', license='MIT', author='happyleaves', author_email='<EMAIL>',", "Language :: Python :: 2', 'Programming Language :: Python ::", "name='firetv', version='1.0.7', description='Communicate with an Amazon Fire TV device via", ":: OS Independent', 'Programming Language :: Python :: 2', 'Programming", "['Flask>=0.10.1', 'PyYAML>=3.12'] }, entry_points={ 'console_scripts': [ 'firetv-server = firetv.__main__:main' ]", "ADB over a network.', url='https://github.com/happyleavesaoc/python-firetv/', license='MIT', author='happyleaves', author_email='<EMAIL>', packages=['firetv'], install_requires=['pycryptodome'," ]
[ "= \"Fake IO\" # This is an inportant choice when", "# 'split-all' : 1 AnalogSignal each 1 channel # 'group-by-same-units'", "following code. Author: sgarcia \"\"\" from neo.io.basefromrawio import BaseFromRaw from", "data as they are in files. Developper are encourage to", ": one 2D AnalogSignal for each group of channel with", "'group-by-same-units' : one 2D AnalogSignal for each group of channel", "neo.rawio.examplerawio import ExampleRawIO class ExampleIO(ExampleRawIO, BaseFromRaw): name = 'example IO'", "API give neo object * neo.rawio: this API give raw", "Author: sgarcia \"\"\" from neo.io.basefromrawio import BaseFromRaw from neo.rawio.examplerawio import", "= 'example IO' description = \"Fake IO\" # This is", "AnalogSignal for each group of channel with same units _prefered_signal_group_mode", "neo.io: this API give neo object * neo.rawio: this API", "neo object * neo.rawio: this API give raw data as", "This is an inportant choice when there are several channels.", "class ExampleIO(ExampleRawIO, BaseFromRaw): name = 'example IO' description = \"Fake", "neo.rawio: this API give raw data as they are in", "ExampleRawIO class ExampleIO(ExampleRawIO, BaseFromRaw): name = 'example IO' description =", "this API give neo object * neo.rawio: this API give", "as they are in files. Developper are encourage to use", "is done the neo.io is done automagically with this king", "\"Fake IO\" # This is an inportant choice when there", "an inportant choice when there are several channels. # 'split-all'", "files. Developper are encourage to use neo.rawio. When this is", "level API: * neo.io: this API give neo object *", "each group of channel with same units _prefered_signal_group_mode = 'group-by-same-units'", "inportant choice when there are several channels. # 'split-all' :", "each 1 channel # 'group-by-same-units' : one 2D AnalogSignal for", "is an inportant choice when there are several channels. #", "2 level API: * neo.io: this API give neo object", "units _prefered_signal_group_mode = 'group-by-same-units' def __init__(self, filename=''): ExampleRawIO.__init__(self, filename=filename) BaseFromRaw.__init__(self,", "API give raw data as they are in files. Developper", "raw data as they are in files. Developper are encourage", "are encourage to use neo.rawio. When this is done the", "there are several channels. # 'split-all' : 1 AnalogSignal each", "IO' description = \"Fake IO\" # This is an inportant", "1 channel # 'group-by-same-units' : one 2D AnalogSignal for each", "* neo.rawio: this API give raw data as they are", ": 1 AnalogSignal each 1 channel # 'group-by-same-units' : one", "# 'group-by-same-units' : one 2D AnalogSignal for each group of", "ExampleIO(ExampleRawIO, BaseFromRaw): name = 'example IO' description = \"Fake IO\"", "sgarcia \"\"\" from neo.io.basefromrawio import BaseFromRaw from neo.rawio.examplerawio import ExampleRawIO", "channel with same units _prefered_signal_group_mode = 'group-by-same-units' def __init__(self, filename=''):", "channel # 'group-by-same-units' : one 2D AnalogSignal for each group", "with this king of following code. Author: sgarcia \"\"\" from", "have been split in 2 level API: * neo.io: this", "to use neo.rawio. When this is done the neo.io is", "give neo object * neo.rawio: this API give raw data", "of channel with same units _prefered_signal_group_mode = 'group-by-same-units' def __init__(self,", "'split-all' : 1 AnalogSignal each 1 channel # 'group-by-same-units' :", "of following code. Author: sgarcia \"\"\" from neo.io.basefromrawio import BaseFromRaw", "give raw data as they are in files. Developper are", "been split in 2 level API: * neo.io: this API", "with same units _prefered_signal_group_mode = 'group-by-same-units' def __init__(self, filename=''): ExampleRawIO.__init__(self,", "* neo.io: this API give neo object * neo.rawio: this", "the neo.io is done automagically with this king of following", "in 2 level API: * neo.io: this API give neo", "done automagically with this king of following code. Author: sgarcia", "When this is done the neo.io is done automagically with", "split in 2 level API: * neo.io: this API give", "# This is an inportant choice when there are several", "channels. # 'split-all' : 1 AnalogSignal each 1 channel #", "from neo.io.basefromrawio import BaseFromRaw from neo.rawio.examplerawio import ExampleRawIO class ExampleIO(ExampleRawIO,", "import ExampleRawIO class ExampleIO(ExampleRawIO, BaseFromRaw): name = 'example IO' description", "this king of following code. Author: sgarcia \"\"\" from neo.io.basefromrawio", "encourage to use neo.rawio. When this is done the neo.io", "name = 'example IO' description = \"Fake IO\" # This", "from neo.rawio.examplerawio import ExampleRawIO class ExampleIO(ExampleRawIO, BaseFromRaw): name = 'example", "this API give raw data as they are in files.", "they are in files. Developper are encourage to use neo.rawio.", "API: * neo.io: this API give neo object * neo.rawio:", "in files. Developper are encourage to use neo.rawio. When this", "'example IO' description = \"Fake IO\" # This is an", "group of channel with same units _prefered_signal_group_mode = 'group-by-same-units' def", "choice when there are several channels. # 'split-all' : 1", "<gh_stars>100-1000 \"\"\" neo.io have been split in 2 level API:", "neo.io.basefromrawio import BaseFromRaw from neo.rawio.examplerawio import ExampleRawIO class ExampleIO(ExampleRawIO, BaseFromRaw):", "BaseFromRaw from neo.rawio.examplerawio import ExampleRawIO class ExampleIO(ExampleRawIO, BaseFromRaw): name =", "IO\" # This is an inportant choice when there are", "\"\"\" from neo.io.basefromrawio import BaseFromRaw from neo.rawio.examplerawio import ExampleRawIO class", "one 2D AnalogSignal for each group of channel with same", "are in files. Developper are encourage to use neo.rawio. When", "1 AnalogSignal each 1 channel # 'group-by-same-units' : one 2D", "neo.io have been split in 2 level API: * neo.io:", "use neo.rawio. When this is done the neo.io is done", "_prefered_signal_group_mode = 'group-by-same-units' def __init__(self, filename=''): ExampleRawIO.__init__(self, filename=filename) BaseFromRaw.__init__(self, filename)", "this is done the neo.io is done automagically with this", "king of following code. Author: sgarcia \"\"\" from neo.io.basefromrawio import", "neo.io is done automagically with this king of following code.", "done the neo.io is done automagically with this king of", "for each group of channel with same units _prefered_signal_group_mode =", "when there are several channels. # 'split-all' : 1 AnalogSignal", "several channels. # 'split-all' : 1 AnalogSignal each 1 channel", "are several channels. # 'split-all' : 1 AnalogSignal each 1", "automagically with this king of following code. Author: sgarcia \"\"\"", "Developper are encourage to use neo.rawio. When this is done", "2D AnalogSignal for each group of channel with same units", "is done automagically with this king of following code. Author:", "same units _prefered_signal_group_mode = 'group-by-same-units' def __init__(self, filename=''): ExampleRawIO.__init__(self, filename=filename)", "\"\"\" neo.io have been split in 2 level API: *", "object * neo.rawio: this API give raw data as they", "code. Author: sgarcia \"\"\" from neo.io.basefromrawio import BaseFromRaw from neo.rawio.examplerawio", "import BaseFromRaw from neo.rawio.examplerawio import ExampleRawIO class ExampleIO(ExampleRawIO, BaseFromRaw): name", "neo.rawio. When this is done the neo.io is done automagically", "BaseFromRaw): name = 'example IO' description = \"Fake IO\" #", "description = \"Fake IO\" # This is an inportant choice", "AnalogSignal each 1 channel # 'group-by-same-units' : one 2D AnalogSignal" ]
[ "django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('scrapyproject',", "model_name='project', name='scraper_function', field=models.TextField(blank=True), ), migrations.AlterField( model_name='project', name='settings', field=models.TextField(blank=True), ), ]", "operations = [ migrations.AlterField( model_name='project', name='link_generator', field=models.TextField(blank=True), ), migrations.AlterField( model_name='project',", "'0002_auto_20170208_1738'), ] operations = [ migrations.AlterField( model_name='project', name='link_generator', field=models.TextField(blank=True), ),", "utf-8 -*- from __future__ import unicode_literals from django.db import migrations,", "-*- from __future__ import unicode_literals from django.db import migrations, models", "migrations.AlterField( model_name='project', name='scraper_function', field=models.TextField(blank=True), ), migrations.AlterField( model_name='project', name='settings', field=models.TextField(blank=True), ),", "name='link_generator', field=models.TextField(blank=True), ), migrations.AlterField( model_name='project', name='scraper_function', field=models.TextField(blank=True), ), migrations.AlterField( model_name='project',", "migrations, models class Migration(migrations.Migration): dependencies = [ ('scrapyproject', '0002_auto_20170208_1738'), ]", "] operations = [ migrations.AlterField( model_name='project', name='link_generator', field=models.TextField(blank=True), ), migrations.AlterField(", "= [ migrations.AlterField( model_name='project', name='link_generator', field=models.TextField(blank=True), ), migrations.AlterField( model_name='project', name='scraper_function',", "model_name='project', name='link_generator', field=models.TextField(blank=True), ), migrations.AlterField( model_name='project', name='scraper_function', field=models.TextField(blank=True), ), migrations.AlterField(", "coding: utf-8 -*- from __future__ import unicode_literals from django.db import", "unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies =", "field=models.TextField(blank=True), ), migrations.AlterField( model_name='project', name='scraper_function', field=models.TextField(blank=True), ), migrations.AlterField( model_name='project', name='settings',", "[ migrations.AlterField( model_name='project', name='link_generator', field=models.TextField(blank=True), ), migrations.AlterField( model_name='project', name='scraper_function', field=models.TextField(blank=True),", "migrations.AlterField( model_name='project', name='link_generator', field=models.TextField(blank=True), ), migrations.AlterField( model_name='project', name='scraper_function', field=models.TextField(blank=True), ),", "= [ ('scrapyproject', '0002_auto_20170208_1738'), ] operations = [ migrations.AlterField( model_name='project',", "# -*- coding: utf-8 -*- from __future__ import unicode_literals from", "dependencies = [ ('scrapyproject', '0002_auto_20170208_1738'), ] operations = [ migrations.AlterField(", "from django.db import migrations, models class Migration(migrations.Migration): dependencies = [", "('scrapyproject', '0002_auto_20170208_1738'), ] operations = [ migrations.AlterField( model_name='project', name='link_generator', field=models.TextField(blank=True),", "), migrations.AlterField( model_name='project', name='scraper_function', field=models.TextField(blank=True), ), migrations.AlterField( model_name='project', name='settings', field=models.TextField(blank=True),", "-*- coding: utf-8 -*- from __future__ import unicode_literals from django.db", "import migrations, models class Migration(migrations.Migration): dependencies = [ ('scrapyproject', '0002_auto_20170208_1738'),", "import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies", "class Migration(migrations.Migration): dependencies = [ ('scrapyproject', '0002_auto_20170208_1738'), ] operations =", "__future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration):", "from __future__ import unicode_literals from django.db import migrations, models class", "Migration(migrations.Migration): dependencies = [ ('scrapyproject', '0002_auto_20170208_1738'), ] operations = [", "[ ('scrapyproject', '0002_auto_20170208_1738'), ] operations = [ migrations.AlterField( model_name='project', name='link_generator',", "models class Migration(migrations.Migration): dependencies = [ ('scrapyproject', '0002_auto_20170208_1738'), ] operations" ]
[ "= [(i, str(i)) for i in range(1, 21)] class CartAddCourseForm(forms.Form):", "gettext_lazy as _ COURSE_QUANTITY_CHOICES = [(i, str(i)) for i in", "choices=COURSE_QUANTITY_CHOICES, coerce=int, label=_(\"Quantité\") ) override = forms.BooleanField( required=False, initial=False, widget=forms.HiddenInput", "from django import forms from django.utils.translation import gettext_lazy as _", "range(1, 21)] class CartAddCourseForm(forms.Form): quantity = forms.TypedChoiceField( choices=COURSE_QUANTITY_CHOICES, coerce=int, label=_(\"Quantité\")", "coerce=int, label=_(\"Quantité\") ) override = forms.BooleanField( required=False, initial=False, widget=forms.HiddenInput )", "django import forms from django.utils.translation import gettext_lazy as _ COURSE_QUANTITY_CHOICES", "in range(1, 21)] class CartAddCourseForm(forms.Form): quantity = forms.TypedChoiceField( choices=COURSE_QUANTITY_CHOICES, coerce=int,", "str(i)) for i in range(1, 21)] class CartAddCourseForm(forms.Form): quantity =", "i in range(1, 21)] class CartAddCourseForm(forms.Form): quantity = forms.TypedChoiceField( choices=COURSE_QUANTITY_CHOICES,", "[(i, str(i)) for i in range(1, 21)] class CartAddCourseForm(forms.Form): quantity", "forms.TypedChoiceField( choices=COURSE_QUANTITY_CHOICES, coerce=int, label=_(\"Quantité\") ) override = forms.BooleanField( required=False, initial=False,", "class CartAddCourseForm(forms.Form): quantity = forms.TypedChoiceField( choices=COURSE_QUANTITY_CHOICES, coerce=int, label=_(\"Quantité\") ) override", "django.utils.translation import gettext_lazy as _ COURSE_QUANTITY_CHOICES = [(i, str(i)) for", "CartAddCourseForm(forms.Form): quantity = forms.TypedChoiceField( choices=COURSE_QUANTITY_CHOICES, coerce=int, label=_(\"Quantité\") ) override =", "for i in range(1, 21)] class CartAddCourseForm(forms.Form): quantity = forms.TypedChoiceField(", "import gettext_lazy as _ COURSE_QUANTITY_CHOICES = [(i, str(i)) for i", "= forms.TypedChoiceField( choices=COURSE_QUANTITY_CHOICES, coerce=int, label=_(\"Quantité\") ) override = forms.BooleanField( required=False,", "21)] class CartAddCourseForm(forms.Form): quantity = forms.TypedChoiceField( choices=COURSE_QUANTITY_CHOICES, coerce=int, label=_(\"Quantité\") )", "as _ COURSE_QUANTITY_CHOICES = [(i, str(i)) for i in range(1,", "from django.utils.translation import gettext_lazy as _ COURSE_QUANTITY_CHOICES = [(i, str(i))", "quantity = forms.TypedChoiceField( choices=COURSE_QUANTITY_CHOICES, coerce=int, label=_(\"Quantité\") ) override = forms.BooleanField(", "forms from django.utils.translation import gettext_lazy as _ COURSE_QUANTITY_CHOICES = [(i,", "import forms from django.utils.translation import gettext_lazy as _ COURSE_QUANTITY_CHOICES =", "_ COURSE_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 21)]", "COURSE_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 21)] class" ]
[ "<reponame>sflippl/patches<gh_stars>0 \"\"\"Datasets of latent predictability tasks. \"\"\" from .pilgrimm import", "\"\"\"Datasets of latent predictability tasks. \"\"\" from .pilgrimm import *" ]
[ "the LICENSE file. import sys import unittest import test_env test_env.setup_test_env()", "license that can be # found in the LICENSE file.", "'\\x00') class DJP(ndb.Model): prop = properties.DeterministicJsonProperty(json_type=dict) class PropertiesTest(test_case.TestCase): def test_DeterministicJsonProperty(self):", "from google.appengine.ext import ndb from components.datastore_utils import properties from support", "test_case class BP(ndb.Model): prop = properties.BytesComputedProperty(lambda _: '\\x00') class DJP(ndb.Model):", "__name__ == '__main__': if '-v' in sys.argv: unittest.TestCase.maxDiff = None", "import test_case class BP(ndb.Model): prop = properties.BytesComputedProperty(lambda _: '\\x00') class", "The Swarming Authors. All rights reserved. # Use of this", "in the LICENSE file. import sys import unittest import test_env", "with self.assertRaises(TypeError): DJP(prop=[]) def test_BytesComputedProperty(self): self.assertEqual('\\x00', BP().prop) BP().put() self.assertEqual('\\x00', BP.query().get().prop)", "BP().prop) BP().put() self.assertEqual('\\x00', BP.query().get().prop) if __name__ == '__main__': if '-v'", "= properties.DeterministicJsonProperty(json_type=dict) class PropertiesTest(test_case.TestCase): def test_DeterministicJsonProperty(self): self.assertEqual({'a': 1}, DJP(prop={'a': 1}).prop)", "test_DeterministicJsonProperty(self): self.assertEqual({'a': 1}, DJP(prop={'a': 1}).prop) DJP(prop={'a': 1}).put() self.assertEqual({'a': 1}, DJP.query().get().prop)", "BP().put() self.assertEqual('\\x00', BP.query().get().prop) if __name__ == '__main__': if '-v' in", "DJP(prop=[]) def test_BytesComputedProperty(self): self.assertEqual('\\x00', BP().prop) BP().put() self.assertEqual('\\x00', BP.query().get().prop) if __name__", "BP(ndb.Model): prop = properties.BytesComputedProperty(lambda _: '\\x00') class DJP(ndb.Model): prop =", "= properties.BytesComputedProperty(lambda _: '\\x00') class DJP(ndb.Model): prop = properties.DeterministicJsonProperty(json_type=dict) class", "found in the LICENSE file. import sys import unittest import", "class DJP(ndb.Model): prop = properties.DeterministicJsonProperty(json_type=dict) class PropertiesTest(test_case.TestCase): def test_DeterministicJsonProperty(self): self.assertEqual({'a':", "reserved. # Use of this source code is governed by", "can be # found in the LICENSE file. import sys", "LICENSE file. import sys import unittest import test_env test_env.setup_test_env() from", "source code is governed by the Apache v2.0 license that", "properties.BytesComputedProperty(lambda _: '\\x00') class DJP(ndb.Model): prop = properties.DeterministicJsonProperty(json_type=dict) class PropertiesTest(test_case.TestCase):", "import sys import unittest import test_env test_env.setup_test_env() from google.appengine.ext import", "test_env test_env.setup_test_env() from google.appengine.ext import ndb from components.datastore_utils import properties", "components.datastore_utils import properties from support import test_case class BP(ndb.Model): prop", "DJP(prop={'a': 1}).put() self.assertEqual({'a': 1}, DJP.query().get().prop) with self.assertRaises(TypeError): DJP(prop=[]) def test_BytesComputedProperty(self):", "DJP(prop={'a': 1}).prop) DJP(prop={'a': 1}).put() self.assertEqual({'a': 1}, DJP.query().get().prop) with self.assertRaises(TypeError): DJP(prop=[])", "# Use of this source code is governed by the", "Use of this source code is governed by the Apache", "the Apache v2.0 license that can be # found in", "that can be # found in the LICENSE file. import", "All rights reserved. # Use of this source code is", "1}, DJP.query().get().prop) with self.assertRaises(TypeError): DJP(prop=[]) def test_BytesComputedProperty(self): self.assertEqual('\\x00', BP().prop) BP().put()", "python # Copyright 2014 The Swarming Authors. All rights reserved.", "of this source code is governed by the Apache v2.0", "self.assertEqual({'a': 1}, DJP(prop={'a': 1}).prop) DJP(prop={'a': 1}).put() self.assertEqual({'a': 1}, DJP.query().get().prop) with", "self.assertEqual('\\x00', BP().prop) BP().put() self.assertEqual('\\x00', BP.query().get().prop) if __name__ == '__main__': if", "self.assertRaises(TypeError): DJP(prop=[]) def test_BytesComputedProperty(self): self.assertEqual('\\x00', BP().prop) BP().put() self.assertEqual('\\x00', BP.query().get().prop) if", "sys import unittest import test_env test_env.setup_test_env() from google.appengine.ext import ndb", "prop = properties.DeterministicJsonProperty(json_type=dict) class PropertiesTest(test_case.TestCase): def test_DeterministicJsonProperty(self): self.assertEqual({'a': 1}, DJP(prop={'a':", "Swarming Authors. All rights reserved. # Use of this source", "2014 The Swarming Authors. All rights reserved. # Use of", "google.appengine.ext import ndb from components.datastore_utils import properties from support import", "is governed by the Apache v2.0 license that can be", "ndb from components.datastore_utils import properties from support import test_case class", "DJP.query().get().prop) with self.assertRaises(TypeError): DJP(prop=[]) def test_BytesComputedProperty(self): self.assertEqual('\\x00', BP().prop) BP().put() self.assertEqual('\\x00',", "if __name__ == '__main__': if '-v' in sys.argv: unittest.TestCase.maxDiff =", "<filename>appengine/components/tests/datastore_utils_properties_test.py #!/usr/bin/env python # Copyright 2014 The Swarming Authors. All", "import properties from support import test_case class BP(ndb.Model): prop =", "class BP(ndb.Model): prop = properties.BytesComputedProperty(lambda _: '\\x00') class DJP(ndb.Model): prop", "import test_env test_env.setup_test_env() from google.appengine.ext import ndb from components.datastore_utils import", "prop = properties.BytesComputedProperty(lambda _: '\\x00') class DJP(ndb.Model): prop = properties.DeterministicJsonProperty(json_type=dict)", "support import test_case class BP(ndb.Model): prop = properties.BytesComputedProperty(lambda _: '\\x00')", "by the Apache v2.0 license that can be # found", "file. import sys import unittest import test_env test_env.setup_test_env() from google.appengine.ext", "def test_DeterministicJsonProperty(self): self.assertEqual({'a': 1}, DJP(prop={'a': 1}).prop) DJP(prop={'a': 1}).put() self.assertEqual({'a': 1},", "rights reserved. # Use of this source code is governed", "def test_BytesComputedProperty(self): self.assertEqual('\\x00', BP().prop) BP().put() self.assertEqual('\\x00', BP.query().get().prop) if __name__ ==", "test_BytesComputedProperty(self): self.assertEqual('\\x00', BP().prop) BP().put() self.assertEqual('\\x00', BP.query().get().prop) if __name__ == '__main__':", "import unittest import test_env test_env.setup_test_env() from google.appengine.ext import ndb from", "self.assertEqual('\\x00', BP.query().get().prop) if __name__ == '__main__': if '-v' in sys.argv:", "# found in the LICENSE file. import sys import unittest", "class PropertiesTest(test_case.TestCase): def test_DeterministicJsonProperty(self): self.assertEqual({'a': 1}, DJP(prop={'a': 1}).prop) DJP(prop={'a': 1}).put()", "Apache v2.0 license that can be # found in the", "1}).prop) DJP(prop={'a': 1}).put() self.assertEqual({'a': 1}, DJP.query().get().prop) with self.assertRaises(TypeError): DJP(prop=[]) def", "Copyright 2014 The Swarming Authors. All rights reserved. # Use", "governed by the Apache v2.0 license that can be #", "DJP(ndb.Model): prop = properties.DeterministicJsonProperty(json_type=dict) class PropertiesTest(test_case.TestCase): def test_DeterministicJsonProperty(self): self.assertEqual({'a': 1},", "test_env.setup_test_env() from google.appengine.ext import ndb from components.datastore_utils import properties from", "1}).put() self.assertEqual({'a': 1}, DJP.query().get().prop) with self.assertRaises(TypeError): DJP(prop=[]) def test_BytesComputedProperty(self): self.assertEqual('\\x00',", "import ndb from components.datastore_utils import properties from support import test_case", "== '__main__': if '-v' in sys.argv: unittest.TestCase.maxDiff = None unittest.main()", "# Copyright 2014 The Swarming Authors. All rights reserved. #", "v2.0 license that can be # found in the LICENSE", "_: '\\x00') class DJP(ndb.Model): prop = properties.DeterministicJsonProperty(json_type=dict) class PropertiesTest(test_case.TestCase): def", "PropertiesTest(test_case.TestCase): def test_DeterministicJsonProperty(self): self.assertEqual({'a': 1}, DJP(prop={'a': 1}).prop) DJP(prop={'a': 1}).put() self.assertEqual({'a':", "this source code is governed by the Apache v2.0 license", "be # found in the LICENSE file. import sys import", "properties from support import test_case class BP(ndb.Model): prop = properties.BytesComputedProperty(lambda", "properties.DeterministicJsonProperty(json_type=dict) class PropertiesTest(test_case.TestCase): def test_DeterministicJsonProperty(self): self.assertEqual({'a': 1}, DJP(prop={'a': 1}).prop) DJP(prop={'a':", "from support import test_case class BP(ndb.Model): prop = properties.BytesComputedProperty(lambda _:", "code is governed by the Apache v2.0 license that can", "Authors. All rights reserved. # Use of this source code", "unittest import test_env test_env.setup_test_env() from google.appengine.ext import ndb from components.datastore_utils", "1}, DJP(prop={'a': 1}).prop) DJP(prop={'a': 1}).put() self.assertEqual({'a': 1}, DJP.query().get().prop) with self.assertRaises(TypeError):", "self.assertEqual({'a': 1}, DJP.query().get().prop) with self.assertRaises(TypeError): DJP(prop=[]) def test_BytesComputedProperty(self): self.assertEqual('\\x00', BP().prop)", "BP.query().get().prop) if __name__ == '__main__': if '-v' in sys.argv: unittest.TestCase.maxDiff", "#!/usr/bin/env python # Copyright 2014 The Swarming Authors. All rights", "from components.datastore_utils import properties from support import test_case class BP(ndb.Model):" ]
[ "{'alias_%s_rule' % rule_type: kwargs} resource = '%s/alias-%s-rules' % (qos.ALIAS, rule_type.replace('_',", "method_name) self.assertEqual(call_args[1], ctxt) self.assertIsInstance(call_args[2], policy_object.QosPolicy) def _create_and_extend_port(self, min_bw_rules, min_pps_rules=None, physical_network='public',", "'name': 'fake-driver', 'supported_parameters': [{ 'parameter_name': 'max_kpps', 'parameter_type': lib_constants.VALUES_TYPE_RANGE, 'parameter_range': {'start':", "is_sriov: binding_prof = { 'pci_slot': '0000:42:41.0', 'pci_vendor_info': '8086:107ed', 'physical_network': 'sriov_phy'", "self.qos_plugin.create_policy_minimum_bandwidth_rule( self.ctxt, _policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) self.mock_qos_load_attr.assert_called_once_with('rules') mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def", "host='fake_host1', vnic_type='fake_vnic_type', vif_type='fake_vif_type', profile={}) port1_binding.create() port1.bindings = [port1_binding] port1.update() port2", "self.qos_plugin._change_placement_allocation( qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': -1000}})", "mock.MagicMock(qos_policy_id=None), mock.MagicMock(qos_policy_id=uuidutils.generate_uuid()), mock.MagicMock(qos_policy_id=None) ] ports = [ mock.MagicMock(qos_policy_id=self.policy.id), ] expected_network_ports", "self.policy.id) def test_get_policy_packet_rate_limit_rules_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_packet_rate_limit_rules, self.ctxt,", "test_get_policy_min_pps_rule(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumPacketRateRule.' 'get_object') as get_object_mock:", "self.qos_plugin.update_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, self.policy.id, self.rule_data) def test_delete_policy_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None):", "None network = self._make_network(qos_policy_id=net_qos_id) kwargs = {\"context\": self.context, \"network\": network}", "port_qos: qos_policy = port_qos_obj elif network_qos: qos_policy = net_qos_obj if", "self.qos_plugin.update_policy_minimum_packet_rate_rule, self.ctxt, self.min_pps_rule.id, self.policy.id, self.rule_data) def test_update_policy_min_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None):", "@mock.patch.object(qos_plugin.QoSPlugin, \"update_policy_rule\") def test_update_rule(self, update_policy_rule_mock): calls = [] for rule_type,", "desired_qos, kwargs['original_port'], port) def test_check_network_for_placement_allocation_change_no_qos_change(self): qos1 = self._make_qos_policy() original_network =", "self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.create_policy_bandwidth_limit_rule, self.ctxt, self.policy.id, self.rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_rule_check_rule_minbw_gr_than_bwlimit(self): _policy", "qos_policy_id=self.policy.id, filter='filter_id') def test_get_policy_packet_rate_limit_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_packet_rate_limit_rule,", "), mock.patch.object(self.qos_plugin, 'get_policy_rule', return_value=rule.to_dict()): self._update_rule(rule_type, rule_id, **data) calls.append(mock.call(mock.ANY, rule_object_class, rule_id,", "'max_kpps': 400, 'direction': self.pps_rule.direction } } with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as", "qos_policy_id=qos1_id, port_id=TestQosPluginDB.PORT_ID) return {\"context\": self.context, \"original_port\": { \"id\": port.id, \"device_owner\":", "mock_validate_policy.assert_not_called() def test_validate_create_network_callback(self): self._test_validate_create_network_callback(network_qos=True) def test_validate_create_network_callback_no_qos(self): self._test_validate_create_network_callback(network_qos=False) def _test_validate_create_port_callback(self, port_qos=False,", "self._make_qos_policy() original_network = self._make_network(qos1.id) network = original_network ml2plugin_mock = mock.MagicMock()", "self.context, port_id=port2.id, host='fake_host2', vnic_type='fake_vnic_type', vif_type='fake_vif_type', profile={}) port2_binding.create() port2.bindings = [port2_binding]", "kwargs = {\"context\": self.context, \"network\": network} with mock.patch.object(self.qos_plugin, 'validate_policy_for_network') \\", "filters=filters) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id, filter='filter_id') def test_get_policy_min_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "as validate_policy_for_ports, mock.patch.object( self.ctxt, \"elevated\", return_value=admin_ctxt ): self.qos_plugin._validate_update_network_callback( \"NETWORK\", \"precommit_update\",", "the License. import copy from unittest import mock from keystoneauth1", "self.qos_plugin.create_policy_bandwidth_limit_rule, self.ctxt, self.policy.id, self.rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_rule_check_rule_minbw_gr_than_bwlimit(self): _policy =", "rule from class reference rule_mock_call = getattr(mock.call.RuleCls(), action)() driver_mock_call =", "get_resources(self): return qos_rules_alias.Qos_rules_alias.get_resources() def get_actions(self): return [] def get_request_extensions(self): return", "def _delete_rule(self, rule_type, rule_id): resource = '%s/alias-%s-rules' % (qos.ALIAS, rule_type.replace('_',", "'QosMinimumBandwidthRule.' 'get_objects') as get_objects_mock: self.qos_plugin.get_policy_minimum_bandwidth_rules( self.ctxt, self.policy.id) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY,", "def test_create_policy_rule_check_rule_max_more_than_min(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.min_bw_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "{ 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': 500}}) def test_change_placement_allocation_decrease(self): original_qos = self._make_qos_policy() desired_qos =", "min_kbps=500) qos1.rules = [rule1_obj] qos2 = self._make_qos_policy() rule2_obj = self._make_qos_minbw_rule(qos2.id,", "get_ports, mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=policy_mock ) as get_policy, mock.patch.object( self.qos_plugin, \"validate_policy_for_network\"", "self.qos_plugin.get_policy_bandwidth_limit_rules( self.ctxt, self.policy.id, filters=filters) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id, filter='filter_id') def", "self.ctxt, self.dscp_rule.id, self.policy.id) def test_get_policy_dscp_marking_rules_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound,", "{'allocation': 'fake_allocation'}) self.assertDictEqual( port2.bindings[0].profile, {'allocation': 'fake_allocation'}) def _prepare_port_for_placement_allocation(self, original_qos, desired_qos=None,", "# We don't use real models as per mocks above.", "# methods that work with real data types mock.patch( 'neutron.objects.base.NeutronDbObject.modify_fields_from_db'", "def test_update_policy_min_pps_rule_bad_policy(self): _policy = self._get_policy() setattr(_policy, \"rules\", []) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "desired_min_kpps=2000, is_sriov=True) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1, qos2,", "1 with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.assertRaises( qos_exc.QoSRuleParameterConflict, self.qos_plugin.update_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, self.policy.id,", "# 8bf8eb46-160e-11ec-8024-9f96be32099d MIN_BW_REQUEST_GROUP_UUID = 'c8bc1b27-59a1-5135-aa33-aeecad6093f4' MIN_BW_RP = 'd7bea120-1626-11ec-9148-c32debfcf0f6' QOS_MIN_PPS_RULE_ID =", "return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumPacketRateRule.' 'get_objects') as get_objects_mock: filters = {'filter':", "self.rule_data = { 'minimum_packet_rate_rule': {'min_kpps': 10, 'direction': 'any'} } class", ") self.assertEqual( 'fake_uuid', port['resource_request']['request_groups'][0]['id'] ) self.assertEqual( ['CUSTOM_PHYSNET_PUBLIC', 'CUSTOM_VNIC_TYPE_NORMAL'], port['resource_request']['request_groups'][0]['required'] )", "def test_get_policy_min_pps_rules_for_policy_with_filters(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumPacketRateRule.' 'get_objects') as", "in compliance with the License. You may obtain # a", "return_value=_policy): setattr(_policy, \"rules\", [self.pps_rule]) self.qos_plugin.update_policy_packet_rate_limit_rule( self.ctxt, self.pps_rule.id, self.policy.id, self.rule_data) self._validate_driver_params('update_policy',", "exceptions as ks_exc import netaddr from neutron_lib.api.definitions import qos from", "port in ports: self.assertEqual( 1, len(port['resource_request']['request_groups']) ) self.assertEqual( 'fake_uuid', port['resource_request']['request_groups'][0]['id']", "self._validate_driver_params('update_policy', self.ctxt) def test_update_policy_dscp_marking_rule(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with", "}, }, port['resource_request']['request_groups'] ) self.assertEqual( ['fake_uuid0', 'fake_uuid1'], port['resource_request']['same_subtree'], ) def", "= mock.Mock() mock_manager.attach_mock(mock_qos_policy_update, 'update') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() fields = obj_utils.get_updatable_fields(", "min_bw_rule_ingress], [self.min_pps_rule, min_pps_rule_ingress], request_groups_uuids=request_groups_uuids) for port in ports: self.assertEqual( 2,", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", []) self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.delete_policy_packet_rate_limit_rule, self.ctxt, self.pps_rule.id,", "def test_delete_policy_dscp_marking_rule(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy):", "mock.patch('neutron.objects.qos.rule.QosRule.get_object', return_value=None): resource = '%s/alias-%s-rules' % (qos.ALIAS, rule_type.replace('_', '-')) request", "self.qos_plugin = directory.get_plugin(plugins_constants.QOS) self.ctxt = context.Context('fake_user', 'fake_tenant') self.rule_objects = {", "resource = '%s/alias-%s-rules' % (qos.ALIAS, rule_type.replace('_', '-')) request = self.new_update_request(resource,", "[self._make_qos_minpps_rule( qos.id, min_kpps=original_min_kpps, rule_id=TestQosPluginDB.QOS_MIN_PPS_RULE_ID)] allocation.update( {TestQosPluginDB.MIN_PPS_REQUEST_GROUP_UUID: TestQosPluginDB.MIN_PPS_RP}) if desired_qos: desired_qos.rules", "_create_and_extend_port(self, min_bw_rules, min_pps_rules=None, physical_network='public', has_qos_policy=True, has_net_qos_policy=False, request_groups_uuids=None): network_id = uuidutils.generate_uuid()", "as get_policy, mock.patch.object( self.qos_plugin, \"validate_policy_for_port\" ) as validate_policy_for_port, mock.patch.object( self.ctxt,", "self.ctxt) policy_delete_mock_call = mock.call.delete() delete_precommit_mock_call = mock.call.driver.call( 'delete_policy_precommit', self.ctxt, mock.ANY)", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.update_policy_minimum_bandwidth_rule( self.ctxt, self.min_bw_rule.id, self.policy.id, self.rule_data) self.mock_qos_load_attr.assert_called_once_with('rules') self._validate_driver_params('update_policy', self.ctxt)", "\"qos_id\": self.policy.id, \"network_id\": network_id, \"vnic_type\": \"normal\", } }, { \"resource_request\":", "qos_consts.RULE_TYPE_BANDWIDTH_LIMIT) self.assertEqual( qos_consts.RULE_TYPE_BANDWIDTH_LIMIT, rule_type_details['type']) self.assertEqual( drivers_details, rule_type_details['drivers']) def test_get_rule_type_as_user(self): self.assertRaises(", "qos2, orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_min_bw_dataplane_enforcement_with_pps( self): qos1 = self._make_qos_policy()", "id=_policy.id) def test_create_policy_rule_check_rule_max_more_than_min(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.min_bw_rule]) with", "mock.ANY)] mock_alloc_change.assert_has_calls(mock_alloc_change_calls, any_order=True) port1.update() port2.update() self.assertDictEqual( port1.bindings[0].profile, {'allocation': 'fake_allocation'}) self.assertDictEqual(", "qos1 = self._make_qos_policy() original_network = self._make_network(qos1.id) network = original_network ml2plugin_mock", "port = self._prepare_port_for_placement_allocation( qos1, qos2, original_min_kbps=1000, desired_min_kbps=1000, original_min_kpps=1000, desired_min_kpps=1000) with", "[{'code': 'placement.concurrent_update'}]} ) self.assertRaises( neutron_qos_exc.QosPlacementAllocationUpdateConflict, self.qos_plugin._change_placement_allocation, qos1, qos2, orig_port, port)", "rule_type, rule_object_class in self.rule_objects.items(): rule_id = uuidutils.generate_uuid() rule_data_name = '%s_rule'", "original_min_kbps=1000, desired_min_kbps=2000, is_sriov=True) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1,", "orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': -1000}}) self._assert_pci_info(port) def test_change_placement_allocation_decrease_min_pps(self):", "self.ctxt, **self.port_data['port']) port_res = {\"binding:vnic_type\": \"normal\"} segment_mock = mock.MagicMock(network_id=network_id, physical_network=physical_network)", "reference rule_mock_call = getattr(mock.call.RuleCls(), action)() driver_mock_call = mock.call.driver.call('update_policy', self.ctxt, mock.ANY)", "'driver') for action, arguments in rule_actions.items(): mock_manager.reset_mock() method = getattr(self.qos_plugin,", "self.assertEqual(call_args[1], ctxt) self.assertIsInstance(call_args[2], policy_object.QosPolicy) def _create_and_extend_port(self, min_bw_rules, min_pps_rules=None, physical_network='public', has_qos_policy=True,", "['fake_uuid'], port['resource_request']['same_subtree'], ) def test_get_ports_with_policy(self): network_ports = [ mock.MagicMock(qos_policy_id=None), mock.MagicMock(qos_policy_id=uuidutils.generate_uuid()),", "qos_policy_id=self.policy.id) def test_get_policy_packet_rate_limit_rules_for_policy_with_filters(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosPacketRateLimitRule.' 'get_objects')", "QoSRuleAliasMinimumPacketRateTestExtensionManager() super(TestQoSRuleAlias, self).setUp(plugin=plugin, ext_mgr=ext_mgr, service_plugins=service_plugins) self.qos_plugin = directory.get_plugin(plugins_constants.QOS) self.ctxt =", "= '6ac5db7e-1626-11ec-8c7f-0b70dbb8a8eb' # uuid -v5 f02f160e-1612-11ec-b2b8-bf60ab98186c # 6ac5db7e-1626-11ec-8c7f-0b70dbb8a8eb MIN_PPS_REQUEST_GROUP_UUID =", "min_kpps=desired_min_kpps)] binding_prof = {} if is_sriov: binding_prof = { 'pci_slot':", "res) def _delete_rule(self, rule_type, rule_id): resource = '%s/alias-%s-rules' % (qos.ALIAS,", "{\"binding:vnic_type\": \"normal\"} segment_mock = mock.MagicMock(network_id=network_id, physical_network=physical_network) min_pps_rules = min_pps_rules if", "network = self._make_network(qos.id) # Port which is not compute bound", "with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_called_once_with(", "'after_update', ml2plugin_mock, payload=events.DBEventPayload( self.context, states=(original_network, network))) mock_alloc_change.assert_not_called() ml2plugin_mock._make_port_dict.assert_not_called() def test_check_network_for_placement_allocation_change_no_ports_to_update(", "mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1, None, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={ self.MIN_BW_RP:", "test_update_policy_rule_check_rule_bwlimit_less_than_minbw(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy):", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_bandwidth_limit_rules, self.ctxt, self.policy.id) def test_create_policy_dscp_marking_rule(self): _policy", "= {\"context\": self.context, \"network\": network} with mock.patch.object(self.qos_plugin, 'validate_policy_for_network') \\ as", "filters=filters) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id, filter='filter_id') def test_get_policy_minimum_bandwidth_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "as get_object_mock: self.qos_plugin.get_policy_minimum_packet_rate_rule( self.ctxt, self.min_pps_rule.id, self.policy.id) get_object_mock.assert_called_once_with( self.ctxt, id=self.min_pps_rule.id) def", "= policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", [self.rule])", "= 'egress' with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1, qos2,", "some actions construct rule from class reference rule_mock_call = getattr(mock.call.RuleCls(),", "rule from policy get_rule_mock_call = getattr( mock.call.QosPolicy.get_policy_obj().get_rule_by_id(), action)() # some", "types = self.qos_plugin.get_rule_types(self.ctxt, filters=filters) self.assertEqual(sorted(qos_consts.VALID_RULE_TYPES), sorted(type_['type'] for type_ in types))", "filters=filters) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id, filter='filter_id') def test_get_policy_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "mock_qos_policy_get): _policy = copy.copy(self.policy) setattr(_policy, \"rules\", []) mock_qos_policy_get.return_value = _policy", "self._prepare_port_for_placement_allocation(qos1, original_min_kbps=1000, original_min_kpps=2000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1,", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosPacketRateLimitRule.' 'get_objects') as get_objects_mock: self.qos_plugin.get_policy_packet_rate_limit_rules( self.ctxt,", "self.ctxt, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def test_create_policy_pps_rule_duplicates(self): _policy = self._get_policy()", "qos2, original_min_kbps=1000, desired_min_kbps=1000, original_min_kpps=1000, desired_min_kpps=1000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc:", "'parameter_range': {'start': 0, 'end': 100} }] }] with mock.patch.object( qos_plugin.QoSPlugin,", "mock.patch('neutron.objects.qos.rule.' 'QosMinimumBandwidthRule.' 'get_objects') as get_objects_mock: filters = {'filter': 'filter_id'} self.qos_plugin.get_policy_minimum_bandwidth_rules(", "self.mock_qos_load_attr.reset_mock() with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.update_policy_minimum_bandwidth_rule( self.ctxt, self.min_bw_rule.id, self.policy.id, self.rule_data) self.mock_qos_load_attr.assert_called_once_with('rules')", "def _test_validate_update_network_callback(self, policy_id=None, original_policy_id=None): network_id = uuidutils.generate_uuid() kwargs = {", "def test_change_placement_allocation_change_direction_min_pps_and_min_bw( self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() orig_port,", "rules) self.mock_qos_load_attr.reset_mock() with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.update_policy_minimum_bandwidth_rule( self.ctxt, self.min_bw_rule.id, self.policy.id, self.rule_data)", "'any'} } class TestQosPluginDB(base.BaseQosTestCase): PORT_ID = 'f02f160e-1612-11ec-b2b8-bf60ab98186c' QOS_MIN_BW_RULE_ID = '8bf8eb46-160e-11ec-8024-9f96be32099d'", "original_policy_id=None): network_id = uuidutils.generate_uuid() kwargs = { \"context\": self.ctxt, \"network\":", "self._make_qos_policy() kwargs = self._prepare_for_port_placement_allocation_change( qos1=qos1_obj, qos2=None) kwargs['port'].pop('qos_policy_id') context = kwargs['context']", "'fake_tenant') self.admin_ctxt = context.get_admin_context() self.policy_data = { 'policy': {'id': uuidutils.generate_uuid(),", "rule_cls_mock.rule_type = 'fake' rule_actions = {'create': [self.ctxt, rule_cls_mock, self.policy.id, {'fake_rule':", "self.ctxt, self.policy.id, self.rule_data) def test_update_policy_min_pps_rule(self): _policy = self._get_policy() setattr(_policy, \"rules\",", "uuidutils.generate_uuid(), 'min_kbps': 20, 'direction': lib_constants.INGRESS_DIRECTION} min_pps_rule_ingress_data = { 'id': uuidutils.generate_uuid(),", "call_args = self.qos_plugin.driver_manager.call.call_args[0] self.assertTrue(self.qos_plugin.driver_manager.call.called) self.assertEqual(call_args[0], method_name) self.assertEqual(call_args[1], ctxt) self.assertIsInstance(call_args[2], policy_object.QosPolicy)", "mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_update_conflict(self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() orig_port,", "net as net_utils import os_resource_classes as orc from oslo_config import", "as get_port, mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=policy_mock ) as get_policy, mock.patch.object( self.qos_plugin,", "mock_manager = mock.Mock() mock_manager.attach_mock(qos_policy_mock, 'QosPolicy') mock_manager.attach_mock(port_mock, 'Port') mock_manager.attach_mock(rule_cls_mock, 'RuleCls') mock_manager.attach_mock(self.qos_plugin.driver_manager,", "self.rule_data) self._validate_driver_params('update_policy', self.ctxt) self.mock_qos_load_attr.assert_called_once_with('rules') mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_rule_check_rule_max_more_than_min(self): _policy =", "network_qos=False): net_qos_obj = self._make_qos_policy() port_qos_obj = self._make_qos_policy() net_qos_id = net_qos_obj.id", "def test_check_port_for_placement_allocation_change(self): qos1_obj = self._make_qos_policy() qos2_obj = self._make_qos_policy() kwargs =", "setattr(_policy, \"rules\", [self.min_bw_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.update_policy_minimum_bandwidth_rule( self.ctxt, self.min_bw_rule.id, self.policy.id,", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises( qos_exc.QoSRulesConflict, self.qos_plugin.create_policy_bandwidth_limit_rule, self.ctxt, _policy.id, new_rule_data)", "self.policy.id, self.rule_data) self.mock_qos_load_attr.assert_called_once_with('rules') self._validate_driver_params('update_policy', self.ctxt) def test_update_policy_rule_check_rule_bwlimit_less_than_minbw(self): _policy = self._get_policy()", "[self.min_pps_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.update_policy_minimum_packet_rate_rule( self.ctxt, self.min_pps_rule.id, self.policy.id, self.rule_data) self._validate_driver_params('update_policy',", "[ mock.call( original_qos, None, {'id': port1.id, 'device_owner': 'compute:uu:id', 'qos_policy_id': None,", "return_value=True ): self.policy.rules = [self.rule] try: self.qos_plugin.validate_policy_for_network( self.ctxt, self.policy, network_id=network)", "100} }] }] with mock.patch.object( qos_plugin.QoSPlugin, \"supported_rule_type_details\", return_value=drivers_details ): rule_type_details", "min_pps_rule_ingress], request_groups_uuids=request_groups_uuids) for port in ports: self.assertEqual( 2, len(port['resource_request']['request_groups']) )", "[ { 'minimum_packet_rate_rule': { 'id': uuidutils.generate_uuid(), 'min_kpps': 10, 'direction': 'ingress'", "2 min_bw_rule_ingress_data = { 'id': uuidutils.generate_uuid(), 'min_kbps': 20, 'direction': lib_constants.INGRESS_DIRECTION}", "port_qos_obj = self._make_qos_policy() net_qos_id = net_qos_obj.id if network_qos else None", "ml2plugin_mock = mock.MagicMock() def fake_make_port_dict(port): return { 'id': port.id, 'device_owner':", "'qos_policy_id': None, 'qos_network_policy_id': None}, mock.ANY), ] mock_alloc_change.assert_has_calls(mock_alloc_change_calls, any_order=True) port1.update() self.assertDictEqual(port1.bindings[0].profile,", "bound self._make_port(network_id=network.id, qos_policy_id=None, device_owner='uu:id') # Port with overwritten QoS policy", "net_utils import os_resource_classes as orc from oslo_config import cfg from", "self.mock_qos_load_attr.assert_called_once_with('rules') self._validate_driver_params('update_policy', self.ctxt) self.rule_data['minimum_bandwidth_rule']['min_kbps'] = 1000 with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.assertRaises(", "def fake_change_placement_allocation(orig_policy, policy, orig_port, port): port['binding:profile'] = {} mock_alloc_change.side_effect =", "from neutron.exceptions import qos as neutron_qos_exc from neutron.extensions import qos_pps_minimum_rule_alias", "self.ctxt, **self.policy_data['policy']) def test_update_policy_rule_bad_policy(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with", "'sriov_phy' } binding_prof.update({'allocation': allocation}) orig_port.update( {'binding:profile': binding_prof, 'device_id': 'uu:id'} )", "self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION ports = self._create_and_extend_ports([self.min_bw_rule]) for port in ports:", "policy.id, self.rule_data) except NotImplementedError: self.fail() @mock.patch( 'neutron.objects.rbac_db.RbacNeutronDbObjectMixin' '.create_rbac_policy') @mock.patch('neutron.objects.qos.policy.QosPolicy') def", "= self._create_and_extend_port( [self.min_bw_rule, min_bw_rule_ingress], [self.min_pps_rule, min_pps_rule_ingress], request_groups_uuids=request_groups_uuids) self.assertEqual( 2, len(port['resource_request']['request_groups'])", "= policy_object.QosPolicy( self.context, project_id=self.project_id, shared=False, is_default=False) qos_policy.create() return qos_policy def", "desired_min_kpps=1000) for rule in qos2.rules: rule.direction = 'any' with mock.patch.object(self.qos_plugin._placement_client,", "'%s/alias-%s-rules' % (qos.ALIAS, rule_type.replace('_', '-')) request = self.new_update_request(resource, data, rule_id,", "raised\") def test_create_min_bw_rule_on_bound_port(self): policy = self._get_policy() policy.rules = [self.min_bw_rule] segment", "test_update_policy_rule_check_rule_min_less_than_max(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy):", "self.assertEqual( ['fake_uuid'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_bulk_min_bw_rule(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION ports", "try: self.qos_plugin.create_policy_minimum_bandwidth_rule( self.ctxt, policy.id, self.rule_data) except NotImplementedError: self.fail() @mock.patch( 'neutron.objects.rbac_db.RbacNeutronDbObjectMixin'", "as mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt, self.policy.id, self.rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def", "}] with mock.patch.object( qos_plugin.QoSPlugin, \"supported_rule_type_details\", return_value=drivers_details ): rule_type_details = self.qos_plugin.get_rule_type(", "self.qos_plugin._check_network_for_placement_allocation_change( 'network', 'after_update', ml2plugin_mock, payload=events.DBEventPayload( self.context, states=(original_network, network))) self.assertEqual(ml2plugin_mock._make_port_dict.call_count, 1)", "any_order=True) port1.update() self.assertDictEqual(port1.bindings[0].profile, {}) def test_check_network_for_placement_allocation_change(self): original_qos = self._make_qos_policy() qos", "= self._prepare_port_for_placement_allocation( qos1, qos2, desired_min_kbps=1000, original_min_kpps=500, desired_min_kpps=1000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation')", "self.assertRaises( qos_exc.QosRuleNotSupported, self.qos_plugin.validate_policy_for_port, self.ctxt, self.policy, port) def test_validate_policy_for_port_all_rules_valid(self): port =", "uuidutils.generate_uuid() with mock.patch('neutron.objects.qos.rule.QosRule.get_object', return_value=None): resource = '%s/alias-%s-rules' % (qos.ALIAS, rule_type.replace('_',", "self.qos_plugin.delete_policy_bandwidth_limit_rule( self.ctxt, self.rule.id, _policy.id) self._validate_driver_params('update_policy', self.ctxt) rule_delete_mock_call = mock.call.delete() update_precommit_mock_call", "self.assertIsInstance(call_args[2], policy_object.QosPolicy) def _create_and_extend_port(self, min_bw_rules, min_pps_rules=None, physical_network='public', has_qos_policy=True, has_net_qos_policy=False, request_groups_uuids=None):", ") self.assertEqual( ['fake_uuid0', 'fake_uuid1'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_non_min_bw_or_min_pps_rule(self): port =", "in rules: with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt,", "'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': -1000}}) self._assert_pci_info(port) def test_change_placement_allocation_no_original_qos(self): qos1 = None qos2 =", "from neutron.tests.unit.services.qos import base DB_PLUGIN_KLASS = 'neutron.db.db_base_plugin_v2.NeutronDbPluginV2' SERVICE_PLUGIN_KLASS = 'neutron.services.qos.qos_plugin.QoSPlugin'", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.assertRaises( qos_exc.QoSRuleParameterConflict, self.qos_plugin.update_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, self.policy.id, self.rule_data)", "= self.qos_plugin.get_rule_type( admin_ctxt, qos_consts.RULE_TYPE_PACKET_RATE_LIMIT) self.assertEqual( qos_consts.RULE_TYPE_PACKET_RATE_LIMIT, rule_type_details['type']) self.assertEqual( drivers_details, rule_type_details['drivers'])", "10}, port['resource_request']['request_groups'][0]['resources'], ) self.assertEqual( ['fake_uuid'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_bulk_min_bw_and_pps_rule(self): self.min_bw_rule.direction", "request.get_response(self.ext_api) self.assertEqual(webob.exc.HTTPNotFound.code, res.status_int) class TestQoSRuleAliasMinimumPacketRate(TestQoSRuleAlias): def setUp(self): # Remove MissingAuthPlugin", "not compute bound self._make_port(network_id=network.id, qos_policy_id=None, device_owner='uu:id') # Port with overwritten", "original_network = self._make_network(original_qos.id) network = self._make_network(qos.id) # Port which is", "direction='ingress', min_kpps=1000, rule_id=None): rule_id = rule_id if rule_id else uuidutils.generate_uuid()", "= rule_object.QosMinimumPacketRateRule( self.ctxt, **self.rule_data['minimum_packet_rate_rule']) def _validate_driver_params(self, method_name, ctxt): call_args =", "test_delete_policy_min_pps_rule_bad_policy(self): _policy = self._get_policy() setattr(_policy, \"rules\", []) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy):", "as qos_consts from neutron_lib.utils import net as net_utils import os_resource_classes", "\"rules\", [self.rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.create_policy_minimum_bandwidth_rule, self.ctxt,", "request.get_response(self.ext_api) if res.status_int >= webob.exc.HTTPClientError.code: raise webob.exc.HTTPClientError(code=res.status_int) return self.deserialize(self.fmt, res)", "uuidutils.generate_uuid() kwargs = { \"context\": self.ctxt, \"network\": { \"id\": network_id,", "new_rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) @mock.patch.object(rule_object.QosBandwidthLimitRule, 'update') def test_update_policy_rule(self, mock_qos_rule_update): mock_manager =", "= self._make_qos_policy() bw_limit_rule1 = rule_object.QosDscpMarkingRule(dscp_mark=16) bw_limit_rule2 = rule_object.QosDscpMarkingRule(dscp_mark=18) qos1.rules =", "self.dscp_rule = rule_object.QosDscpMarkingRule( self.ctxt, **self.rule_data['dscp_marking_rule']) self.min_bw_rule = rule_object.QosMinimumBandwidthRule( self.ctxt, **self.rule_data['minimum_bandwidth_rule'])", "'binding:profile': {}} port = {} with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc:", "original_policy_id: get_port.assert_not_called() get_policy.assert_not_called() validate_policy_for_port.assert_not_called() else: get_port.assert_called_once_with(self.ctxt, id=port_id) get_policy.assert_called_once_with(admin_ctxt, id=policy_id) validate_policy_for_port.assert_called_once_with(", "self.assertRaises(NotImplementedError, self.qos_plugin._change_placement_allocation, qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_min_bw_dataplane_enforcement(self): qos1", "'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_min_bw_dataplane_enforcement_with_pps(", "= {'filter': 'filter_id'} self.qos_plugin.get_policy_minimum_bandwidth_rules( self.ctxt, self.policy.id, filters=filters) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY,", "'direction': self.min_pps_rule.direction, }, } with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises(", "self.qos_plugin._change_placement_allocation(qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_new_rule_not_min_bw(self): qos1 = self._make_qos_policy()", "id=rule_id) qos_rule.create() return qos_rule def _make_qos_minpps_rule(self, policy_id, direction='ingress', min_kpps=1000, rule_id=None):", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_dscp_marking_rules, self.ctxt, self.policy.id) def test_get_policy_minimum_bandwidth_rule(self):", "\\ mock.patch( 'neutron.objects.network.Network.get_object', return_value=net), \\ mock.patch.object( self.qos_plugin, '_get_ports_with_policy', return_value=[port]): self.assertRaises(", "self.rule_data) self._validate_driver_params('update_policy', self.ctxt) self.mock_qos_load_attr.assert_called_once_with('rules') mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_rule_check_rule_bwlimit_less_than_minbw(self): _policy =", "ext_mgr=ext_mgr, service_plugins=service_plugins) self.qos_plugin = directory.get_plugin(plugins_constants.QOS) self.ctxt = context.Context('fake_user', 'fake_tenant') self.rule_objects", "def test_create_policy_rule_check_rule_minbw_gr_than_bwlimit(self): _policy = self._get_policy() self.rule_data['minimum_bandwidth_rule']['min_kbps'] = 1000000 setattr(_policy, \"rules\",", "= self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation( qos1, qos2, original_min_kbps=1000, desired_min_kbps=2000,", "manager.init() self.qos_plugin = directory.get_plugin(plugins_constants.QOS) self.qos_plugin.driver_manager = mock.Mock() self.rpc_push = mock.patch('neutron.api.rpc.handlers.resources_rpc'", "neutron_lib.plugins import constants as plugins_constants from neutron_lib.plugins import directory from", "exceptions as lib_exc from neutron_lib.exceptions import placement as pl_exc from", "'policy': {'id': policy_id, 'project_id': project_id, 'tenant_id': project_id, 'name': 'test-policy', 'description':", "drivers_details, rule_type_details['drivers']) def test_get_pps_rule_type_as_user(self): self.assertRaises( lib_exc.NotAuthorized, self.qos_plugin.get_rule_type, self.ctxt, qos_consts.RULE_TYPE_PACKET_RATE_LIMIT) def", "{'fake_rule': {}}], 'delete': [self.ctxt, rule_cls_mock, self.rule.id, self.policy.id]} mock_manager = mock.Mock()", "= mock.MagicMock(id=port_id, qos_policy_id=policy_id) policy_mock = mock.MagicMock(id=policy_id) admin_ctxt = mock.Mock() with", "): self.policy.rules = [self.rule] try: self.qos_plugin.validate_policy_for_network( self.ctxt, self.policy, network_id=network) except", "self._test_validate_create_port_callback(network_qos=True) def test_validate_create_port_callback_no_policy(self): self._test_validate_create_port_callback() def _prepare_for_port_placement_allocation_change(self, qos1, qos2, qos_network_policy=None): qos1_id", "= 1000000 setattr(_policy, \"rules\", [self.rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj:", "MissingAuthPlugin exception from logs self.patch_notifier = mock.patch( 'neutron.notifiers.batch_notifier.BatchNotifier._notify') self.patch_notifier.start() plugin", "self.policy.id, self.rule_data) def test_update_policy_rule_check_rule_minbw_gr_than_bwlimit(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.min_bw_rule])", "self.ctxt, self.min_pps_rule.id, self.policy.id) get_object_mock.assert_called_once_with( self.ctxt, id=self.min_pps_rule.id) def test_get_policy_min_pps_rules_for_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "qos_exc.QoSRulesConflict, self.qos_plugin.create_policy_bandwidth_limit_rule, self.ctxt, _policy.id, new_rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) @mock.patch.object(rule_object.QosBandwidthLimitRule, 'update') def", "mock.patch.object(self.qos_plugin, 'get_policy_rule', return_value=rule.to_dict()): self._update_rule(rule_type, rule_id, **data) calls.append(mock.call(mock.ANY, rule_object_class, rule_id, self.qos_policy_id,", "= self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation( qos1, qos2, desired_min_kbps=1000, original_min_kpps=500,", "port = self._prepare_port_for_placement_allocation( qos1, qos2, desired_min_kbps=2000) qos1.rules = [bw_limit_rule] with", "self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) rule_update_mock_call = mock.call.update() update_precommit_mock_call = mock.call.driver.call(", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.create_policy_bandwidth_limit_rule, self.ctxt, self.policy.id, self.rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt,", "self.qos_plugin.get_policy_packet_rate_limit_rules( self.ctxt, self.policy.id) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id) def test_get_policy_packet_rate_limit_rules_for_policy_with_filters(self): with", "self.assertEqual( {orc.NET_BW_EGR_KILOBIT_PER_SEC: 10}, port['resource_request']['request_groups'][0]['resources'], ) self.assertEqual( ['fake_uuid'], port['resource_request']['same_subtree'], ) def", "qos_consts.RULE_TYPE_MINIMUM_PACKET_RATE) self.assertEqual( qos_consts.RULE_TYPE_MINIMUM_PACKET_RATE, rule_type_details['type']) self.assertEqual( drivers_details, rule_type_details['drivers']) def test_get_min_pps_rule_type_as_user(self): self.assertRaises(", "import qos as neutron_qos_exc from neutron.extensions import qos_pps_minimum_rule_alias from neutron.extensions", "'neutron.objects.qos.rule.QosMinimumBandwidthRule.' 'get_objects', return_value=min_bw_rules), \\ mock.patch( 'neutron.objects.qos.rule.QosMinimumPacketRateRule.' 'get_objects', return_value=min_pps_rules), \\ mock.patch(", "physical_network=None) self.assertIsNone(port.get('resource_request')) def test__extend_port_resource_request_mix_rules_non_provider_net(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION port = self._create_and_extend_port([self.min_bw_rule],", "self.qos_plugin.get_policy_minimum_bandwidth_rules( self.ctxt, self.policy.id, filters=filters) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id, filter='filter_id') def", "def _make_qos_minbw_rule(self, policy_id, direction='ingress', min_kbps=1000, rule_id=None): rule_id = rule_id if", "network_id, qos_consts.QOS_POLICY_ID: original_policy_id } } port_mock_with_own_policy = mock.MagicMock( id=uuidutils.generate_uuid(), qos_policy_id=uuidutils.generate_uuid())", "to in writing, software # distributed under the License is", "= policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", [])", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", []) self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.delete_policy_bandwidth_limit_rule, self.ctxt, self.rule.id,", "] setattr(_policy, 'rules', rules) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict,", "'%s/alias-%s-rules' % (qos.ALIAS, rule_type.replace('_', '-')) request = self.new_show_request(resource, rule_id, self.fmt)", "id=self.pps_rule.id) def test_get_policy_packet_rate_limit_rules_for_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosPacketRateLimitRule.' 'get_objects')", "qos2_id = qos2.id if qos2 else None qos_network_policy_id = (", "def test_check_port_for_placement_allocation_change_no_qos_change(self): qos1_obj = self._make_qos_policy() kwargs = self._prepare_for_port_placement_allocation_change( qos1=qos1_obj, qos2=qos1_obj)", "qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_update_conflict(self): qos1 = self._make_qos_policy()", "consumer=self.MIN_BW_RP)) self.assertRaises( pl_exc.PlacementAllocationGenerationConflict, self.qos_plugin._change_placement_allocation, qos1, qos2, orig_port, port) def test_change_placement_allocation_qos_network_policy(self):", "port_id, qos_consts.QOS_POLICY_ID: original_policy_id } } port_mock = mock.MagicMock(id=port_id, qos_policy_id=policy_id) policy_mock", "_policy.id) def test_get_policy_packet_rate_limit_rule(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosPacketRateLimitRule.' 'get_object')", "{ 'policy': {'id': uuidutils.generate_uuid(), 'project_id': uuidutils.generate_uuid(), 'name': 'test-policy', 'description': 'Test", "[] with mock.patch('neutron.objects.network.NetworkSegment.get_objects', return_value=[segment_mock]), \\ mock.patch( 'neutron.objects.qos.rule.QosMinimumBandwidthRule.' 'get_objects', return_value=min_bw_rules), \\", "**self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", [self.dscp_rule]) self.qos_plugin.create_policy_dscp_marking_rule( self.ctxt, self.policy.id,", "or agreed to in writing, software # distributed under the", "{'id': uuidutils.generate_uuid()} with mock.patch.object( self.qos_plugin.driver_manager, \"validate_rule_for_port\", return_value=True ): self.policy.rules =", "self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_dscp_marking_rule, self.ctxt, self.dscp_rule.id, self.policy.id) def test_get_policy_dscp_marking_rules_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "setattr(_policy, \"rules\", []) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.delete_policy_minimum_packet_rate_rule, self.ctxt,", "self.rule_objects = { 'bandwidth_limit': rule_object.QosBandwidthLimitRule, 'dscp_marking': rule_object.QosDscpMarkingRule, 'minimum_bandwidth': rule_object.QosMinimumBandwidthRule }", "} def _update_rule(self, rule_type, rule_id, **kwargs): data = {'alias_%s_rule' %", "base_mac = ['aa', 'bb', 'cc', 'dd', 'ee', 'ff'] mac =", "policy description', 'shared': True, 'is_default': False} with mock.patch('neutron.objects.qos.policy.QosPolicy') as QosMocked:", "['fake_uuid'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_bulk_min_bw_and_pps_rule(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION self.min_pps_rule.direction =", "validate_policy_for_network.assert_not_called() get_ports.assert_not_called() validate_policy_for_ports.assert_not_called() else: get_policy.assert_called_once_with(admin_ctxt, id=policy_id) get_ports.assert_called_once_with(self.ctxt, network_id=network_id) validate_policy_for_ports.assert_called_once_with( self.ctxt,", "'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id',", "which is not compute bound self._make_port(network_id=network.id, qos_policy_id=None, device_owner='uu:id') # Port", "qos2, orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_new_policy_empty(self): qos1 = self._make_qos_policy() orig_port,", "original_min_kbps=1000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1, qos2, orig_port,", "alloc_diff={self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': 1000}}) self._assert_pci_info(port) def test_change_placement_allocation_increase_min_pps_and_min_bw(self): qos1 = self._make_qos_policy()", "self.policy.id, self.rule_data) def test_delete_policy_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.delete_policy_packet_rate_limit_rule,", "self.assertEqual( ['CUSTOM_PHYSNET_PUBLIC', 'CUSTOM_VNIC_TYPE_NORMAL'], port['resource_request']['request_groups'][0]['required'] ) self.assertEqual( {orc.NET_BW_EGR_KILOBIT_PER_SEC: 10}, port['resource_request']['request_groups'][0]['resources'], )", "network_id = uuidutils.generate_uuid() ports_res = [ { \"resource_request\": { \"port_id\":", "test_get_policy_bandwidth_limit_rules_for_policy_with_filters(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosBandwidthLimitRule.' 'get_objects') as get_objects_mock:", "{ 'minimum_packet_rate': rule_object.QosMinimumPacketRateRule } self.qos_policy_id = uuidutils.generate_uuid() self.rule_data = {", "context.Context('fake_user', 'fake_tenant') self.rule_objects = { 'bandwidth_limit': rule_object.QosBandwidthLimitRule, 'dscp_marking': rule_object.QosDscpMarkingRule, 'minimum_bandwidth':", "_policy = self._get_policy() setattr(_policy, \"rules\", [self.rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.update_policy_bandwidth_limit_rule(", "self.ctxt, self.min_pps_rule.id, self.policy.id, self.rule_data) def test_update_policy_min_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises(", "context, states=(original_port, port))) mock_alloc_change.assert_called_once_with( qos1_obj, None, kwargs['original_port'], port) def test_check_port_for_placement_allocation_change_no_qos_update(self):", "[] if desired_min_kbps: desired_qos.rules += [self._make_qos_minbw_rule( desired_qos.id, min_kbps=desired_min_kbps)] if desired_min_kpps:", "= self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation(qos1, original_min_kbps=1000, original_min_kpps=2000) with mock.patch.object(self.qos_plugin._placement_client,", "device_owner='') with mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=policy), \\ mock.patch( 'neutron.objects.network.Network.get_object', return_value=net), \\", "[self.dscp_rule]) self.qos_plugin.delete_policy_dscp_marking_rule( self.ctxt, self.dscp_rule.id, self.policy.id) self._validate_driver_params('update_policy', self.ctxt) def test_get_policy_dscp_marking_rules(self): with", "mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': -1000}}) def test_change_placement_allocation_equal_minkbps_and_minkpps(self): qos1 = self._make_qos_policy()", "uuidutils.generate_uuid() self.port_data = { 'port': {'id': uuidutils.generate_uuid(), 'network_id': network_id} }", "{\"context\": self.context, \"network\": network} with mock.patch.object(self.qos_plugin, 'validate_policy_for_network') \\ as mock_validate_policy:", "def test_get_policy_packet_rate_limit_rules_for_policy_with_filters(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosPacketRateLimitRule.' 'get_objects') as", "mock.patch.object( self.qos_plugin, '_get_ports_with_policy', return_value=[port]): self.assertRaises( NotImplementedError, self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt, _policy.id, self.rule_data)", "'get_policy_rule', return_value=rule.to_dict()): self._update_rule(rule_type, rule_id, **data) calls.append(mock.call(mock.ANY, rule_object_class, rule_id, self.qos_policy_id, {rule_data_name:", "Apache License, Version 2.0 (the \"License\"); you may # not", "rule_object.QosDscpMarkingRule, 'minimum_bandwidth': rule_object.QosMinimumBandwidthRule } self.qos_policy_id = uuidutils.generate_uuid() self.rule_data = {", "ext_mgr = QoSRuleAliasMinimumPacketRateTestExtensionManager() super(TestQoSRuleAlias, self).setUp(plugin=plugin, ext_mgr=ext_mgr, service_plugins=service_plugins) self.qos_plugin = directory.get_plugin(plugins_constants.QOS)", "allocation}) orig_port.update( {'binding:profile': binding_prof, 'device_id': 'uu:id'} ) return orig_port, kwargs['port']", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumBandwidthRule.' 'get_objects') as get_objects_mock: self.qos_plugin.get_policy_minimum_bandwidth_rules(", "lib_constants.EGRESS_DIRECTION ports = self._create_and_extend_ports([self.min_bw_rule]) for port in ports: self.assertEqual( 1,", "= ports + expected_network_ports with mock.patch( 'neutron.objects.ports.Port.get_objects', side_effect=[network_ports, ports] ),", "def test_change_placement_allocation_increase_min_pps_and_min_bw(self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() orig_port, port", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, self.policy.id) def", "ports_object.Port( self.context, network_id=network_id, device_owner=device_owner, project_id=self.project_id, admin_state_up=True, status='DOWN', device_id='2', qos_policy_id=qos_policy_id, qos_network_policy_id=qos_network_policy_id,", "self.policy.id, filters=filters) get_objects_mock.assert_called_once_with( self.ctxt, qos_policy_id=self.policy.id, _pager=mock.ANY, filter='filter_id') def test_get_policy_dscp_marking_rule_for_nonexistent_policy(self): with", "'dscp_marking_rule': {'id': uuidutils.generate_uuid(), 'dscp_mark': 16}, 'minimum_bandwidth_rule': { 'id': uuidutils.generate_uuid(), 'min_kbps':", "def get_actions(self): return [] def get_request_extensions(self): return [] class QoSRuleAliasMinimumPacketRateTestExtensionManager(object):", "qos_plugin.QoSPlugin, \"supported_rule_type_details\", return_value=drivers_details ): rule_type_details = self.qos_plugin.get_rule_type( admin_ctxt, qos_consts.RULE_TYPE_PACKET_RATE_LIMIT) self.assertEqual(", "port_id = port_id if port_id else uuidutils.generate_uuid() base_mac = ['aa',", "self.ctxt, **self.policy_data['policy']) setattr(_policy, \"rules\", [self.rule]) with mock.patch('neutron.objects.qos.rule.get_rules', return_value=[self.rule]), mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object',", "'QosPacketRateLimitRule.' 'get_objects') as get_objects_mock: filters = {'filter': 'filter_id'} self.qos_plugin.get_policy_packet_rate_limit_rules( self.ctxt,", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.delete_policy_minimum_packet_rate_rule, self.ctxt, self.min_pps_rule.id, _policy.id) def", "self.ctxt, self.policy.id, filters=filters) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id, filter='filter_id') def test_get_policy_minimum_bandwidth_rule_for_nonexistent_policy(self):", "mock.patch.object(policy_object.QosPolicy, 'unset_default').start() mock.patch.object(policy_object.QosPolicy, 'set_default').start() cfg.CONF.set_override(\"core_plugin\", DB_PLUGIN_KLASS) cfg.CONF.set_override(\"service_plugins\", [\"qos\"]) manager.init() self.qos_plugin", "self.policy.id) get_object_mock.assert_called_once_with(self.ctxt, id=self.rule.id) def test_get_policy_minimum_bandwidth_rules_for_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.'", "'PORT', 'before_update', 'test_plugin', payload=events.DBEventPayload( context, states=(original_port, port))) mock_alloc_change.assert_not_called() def test_check_port_for_placement_allocation_change_qos_network_policy(", "uuidutils.generate_uuid() project_id = uuidutils.generate_uuid() tenant_policy = { 'policy': {'id': policy_id,", "orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_update_conflict(self): qos1 = self._make_qos_policy() qos2 =", "\"rules\", [self.rule]) new_rule_data = { 'bandwidth_limit_rule': { 'max_kbps': 5000, 'direction':", "mock_update_qos_alloc.side_effect = ( pl_exc.PlacementAllocationGenerationConflict( consumer=self.MIN_BW_RP)) self.assertRaises( pl_exc.PlacementAllocationGenerationConflict, self.qos_plugin._change_placement_allocation, qos1, qos2,", "port for port in network_ports if port.qos_policy_id is None] expected_ports", "'device_owner': 'compute:uu:id', 'qos_policy_id': None, 'qos_network_policy_id': qos.id}, mock.ANY), mock.call( original_qos, qos,", "webob.exc.HTTPClientError(code=res.status_int) return self.deserialize(self.fmt, res) def _show_rule(self, rule_type, rule_id): resource =", "= ['fake_uuid0', 'fake_uuid1'] min_bw_rule_ingress_data = { 'id': uuidutils.generate_uuid(), 'min_kbps': 20,", "self.policy.id) get_object_mock.assert_called_once_with( self.ctxt, id=self.min_pps_rule.id) def test_get_policy_min_pps_rules_for_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with", "self.assertEqual( drivers_details, rule_type_details['drivers']) def test_get_rule_type_as_user(self): self.assertRaises( lib_exc.NotAuthorized, self.qos_plugin.get_rule_type, self.ctxt, qos_consts.RULE_TYPE_BANDWIDTH_LIMIT)", "License, Version 2.0 (the \"License\"); you may # not use", "with mock.patch( 'neutron.objects.ports.Port.get_objects', side_effect=[network_ports, ports] ), mock.patch.object( self.policy, \"get_bound_networks\" ),", "\" \"exception unexpectedly raised\") def test_create_min_bw_rule_on_bound_port(self): policy = self._get_policy() policy.rules", "device_owner='compute:fake-zone') with mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy), \\ mock.patch( 'neutron.objects.network.Network.get_object', return_value=net), \\", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.create_policy_minimum_packet_rate_rule( self.ctxt, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def test_create_policy_min_pps_rule_duplicates(self):", "} port_mock = mock.MagicMock(id=port_id, qos_policy_id=policy_id) policy_mock = mock.MagicMock(id=policy_id) admin_ctxt =", "kwargs['original_port'], port) def test_check_port_for_placement_allocation_change_no_new_policy(self): qos1_obj = self._make_qos_policy() kwargs = self._prepare_for_port_placement_allocation_change(", "= self._make_network() ml2plugin_mock = mock.MagicMock() def fake_make_port_dict(port): return { 'id':", "self.qos_plugin.create_policy(self.ctxt, tenant_policy) QosMocked.assert_called_once_with(self.ctxt, **policy_details) @mock.patch.object(policy_object.QosPolicy, \"get_object\") @mock.patch( 'neutron.objects.rbac_db.RbacNeutronDbObjectMixin' '.create_rbac_policy') @mock.patch.object(policy_object.QosPolicy,", "= self._make_qos_policy() kwargs = self._prepare_for_port_placement_allocation_change( qos1=None, qos2=desired_qos, qos_network_policy=qos_network) context =", "states=(original_port, port))) mock_alloc_change.assert_called_once_with( qos_network, desired_qos, kwargs['original_port'], port) def test_check_network_for_placement_allocation_change_no_qos_change(self): qos1", "id=self.rule.id) def test_get_policy_minimum_bandwidth_rules_for_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumBandwidthRule.' 'get_objects')", "as pl_exc from neutron_lib.exceptions import qos as qos_exc from neutron_lib.objects", "import ports as ports_object from neutron.objects.qos import policy as policy_object", "self._validate_driver_params('update_policy', self.ctxt) rule_create_mock_call = mock.call.create() update_precommit_mock_call = mock.call.driver.call( 'update_policy_precommit', self.ctxt,", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_minimum_packet_rate_rule, self.ctxt, self.min_pps_rule.id, self.policy.id) def", "self.qos_plugin._change_placement_allocation, qos1, qos2, orig_port, port) def test_change_placement_allocation_qos_network_policy(self): qos_network = self._make_qos_policy()", "[{ 'name': 'fake-driver', 'supported_parameters': [{ 'parameter_name': 'max_kpps', 'parameter_type': lib_constants.VALUES_TYPE_RANGE, 'parameter_range':", "mock.patch( 'neutron.objects.qos.policy.QosPolicy.obj_load_attr') self.mock_qos_load_attr = _mock_qos_load_attr.start() # We don't use real", "= uuidutils.generate_uuid() rule_data_name = '%s_rule' % rule_type data = self.rule_data[rule_data_name]", "network.id) else: mock_validate_policy.assert_not_called() def test_validate_create_network_callback(self): self._test_validate_create_network_callback(network_qos=True) def test_validate_create_network_callback_no_qos(self): self._test_validate_create_network_callback(network_qos=False) def", "= self._make_qos_policy() desired_qos = self._make_qos_policy() kwargs = self._prepare_for_port_placement_allocation_change( qos1=None, qos2=desired_qos,", "self.context, port_id=port1.id, host='fake_host1', vnic_type='fake_vnic_type', vif_type='fake_vif_type', profile={'allocation': 'fake_allocation'}) port1_binding.create() port1.bindings =", "'parameter_type': lib_constants.VALUES_TYPE_RANGE, 'parameter_range': {'start': 0, 'end': 100} }] }] with", "not use this file except in compliance with the License.", "= mock.Mock() mock_manager.attach_mock(mock_qos_rule_create, 'create') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() with mock.patch('neutron.objects.qos.qos_policy_validator' '.check_bandwidth_rule_conflict',", "{'filter': 'filter_id'} self.qos_plugin.get_policy_packet_rate_limit_rules( self.ctxt, self.policy.id, filters=filters) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id,", "uuidutils.generate_uuid(), 'max_kbps': 100, 'max_burst_kbps': 150}, 'dscp_marking_rule': {'id': uuidutils.generate_uuid(), 'dscp_mark': 16},", "mock_manager.mock_calls.index( get_rule_mock_call) self.assertLess( action_index, mock_manager.mock_calls.index(driver_mock_call)) def test_create_policy_packet_rate_limit_rule(self): _policy = policy_object.QosPolicy(", "def test_validate_create_network_callback_no_qos(self): self._test_validate_create_network_callback(network_qos=False) def _test_validate_create_port_callback(self, port_qos=False, network_qos=False): net_qos_obj = self._make_qos_policy()", "validate_policy_for_ports, mock.patch.object( self.ctxt, \"elevated\", return_value=admin_ctxt ): self.qos_plugin._validate_update_network_callback( \"NETWORK\", \"precommit_update\", \"test_plugin\",", "def _prepare_port_for_placement_allocation(self, original_qos, desired_qos=None, qos_network_policy=None, original_min_kbps=None, desired_min_kbps=None, original_min_kpps=None, desired_min_kpps=None, is_sriov=False):", "desired_min_kbps=2000, is_sriov=True) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1, qos2,", "'update') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() fields = obj_utils.get_updatable_fields( policy_object.QosPolicy, self.policy_data['policy']) self.qos_plugin.update_policy(", "self.ctxt) self.rule_data['bandwidth_limit_rule']['max_kbps'] = 1 with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.assertRaises( qos_exc.QoSRuleParameterConflict, self.qos_plugin.update_policy_bandwidth_limit_rule,", "qos2, orig_port, port) def test_change_placement_allocation_qos_network_policy(self): qos_network = self._make_qos_policy() desired_qos =", "if qos2 else None qos_network_policy_id = ( qos_network_policy.id if qos_network_policy", "qos1, qos2, original_min_kpps=1000, desired_min_kpps=1000) for rule in qos2.rules: rule.direction =", "self.qos_plugin.driver_manager, \"validate_rule_for_port\", return_value=True ): self.policy.rules = [self.rule] try: self.qos_plugin.validate_policy_for_port( self.ctxt,", "\\ mock.patch( 'uuid.uuid5', return_value='fake_uuid', side_effect=request_groups_uuids): return qos_plugin.QoSPlugin._extend_port_resource_request( port_res, self.port) def", "_get_policy(self): return policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) def test_update_policy_rule_bad_policy(self): _policy = policy_object.QosPolicy(", "'fake_tenant') self.rule_objects = { 'bandwidth_limit': rule_object.QosBandwidthLimitRule, 'dscp_marking': rule_object.QosDscpMarkingRule, 'minimum_bandwidth': rule_object.QosMinimumBandwidthRule", "'direction': lib_constants.INGRESS_DIRECTION} min_pps_rule_ingress_data = { 'id': uuidutils.generate_uuid(), 'min_kpps': 20, 'direction':", "network))) self.assertEqual(ml2plugin_mock._make_port_dict.call_count, 1) mock_alloc_change_calls = [ mock.call( original_qos, None, {'id':", ") as validate_policy_for_port, mock.patch.object( self.ctxt, \"elevated\", return_value=admin_ctxt ): self.qos_plugin._validate_update_port_callback( \"PORT\",", "'direction': self.pps_rule.direction } } with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises(", "mock.patch.object(self.qos_plugin, 'get_policy_rule', return_value=rule.to_dict()): self._delete_rule(rule_type, rule_id) calls.append(mock.call(mock.ANY, rule_object_class, rule_id, self.qos_policy_id)) delete_policy_rule_mock.assert_has_calls(calls,", "ports: self.assertEqual( 1, len(port['resource_request']['request_groups']) ) self.assertEqual( 'fake_uuid', port['resource_request']['request_groups'][0]['id'] ) self.assertEqual(", "'max_burst_kbps': 150}, 'dscp_marking_rule': {'id': uuidutils.generate_uuid(), 'dscp_mark': 16}, 'minimum_bandwidth_rule': { 'id':", "import manager from neutron.objects import network as network_object from neutron.objects", "qos_policy_id=policy_id, direction=direction, min_kpps=min_kpps, id=rule_id) qos_rule.create() return qos_rule def _make_port(self, network_id,", "self._test_validate_create_port_callback(port_qos=True, network_qos=True) def test_validate_create_port_callback_policy_on_network(self): self._test_validate_create_port_callback(network_qos=True) def test_validate_create_port_callback_no_policy(self): self._test_validate_create_port_callback() def _prepare_for_port_placement_allocation_change(self,", "= uuidutils.generate_uuid() with mock.patch.object( self.qos_plugin.driver_manager, \"validate_rule_for_network\", return_value=True ): self.policy.rules =", "neutron_lib.services.qos import constants as qos_consts from neutron_lib.utils import net as", "self.ctxt, mock.ANY) update_mock_call = mock.call.driver.call( 'update_policy', self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(rule_update_mock_call)", "get_objects_mock: self.qos_plugin.get_policy_minimum_packet_rate_rules( self.ctxt, self.policy.id) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id) def test_get_policy_min_pps_rules_for_policy_with_filters(self):", "qos_consts.RULE_TYPE_PACKET_RATE_LIMIT, rule_type_details['type']) self.assertEqual( drivers_details, rule_type_details['drivers']) def test_get_pps_rule_type_as_user(self): self.assertRaises( lib_exc.NotAuthorized, self.qos_plugin.get_rule_type,", "= 'neutron.services.qos.qos_plugin.QoSPlugin' class TestQosPlugin(base.BaseQosTestCase): def setUp(self): super(TestQosPlugin, self).setUp() self.setup_coreplugin(load_plugins=False) mock.patch('neutron.objects.db.api.create_object').start()", "uuidutils.generate_uuid() tenant_policy = { 'policy': {'id': policy_id, 'project_id': project_id, 'tenant_id':", "self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.update_policy_packet_rate_limit_rule, self.ctxt, self.pps_rule.id, self.policy.id, self.rule_data) def test_delete_policy_pps_rule_for_nonexistent_policy(self): with", "original_qos = self._make_qos_policy() original_network = self._make_network(original_qos.id) network = self._make_network() ml2plugin_mock", "= 'neutron.db.db_base_plugin_v2.NeutronDbPluginV2' SERVICE_PLUGIN_KLASS = 'neutron.services.qos.qos_plugin.QoSPlugin' class TestQosPlugin(base.BaseQosTestCase): def setUp(self): super(TestQosPlugin,", "import context from neutron_lib import exceptions as lib_exc from neutron_lib.exceptions", "min_bw_rule_ingress], [self.min_pps_rule, min_pps_rule_ingress], request_groups_uuids=request_groups_uuids) self.assertEqual( 2, len(port['resource_request']['request_groups']) ) self.assertIn( {", "150}, 'dscp_marking_rule': {'id': uuidutils.generate_uuid(), 'dscp_mark': 16}, 'minimum_bandwidth_rule': { 'id': uuidutils.generate_uuid(),", "mock.call.driver.call( 'update_policy', self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(rule_create_mock_call) < mock_manager.mock_calls.index(update_precommit_mock_call) < mock_manager.mock_calls.index(update_mock_call))", "for rule_data in rules_data: rules = [ rule_object.QosMinimumPacketRateRule( self.ctxt, **rules_data[0]['minimum_packet_rate_rule']),", "{ \"id\": port.id, \"device_owner\": \"compute:uu:id\", \"qos_policy_id\": qos1_id, \"qos_network_policy_id\": qos_network_policy_id}, \"port\":", "= {'qos_plugin_name': SERVICE_PLUGIN_KLASS} ext_mgr = QoSRuleAliasMinimumPacketRateTestExtensionManager() super(TestQoSRuleAlias, self).setUp(plugin=plugin, ext_mgr=ext_mgr, service_plugins=service_plugins)", "min_kbps=1000, rule_id=None): rule_id = rule_id if rule_id else uuidutils.generate_uuid() qos_rule", "rule_id=TestQosPluginDB.QOS_MIN_PPS_RULE_ID)] allocation.update( {TestQosPluginDB.MIN_PPS_REQUEST_GROUP_UUID: TestQosPluginDB.MIN_PPS_RP}) if desired_qos: desired_qos.rules = [] if", "if min_pps_rules else [] with mock.patch('neutron.objects.network.NetworkSegment.get_objects', return_value=[segment_mock]), \\ mock.patch( 'neutron.objects.qos.rule.QosMinimumBandwidthRule.'", "super(TestQosPluginDB, self).setUp() self.setup_coreplugin(load_plugins=False) cfg.CONF.set_override(\"core_plugin\", DB_PLUGIN_KLASS) cfg.CONF.set_override(\"service_plugins\", [\"qos\"]) manager.init() self.qos_plugin =", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises( qos_exc.QoSRulesConflict, self.qos_plugin.create_policy_packet_rate_limit_rule, self.ctxt, _policy.id,", "qos2.rules = [rule2_obj] orig_port = {'id': 'u:u', 'device_id': 'i:d', 'binding:profile':", "constants as lib_constants from neutron_lib import context from neutron_lib import", "as mock_alloc_change: self.qos_plugin._check_network_for_placement_allocation_change( 'network', 'after_update', ml2plugin_mock, payload=events.DBEventPayload( self.context, states=(original_network, network)))", "): rule_type_details = self.qos_plugin.get_rule_type( admin_ctxt, qos_consts.RULE_TYPE_BANDWIDTH_LIMIT) self.assertEqual( qos_consts.RULE_TYPE_BANDWIDTH_LIMIT, rule_type_details['type']) self.assertEqual(", "network_qos=True) def test_validate_create_port_callback_policy_on_network(self): self._test_validate_create_port_callback(network_qos=True) def test_validate_create_port_callback_no_policy(self): self._test_validate_create_port_callback() def _prepare_for_port_placement_allocation_change(self, qos1,", "ml2plugin_mock = mock.MagicMock() with mock.patch.object( self.qos_plugin, '_change_placement_allocation') as mock_alloc_change: self.qos_plugin._check_network_for_placement_allocation_change(", "binding_prof.update({'allocation': allocation}) orig_port.update( {'binding:profile': binding_prof, 'device_id': 'uu:id'} ) return orig_port,", "desired_qos, original_min_kbps=2000, desired_min_kbps=1000, is_sriov=True) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(", "self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.create_policy_minimum_bandwidth_rule, self.ctxt, self.policy.id, self.rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_rule_duplicates(self): _policy", "events from neutron_lib import constants as lib_constants from neutron_lib import", "self.ctxt, desired_state=kwargs['network'], states=(kwargs['original_network'],))) if policy_id is None or policy_id ==", "with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_not_called()", "port = self._create_and_extend_port([self.min_bw_rule], has_net_qos_policy=True) self.assertEqual( 1, len(port['resource_request']['request_groups']) ) self.assertEqual( 'fake_uuid',", "self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.delete_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, self.policy.id) def test_verify_bad_method_call(self): self.assertRaises(AttributeError, getattr,", "service_plugins=service_plugins) self.qos_plugin = directory.get_plugin(plugins_constants.QOS) self.ctxt = context.Context('fake_user', 'fake_tenant') self.rule_objects =", "**self.rule_data['packet_rate_limit_rule']) self.min_pps_rule = rule_object.QosMinimumPacketRateRule( self.ctxt, **self.rule_data['minimum_packet_rate_rule']) def _validate_driver_params(self, method_name, ctxt):", "as ks_exc import netaddr from neutron_lib.api.definitions import qos from neutron_lib.callbacks", "mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC':", "= rule_object.QosDscpMarkingRule(dscp_mark=16) orig_port, port = self._prepare_port_for_placement_allocation( qos1, qos2, desired_min_kbps=2000) qos1.rules", "= self._make_qos_minbw_rule(qos1.id, min_kbps=500) qos1.rules = [rule1_obj] qos2 = self._make_qos_policy() rule2_obj", "self.policy.id, self.rule_data) def test_delete_policy_min_pps_rule(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.min_pps_rule])", "policy_mock_call = mock.call.QosPolicy().create() create_precommit_mock_call = mock.call.driver.call( 'create_policy_precommit', self.ctxt, mock.ANY) create_mock_call", "License is distributed on an \"AS IS\" BASIS, WITHOUT #", "policy_id=None, original_policy_id=None): port_id = uuidutils.generate_uuid() kwargs = { \"port\": {", "mock.patch('neutron.objects.qos.rule.' 'QosMinimumPacketRateRule.' 'get_object') as get_object_mock: self.qos_plugin.get_policy_minimum_packet_rate_rule( self.ctxt, self.min_pps_rule.id, self.policy.id) get_object_mock.assert_called_once_with(", "NotImplementedError: self.fail() @mock.patch( 'neutron.objects.rbac_db.RbacNeutronDbObjectMixin' '.create_rbac_policy') @mock.patch('neutron.objects.qos.policy.QosPolicy') def test_add_policy(self, mock_qos_policy, mock_create_rbac_policy):", "rule_id = uuidutils.generate_uuid() rule_data_name = '%s_rule' % rule_type data =", "= rule_id if rule_id else uuidutils.generate_uuid() qos_rule = rule_object.QosMinimumPacketRateRule( self.context,", "def test_check_port_for_placement_allocation_change_qos_network_policy( self): qos_network = self._make_qos_policy() desired_qos = self._make_qos_policy() kwargs", "= self._make_network(qos.id) # Port which is not compute bound self._make_port(network_id=network.id,", "'required': ['CUSTOM_PHYSNET_PUBLIC', 'CUSTOM_VNIC_TYPE_NORMAL'], 'resources': { orc.NET_BW_EGR_KILOBIT_PER_SEC: 10, orc.NET_BW_IGR_KILOBIT_PER_SEC: 20}, },", "_policy = self._get_policy() setattr(_policy, \"rules\", [self.min_pps_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.delete_policy_minimum_packet_rate_rule(", "orig_port, port = self._prepare_port_for_placement_allocation( qos1, qos2, original_min_kbps=1000, desired_min_kbps=2000, original_min_kpps=500, desired_min_kpps=1000)", "mock.Mock() mock_manager.attach_mock(mock_qos_policy_delete, 'delete') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() self.qos_plugin.delete_policy(self.ctxt, self.policy.id) self._validate_driver_params('delete_policy', self.ctxt)", "self.mock_qos_load_attr.assert_called_once_with('rules') self._validate_driver_params('update_policy', self.ctxt) def test_update_policy_rule_check_rule_bwlimit_less_than_minbw(self): _policy = self._get_policy() setattr(_policy, \"rules\",", "\"License\"); you may # not use this file except in", "qos1_obj, qos2_obj, kwargs['original_port'], port) def test_check_port_for_placement_allocation_change_no_new_policy(self): qos1_obj = self._make_qos_policy() kwargs", "id=_policy.id) for rule_data in rules: min_pps_rule = rule_object.QosMinimumPacketRateRule( self.ctxt, **rule_data['minimum_packet_rate_rule'])", "}, \"original_network\": { \"id\": network_id, qos_consts.QOS_POLICY_ID: original_policy_id } } port_mock_with_own_policy", "import base DB_PLUGIN_KLASS = 'neutron.db.db_base_plugin_v2.NeutronDbPluginV2' SERVICE_PLUGIN_KLASS = 'neutron.services.qos.qos_plugin.QoSPlugin' class TestQosPlugin(base.BaseQosTestCase):", "kwargs['original_port'], port) def test_check_network_for_placement_allocation_change_no_qos_change(self): qos1 = self._make_qos_policy() original_network = self._make_network(qos1.id)", "self.ctxt) def test_update_policy_dscp_marking_rule(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", [self.rule]) self.qos_plugin.delete_policy_bandwidth_limit_rule( self.ctxt,", "self.context, project_id=self.project_id, qos_policy_id=policy_id, direction=direction, min_kbps=min_kbps, id=rule_id) qos_rule.create() return qos_rule def", "'update') def test_update_policy(self, mock_qos_policy_update, mock_create_rbac_policy, mock_qos_policy_get): mock_qos_policy_get.return_value = self.policy mock_manager", "**self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", []) self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.update_policy_bandwidth_limit_rule,", "[bw_limit_rule1] qos2.rules = [bw_limit_rule2] orig_port = { 'binding:profile': {'allocation': {", "} if has_qos_policy: self.port_data['port']['qos_policy_id'] = self.policy.id elif has_net_qos_policy: self.port_data['port']['qos_network_policy_id'] =", "[self.pps_rule]) self.qos_plugin.delete_policy_packet_rate_limit_rule( self.ctxt, self.pps_rule.id, self.policy.id) self._validate_driver_params('update_policy', self.ctxt) def test_delete_policy_pps_rule_bad_policy(self): _policy", "qos, {'id': port2.id, 'device_owner': 'compute:uu:id', 'qos_policy_id': None, 'qos_network_policy_id': qos.id}, mock.ANY)]", "None or policy_id == original_policy_id: get_port.assert_not_called() get_policy.assert_not_called() validate_policy_for_port.assert_not_called() else: get_port.assert_called_once_with(self.ctxt,", "'tenant_id': project_id, 'name': 'test-policy', 'description': 'Test policy description', 'shared': True,", "'filter_id'} self.qos_plugin.get_policy_minimum_bandwidth_rules( self.ctxt, self.policy.id, filters=filters) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id, filter='filter_id')", "with mock.patch('neutron.objects.qos.rule.QosRule.get_object', return_value=rule): self._show_rule(rule_type, rule_id) calls.append(mock.call(mock.ANY, rule_object_class, rule_id, self.qos_policy_id)) get_policy_rule_mock.assert_has_calls(calls,", "orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': -1000}}) def test_change_placement_allocation_equal_minkbps_and_minkpps(self): qos1", "desired_min_kbps=1000, original_min_kpps=500, desired_min_kpps=1000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(qos1, qos2,", "self.MIN_BW_REQUEST_GROUP_UUID: self.MIN_BW_RP}}, 'device_id': 'uu:id', 'id': '9416c220-160a-11ec-ba3d-474633eb825c', } port = {}", "_policy.id, new_rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) @mock.patch.object(rule_object.QosBandwidthLimitRule, 'update') def test_update_policy_rule(self, mock_qos_rule_update): mock_manager", "'qos_network_policy_id': port.qos_network_policy_id, } ml2plugin_mock._make_port_dict.side_effect = fake_make_port_dict port1 = self._make_port( network_id=network.id,", "def test_change_placement_allocation_change_dir_min_pps_ingress_to_any( self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() orig_port,", "consumer_uuid='uu:id', alloc_diff={ self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': -500, 'NET_PACKET_RATE_EGR_KILOPACKET_PER_SEC': 1000}, self.MIN_BW_RP: {", "else None network = self._make_network(qos_policy_id=net_qos_id) port = self._make_port(network.id, qos_policy_id=port_qos_id) kwargs", "validate_policy_for_port.assert_called_once_with( self.ctxt, policy_mock, port_mock) def test_validate_update_port_callback_policy_changed(self): self._test_validate_update_port_callback( policy_id=uuidutils.generate_uuid()) def test_validate_update_port_callback_policy_not_changed(self):", "500}}) def test_change_placement_allocation_decrease(self): original_qos = self._make_qos_policy() desired_qos = self._make_qos_policy() orig_port,", "port_qos_obj.id if port_qos else None network = self._make_network(qos_policy_id=net_qos_id) port =", "_policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) self.mock_qos_load_attr.assert_called_once_with('rules') mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_rule_check_rule_max_more_than_min(self): _policy", "payload=events.DBEventPayload( self.context, states=(original_network, network))) mock_alloc_change.assert_not_called() ml2plugin_mock._make_port_dict.assert_not_called() def test_check_network_for_placement_allocation_change_no_ports_to_update( self): original_qos", "def _assert_pci_info(self, port): self.assertIn('pci_slot', port['binding:profile']) self.assertIn('pci_vendor_info', port['binding:profile']) self.assertIn('physical_network', port['binding:profile']) def", "qos_policy = policy_object.QosPolicy( self.context, project_id=self.project_id, shared=False, is_default=False) qos_policy.create() return qos_policy", "= self._make_qos_policy() port_qos_obj = self._make_qos_policy() net_qos_id = net_qos_obj.id if network_qos", "= self._get_policy() rules_data = [ { 'minimum_packet_rate_rule': { 'id': uuidutils.generate_uuid(),", "mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_called_once_with(", "from neutron_lib.callbacks import events from neutron_lib import constants as lib_constants", "= getattr(self.qos_plugin, \"%s_policy_rule\" % action) method(*arguments) # some actions get", "def test_delete_policy_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.delete_policy_bandwidth_limit_rule, self.ctxt, self.rule.id,", "len(policy_ports)) for port in expected_ports: self.assertIn(port, policy_ports) def _test_validate_update_port_callback(self, policy_id=None,", "admin_ctxt = mock.Mock() with mock.patch( 'neutron.objects.ports.Port.get_object', return_value=port_mock ) as get_port,", "self.context, qos_policy, network.id) else: mock_validate_policy.assert_not_called() def test_validate_create_network_callback(self): self._test_validate_create_network_callback(network_qos=True) def test_validate_create_network_callback_no_qos(self):", "get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id) def test_get_policy_dscp_marking_rules_for_policy_with_filters(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with", "{'NET_BW_IGR_KILOBIT_PER_SEC': -1000}, self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': -2000}}) def test_change_placement_allocation_no_min_bw(self): qos1 =", "self.policy.id) def test_get_policy_dscp_marking_rules_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_dscp_marking_rules, self.ctxt,", "return_value=admin_ctxt ): self.qos_plugin._validate_update_network_callback( \"NETWORK\", \"precommit_update\", \"test_plugin\", payload=events.DBEventPayload( self.ctxt, desired_state=kwargs['network'], states=(kwargs['original_network'],)))", "\"get_policy_rule\") def test_show_rule(self, get_policy_rule_mock): calls = [] for rule_type, rule_object_class", "self.policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) self.rule = rule_object.QosBandwidthLimitRule( self.ctxt, **self.rule_data['bandwidth_limit_rule'])", "= [] for rule_type, rule_object_class in self.rule_objects.items(): rule_id = uuidutils.generate_uuid()", "self.qos_plugin.get_policy_dscp_marking_rules( self.ctxt, self.policy.id, filters=filters) get_objects_mock.assert_called_once_with( self.ctxt, qos_policy_id=self.policy.id, _pager=mock.ANY, filter='filter_id') def", "port.qos_policy_id, 'qos_network_policy_id': port.qos_network_policy_id, } ml2plugin_mock._make_port_dict.side_effect = fake_make_port_dict port1 = self._make_port(", "[self.min_pps_rule]) self.assertEqual( 1, len(port['resource_request']['request_groups']) ) self.assertEqual( 'fake_uuid', port['resource_request']['request_groups'][0]['id'] ) self.assertEqual(", "test_change_placement_allocation_old_rule_not_min_bw(self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() bw_limit_rule = rule_object.QosDscpMarkingRule(dscp_mark=16)", "self.policy.rules = [self.rule] self.assertRaises( qos_exc.QosRuleNotSupported, self.qos_plugin.validate_policy_for_port, self.ctxt, self.policy, port) def", "port = ports_object.Port( self.ctxt, id=uuidutils.generate_uuid(), network_id=uuidutils.generate_uuid(), device_owner='') with mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object',", "self.qos_plugin.get_policy_packet_rate_limit_rule( self.ctxt, self.pps_rule.id, self.policy.id) get_object_mock.assert_called_once_with(self.ctxt, id=self.pps_rule.id) def test_get_policy_packet_rate_limit_rules_for_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "self.assertEqual( 1, len(port['resource_request']['request_groups']) ) self.assertEqual( 'fake_uuid', port['resource_request']['request_groups'][0]['id'] ) self.assertEqual( ['CUSTOM_VNIC_TYPE_NORMAL'],", "import events from neutron_lib import constants as lib_constants from neutron_lib", "self.policy.id) self._validate_driver_params('delete_policy', self.ctxt) policy_delete_mock_call = mock.call.delete() delete_precommit_mock_call = mock.call.driver.call( 'delete_policy_precommit',", "ml2plugin_mock, payload=events.DBEventPayload( self.context, states=(original_network, network))) self.assertEqual(ml2plugin_mock._make_port_dict.call_count, 2) mock_alloc_change_calls = [", "rule = rule_object_class(self.ctxt, id=rule_id, qos_policy_id=self.qos_policy_id, **data) with mock.patch('neutron.objects.qos.rule.QosRule.get_object', return_value=rule): self._show_rule(rule_type,", "rule_object_class, rule_id, self.qos_policy_id, {rule_data_name: data})) update_policy_rule_mock.assert_has_calls(calls, any_order=True) @mock.patch.object(qos_plugin.QoSPlugin, \"get_policy_rule\") def", "constants as plugins_constants from neutron_lib.plugins import directory from neutron_lib.services.qos import", "\"original_port\": { \"id\": port_id, qos_consts.QOS_POLICY_ID: original_policy_id } } port_mock =", "= mock.MagicMock() def fake_make_port_dict(port): return { 'id': port.id, 'device_owner': port.device_owner,", "return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_minimum_bandwidth_rules, self.ctxt, self.policy.id) def test_create_policy_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "= mock.call.driver.call( 'update_policy_precommit', self.ctxt, mock.ANY) update_mock_call = mock.call.driver.call( 'update_policy', self.ctxt,", "setattr(_policy, \"rules\", [self.pps_rule]) self.qos_plugin.update_policy_packet_rate_limit_rule( self.ctxt, self.pps_rule.id, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt)", "vif_type='fake_vif_type', profile={}) port2_binding.create() port2.bindings = [port2_binding] port2.update() with mock.patch.object( self.qos_plugin,", "mock_manager.mock_calls.index(update_mock_call)) def test_update_policy_rule_check_rule_min_less_than_max(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.rule]) with", "'packet_rate_limit_rule': { 'max_kpps': 400, 'direction': self.pps_rule.direction } } with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "= { 'packet_rate_limit_rule': { 'max_kpps': 400, 'direction': self.pps_rule.direction } }", "self.qos_plugin, '_change_placement_allocation') as mock_alloc_change: self.qos_plugin._check_network_for_placement_allocation_change( 'network', 'after_update', ml2plugin_mock, payload=events.DBEventPayload( self.context,", "mock.MagicMock(network_id=network_id, physical_network=physical_network) min_pps_rules = min_pps_rules if min_pps_rules else [] with", "if rule_id else uuidutils.generate_uuid() qos_rule = rule_object.QosMinimumBandwidthRule( self.context, project_id=self.project_id, qos_policy_id=policy_id,", "uuid -v5 f02f160e-1612-11ec-b2b8-bf60ab98186c # 8bf8eb46-160e-11ec-8024-9f96be32099d MIN_BW_REQUEST_GROUP_UUID = 'c8bc1b27-59a1-5135-aa33-aeecad6093f4' MIN_BW_RP =", "mock.patch.object( self.qos_plugin, '_change_placement_allocation') as mock_alloc_change: self.qos_plugin._check_port_for_placement_allocation_change( 'PORT', 'before_update', 'test_plugin', payload=events.DBEventPayload(", "get_objects_mock.assert_called_once_with( self.ctxt, qos_policy_id=self.policy.id, _pager=mock.ANY, filter='filter_id') def test_get_policy_dscp_marking_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None):", "self.rule.id, self.policy.id]} mock_manager = mock.Mock() mock_manager.attach_mock(qos_policy_mock, 'QosPolicy') mock_manager.attach_mock(port_mock, 'Port') mock_manager.attach_mock(rule_cls_mock,", "uuidutils.generate_uuid() self._test_validate_update_port_callback( policy_id=policy_id, original_policy_id=policy_id) def test_validate_update_port_callback_policy_removed(self): self._test_validate_update_port_callback( policy_id=None, original_policy_id=uuidutils.generate_uuid()) def", "port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_bulk_min_pps_rule(self): ports = self._create_and_extend_ports([], [self.min_pps_rule]) for port", "self.rule.id, self.policy.id) get_object_mock.assert_called_once_with(self.ctxt, id=self.rule.id) def test_get_policy_bandwidth_limit_rules_for_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with", "test__extend_port_resource_request_bulk_min_bw_rule(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION ports = self._create_and_extend_ports([self.min_bw_rule]) for port in", "setattr(_policy, \"rules\", [self.pps_rule]) self.qos_plugin.delete_policy_packet_rate_limit_rule( self.ctxt, self.pps_rule.id, self.policy.id) self._validate_driver_params('update_policy', self.ctxt) def", "self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def test_update_policy_pps_rule_bad_policy(self): _policy = policy_object.QosPolicy( self.ctxt,", "self._prepare_for_port_placement_allocation_change( qos1=qos1_obj, qos2=None) kwargs['port'].pop('qos_policy_id') context = kwargs['context'] original_port = kwargs['original_port']", "self._delete_rule(rule_type, rule_id) calls.append(mock.call(mock.ANY, rule_object_class, rule_id, self.qos_policy_id)) delete_policy_rule_mock.assert_has_calls(calls, any_order=True) def test_show_non_existing_rule(self):", "= self._make_network(original_qos.id) network = self._make_network() ml2plugin_mock = mock.MagicMock() def fake_make_port_dict(port):", "self.port_data['port']['qos_policy_id'] = self.policy.id elif has_net_qos_policy: self.port_data['port']['qos_network_policy_id'] = self.policy.id self.port =", "else: action_index = mock_manager.mock_calls.index( get_rule_mock_call) self.assertLess( action_index, mock_manager.mock_calls.index(driver_mock_call)) def test_create_policy_packet_rate_limit_rule(self):", "self.assertEqual( qos_consts.RULE_TYPE_PACKET_RATE_LIMIT, rule_type_details['type']) self.assertEqual( drivers_details, rule_type_details['drivers']) def test_get_pps_rule_type_as_user(self): self.assertRaises( lib_exc.NotAuthorized,", "self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt, self.policy.id, new_rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) for rule_data in", "self.policy, \"get_bound_networks\" ), mock.patch.object( self.policy, \"get_bound_ports\" ): policy_ports = self.qos_plugin._get_ports_with_policy(", "desired_qos = self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation( None, desired_qos, qos_network_policy=qos_network,", "min_kbps=desired_min_kbps)] if desired_min_kpps: desired_qos.rules += [self._make_qos_minpps_rule( desired_qos.id, min_kpps=desired_min_kpps)] binding_prof =", "def test_update_policy_rule_check_rule_minbw_gr_than_bwlimit(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.min_bw_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "= self.qos_plugin._get_ports_with_policy( self.ctxt, self.policy) self.assertEqual( len(expected_ports), len(policy_ports)) for port in", "test_change_placement_allocation_min_bw_dataplane_enforcement(self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() orig_port, port =", "self.assertEqual( 'fake_uuid', port['resource_request']['request_groups'][0]['id'] ) self.assertEqual( ['CUSTOM_PHYSNET_PUBLIC', 'CUSTOM_VNIC_TYPE_NORMAL'], port['resource_request']['request_groups'][0]['required'] ) self.assertEqual(", "qos_policy_mock, port_mock): rule_cls_mock = mock.Mock() rule_cls_mock.rule_type = 'fake' rule_actions =", "def test_get_policy_min_pps_rule(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumPacketRateRule.' 'get_object') as", "'project_id': uuidutils.generate_uuid(), 'name': 'test-policy', 'description': 'Test policy description', 'shared': True,", "'neutron.objects.rbac_db.RbacNeutronDbObjectMixin' '.create_rbac_policy') @mock.patch('neutron.objects.qos.policy.QosPolicy') def test_add_policy(self, mock_qos_policy, mock_create_rbac_policy): mock_manager = mock.Mock()", "qos_exc.QosRuleNotFound, self.qos_plugin.update_policy_minimum_packet_rate_rule, self.ctxt, self.min_pps_rule.id, self.policy.id, self.rule_data) def test_update_policy_min_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "'driver') mock_manager.reset_mock() _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) setattr(_policy, \"rules\", [self.rule])", "'neutron.objects.qos.policy.QosPolicy.obj_load_attr') self.mock_qos_load_attr = _mock_qos_load_attr.start() # We don't use real models", "test_delete_policy_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.delete_policy_packet_rate_limit_rule, self.ctxt, self.pps_rule.id, self.policy.id)", "= context.get_admin_context() self.project_id = uuidutils.generate_uuid() def _make_qos_policy(self): qos_policy = policy_object.QosPolicy(", "from neutron.tests.unit.db import test_db_base_plugin_v2 from neutron.tests.unit.services.qos import base DB_PLUGIN_KLASS =", "self.ctxt, self.policy.id, self.rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_rule_duplicates(self): _policy = self._get_policy()", "rule_object.QosDscpMarkingRule( self.ctxt, **self.rule_data['dscp_marking_rule']) self.min_bw_rule = rule_object.QosMinimumBandwidthRule( self.ctxt, **self.rule_data['minimum_bandwidth_rule']) self.pps_rule =", "network_id=uuidutils.generate_uuid(), device_owner='compute:fake-zone') with mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=policy), \\ mock.patch( 'neutron.objects.network.Network.get_object', return_value=net),", "self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation( original_qos, desired_qos, original_min_kpps=2000, desired_min_kpps=1000, is_sriov=True)", "= self._prepare_port_for_placement_allocation( qos1, qos2, desired_min_kbps=2000) qos1.rules = [bw_limit_rule] with mock.patch.object(self.qos_plugin._placement_client,", ") self.assertEqual( ['CUSTOM_PHYSNET_PUBLIC', 'CUSTOM_VNIC_TYPE_NORMAL'], port['resource_request']['request_groups'][0]['required'] ) self.assertEqual( {orc.NET_BW_EGR_KILOBIT_PER_SEC: 10}, port['resource_request']['request_groups'][0]['resources'],", "qos_exc from neutron_lib.objects import utils as obj_utils from neutron_lib.plugins import", "types mock.patch( 'neutron.objects.base.NeutronDbObject.modify_fields_from_db' ).start() mock.patch.object(policy_object.QosPolicy, 'unset_default').start() mock.patch.object(policy_object.QosPolicy, 'set_default').start() cfg.CONF.set_override(\"core_plugin\", DB_PLUGIN_KLASS)", "\\ mock.patch( 'neutron.objects.qos.rule.QosMinimumBandwidthRule.' 'get_objects', return_value=min_bw_rules), \\ mock.patch( 'neutron.objects.qos.rule.QosMinimumPacketRateRule.' 'get_objects', return_value=min_pps_rules),", "'id': 'fake_uuid1', 'required': ['CUSTOM_VNIC_TYPE_NORMAL'], 'resources': { orc.NET_PACKET_RATE_EGR_KILOPACKET_PER_SEC: 10, orc.NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC: 20,", "'update_policy_precommit', self.ctxt, mock.ANY) update_mock_call = mock.call.driver.call( 'update_policy', self.ctxt, mock.ANY) self.assertTrue(", "self.policy.id, self.rule_data) def test_delete_policy_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.delete_policy_bandwidth_limit_rule,", "def test_create_policy_rule_duplicates(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.rule]) new_rule_data =", "def test_update_rule(self, update_policy_rule_mock): calls = [] for rule_type, rule_object_class in", "\"id\": port_id, qos_consts.QOS_POLICY_ID: original_policy_id } } port_mock = mock.MagicMock(id=port_id, qos_policy_id=policy_id)", "id=rule_id, qos_policy_id=self.qos_policy_id, **data) with mock.patch( 'neutron.objects.qos.rule.QosRule.get_object', return_value=rule ), mock.patch.object(self.qos_plugin, 'get_policy_rule',", "if original_min_kbps: qos.rules += [self._make_qos_minbw_rule( qos.id, min_kbps=original_min_kbps, rule_id=TestQosPluginDB.QOS_MIN_BW_RULE_ID)] allocation.update( {TestQosPluginDB.MIN_BW_REQUEST_GROUP_UUID:", "port['resource_request']['request_groups'][0]['resources'], ) self.assertEqual( ['fake_uuid'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_bulk_min_bw_rule(self): self.min_bw_rule.direction =", "'name': 'test-policy', 'description': 'Test policy description', 'shared': True, 'is_default': False}", "_show_rule(self, rule_type, rule_id): resource = '%s/alias-%s-rules' % (qos.ALIAS, rule_type.replace('_', '-'))", "self.qos_plugin.get_rule_type, self.ctxt, qos_consts.RULE_TYPE_BANDWIDTH_LIMIT) def test_get_rule_types(self): filters = {'type': 'type_id'} with", "{} if original_min_kbps: qos.rules += [self._make_qos_minbw_rule( qos.id, min_kbps=original_min_kbps, rule_id=TestQosPluginDB.QOS_MIN_BW_RULE_ID)] allocation.update(", "qos_consts.QOS_POLICY_ID: policy_id }, \"original_network\": { \"id\": network_id, qos_consts.QOS_POLICY_ID: original_policy_id }", "{ \"id\": port_id, qos_consts.QOS_POLICY_ID: policy_id }, \"original_port\": { \"id\": port_id,", "port_id, qos_consts.QOS_POLICY_ID: policy_id }, \"original_port\": { \"id\": port_id, qos_consts.QOS_POLICY_ID: original_policy_id", "= net_qos_obj.id if network_qos else None port_qos_id = port_qos_obj.id if", "from neutron_lib import constants as lib_constants from neutron_lib import context", "def test_get_ports_with_policy(self): network_ports = [ mock.MagicMock(qos_policy_id=None), mock.MagicMock(qos_policy_id=uuidutils.generate_uuid()), mock.MagicMock(qos_policy_id=None) ] ports", "None] expected_ports = ports + expected_network_ports with mock.patch( 'neutron.objects.ports.Port.get_objects', side_effect=[network_ports,", "% action) method(*arguments) # some actions get rule from policy", "% rule_type: kwargs} resource = '%s/alias-%s-rules' % (qos.ALIAS, rule_type.replace('_', '-'))", "def test_change_placement_allocation_decrease(self): original_qos = self._make_qos_policy() desired_qos = self._make_qos_policy() orig_port, port", "self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id) def test_get_policy_min_pps_rules_for_policy_with_filters(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.'", "self._create_and_extend_ports( [self.min_bw_rule, min_bw_rule_ingress], [self.min_pps_rule, min_pps_rule_ingress], request_groups_uuids=request_groups_uuids) for port in ports:", "'fake-driver', 'supported_parameters': [{ 'parameter_name': 'max_kbps', 'parameter_type': lib_constants.VALUES_TYPE_RANGE, 'parameter_range': {'start': 0,", "= self._get_policy() setattr(_policy, \"rules\", [self.min_pps_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.delete_policy_minimum_packet_rate_rule( self.ctxt,", "distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR", "self._validate_driver_params('update_policy', self.ctxt) def test_delete_policy_min_pps_rule_bad_policy(self): _policy = self._get_policy() setattr(_policy, \"rules\", [])", "policy_update_mock_call = mock.call.update() update_precommit_mock_call = mock.call.driver.call( 'update_policy_precommit', self.ctxt, mock.ANY) update_mock_call", "{'allocation': 'fake_allocation'} mock_alloc_change.side_effect = fake_change_placement_allocation self.qos_plugin._check_network_for_placement_allocation_change( 'network', 'after_update', ml2plugin_mock, payload=events.DBEventPayload(", "desired_min_kpps: desired_qos.rules += [self._make_qos_minpps_rule( desired_qos.id, min_kpps=desired_min_kpps)] binding_prof = {} if", "mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': -1000}}) self._assert_pci_info(port) def test_change_placement_allocation_no_original_qos(self): qos1", "return_value=net), \\ mock.patch.object( self.qos_plugin, '_get_ports_with_policy', return_value=[port]): self.assertRaises( NotImplementedError, self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt,", "neutron.services.qos import qos_plugin from neutron.tests.unit.db import test_db_base_plugin_v2 from neutron.tests.unit.services.qos import", "get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id) def test_get_policy_bandwidth_limit_rules_for_policy_with_filters(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with", "self._make_network(original_qos.id) network = self._make_network() ml2plugin_mock = mock.MagicMock() def fake_make_port_dict(port): return", "{ orc.NET_BW_EGR_KILOBIT_PER_SEC: 10, orc.NET_BW_IGR_KILOBIT_PER_SEC: 20}, }, port['resource_request']['request_groups'] ) self.assertIn( {", "self.ctxt, id=uuidutils.generate_uuid(), network_id=uuidutils.generate_uuid(), device_owner='compute:fake-zone') with mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=policy), \\ mock.patch(", "mock_manager.reset_mock() _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) setattr(_policy, \"rules\", [self.rule]) with", "mock_alloc_change.assert_called_once_with( qos_network, desired_qos, kwargs['original_port'], port) def test_check_network_for_placement_allocation_change_no_qos_change(self): qos1 = self._make_qos_policy()", "qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation(", "original_network ml2plugin_mock = mock.MagicMock() with mock.patch.object( self.qos_plugin, '_change_placement_allocation') as mock_alloc_change:", "for rule_data in rules: min_pps_rule = rule_object.QosMinimumPacketRateRule( self.ctxt, **rule_data['minimum_packet_rate_rule']) setattr(_policy,", "mock.patch('neutron.objects.db.api.update_object').start() mock.patch('neutron.objects.db.api.delete_object').start() mock.patch('neutron.objects.db.api.get_object').start() _mock_qos_load_attr = mock.patch( 'neutron.objects.qos.policy.QosPolicy.obj_load_attr') self.mock_qos_load_attr = _mock_qos_load_attr.start()", "else None qos_network_policy_id = ( qos_network_policy.id if qos_network_policy else None)", "mock.call.driver.call( 'create_policy', self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(policy_mock_call) < mock_manager.mock_calls.index(create_precommit_mock_call) < mock_manager.mock_calls.index(create_mock_call))", "as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( original_qos, desired_qos, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_PPS_RP:", "self._assert_pci_info(port) def test_change_placement_allocation_no_original_qos(self): qos1 = None qos2 = self._make_qos_policy() rule2_obj", "neutron_qos_exc.QosPlacementAllocationUpdateConflict, self.qos_plugin._change_placement_allocation, qos1, qos2, orig_port, port) def test_change_placement_allocation_update_generation_conflict(self): qos1 =", "obj_utils.get_updatable_fields( policy_object.QosPolicy, self.policy_data['policy']) self.qos_plugin.update_policy( self.ctxt, self.policy.id, {'policy': fields}) self._validate_driver_params('update_policy', self.ctxt)", "port_qos = self._make_qos_policy() original_network = self._make_network(original_qos.id) network = self._make_network(qos.id) #", "test_get_pps_rule_type_as_user(self): self.assertRaises( lib_exc.NotAuthorized, self.qos_plugin.get_rule_type, self.ctxt, qos_consts.RULE_TYPE_PACKET_RATE_LIMIT) def test_create_min_pps_rule_on_bound_port(self): _policy =", "network_object.Network(self.context, qos_policy_id=qos_policy_id) network.create() return network def _test_validate_create_network_callback(self, network_qos=False): net_qos_obj =", "original_min_kbps=1000, desired_min_kbps=1000, original_min_kpps=1000, desired_min_kpps=1000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(", "{'id': uuidutils.generate_uuid(), 'project_id': uuidutils.generate_uuid(), 'name': 'test-policy', 'description': 'Test policy description',", "2) mock_alloc_change_calls = [ mock.call( original_qos, qos, {'id': port1.id, 'device_owner':", "'neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.rule_data['bandwidth_limit_rule']['max_kbps'] = 1 self.qos_plugin.update_policy_bandwidth_limit_rule( self.ctxt, self.rule.id, self.policy.id, self.rule_data)", "mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.update_policy_minimum_packet_rate_rule, self.ctxt, rule_data['minimum_packet_rate_rule']['id'], self.policy.id, self.rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def", "payload=events.DBEventPayload( self.context, states=(original_network, network))) mock_alloc_change.assert_not_called() ml2plugin_mock._make_port_dict.assert_not_called() def test_check_network_for_placement_allocation_change_remove_qos(self): original_qos =", "network))) mock_alloc_change.assert_not_called() ml2plugin_mock._make_port_dict.assert_not_called() def test_check_network_for_placement_allocation_change_remove_qos(self): original_qos = self._make_qos_policy() original_network =", "= self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation( original_qos, desired_qos, original_min_kbps=2000, desired_min_kbps=1000,", "qos from neutron_lib.callbacks import events from neutron_lib import constants as", "test_validate_update_port_callback_policy_removed(self): self._test_validate_update_port_callback( policy_id=None, original_policy_id=uuidutils.generate_uuid()) def _test_validate_update_network_callback(self, policy_id=None, original_policy_id=None): network_id =", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.delete_policy_packet_rate_limit_rule, self.ctxt, self.pps_rule.id, self.policy.id) def", "= obj_utils.get_updatable_fields( policy_object.QosPolicy, self.policy_data['policy']) self.qos_plugin.update_policy( self.ctxt, self.policy.id, {'policy': fields}) self._validate_driver_params('update_policy',", "Version 2.0 (the \"License\"); you may # not use this", "return_value=min_bw_rules), \\ mock.patch( 'neutron.objects.qos.rule.QosMinimumPacketRateRule.' 'get_objects', return_value=min_pps_rules), \\ mock.patch( 'uuid.uuid5', return_value='fake_uuid',", "@mock.patch.object(policy_object.QosPolicy, \"get_object\") @mock.patch( 'neutron.objects.rbac_db.RbacNeutronDbObjectMixin' '.create_rbac_policy') @mock.patch.object(policy_object.QosPolicy, 'update') def test_update_policy(self, mock_qos_policy_update,", "getattr, self.qos_plugin, 'create_policy_bandwidth_limit_rules') def test_get_rule_type(self): admin_ctxt = context.get_admin_context() drivers_details =", "self.ctxt, self.policy.id) def test_get_min_pps_rule_type(self): admin_ctxt = context.get_admin_context() drivers_details = [{", "# Port which is not compute bound self._make_port(network_id=network.id, qos_policy_id=None, device_owner='uu:id')", "self._prepare_for_port_placement_allocation_change( qos1=qos1_obj, qos2=None) context = kwargs['context'] original_port = kwargs['original_port'] port", "policy_id=policy_id, original_policy_id=policy_id) def test_validate_update_port_callback_policy_removed(self): self._test_validate_update_port_callback( policy_id=None, original_policy_id=uuidutils.generate_uuid()) def _test_validate_update_network_callback(self, policy_id=None,", "{ 'minimum_packet_rate_rule': { 'id': uuidutils.generate_uuid(), 'min_kpps': 10, 'direction': 'egress' }", "= ( pl_exc.PlacementAllocationGenerationConflict( consumer=self.MIN_BW_RP)) self.assertRaises( pl_exc.PlacementAllocationGenerationConflict, self.qos_plugin._change_placement_allocation, qos1, qos2, orig_port,", "'test_plugin', payload=events.DBEventPayload( context, states=(original_port, port))) mock_alloc_change.assert_called_once_with( qos1_obj, qos2_obj, kwargs['original_port'], port)", "qos2, orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_update_conflict(self): qos1 = self._make_qos_policy() qos2", "_update_rule(self, rule_type, rule_id, **kwargs): data = {'alias_%s_rule' % rule_type: kwargs}", "self._make_qos_policy() bw_limit_rule = rule_object.QosDscpMarkingRule(dscp_mark=16) qos2.rules = [bw_limit_rule] orig_port, port =", "_policy = self._get_policy() setattr(_policy, \"rules\", [self.min_pps_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.create_policy_minimum_packet_rate_rule(", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.update_policy_minimum_packet_rate_rule, self.ctxt, self.min_pps_rule.id, self.policy.id, self.rule_data)", "test_check_network_for_placement_allocation_change_remove_qos(self): original_qos = self._make_qos_policy() original_network = self._make_network(original_qos.id) network = self._make_network()", "**min_pps_rule_ingress_data) ports = self._create_and_extend_ports( [self.min_bw_rule, min_bw_rule_ingress], [self.min_pps_rule, min_pps_rule_ingress], request_groups_uuids=request_groups_uuids) for", "= self._get_policy() self.rule_data['minimum_packet_rate_rule']['direction'] = 'any' setattr(_policy, \"rules\", [self.min_pps_rule]) rules =", "= [port2_binding] port2.update() with mock.patch.object( self.qos_plugin, '_change_placement_allocation') as mock_alloc_change: def", "def test_create_policy_dscp_marking_rule(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy):", "ml2plugin_mock, payload=events.DBEventPayload( self.context, states=(original_network, network))) mock_alloc_change.assert_not_called() ml2plugin_mock._make_port_dict.assert_not_called() def test_check_network_for_placement_allocation_change_remove_qos(self): original_qos", "mock.ANY) update_mock_call = mock.call.driver.call( 'update_policy', self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(rule_delete_mock_call) <", "mock.call.driver.call( 'create_policy_precommit', self.ctxt, mock.ANY) create_mock_call = mock.call.driver.call( 'create_policy', self.ctxt, mock.ANY)", "self._validate_driver_params('update_policy', self.ctxt) def test_get_policy_dscp_marking_rules(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosDscpMarkingRule.'", "_make_qos_minbw_rule(self, policy_id, direction='ingress', min_kbps=1000, rule_id=None): rule_id = rule_id if rule_id", "admin_state_up=True, status='DOWN', device_id='2', qos_policy_id=qos_policy_id, qos_network_policy_id=qos_network_policy_id, mac_address=mac, id=port_id) port.create() return port", "= kwargs['original_port'] port = kwargs['port'] with mock.patch.object( self.qos_plugin, '_change_placement_allocation') as", "min_kpps=original_min_kpps, rule_id=TestQosPluginDB.QOS_MIN_PPS_RULE_ID)] allocation.update( {TestQosPluginDB.MIN_PPS_REQUEST_GROUP_UUID: TestQosPluginDB.MIN_PPS_RP}) if desired_qos: desired_qos.rules = []", "qos1, qos2, orig_port, port) def test_change_placement_allocation_update_generation_conflict(self): qos1 = self._make_qos_policy() qos2", "in rules_data: rules = [ rule_object.QosMinimumPacketRateRule( self.ctxt, **rules_data[0]['minimum_packet_rate_rule']), rule_object.QosMinimumPacketRateRule( self.ctxt,", "= mock.Mock() self.rpc_push = mock.patch('neutron.api.rpc.handlers.resources_rpc' '.ResourcesPushRpcApi.push').start() self.ctxt = context.Context('fake_user', 'fake_tenant')", "self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id) def test_get_policy_packet_rate_limit_rules_for_policy_with_filters(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.'", "original_policy_id } } port_mock = mock.MagicMock(id=port_id, qos_policy_id=policy_id) policy_mock = mock.MagicMock(id=policy_id)", "import policy as policy_object from neutron.objects.qos import rule as rule_object", "< mock_manager.mock_calls.index(delete_mock_call)) @mock.patch.object(policy_object.QosPolicy, \"get_object\") @mock.patch.object(rule_object.QosBandwidthLimitRule, 'create') def test_create_policy_rule(self, mock_qos_rule_create, mock_qos_policy_get):", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", [self.dscp_rule]) self.qos_plugin.update_policy_dscp_marking_rule( self.ctxt, self.dscp_rule.id, self.policy.id, self.rule_data)", "self.ctxt, qos_consts.RULE_TYPE_BANDWIDTH_LIMIT) def test_get_rule_types(self): filters = {'type': 'type_id'} with mock.patch.object(qos_plugin.QoSPlugin,", "'_change_placement_allocation') as mock_alloc_change: self.qos_plugin._check_port_for_placement_allocation_change( 'PORT', 'before_update', 'test_plugin', payload=events.DBEventPayload( context, states=(original_port,", "rule_actions.items(): mock_manager.reset_mock() method = getattr(self.qos_plugin, \"%s_policy_rule\" % action) method(*arguments) #", "self.qos_plugin._validate_update_network_callback( \"NETWORK\", \"precommit_update\", \"test_plugin\", payload=events.DBEventPayload( self.ctxt, desired_state=kwargs['network'], states=(kwargs['original_network'],))) if policy_id", "as mock_alloc_change: self.qos_plugin._check_port_for_placement_allocation_change( 'PORT', 'before_update', 'test_plugin', payload=events.DBEventPayload( context, states=(original_port, port)))", "**self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", [self.pps_rule]) self.qos_plugin.update_policy_packet_rate_limit_rule( self.ctxt, self.pps_rule.id,", "setattr(_policy, \"rules\", []) self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.update_policy_packet_rate_limit_rule, self.ctxt, self.pps_rule.id, self.policy.id, self.rule_data)", "self.ctxt, self.policy.id, filters=filters) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id, filter='filter_id') def test_get_policy_min_pps_rule_for_nonexistent_policy(self):", "qos_network_policy else None) network = self._make_network(qos_policy_id=qos_network_policy_id) port = self._make_port( network.id,", "def setUp(self): super(TestQosPlugin, self).setUp() self.setup_coreplugin(load_plugins=False) mock.patch('neutron.objects.db.api.create_object').start() mock.patch('neutron.objects.db.api.update_object').start() mock.patch('neutron.objects.db.api.delete_object').start() mock.patch('neutron.objects.db.api.get_object').start() _mock_qos_load_attr", "self.min_pps_rule.id, self.policy.id, self.rule_data) def test_delete_policy_min_pps_rule(self): _policy = self._get_policy() setattr(_policy, \"rules\",", "self.qos_policy_id)) delete_policy_rule_mock.assert_has_calls(calls, any_order=True) def test_show_non_existing_rule(self): for rule_type, rule_object_class in self.rule_objects.items():", "create_mock_call = mock.call.driver.call( 'create_policy', self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(policy_mock_call) < mock_manager.mock_calls.index(create_precommit_mock_call)", "[]) self.assertIsNone(port.get('resource_request')) def test__extend_port_resource_request_min_bw_non_provider_net(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION port = self._create_and_extend_port([self.min_bw_rule],", "test_check_port_for_placement_allocation_change_no_qos_change(self): qos1_obj = self._make_qos_policy() kwargs = self._prepare_for_port_placement_allocation_change( qos1=qos1_obj, qos2=qos1_obj) context", "mock_update_qos_alloc: mock_update_qos_alloc.side_effect = ( pl_exc.PlacementAllocationGenerationConflict( consumer=self.MIN_BW_RP)) self.assertRaises( pl_exc.PlacementAllocationGenerationConflict, self.qos_plugin._change_placement_allocation, qos1,", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_minimum_bandwidth_rule, self.ctxt, self.rule.id, self.policy.id) def test_get_policy_minimum_bandwidth_rules_for_nonexistent_policy(self):", "self.ctxt, self.policy.id) def test_create_policy_dscp_marking_rule(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with", "rule_object_class(self.ctxt, id=rule_id, qos_policy_id=self.qos_policy_id, **data) with mock.patch( 'neutron.objects.qos.rule.QosRule.get_object', return_value=rule ), mock.patch.object(self.qos_plugin,", "\"NETWORK\", \"precommit_create\", \"test_plugin\", payload=events.DBEventPayload( self.context, resource_id=kwargs['network']['id'],)) qos_policy = None if", "id=uuidutils.generate_uuid(), qos_policy_id=uuidutils.generate_uuid()) port_mock_without_own_policy = mock.MagicMock( id=uuidutils.generate_uuid(), qos_policy_id=None) ports = [port_mock_with_own_policy,", "policy_id=None, original_policy_id=uuidutils.generate_uuid()) def _test_validate_update_network_callback(self, policy_id=None, original_policy_id=None): network_id = uuidutils.generate_uuid() kwargs", "'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': 500}, self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': 1000}}) def test_change_placement_allocation_change_direction_min_pps_and_min_bw( self): qos1 =", "port = self._create_and_extend_port([self.min_bw_rule]) self.assertEqual( 1, len(port['resource_request']['request_groups']) ) self.assertEqual( 'fake_uuid', port['resource_request']['request_groups'][0]['id']", "test_rule_notification_and_driver_ordering(self, qos_policy_mock, port_mock): rule_cls_mock = mock.Mock() rule_cls_mock.rule_type = 'fake' rule_actions", "netaddr.EUI(next(net_utils.random_mac_generator(base_mac))) device_owner = device_owner if device_owner else '3' port =", ") self.assertEqual( ['fake_uuid'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_min_bw_and_pps_rule(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION", "def test_validate_policy_for_network(self): network = uuidutils.generate_uuid() with mock.patch.object( self.qos_plugin.driver_manager, \"validate_rule_for_network\", return_value=True", "'neutron.objects.rbac_db.RbacNeutronDbObjectMixin' '.create_rbac_policy') @mock.patch.object(policy_object.QosPolicy, 'update') def test_update_policy(self, mock_qos_policy_update, mock_create_rbac_policy, mock_qos_policy_get): mock_qos_policy_get.return_value", "self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.create_policy_bandwidth_limit_rule, self.ctxt, self.policy.id, self.rule_data) def test_update_policy_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "policy_mock = mock.MagicMock(id=policy_id) admin_ctxt = mock.Mock() with mock.patch( 'neutron.objects.ports.Port.get_objects', return_value=ports", "= policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", [self.pps_rule])", "\"rules\", [self.pps_rule]) new_rule_data = { 'packet_rate_limit_rule': { 'max_kpps': 400, 'direction':", "= { 'bandwidth_limit_rule': {'max_kbps': 100, 'max_burst_kbps': 150}, 'dscp_marking_rule': {'dscp_mark': 16},", "rule_type.replace('_', '-')) request = self.new_show_request(resource, rule_id, self.fmt) res = request.get_response(self.ext_api)", "[]) mock_qos_policy_get.return_value = _policy mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_rule_create, 'create') mock_manager.attach_mock(self.qos_plugin.driver_manager,", "net_qos_obj = self._make_qos_policy() port_qos_obj = self._make_qos_policy() net_qos_id = net_qos_obj.id if", "original_qos = self._make_qos_policy() qos = self._make_qos_policy() port_qos = self._make_qos_policy() original_network", "'dscp_marking_rule': {'dscp_mark': 16}, 'minimum_bandwidth_rule': {'min_kbps': 10} } def _update_rule(self, rule_type,", "return_value=_policy): self.qos_plugin.update_policy_minimum_bandwidth_rule( self.ctxt, self.min_bw_rule.id, self.policy.id, self.rule_data) self.mock_qos_load_attr.assert_called_once_with('rules') self._validate_driver_params('update_policy', self.ctxt) def", "self.ctxt, self.min_bw_rule.id, self.policy.id, self.rule_data) self.mock_qos_load_attr.assert_called_once_with('rules') self._validate_driver_params('update_policy', self.ctxt) def test_update_policy_rule_check_rule_bwlimit_less_than_minbw(self): _policy", "= self.new_show_request(resource, rule_id, self.fmt) res = request.get_response(self.ext_api) if res.status_int >=", "self.qos_policy_id)) get_policy_rule_mock.assert_has_calls(calls, any_order=True) @mock.patch.object(qos_plugin.QoSPlugin, \"delete_policy_rule\") def test_delete_rule(self, delete_policy_rule_mock): calls =", "= mock.MagicMock( id=uuidutils.generate_uuid(), qos_policy_id=uuidutils.generate_uuid()) port_mock_without_own_policy = mock.MagicMock( id=uuidutils.generate_uuid(), qos_policy_id=None) ports", "self._make_network(qos.id) # Port which is not compute bound self._make_port(network_id=network.id, qos_policy_id=None,", "rules = [ rule_object.QosMinimumPacketRateRule( self.ctxt, **rules_data[0]['minimum_packet_rate_rule']), rule_object.QosMinimumPacketRateRule( self.ctxt, **rules_data[1]['minimum_packet_rate_rule']), ]", "test_update_policy_pps_rule_bad_policy(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy,", "def test_verify_bad_method_call(self): self.assertRaises(AttributeError, getattr, self.qos_plugin, 'create_policy_bandwidth_limit_rules') def test_get_rule_type(self): admin_ctxt =", "mock_manager.attach_mock(port_mock, 'Port') mock_manager.attach_mock(rule_cls_mock, 'RuleCls') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') for action, arguments in", "for type_ in types)) @mock.patch('neutron.objects.ports.Port') @mock.patch('neutron.objects.qos.policy.QosPolicy') def test_rule_notification_and_driver_ordering(self, qos_policy_mock, port_mock):", "self.rule_data) @mock.patch.object(rule_object.QosBandwidthLimitRule, 'delete') def test_delete_policy_rule(self, mock_qos_rule_delete): mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_rule_delete,", "} self.qos_policy_id = uuidutils.generate_uuid() self.rule_data = { 'minimum_packet_rate_rule': {'min_kpps': 10,", "as get_ports, mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=policy_mock ) as get_policy, mock.patch.object( self.qos_plugin,", "= [self.min_bw_rule] segment = network_object.NetworkSegment( physical_network='fake physnet') net = network_object.Network(", ") as validate_policy_for_network, mock.patch.object( self.qos_plugin, \"validate_policy_for_ports\" ) as validate_policy_for_ports, mock.patch.object(", "mock_api_get_policy): mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_policy_delete, 'delete') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() self.qos_plugin.delete_policy(self.ctxt,", "return_value=_policy): setattr(_policy, \"rules\", [self.dscp_rule]) self.qos_plugin.update_policy_dscp_marking_rule( self.ctxt, self.dscp_rule.id, self.policy.id, self.rule_data) self._validate_driver_params('update_policy',", "uuidutils.generate_uuid(), 'min_kpps': 10, 'direction': 'egress' } }, ] for new_rule_data", "port_id if port_id else uuidutils.generate_uuid() base_mac = ['aa', 'bb', 'cc',", "compliance with the License. You may obtain # a copy", "= [ mock.call( original_qos, None, {'id': port1.id, 'device_owner': 'compute:uu:id', 'qos_policy_id':", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_packet_rate_limit_rules, self.ctxt, self.policy.id) def test_create_policy_pps_rule_for_nonexistent_policy(self): with", "qos1=qos1_obj, qos2=None) kwargs['port'].pop('qos_policy_id') context = kwargs['context'] original_port = kwargs['original_port'] port", "= { \"port\": { \"id\": port_id, qos_consts.QOS_POLICY_ID: policy_id }, \"original_port\":", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumBandwidthRule.' 'get_objects') as get_objects_mock: filters =", "self.context, project_id=self.project_id, qos_policy_id=policy_id, direction=direction, min_kpps=min_kpps, id=rule_id) qos_rule.create() return qos_rule def", "physical_network=None) self.assertEqual( 1, len(port['resource_request']['request_groups']) ) self.assertEqual( 'fake_uuid', port['resource_request']['request_groups'][0]['id'] ) self.assertEqual(", "mock.patch.object(qos_plugin.QoSPlugin, 'supported_rule_types', return_value=qos_consts.VALID_RULE_TYPES): types = self.qos_plugin.get_rule_types(self.ctxt, filters=filters) self.assertEqual(sorted(qos_consts.VALID_RULE_TYPES), sorted(type_['type'] for", "mock.Mock() rule_cls_mock.rule_type = 'fake' rule_actions = {'create': [self.ctxt, rule_cls_mock, self.policy.id,", "'QosDscpMarkingRule.' 'get_objects') as get_objects_mock: filters = {'filter': 'filter_id'} self.qos_plugin.get_policy_dscp_marking_rules( self.ctxt,", "[]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.delete_policy_minimum_packet_rate_rule, self.ctxt, self.min_pps_rule.id, _policy.id)", "6ac5db7e-1626-11ec-8c7f-0b70dbb8a8eb MIN_PPS_REQUEST_GROUP_UUID = '995008f4-f120-547a-b051-428b89076067' MIN_PPS_RP = 'e16161f4-1626-11ec-a5a2-1fc9396e27cc' def setUp(self): super(TestQosPluginDB,", "net_qos_obj.id if network_qos else None network = self._make_network(qos_policy_id=net_qos_id) kwargs =", "= self._prepare_for_port_placement_allocation_change( qos1=None, qos2=desired_qos, qos_network_policy=qos_network) context = kwargs['context'] original_port =", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosBandwidthLimitRule.' 'get_objects') as get_objects_mock: self.qos_plugin.get_policy_bandwidth_limit_rules(", "self).setUp(plugin=plugin, ext_mgr=ext_mgr, service_plugins=service_plugins) self.qos_plugin = directory.get_plugin(plugins_constants.QOS) self.ctxt = context.Context('fake_user', 'fake_tenant')", "qos1, qos2, desired_min_kbps=1000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(qos1, qos2,", "self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id, filter='filter_id') def test_get_policy_minimum_bandwidth_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises(", "id=uuidutils.generate_uuid(), qos_policy_id=None) ports = [port_mock_with_own_policy, port_mock_without_own_policy] policy_mock = mock.MagicMock(id=policy_id) admin_ctxt", "self.policy.id, self.rule_data) def test_update_policy_min_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.update_policy_minimum_packet_rate_rule,", "mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_rule_update, 'update') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() _policy =", "with mock.patch.object( self.qos_plugin, '_change_placement_allocation') as mock_alloc_change: self.qos_plugin._check_network_for_placement_allocation_change( 'network', 'after_update', ml2plugin_mock,", "return_value=_policy): self.qos_plugin.update_policy_bandwidth_limit_rule( self.ctxt, self.rule.id, self.policy.id, self.rule_data) self.mock_qos_load_attr.assert_called_once_with('rules') self._validate_driver_params('update_policy', self.ctxt) self.rule_data['minimum_bandwidth_rule']['min_kbps']", "= _policy mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_rule_create, 'create') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock()", "\"supported_rule_type_details\", return_value=drivers_details ): rule_type_details = self.qos_plugin.get_rule_type( admin_ctxt, qos_consts.RULE_TYPE_BANDWIDTH_LIMIT) self.assertEqual( qos_consts.RULE_TYPE_BANDWIDTH_LIMIT,", "self.deserialize(self.fmt, res) def _delete_rule(self, rule_type, rule_id): resource = '%s/alias-%s-rules' %", "mock.MagicMock(id=policy_id) admin_ctxt = mock.Mock() with mock.patch( 'neutron.objects.ports.Port.get_objects', return_value=ports ) as", "= [self.rule] try: self.qos_plugin.validate_policy_for_network( self.ctxt, self.policy, network_id=network) except qos_exc.QosRuleNotSupportedByNetwork: self.fail(\"QosRuleNotSupportedByNetwork", "original_min_kpps=500, desired_min_kpps=1000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1, qos2,", "mock_manager.mock_calls: action_index = mock_manager.mock_calls.index(rule_mock_call) else: action_index = mock_manager.mock_calls.index( get_rule_mock_call) self.assertLess(", "self.qos_plugin.delete_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, _policy.id) def test_get_policy_bandwidth_limit_rule(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with", "'get_policy_rule', return_value=rule.to_dict()): self._delete_rule(rule_type, rule_id) calls.append(mock.call(mock.ANY, rule_object_class, rule_id, self.qos_policy_id)) delete_policy_rule_mock.assert_has_calls(calls, any_order=True)", "self.rule_data) self.mock_qos_load_attr.assert_called_once_with('rules') self._validate_driver_params('update_policy', self.ctxt) self.rule_data['bandwidth_limit_rule']['max_kbps'] = 1 with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy):", "self.qos_plugin.driver_manager = mock.Mock() self.rpc_push = mock.patch('neutron.api.rpc.handlers.resources_rpc' '.ResourcesPushRpcApi.push').start() self.ctxt = context.Context('fake_user',", "self._make_qos_policy() desired_qos = self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation( None, desired_qos,", "{}} port = {} with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(qos1,", "# # Unless required by applicable law or agreed to", "test_get_min_pps_rule_type_as_user(self): self.assertRaises( lib_exc.NotAuthorized, self.qos_plugin.get_rule_type, self.ctxt, qos_consts.RULE_TYPE_MINIMUM_PACKET_RATE) class QoSRuleAliasTestExtensionManager(object): def get_resources(self):", "raise webob.exc.HTTPClientError(code=res.status_int) return self.deserialize(self.fmt, res) def _delete_rule(self, rule_type, rule_id): resource", "original_min_kpps=None, desired_min_kpps=None, is_sriov=False): kwargs = self._prepare_for_port_placement_allocation_change( original_qos, desired_qos, qos_network_policy=qos_network_policy) orig_port", "self._make_qos_policy() original_network = self._make_network(original_qos.id) network = self._make_network(qos.id) ml2plugin_mock = mock.MagicMock()", "NotImplementedError, self.qos_plugin.create_policy_minimum_bandwidth_rule, self.ctxt, policy.id, self.rule_data) def test_create_min_bw_rule_on_unbound_port(self): policy = self._get_policy()", "20, 'direction': lib_constants.INGRESS_DIRECTION} min_bw_rule_ingress = rule_object.QosMinimumBandwidthRule( self.ctxt, **min_bw_rule_ingress_data) min_pps_rule_ingress =", "qos2.rules = [bw_limit_rule2] orig_port = { 'binding:profile': {'allocation': { self.MIN_BW_REQUEST_GROUP_UUID:", "\"rules\", []) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.update_policy_minimum_packet_rate_rule, self.ctxt, self.min_pps_rule.id,", "qos_exc.QosRuleNotSupported: self.fail(\"QosRuleNotSupported exception unexpectedly raised\") def test_validate_policy_for_network(self): network = uuidutils.generate_uuid()", "self._create_and_extend_ports([], [self.min_pps_rule]) for port in ports: self.assertEqual( 1, len(port['resource_request']['request_groups']) )", "def test__extend_port_resource_request_min_bw_rule(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION port = self._create_and_extend_port([self.min_bw_rule]) self.assertEqual( 1,", "'fake' rule_actions = {'create': [self.ctxt, rule_cls_mock, self.policy.id, {'fake_rule': {}}], 'update':", "rule_data_name = '%s_rule' % rule_type data = self.rule_data[rule_data_name] rule =", "test_validate_create_port_callback_no_policy(self): self._test_validate_create_port_callback() def _prepare_for_port_placement_allocation_change(self, qos1, qos2, qos_network_policy=None): qos1_id = qos1.id", "= ports_object.Port( self.ctxt, id=uuidutils.generate_uuid(), network_id=uuidutils.generate_uuid(), device_owner='compute:fake-zone') with mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=policy),", "mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) for rule_data in rules: min_pps_rule = rule_object.QosMinimumPacketRateRule( self.ctxt,", "= lib_constants.EGRESS_DIRECTION self.min_bw_rule.qos_policy_id = self.policy.id port = self._create_and_extend_port([self.min_bw_rule], has_net_qos_policy=True) self.assertEqual(", "self.qos_plugin._change_placement_allocation(qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_new_policy_empty(self): qos1 = self._make_qos_policy()", "delete_policy_rule_mock.assert_has_calls(calls, any_order=True) def test_show_non_existing_rule(self): for rule_type, rule_object_class in self.rule_objects.items(): rule_id", "'delete': [self.ctxt, rule_cls_mock, self.rule.id, self.policy.id]} mock_manager = mock.Mock() mock_manager.attach_mock(qos_policy_mock, 'QosPolicy')", "def test_create_min_bw_rule_on_bound_port(self): policy = self._get_policy() policy.rules = [self.min_bw_rule] segment =", "port_mock_without_own_policy] policy_mock = mock.MagicMock(id=policy_id) admin_ctxt = mock.Mock() with mock.patch( 'neutron.objects.ports.Port.get_objects',", "'dd', 'ee', 'ff'] mac = netaddr.EUI(next(net_utils.random_mac_generator(base_mac))) device_owner = device_owner if", "self): original_qos = self._make_qos_policy() qos = self._make_qos_policy() port_qos = self._make_qos_policy()", "port = self._prepare_port_for_placement_allocation( qos1, qos2, original_min_kbps=1000, desired_min_kbps=2000, original_min_kpps=500, desired_min_kpps=1000) with", "policy_id = uuidutils.generate_uuid() self._test_validate_update_port_callback( policy_id=policy_id, original_policy_id=policy_id) def test_validate_update_port_callback_policy_removed(self): self._test_validate_update_port_callback( policy_id=None,", "desired_qos = self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation( original_qos, desired_qos, original_min_kpps=2000,", "from neutron_lib.api.definitions import qos from neutron_lib.callbacks import events from neutron_lib", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises( qos_exc.QoSRulesConflict, self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt, _policy.id, new_rule_data)", "raise webob.exc.HTTPClientError(code=res.status_int) return self.deserialize(self.fmt, res) def _show_rule(self, rule_type, rule_id): resource", "qos1, None, orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_old_rule_not_min_bw(self): qos1 = self._make_qos_policy()", "self.ctxt, **self.rule_data['dscp_marking_rule']) self.min_bw_rule = rule_object.QosMinimumBandwidthRule( self.ctxt, **self.rule_data['minimum_bandwidth_rule']) self.pps_rule = rule_object.QosPacketRateLimitRule(", "len(port['resource_request']['request_groups']) ) self.assertEqual( 'fake_uuid', port['resource_request']['request_groups'][0]['id'] ) self.assertEqual( ['CUSTOM_VNIC_TYPE_NORMAL'], port['resource_request']['request_groups'][0]['required'] )", "self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(rule_create_mock_call) < mock_manager.mock_calls.index(update_precommit_mock_call) < mock_manager.mock_calls.index(update_mock_call)) def test_create_policy_rule_check_rule_min_less_than_max(self):", "self.rule_data['bandwidth_limit_rule']['max_kbps'] = 1 self.qos_plugin.update_policy_bandwidth_limit_rule( self.ctxt, self.rule.id, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt)", "qos2 else None qos_network_policy_id = ( qos_network_policy.id if qos_network_policy else", "policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", [self.dscp_rule]) self.qos_plugin.delete_policy_dscp_marking_rule(", "100, 'max_burst_kbps': 150}, 'dscp_marking_rule': {'id': uuidutils.generate_uuid(), 'dscp_mark': 16}, 'minimum_bandwidth_rule': {", "self.qos_plugin, '_get_ports_with_policy', return_value=[port]): self.assertRaises( NotImplementedError, self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt, _policy.id, self.rule_data) def", "self._make_port(network_id=network.id, qos_policy_id=None, device_owner='uu:id') # Port with overwritten QoS policy self._make_port(network_id=network.id,", "self.rule.id, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) rule_update_mock_call = mock.call.update() update_precommit_mock_call =", "test_get_policy_bandwidth_limit_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, self.policy.id)", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.delete_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, self.policy.id) def test_verify_bad_method_call(self):", "self.policy.id) def test_get_pps_rule_type(self): admin_ctxt = context.get_admin_context() drivers_details = [{ 'name':", "port1.bindings = [port1_binding] port1.update() port2 = self._make_port( network_id=network.id, qos_policy_id=None, device_owner='compute:uu:id')", "desired_min_kpps=1000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1, qos2, orig_port,", "mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1, None, orig_port, port) mock_update_qos_alloc.assert_called_once_with(", "'.check_min_pps_rule_conflict', return_value=None): self.qos_plugin.create_policy_bandwidth_limit_rule( self.ctxt, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) rule_create_mock_call =", "self.policy.id) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id) def test_get_policy_min_pps_rules_for_policy_with_filters(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy):", "% (qos.ALIAS, rule_type.replace('_', '-')) request = self.new_show_request(resource, rule_id, self.fmt) res", "{'NET_BW_IGR_KILOBIT_PER_SEC': 1000}}) def test_change_placement_allocation_change_direction_min_pps_and_min_bw( self): qos1 = self._make_qos_policy() qos2 =", "return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.update_policy_packet_rate_limit_rule, self.ctxt, self.pps_rule.id, self.policy.id, self.rule_data) def test_delete_policy_pps_rule_for_nonexistent_policy(self):", "setattr(_policy, \"rules\", []) mock_qos_policy_get.return_value = _policy mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_rule_create,", "= self._get_policy() policy.rules = [self.min_bw_rule] segment = network_object.NetworkSegment( physical_network='fake physnet')", "mock_qos_policy_delete, mock_api_get_policy): mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_policy_delete, 'delete') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock()", "{\"context\": self.context, \"original_port\": { \"id\": port.id, \"device_owner\": \"compute:uu:id\", \"qos_policy_id\": qos1_id,", ") as get_port, mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=policy_mock ) as get_policy, mock.patch.object(", "desired_qos: desired_qos.rules = [] if desired_min_kbps: desired_qos.rules += [self._make_qos_minbw_rule( desired_qos.id,", "with mock.patch('neutron.objects.qos.rule.' 'QosBandwidthLimitRule.' 'get_objects') as get_objects_mock: filters = {'filter': 'filter_id'}", "ports = self._create_and_extend_ports([self.min_bw_rule]) for port in ports: self.assertEqual( 1, len(port['resource_request']['request_groups'])", "self.rule_data['minimum_packet_rate_rule']['direction'] = 'any' setattr(_policy, \"rules\", [self.min_pps_rule]) rules = [ {", "< mock_manager.mock_calls.index(update_mock_call)) @mock.patch('neutron.objects.db.api.get_object', return_value=None) @mock.patch.object(policy_object.QosPolicy, 'delete') def test_delete_policy(self, mock_qos_policy_delete, mock_api_get_policy):", "self.ctxt, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def test_create_policy_min_pps_rule_duplicates(self): _policy = self._get_policy()", "# Port with overwritten QoS policy self._make_port(network_id=network.id, qos_policy_id=port_qos.id, device_owner='compute:uu:id') ml2plugin_mock", "-v5 f02f160e-1612-11ec-b2b8-bf60ab98186c # 8bf8eb46-160e-11ec-8024-9f96be32099d MIN_BW_REQUEST_GROUP_UUID = 'c8bc1b27-59a1-5135-aa33-aeecad6093f4' MIN_BW_RP = 'd7bea120-1626-11ec-9148-c32debfcf0f6'", "test_create_policy_min_pps_rule_duplicates(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.min_pps_rule]) new_rule_data = {", "rule_object.QosMinimumBandwidthRule( self.ctxt, **self.rule_data['minimum_bandwidth_rule']) self.pps_rule = rule_object.QosPacketRateLimitRule( self.ctxt, **self.rule_data['packet_rate_limit_rule']) self.min_pps_rule =", "port1 = self._make_port( network_id=network.id, qos_policy_id=None, device_owner='compute:uu:id') port1_binding = ports_object.PortBinding( self.context,", "1, len(port['resource_request']['request_groups']) ) self.assertEqual( 'fake_uuid', port['resource_request']['request_groups'][0]['id'] ) self.assertEqual( ['CUSTOM_VNIC_TYPE_NORMAL'], port['resource_request']['request_groups'][0]['required']", "\"validate_rule_for_network\", return_value=True ): self.policy.rules = [self.rule] try: self.qos_plugin.validate_policy_for_network( self.ctxt, self.policy,", "orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={ self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': -500, 'NET_PACKET_RATE_EGR_KILOPACKET_PER_SEC':", "'min_kpps': 10, 'direction': 'egress' } }, ] self.rule_data['minimum_packet_rate_rule']['direction'] = 'any'", "\"precommit_create\", \"test_plugin\", payload=events.DBEventPayload( self.context, resource_id=kwargs['port']['id'],)) qos_policy = None if port_qos:", "self.qos_plugin, '_get_ports_with_policy', return_value=[port]): self.assertRaises( NotImplementedError, self.qos_plugin.create_policy_minimum_bandwidth_rule, self.ctxt, policy.id, self.rule_data) def", "original_min_kbps=1000, desired_min_kbps=2000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos_network, desired_qos,", "self._test_validate_update_port_callback( policy_id=policy_id, original_policy_id=policy_id) def test_validate_update_port_callback_policy_removed(self): self._test_validate_update_port_callback( policy_id=None, original_policy_id=uuidutils.generate_uuid()) def _test_validate_update_network_callback(self,", "min_bw_rules, min_pps_rules=None, physical_network='public', request_groups_uuids=None): network_id = uuidutils.generate_uuid() ports_res = [", "uuidutils.generate_uuid(), 'project_id': uuidutils.generate_uuid(), 'name': 'test-policy', 'description': 'Test policy description', 'shared':", "if port_id else uuidutils.generate_uuid() base_mac = ['aa', 'bb', 'cc', 'dd',", "'packet_rate_limit_rule': { 'id': uuidutils.generate_uuid(), 'max_kpps': 20, 'max_burst_kpps': 130}, 'minimum_packet_rate_rule': {", "**self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", [self.rule]) self.qos_plugin.delete_policy_bandwidth_limit_rule( self.ctxt, self.rule.id,", "_pager=mock.ANY, qos_policy_id=self.policy.id) def test_get_policy_min_pps_rules_for_policy_with_filters(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumPacketRateRule.'", "self.admin_ctxt = context.get_admin_context() self.policy_data = { 'policy': {'id': uuidutils.generate_uuid(), 'project_id':", "= '%s/alias-%s-rules' % (qos.ALIAS, rule_type.replace('_', '-')) request = self.new_show_request(resource, rule_id,", "get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id) def test_get_policy_min_pps_rules_for_policy_with_filters(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with", "if original_min_kpps: qos.rules += [self._make_qos_minpps_rule( qos.id, min_kpps=original_min_kpps, rule_id=TestQosPluginDB.QOS_MIN_PPS_RULE_ID)] allocation.update( {TestQosPluginDB.MIN_PPS_REQUEST_GROUP_UUID:", "lib_exc.NotAuthorized, self.qos_plugin.get_rule_type, self.ctxt, qos_consts.RULE_TYPE_PACKET_RATE_LIMIT) def test_create_min_pps_rule_on_bound_port(self): _policy = self._get_policy() setattr(_policy,", "BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either", "mock.Mock() self.rpc_push = mock.patch('neutron.api.rpc.handlers.resources_rpc' '.ResourcesPushRpcApi.push').start() self.context = context.get_admin_context() self.project_id =", "= kwargs['original_port'] qos = original_qos or qos_network_policy qos.rules = []", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", []) self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.update_policy_packet_rate_limit_rule, self.ctxt,", "= request.get_response(self.ext_api) if res.status_int >= webob.exc.HTTPClientError.code: raise webob.exc.HTTPClientError(code=res.status_int) @mock.patch.object(qos_plugin.QoSPlugin, \"update_policy_rule\")", "def test_change_placement_allocation_min_bw_dataplane_enforcement_with_pps( self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() orig_port,", "ports_object.Port( self.ctxt, id=uuidutils.generate_uuid(), network_id=uuidutils.generate_uuid(), device_owner='compute:fake-zone') with mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=policy), \\", "{}}], 'update': [self.ctxt, rule_cls_mock, self.rule.id, self.policy.id, {'fake_rule': {}}], 'delete': [self.ctxt,", "\"rules\", [self.min_pps_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.delete_policy_minimum_packet_rate_rule( self.ctxt, self.min_pps_rule.id, self.policy.id) self._validate_driver_params('update_policy',", "'PORT', 'before_update', 'test_plugin', payload=events.DBEventPayload( context, states=(original_port, port))) mock_alloc_change.assert_called_once_with( qos1_obj, None,", "mock_update_qos_alloc: mock_update_qos_alloc.side_effect = ks_exc.Conflict( response={'errors': [{'code': 'placement.concurrent_update'}]} ) self.assertRaises( neutron_qos_exc.QosPlacementAllocationUpdateConflict,", "_create_and_extend_ports(self, min_bw_rules, min_pps_rules=None, physical_network='public', request_groups_uuids=None): network_id = uuidutils.generate_uuid() ports_res =", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumBandwidthRule.' 'get_objects') as get_objects_mock: filters", "'update': [self.ctxt, rule_cls_mock, self.rule.id, self.policy.id, {'fake_rule': {}}], 'delete': [self.ctxt, rule_cls_mock,", "def test_create_policy_rule(self, mock_qos_rule_create, mock_qos_policy_get): _policy = copy.copy(self.policy) setattr(_policy, \"rules\", [])", "{ orc.NET_PACKET_RATE_EGR_KILOPACKET_PER_SEC: 10, orc.NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC: 20, }, }, port['resource_request']['request_groups'] ) self.assertEqual(", "'QosMinimumBandwidthRule.' 'get_object') as get_object_mock: self.qos_plugin.get_policy_minimum_bandwidth_rule( self.ctxt, self.rule.id, self.policy.id) get_object_mock.assert_called_once_with(self.ctxt, id=self.rule.id)", "'qos_policy_id': None, 'qos_network_policy_id': qos.id}, mock.ANY)] mock_alloc_change.assert_has_calls(mock_alloc_change_calls, any_order=True) port1.update() port2.update() self.assertDictEqual(", "self._make_qos_policy() qos2 = self._make_qos_policy() bw_limit_rule = rule_object.QosDscpMarkingRule(dscp_mark=16) qos2.rules = [bw_limit_rule]", "test_get_policy_minimum_bandwidth_rules_for_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumBandwidthRule.' 'get_objects') as get_objects_mock:", "neutron_lib import constants as lib_constants from neutron_lib import context from", "test_update_policy_min_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.update_policy_minimum_packet_rate_rule, self.ctxt, self.min_pps_rule.id, self.policy.id,", ">= webob.exc.HTTPClientError.code: raise webob.exc.HTTPClientError(code=res.status_int) return self.deserialize(self.fmt, res) def _delete_rule(self, rule_type,", "self.qos_plugin._get_ports_with_policy( self.ctxt, self.policy) self.assertEqual( len(expected_ports), len(policy_ports)) for port in expected_ports:", "**self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", [self.pps_rule]) self.qos_plugin.delete_policy_packet_rate_limit_rule( self.ctxt, self.pps_rule.id,", "rule_id, self.qos_policy_id, {rule_data_name: data})) update_policy_rule_mock.assert_has_calls(calls, any_order=True) @mock.patch.object(qos_plugin.QoSPlugin, \"get_policy_rule\") def test_show_rule(self,", "= {} if is_sriov: binding_prof = { 'pci_slot': '0000:42:41.0', 'pci_vendor_info':", "self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id, filter='filter_id') def test_get_policy_packet_rate_limit_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises(", "mock.patch('neutron.api.rpc.handlers.resources_rpc' '.ResourcesPushRpcApi.push').start() self.context = context.get_admin_context() self.project_id = uuidutils.generate_uuid() def _make_qos_policy(self):", "qos_exc.QoSRulesConflict, self.qos_plugin.create_policy_packet_rate_limit_rule, self.ctxt, _policy.id, new_rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_update_policy_packet_rate_limit_rule(self): _policy", "self._create_and_extend_port([self.min_bw_rule], has_net_qos_policy=True) self.assertEqual( 1, len(port['resource_request']['request_groups']) ) self.assertEqual( 'fake_uuid', port['resource_request']['request_groups'][0]['id'] )", "device_owner='compute:uu:id') port1_binding = ports_object.PortBinding( self.context, port_id=port1.id, host='fake_host1', vnic_type='fake_vnic_type', vif_type='fake_vif_type', profile={})", "self.assertRaises( NotImplementedError, self.qos_plugin.create_policy_minimum_bandwidth_rule, self.ctxt, policy.id, self.rule_data) def test_create_min_bw_rule_on_unbound_port(self): policy =", "\"rules\", [self.min_bw_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.qos_plugin.create_policy_bandwidth_limit_rule( self.ctxt, _policy.id,", "min_pps_rule = rule_object.QosMinimumPacketRateRule( self.ctxt, **rule_data['minimum_packet_rate_rule']) setattr(_policy, \"rules\", [min_pps_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "1000}}) self._assert_pci_info(port) def test_change_placement_allocation_increase_min_pps(self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy()", "[]) self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.delete_policy_packet_rate_limit_rule, self.ctxt, self.pps_rule.id, _policy.id) def test_get_policy_packet_rate_limit_rule(self): with", "\"id\": port_id, qos_consts.QOS_POLICY_ID: policy_id }, \"original_port\": { \"id\": port_id, qos_consts.QOS_POLICY_ID:", "test_update_policy_rule_check_rule_min_pps_direction_conflict(self): _policy = self._get_policy() rules_data = [ { 'minimum_packet_rate_rule': {", "test_change_placement_allocation_qos_network_policy(self): qos_network = self._make_qos_policy() desired_qos = self._make_qos_policy() orig_port, port =", "**self.rule_data['dscp_marking_rule']) self.min_bw_rule = rule_object.QosMinimumBandwidthRule( self.ctxt, **self.rule_data['minimum_bandwidth_rule']) self.pps_rule = rule_object.QosPacketRateLimitRule( self.ctxt,", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.delete_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, self.policy.id) def", "[self.ctxt, rule_cls_mock, self.rule.id, self.policy.id, {'fake_rule': {}}], 'delete': [self.ctxt, rule_cls_mock, self.rule.id,", "qos2 = self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation( qos1, qos2, original_min_kbps=1000,", "neutron.tests.unit.services.qos import base DB_PLUGIN_KLASS = 'neutron.db.db_base_plugin_v2.NeutronDbPluginV2' SERVICE_PLUGIN_KLASS = 'neutron.services.qos.qos_plugin.QoSPlugin' class", "port1_binding = ports_object.PortBinding( self.context, port_id=port1.id, host='fake_host1', vnic_type='fake_vnic_type', vif_type='fake_vif_type', profile={'allocation': 'fake_allocation'})", "qos1, qos2, original_min_kbps=1000, desired_min_kbps=2000, original_min_kpps=500, desired_min_kpps=1000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as", "may obtain # a copy of the License at #", "def test_check_port_for_placement_allocation_change_no_new_policy(self): qos1_obj = self._make_qos_policy() kwargs = self._prepare_for_port_placement_allocation_change( qos1=qos1_obj, qos2=None)", "as get_object_mock: self.qos_plugin.get_policy_bandwidth_limit_rule( self.ctxt, self.rule.id, self.policy.id) get_object_mock.assert_called_once_with(self.ctxt, id=self.rule.id) def test_get_policy_bandwidth_limit_rules_for_policy(self):", "mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_rule_check_rule_minbw_gr_than_bwlimit(self): _policy = self._get_policy() self.rule_data['minimum_bandwidth_rule']['min_kbps'] = 1000000", "= mock.Mock() mock_manager.attach_mock(mock_qos_rule_delete, 'delete') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() _policy = policy_object.QosPolicy(", "'-')) request = self.new_show_request(resource, rule_id, self.fmt) res = request.get_response(self.ext_api) self.assertEqual(webob.exc.HTTPNotFound.code,", "'delete_policy_precommit', self.ctxt, mock.ANY) delete_mock_call = mock.call.driver.call( 'delete_policy', self.ctxt, mock.ANY) self.assertTrue(", "= self._prepare_port_for_placement_allocation( qos1, qos2, original_min_kbps=1000, desired_min_kbps=1000, original_min_kpps=1000, desired_min_kpps=1000) with mock.patch.object(self.qos_plugin._placement_client,", "def test_delete_policy_pps_rule_bad_policy(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy):", "'id': uuidutils.generate_uuid(), 'min_kpps': 1234, 'direction': self.min_pps_rule.direction, }, } with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "Unless required by applicable law or agreed to in writing,", "port1.update() port2 = self._make_port( network_id=network.id, qos_policy_id=None, device_owner='compute:uu:id') port2_binding = ports_object.PortBinding(", "with mock.patch.object( self.qos_plugin.driver_manager, \"validate_rule_for_port\", return_value=False ): self.policy.rules = [self.rule] self.assertRaises(", "test_update_policy_packet_rate_limit_rule(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy,", "def test_change_placement_allocation_increase(self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() orig_port, port", "['fake_uuid'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_bulk_min_bw_rule(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION ports =", "setattr(_policy, \"rules\", [self.rule]) with mock.patch('neutron.objects.qos.rule.get_rules', return_value=[self.rule]), mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.rule_data['bandwidth_limit_rule']['max_kbps']", "rule_id=TestQosPluginDB.QOS_MIN_BW_RULE_ID)] allocation.update( {TestQosPluginDB.MIN_BW_REQUEST_GROUP_UUID: TestQosPluginDB.MIN_BW_RP}) if original_min_kpps: qos.rules += [self._make_qos_minpps_rule( qos.id,", "mock_manager.mock_calls.index(update_precommit_mock_call) < mock_manager.mock_calls.index(update_mock_call)) def test_delete_policy_rule_bad_policy(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy'])", "rule_id): resource = '%s/alias-%s-rules' % (qos.ALIAS, rule_type.replace('_', '-')) request =", "def _test_validate_create_port_callback(self, port_qos=False, network_qos=False): net_qos_obj = self._make_qos_policy() port_qos_obj = self._make_qos_policy()", "as get_objects_mock: filters = {'filter': 'filter_id'} self.qos_plugin.get_policy_packet_rate_limit_rules( self.ctxt, self.policy.id, filters=filters)", "'u:u', 'device_id': 'i:d', 'binding:profile': {}} port = {} with mock.patch.object(self.qos_plugin._placement_client,", "original_min_kbps=1000, original_min_kpps=2000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1, None,", "self._prepare_port_for_placement_allocation( qos1, qos2, original_min_kbps=1000, desired_min_kbps=2000, original_min_kpps=500, desired_min_kpps=1000) for rule in", "self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation( qos1, qos2, original_min_kpps=1000, desired_min_kpps=1000) for", "for port in ports: self.assertEqual( 1, len(port['resource_request']['request_groups']) ) self.assertEqual( 'fake_uuid',", "_policy = self._get_policy() setattr(_policy, \"rules\", [self.min_pps_rule]) new_rule_data = { 'minimum_packet_rate_rule':", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_minimum_packet_rate_rule, self.ctxt, self.min_pps_rule.id, self.policy.id) def test_get_policy_min_pps_rules_for_nonexistent_policy(self):", "rule_id) calls.append(mock.call(mock.ANY, rule_object_class, rule_id, self.qos_policy_id)) get_policy_rule_mock.assert_has_calls(calls, any_order=True) @mock.patch.object(qos_plugin.QoSPlugin, \"delete_policy_rule\") def", "return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, self.policy.id) def test_get_policy_bandwidth_limit_rules_for_nonexistent_policy(self): with", "else: get_port.assert_called_once_with(self.ctxt, id=port_id) get_policy.assert_called_once_with(admin_ctxt, id=policy_id) validate_policy_for_port.assert_called_once_with( self.ctxt, policy_mock, port_mock) def", "self.ctxt) self.rule_data['minimum_bandwidth_rule']['min_kbps'] = 1000 with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.assertRaises( qos_exc.QoSRuleParameterConflict, self.qos_plugin.update_policy_minimum_bandwidth_rule,", "device_id='2', qos_policy_id=qos_policy_id, qos_network_policy_id=qos_network_policy_id, mac_address=mac, id=port_id) port.create() return port def _make_network(self,", "'fake_allocation'} mock_alloc_change.side_effect = fake_change_placement_allocation self.qos_plugin._check_network_for_placement_allocation_change( 'network', 'after_update', ml2plugin_mock, payload=events.DBEventPayload( self.context,", "'i:d', 'binding:profile': {}} port = {} with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as", "qos_rules_alias from neutron import manager from neutron.objects import network as", "def test_validate_policy_for_port_all_rules_valid(self): port = {'id': uuidutils.generate_uuid()} with mock.patch.object( self.qos_plugin.driver_manager, \"validate_rule_for_port\",", "test_get_pps_rule_type(self): admin_ctxt = context.get_admin_context() drivers_details = [{ 'name': 'fake-driver', 'supported_parameters':", "self.ctxt, self.policy.id, new_rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) for rule_data in rules: min_pps_rule", "self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation( qos1, qos2, desired_min_kbps=1000) with mock.patch.object(self.qos_plugin._placement_client,", "[bw_limit_rule] with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(qos1, qos2, orig_port, port)", "self.setup_coreplugin(load_plugins=False) cfg.CONF.set_override(\"core_plugin\", DB_PLUGIN_KLASS) cfg.CONF.set_override(\"service_plugins\", [\"qos\"]) manager.init() self.qos_plugin = directory.get_plugin(plugins_constants.QOS) self.qos_plugin.driver_manager", "self.policy_data) policy_mock_call = mock.call.QosPolicy().create() create_precommit_mock_call = mock.call.driver.call( 'create_policy_precommit', self.ctxt, mock.ANY)", "= { 'bandwidth_limit_rule': { 'max_kbps': 5000, 'direction': self.rule.direction } }", "test_check_port_for_placement_allocation_change_qos_network_policy( self): qos_network = self._make_qos_policy() desired_qos = self._make_qos_policy() kwargs =", "qos_plugin.QoSPlugin._extend_port_resource_request_bulk( ports_res, None) def test__extend_port_resource_request_min_bw_rule(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION port =", "port = {'id': uuidutils.generate_uuid()} with mock.patch.object( self.qos_plugin.driver_manager, \"validate_rule_for_port\", return_value=True ):", "policy_id=None, original_policy_id=uuidutils.generate_uuid()) def test_validate_policy_for_port_rule_not_valid(self): port = {'id': uuidutils.generate_uuid()} with mock.patch.object(", "get_object_mock: self.qos_plugin.get_policy_minimum_packet_rate_rule( self.ctxt, self.min_pps_rule.id, self.policy.id) get_object_mock.assert_called_once_with( self.ctxt, id=self.min_pps_rule.id) def test_get_policy_min_pps_rules_for_policy(self):", "self.ctxt, **self.policy_data['policy']) self.rule = rule_object.QosBandwidthLimitRule( self.ctxt, **self.rule_data['bandwidth_limit_rule']) self.dscp_rule = rule_object.QosDscpMarkingRule(", "None, 'qos_network_policy_id': qos.id}, mock.ANY)] mock_alloc_change.assert_has_calls(mock_alloc_change_calls, any_order=True) port1.update() port2.update() self.assertDictEqual( port1.bindings[0].profile,", "\"rules\", rules) self.mock_qos_load_attr.reset_mock() with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.update_policy_minimum_bandwidth_rule( self.ctxt, self.min_bw_rule.id, self.policy.id,", "= original_qos or qos_network_policy qos.rules = [] allocation = {}", "'supported_rule_types', return_value=qos_consts.VALID_RULE_TYPES): types = self.qos_plugin.get_rule_types(self.ctxt, filters=filters) self.assertEqual(sorted(qos_consts.VALID_RULE_TYPES), sorted(type_['type'] for type_", "'QosPolicy') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() self.qos_plugin.create_policy(self.ctxt, self.policy_data) policy_mock_call = mock.call.QosPolicy().create() create_precommit_mock_call", "'egress' with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1, qos2, orig_port,", "policy_id == original_policy_id: get_port.assert_not_called() get_policy.assert_not_called() validate_policy_for_port.assert_not_called() else: get_port.assert_called_once_with(self.ctxt, id=port_id) get_policy.assert_called_once_with(admin_ctxt,", "self._make_qos_policy() net_qos_id = net_qos_obj.id if network_qos else None port_qos_id =", "}] }] with mock.patch.object( qos_plugin.QoSPlugin, \"supported_rule_type_details\", return_value=drivers_details ): rule_type_details =", "test_add_policy_with_extra_tenant_keyword(self, *mocks): policy_id = uuidutils.generate_uuid() project_id = uuidutils.generate_uuid() tenant_policy =", "get_policy.assert_called_once_with(admin_ctxt, id=policy_id) validate_policy_for_port.assert_called_once_with( self.ctxt, policy_mock, port_mock) def test_validate_update_port_callback_policy_changed(self): self._test_validate_update_port_callback( policy_id=uuidutils.generate_uuid())", "self.min_bw_rule] setattr(_policy, \"rules\", rules) self.mock_qos_load_attr.reset_mock() with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.update_policy_minimum_bandwidth_rule( self.ctxt,", "self._validate_driver_params('update_policy', self.ctxt) def test_create_policy_pps_rule_duplicates(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.pps_rule])", "def test_update_policy_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.update_policy_packet_rate_limit_rule, self.ctxt, self.pps_rule.id,", "qos2, original_min_kbps=1000, desired_min_kbps=2000, original_min_kpps=500, desired_min_kpps=1000) for rule in qos2.rules: rule.direction", "def test_get_min_pps_rule_type(self): admin_ctxt = context.get_admin_context() drivers_details = [{ 'name': 'fake-driver',", "validate_policy_for_ports.assert_called_once_with( self.ctxt, policy_mock, [port_mock_without_own_policy]) def test_validate_update_network_callback_policy_changed(self): self._test_validate_update_network_callback( policy_id=uuidutils.generate_uuid()) def test_validate_update_network_callback_policy_not_changed(self):", "port_res = {\"binding:vnic_type\": \"normal\"} segment_mock = mock.MagicMock(network_id=network_id, physical_network=physical_network) min_pps_rules =", "self.qos_plugin.update_policy_minimum_bandwidth_rule, self.ctxt, self.min_bw_rule.id, self.policy.id, self.rule_data) def test_update_policy_rule_check_rule_minbw_gr_than_bwlimit(self): _policy = self._get_policy()", "test_verify_bad_method_call(self): self.assertRaises(AttributeError, getattr, self.qos_plugin, 'create_policy_bandwidth_limit_rules') def test_get_rule_type(self): admin_ctxt = context.get_admin_context()", "qos2, desired_min_kbps=1000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(qos1, qos2, orig_port,", "self._prepare_port_for_placement_allocation( original_qos, desired_qos, original_min_kpps=2000, desired_min_kpps=1000, is_sriov=True) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as", "qos2, original_min_kpps=1000, desired_min_kpps=1000) for rule in qos2.rules: rule.direction = 'any'", "port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_non_min_bw_or_min_pps_rule(self): port = self._create_and_extend_port([], []) self.assertIsNone(port.get('resource_request')) def", "mock_qos_policy_get.return_value = self.policy mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_policy_update, 'update') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver')", "self._get_policy() self.rule_data['minimum_packet_rate_rule']['direction'] = 'any' setattr(_policy, \"rules\", [self.min_pps_rule]) rules = [", "def test_get_policy_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy, self.ctxt, self.policy.id)", "_pager=mock.ANY, qos_policy_id=self.policy.id) def test_get_policy_dscp_marking_rules_for_policy_with_filters(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosDscpMarkingRule.'", "get_objects_mock: self.qos_plugin.get_policy_minimum_bandwidth_rules( self.ctxt, self.policy.id) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id) def test_get_policy_minimum_bandwidth_rules_for_policy_with_filters(self):", "get_object_mock: self.qos_plugin.get_policy_minimum_bandwidth_rule( self.ctxt, self.rule.id, self.policy.id) get_object_mock.assert_called_once_with(self.ctxt, id=self.rule.id) def test_get_policy_minimum_bandwidth_rules_for_policy(self): with", "[self.min_pps_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.create_policy_minimum_packet_rate_rule( self.ctxt, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt)", "qos_policy = net_qos_obj if qos_policy: mock_validate_policy.assert_called_once_with( self.context, qos_policy, port) else:", "{ 'port': {'id': uuidutils.generate_uuid(), 'network_id': network_id} } if has_qos_policy: self.port_data['port']['qos_policy_id']", "port1.id, 'device_owner': 'compute:uu:id', 'qos_policy_id': None, 'qos_network_policy_id': qos.id}, mock.ANY), mock.call( original_qos,", "get_objects_mock: filters = {'filter': 'filter_id'} self.qos_plugin.get_policy_minimum_bandwidth_rules( self.ctxt, self.policy.id, filters=filters) get_objects_mock.assert_called_once_with(", "_pager=mock.ANY, filter='filter_id') def test_get_policy_dscp_marking_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_dscp_marking_rule,", "self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation( qos1, qos2, original_min_kpps=1000, desired_min_kpps=2000, is_sriov=True)", "self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation( qos1, qos2, original_min_kbps=1000, desired_min_kbps=2000) with", "orig_port, port = self._prepare_port_for_placement_allocation( qos1, qos2, original_min_kbps=1000, desired_min_kbps=2000, is_sriov=True) with", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumBandwidthRule.' 'get_objects') as get_objects_mock: self.qos_plugin.get_policy_minimum_bandwidth_rules( self.ctxt,", "= request.get_response(self.ext_api) if res.status_int >= webob.exc.HTTPClientError.code: raise webob.exc.HTTPClientError(code=res.status_int) return self.deserialize(self.fmt,", "import constants as lib_constants from neutron_lib import context from neutron_lib", "policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", [self.dscp_rule]) self.qos_plugin.create_policy_dscp_marking_rule(", "self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def test_update_policy_dscp_marking_rule(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy'])", "'QosMinimumPacketRateRule.' 'get_object') as get_object_mock: self.qos_plugin.get_policy_minimum_packet_rate_rule( self.ctxt, self.min_pps_rule.id, self.policy.id) get_object_mock.assert_called_once_with( self.ctxt,", "self.policy.id, self.rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_update_policy_min_pps_rule_bad_policy(self): _policy = self._get_policy() setattr(_policy,", "from logs self.patch_notifier = mock.patch( 'neutron.notifiers.batch_notifier.BatchNotifier._notify') self.patch_notifier.start() plugin = 'ml2'", "= rule_id if rule_id else uuidutils.generate_uuid() qos_rule = rule_object.QosMinimumBandwidthRule( self.context,", "= self._prepare_port_for_placement_allocation( qos1, qos2, original_min_kbps=1000, desired_min_kbps=2000, original_min_kpps=500, desired_min_kpps=1000) for rule", "import qos from neutron_lib.callbacks import events from neutron_lib import constants", "self.qos_plugin, \"validate_policy_for_port\" ) as validate_policy_for_port, mock.patch.object( self.ctxt, \"elevated\", return_value=admin_ctxt ):", "= mock.Mock() self.rpc_push = mock.patch('neutron.api.rpc.handlers.resources_rpc' '.ResourcesPushRpcApi.push').start() self.context = context.get_admin_context() self.project_id", "[self.rule] try: self.qos_plugin.validate_policy_for_network( self.ctxt, self.policy, network_id=network) except qos_exc.QosRuleNotSupportedByNetwork: self.fail(\"QosRuleNotSupportedByNetwork \"", "self.qos_plugin._validate_create_port_callback( \"PORT\", \"precommit_create\", \"test_plugin\", payload=events.DBEventPayload( self.context, resource_id=kwargs['port']['id'],)) qos_policy = None", "original_qos, None, {'id': port1.id, 'device_owner': 'compute:uu:id', 'qos_policy_id': None, 'qos_network_policy_id': None},", "'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_no_original_allocation(self):", "= lib_constants.EGRESS_DIRECTION self.min_pps_rule.direction = lib_constants.EGRESS_DIRECTION request_groups_uuids = ['fake_uuid0', 'fake_uuid1'] min_bw_rule_ingress_data", "= self.rule_data[rule_data_name] rule = rule_object_class(self.ctxt, id=rule_id, qos_policy_id=self.qos_policy_id, **data) with mock.patch('neutron.objects.qos.rule.QosRule.get_object',", "self.ctxt, self.policy, network_id=network) except qos_exc.QosRuleNotSupportedByNetwork: self.fail(\"QosRuleNotSupportedByNetwork \" \"exception unexpectedly raised\")", "_policy = self._get_policy() setattr(_policy, \"rules\", [self.min_bw_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.update_policy_minimum_bandwidth_rule(", "mock_manager.reset_mock() with mock.patch('neutron.objects.qos.qos_policy_validator' '.check_bandwidth_rule_conflict', return_value=None), \\ mock.patch( 'neutron.objects.qos.qos_policy_validator' '.check_min_pps_rule_conflict', return_value=None):", "self.rule_data['bandwidth_limit_rule']['max_kbps'] = 1 setattr(_policy, \"rules\", [self.min_bw_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.assertRaises( qos_exc.QoSRuleParameterConflict, self.qos_plugin.update_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, self.policy.id, self.rule_data) def", "= self.new_delete_request(resource, rule_id, self.fmt) res = request.get_response(self.ext_api) if res.status_int >=", "qos2, qos_network_policy=None): qos1_id = qos1.id if qos1 else None qos2_id", "\"rules\", []) self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.delete_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, _policy.id) def test_get_policy_bandwidth_limit_rule(self):", "or policy_id == original_policy_id: get_port.assert_not_called() get_policy.assert_not_called() validate_policy_for_port.assert_not_called() else: get_port.assert_called_once_with(self.ctxt, id=port_id)", "self.mock_qos_load_attr.assert_called_once_with('rules') mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_rule_check_rule_max_more_than_min(self): _policy = self._get_policy() setattr(_policy, \"rules\",", "test_delete_policy_rule(self, mock_qos_rule_delete): mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_rule_delete, 'delete') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock()", "self.rule.id, self.policy.id, {'fake_rule': {}}], 'delete': [self.ctxt, rule_cls_mock, self.rule.id, self.policy.id]} mock_manager", "either express or implied. See the # License for the", "self.assertEqual( ['CUSTOM_VNIC_TYPE_NORMAL'], port['resource_request']['request_groups'][0]['required'] ) self.assertEqual( {orc.NET_PACKET_RATE_KILOPACKET_PER_SEC: 10}, port['resource_request']['request_groups'][0]['resources'], ) self.assertEqual(", "try: self.qos_plugin.validate_policy_for_network( self.ctxt, self.policy, network_id=network) except qos_exc.QosRuleNotSupportedByNetwork: self.fail(\"QosRuleNotSupportedByNetwork \" \"exception", "'required': ['CUSTOM_VNIC_TYPE_NORMAL'], 'resources': { orc.NET_PACKET_RATE_EGR_KILOPACKET_PER_SEC: 10, orc.NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC: 20, }, },", "mock_manager.attach_mock(mock_qos_rule_delete, 'delete') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy'])", "filters=filters) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id, filter='filter_id') def test_get_policy_packet_rate_limit_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "True, 'is_default': False} with mock.patch('neutron.objects.qos.policy.QosPolicy') as QosMocked: self.qos_plugin.create_policy(self.ctxt, tenant_policy) QosMocked.assert_called_once_with(self.ctxt,", "request_groups_uuids = ['fake_uuid0', 'fake_uuid1'] min_bw_rule_ingress_data = { 'id': uuidutils.generate_uuid(), 'min_kbps':", "'dscp_marking': rule_object.QosDscpMarkingRule, 'minimum_bandwidth': rule_object.QosMinimumBandwidthRule } self.qos_policy_id = uuidutils.generate_uuid() self.rule_data =", "self._make_qos_policy() qos = self._make_qos_policy() port_qos = self._make_qos_policy() original_network = self._make_network(original_qos.id)", "'qos_network_policy_id': None}, mock.ANY), ] mock_alloc_change.assert_has_calls(mock_alloc_change_calls, any_order=True) port1.update() self.assertDictEqual(port1.bindings[0].profile, {}) def", "_policy = self._get_policy() setattr(_policy, \"rules\", []) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.assertRaises(", "qos2, orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_no_original_allocation(self): qos1 = self._make_qos_policy() rule1_obj", "None qos2 = self._make_qos_policy() rule2_obj = self._make_qos_minbw_rule(qos2.id, min_kbps=1000) qos2.rules =", "may # not use this file except in compliance with", "port['binding:profile'] = {} mock_alloc_change.side_effect = fake_change_placement_allocation self.qos_plugin._check_network_for_placement_allocation_change( 'network', 'after_update', ml2plugin_mock,", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.delete_policy_minimum_packet_rate_rule( self.ctxt, self.min_pps_rule.id, self.policy.id) self._validate_driver_params('update_policy', self.ctxt) def test_delete_policy_min_pps_rule_bad_policy(self):", "port = self._create_and_extend_port([self.min_bw_rule], [self.min_pps_rule], physical_network=None) self.assertEqual( 1, len(port['resource_request']['request_groups']) ) self.assertEqual(", "= 'f02f160e-1612-11ec-b2b8-bf60ab98186c' QOS_MIN_BW_RULE_ID = '8bf8eb46-160e-11ec-8024-9f96be32099d' # uuid -v5 f02f160e-1612-11ec-b2b8-bf60ab98186c #", "'neutron.objects.ports.Port.get_objects', return_value=ports ) as get_ports, mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=policy_mock ) as", "[self.min_bw_rule, min_bw_rule_ingress], [self.min_pps_rule, min_pps_rule_ingress], request_groups_uuids=request_groups_uuids) self.assertEqual( 2, len(port['resource_request']['request_groups']) ) self.assertIn(", "self.min_pps_rule.id, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def test_update_policy_rule_check_rule_min_pps_direction_conflict(self): _policy = self._get_policy()", "rule_object.QosDscpMarkingRule(dscp_mark=16) orig_port, port = self._prepare_port_for_placement_allocation( qos1, qos2, desired_min_kbps=2000) qos1.rules =", "= [port1_binding] port1.update() with mock.patch.object( self.qos_plugin, '_change_placement_allocation') as mock_alloc_change: def", "_policy = self._get_policy() self.rule_data['minimum_packet_rate_rule']['direction'] = 'any' setattr(_policy, \"rules\", [self.min_pps_rule]) rules", "return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumBandwidthRule.' 'get_object') as get_object_mock: self.qos_plugin.get_policy_minimum_bandwidth_rule( self.ctxt, self.rule.id,", "def test_create_min_pps_rule_on_unbound_port(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.min_pps_rule]) segment =", "{'NET_BW_IGR_KILOBIT_PER_SEC': -1000}}) self._assert_pci_info(port) def test_change_placement_allocation_decrease_min_pps(self): original_qos = self._make_qos_policy() desired_qos =", "mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_rule_duplicates(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.rule])", "self.ctxt, self.policy.id, {'policy': fields}) self._validate_driver_params('update_policy', self.ctxt) policy_update_mock_call = mock.call.update() update_precommit_mock_call", "self.ctxt, **min_bw_rule_ingress_data) min_pps_rule_ingress = rule_object.QosMinimumPacketRateRule( self.ctxt, **min_pps_rule_ingress_data) port = self._create_and_extend_port(", "new_rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) for rule_data in rules: min_pps_rule = rule_object.QosMinimumPacketRateRule(", "self.fmt) res = request.get_response(self.ext_api) self.assertEqual(webob.exc.HTTPNotFound.code, res.status_int) class TestQoSRuleAliasMinimumPacketRate(TestQoSRuleAlias): def setUp(self):", "return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosDscpMarkingRule.' 'get_objects') as get_objects_mock: filters = {'filter':", "ports_res, None) def test__extend_port_resource_request_min_bw_rule(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION port = self._create_and_extend_port([self.min_bw_rule])", "{'type': 'type_id'} with mock.patch.object(qos_plugin.QoSPlugin, 'supported_rule_types', return_value=qos_consts.VALID_RULE_TYPES): types = self.qos_plugin.get_rule_types(self.ctxt, filters=filters)", "self.ctxt, policy_mock, port_mock) def test_validate_update_port_callback_policy_changed(self): self._test_validate_update_port_callback( policy_id=uuidutils.generate_uuid()) def test_validate_update_port_callback_policy_not_changed(self): policy_id", "policy_id=None, original_policy_id=None): network_id = uuidutils.generate_uuid() kwargs = { \"context\": self.ctxt,", "self.pps_rule.id, self.policy.id) def test_get_policy_packet_rate_limit_rules_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_packet_rate_limit_rules,", "qos_policy_id=self.policy.id, filter='filter_id') def test_get_policy_min_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_minimum_packet_rate_rule,", "net_qos_obj.id if network_qos else None port_qos_id = port_qos_obj.id if port_qos", "qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_bandwidth_limit_rules, self.ctxt, self.policy.id) def test_create_policy_dscp_marking_rule(self): _policy = policy_object.QosPolicy( self.ctxt,", "rules: with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt, self.policy.id,", "'3' port = ports_object.Port( self.context, network_id=network_id, device_owner=device_owner, project_id=self.project_id, admin_state_up=True, status='DOWN',", "= self._make_qos_policy() kwargs = self._prepare_for_port_placement_allocation_change( qos1=qos1_obj, qos2=None) kwargs['port'].pop('qos_policy_id') context =", "host='fake_host2', vnic_type='fake_vnic_type', vif_type='fake_vif_type', profile={}) port2_binding.create() port2.bindings = [port2_binding] port2.update() with", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumPacketRateRule.' 'get_objects') as get_objects_mock: self.qos_plugin.get_policy_minimum_packet_rate_rules(", "qos.rules += [self._make_qos_minbw_rule( qos.id, min_kbps=original_min_kbps, rule_id=TestQosPluginDB.QOS_MIN_BW_RULE_ID)] allocation.update( {TestQosPluginDB.MIN_BW_REQUEST_GROUP_UUID: TestQosPluginDB.MIN_BW_RP}) if", "self.qos_plugin.get_policy, self.ctxt, self.policy.id) def test_get_policy_bandwidth_limit_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound,", "qos as qos_exc from neutron_lib.objects import utils as obj_utils from", "the License is distributed on an \"AS IS\" BASIS, WITHOUT", "def test_create_policy_packet_rate_limit_rule(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy):", "= self._make_network(qos_policy_id=net_qos_id) kwargs = {\"context\": self.context, \"network\": network} with mock.patch.object(self.qos_plugin,", "= net_qos_obj if qos_policy: mock_validate_policy.assert_called_once_with( self.context, qos_policy, port) else: mock_validate_policy.assert_not_called()", "'egress' } }, ] for new_rule_data in rules: with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "test_change_placement_allocation_no_original_qos(self): qos1 = None qos2 = self._make_qos_policy() rule2_obj = self._make_qos_minbw_rule(qos2.id,", "rule_object_class in self.rule_objects.items(): rule_id = uuidutils.generate_uuid() with mock.patch('neutron.objects.qos.rule.QosRule.get_object', return_value=None): resource", "else None network = self._make_network(qos_policy_id=net_qos_id) kwargs = {\"context\": self.context, \"network\":", "self._get_policy() setattr(_policy, \"rules\", [self.min_pps_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.delete_policy_minimum_packet_rate_rule( self.ctxt, self.min_pps_rule.id,", "def _test_validate_create_network_callback(self, network_qos=False): net_qos_obj = self._make_qos_policy() net_qos_id = net_qos_obj.id if", "= 'ml2' service_plugins = {'qos_plugin_name': SERVICE_PLUGIN_KLASS} ext_mgr = QoSRuleAliasMinimumPacketRateTestExtensionManager() super(TestQoSRuleAlias,", "port.qos_network_policy_id, } ml2plugin_mock._make_port_dict.side_effect = fake_make_port_dict port1 = self._make_port( network_id=network.id, qos_policy_id=None,", "'PORT', 'before_update', 'test_plugin', payload=events.DBEventPayload( context, states=(original_port, port))) mock_alloc_change.assert_called_once_with( qos1_obj, qos2_obj,", "else: mock_validate_policy.assert_not_called() def test_validate_create_network_callback(self): self._test_validate_create_network_callback(network_qos=True) def test_validate_create_network_callback_no_qos(self): self._test_validate_create_network_callback(network_qos=False) def _test_validate_create_port_callback(self,", "desired_qos, qos_network_policy=qos_network, original_min_kbps=1000, desired_min_kbps=2000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(", "mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1, None, orig_port, port) mock_update_qos_alloc.assert_not_called()", "return_value=None), \\ mock.patch( 'neutron.objects.qos.qos_policy_validator' '.check_min_pps_rule_conflict', return_value=None): self.qos_plugin.create_policy_bandwidth_limit_rule( self.ctxt, self.policy.id, self.rule_data)", "self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy, self.ctxt, self.policy.id) def test_get_policy_bandwidth_limit_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None):", "if port.qos_policy_id is None] expected_ports = ports + expected_network_ports with", "policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", [self.pps_rule]) self.qos_plugin.create_policy_packet_rate_limit_rule(", "\"rules\", []) self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.update_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, self.policy.id, self.rule_data) @mock.patch.object(rule_object.QosBandwidthLimitRule,", "< mock_manager.mock_calls.index(update_mock_call)) def test_delete_policy_rule_bad_policy(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with", "network_qos: qos_policy = net_qos_obj if qos_policy: mock_validate_policy.assert_called_once_with( self.context, qos_policy, network.id)", "port = self._prepare_port_for_placement_allocation(qos1, original_min_kbps=1000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(", "**min_bw_rule_ingress_data) min_pps_rule_ingress = rule_object.QosMinimumPacketRateRule( self.ctxt, **min_pps_rule_ingress_data) port = self._create_and_extend_port( [self.min_bw_rule,", "test_change_placement_allocation_equal_minkbps_and_minkpps(self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() orig_port, port =", "setattr(_policy, \"rules\", [self.min_pps_rule]) new_rule_data = { 'minimum_packet_rate_rule': { 'id': uuidutils.generate_uuid(),", "{ 'NET_BW_IGR_KILOBIT_PER_SEC': -1000, 'NET_BW_EGR_KILOBIT_PER_SEC': 2000}}) def test_change_placement_allocation_change_dir_min_pps_ingress_to_any( self): qos1 =", "['CUSTOM_VNIC_TYPE_NORMAL'], 'resources': { orc.NET_PACKET_RATE_EGR_KILOPACKET_PER_SEC: 10, orc.NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC: 20, }, }, port['resource_request']['request_groups']", "= [self.rule] self.assertRaises( qos_exc.QosRuleNotSupported, self.qos_plugin.validate_policy_for_port, self.ctxt, self.policy, port) def test_validate_policy_for_port_all_rules_valid(self):", "physical_network=physical_network) min_pps_rules = min_pps_rules if min_pps_rules else [] with mock.patch('neutron.objects.network.NetworkSegment.get_objects',", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.update_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, self.policy.id, self.rule_data) def", ") self.assertEqual( ['CUSTOM_VNIC_TYPE_NORMAL'], port['resource_request']['request_groups'][0]['required'] ) self.assertEqual( {orc.NET_PACKET_RATE_KILOPACKET_PER_SEC: 10}, port['resource_request']['request_groups'][0]['resources'], )", "self._make_qos_policy() desired_qos = self._make_qos_policy() kwargs = self._prepare_for_port_placement_allocation_change( qos1=None, qos2=desired_qos, qos_network_policy=qos_network)", "< mock_manager.mock_calls.index(update_precommit_mock_call) < mock_manager.mock_calls.index(update_mock_call)) def test_delete_policy_rule_bad_policy(self): _policy = policy_object.QosPolicy( self.ctxt,", "10, 'direction': 'ingress' } }, { 'minimum_packet_rate_rule': { 'id': uuidutils.generate_uuid(),", "= 'any' with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.assertRaises(NotImplementedError, self.qos_plugin._change_placement_allocation, qos1,", "self.ctxt, self.pps_rule.id, self.policy.id, self.rule_data) def test_delete_policy_packet_rate_limit_rule(self): _policy = policy_object.QosPolicy( self.ctxt,", "'get_objects') as get_objects_mock: self.qos_plugin.get_policy_packet_rate_limit_rules( self.ctxt, self.policy.id) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id)", "self.qos_plugin.delete_policy_packet_rate_limit_rule( self.ctxt, self.pps_rule.id, self.policy.id) self._validate_driver_params('update_policy', self.ctxt) def test_delete_policy_pps_rule_bad_policy(self): _policy =", "self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.delete_policy_minimum_packet_rate_rule, self.ctxt, self.min_pps_rule.id, self.policy.id) def test_get_policy_min_pps_rule(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "as net_utils import os_resource_classes as orc from oslo_config import cfg", "\"update_policy_rule\") def test_update_rule(self, update_policy_rule_mock): calls = [] for rule_type, rule_object_class", "port = self._prepare_port_for_placement_allocation( qos1, qos2, original_min_kbps=1000, desired_min_kbps=2000, is_sriov=True) with mock.patch.object(self.qos_plugin._placement_client,", "mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() fields = obj_utils.get_updatable_fields( policy_object.QosPolicy, self.policy_data['policy']) self.qos_plugin.update_policy( self.ctxt,", "rule_cls_mock = mock.Mock() rule_cls_mock.rule_type = 'fake' rule_actions = {'create': [self.ctxt,", "self.min_pps_rule.id, self.policy.id, self.rule_data) def test_update_policy_min_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound,", "qos.id, min_kbps=original_min_kbps, rule_id=TestQosPluginDB.QOS_MIN_BW_RULE_ID)] allocation.update( {TestQosPluginDB.MIN_BW_REQUEST_GROUP_UUID: TestQosPluginDB.MIN_BW_RP}) if original_min_kpps: qos.rules +=", "self.rule.id, self.policy.id, self.rule_data) self.mock_qos_load_attr.assert_called_once_with('rules') self._validate_driver_params('update_policy', self.ctxt) rules = [self.rule, self.min_bw_rule]", "'after_update', ml2plugin_mock, payload=events.DBEventPayload( self.context, states=(original_network, network))) mock_alloc_change.assert_not_called() ml2plugin_mock._make_port_dict.assert_not_called() def test_check_network_for_placement_allocation_change_remove_qos(self):", "mock.patch.object( self.qos_plugin, '_get_ports_with_policy', return_value=[port]): try: self.qos_plugin.create_policy_minimum_packet_rate_rule( self.ctxt, _policy.id, self.rule_data) except", "@mock.patch('neutron.objects.ports.Port') @mock.patch('neutron.objects.qos.policy.QosPolicy') def test_rule_notification_and_driver_ordering(self, qos_policy_mock, port_mock): rule_cls_mock = mock.Mock() rule_cls_mock.rule_type", "direction=direction, min_kbps=min_kbps, id=rule_id) qos_rule.create() return qos_rule def _make_qos_minpps_rule(self, policy_id, direction='ingress',", "self._prepare_for_port_placement_allocation_change( original_qos, desired_qos, qos_network_policy=qos_network_policy) orig_port = kwargs['original_port'] qos = original_qos", "self.ctxt, _policy.id, new_rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) @mock.patch.object(rule_object.QosBandwidthLimitRule, 'update') def test_update_policy_rule(self, mock_qos_rule_update):", "[port2_binding] port2.update() with mock.patch.object( self.qos_plugin, '_change_placement_allocation') as mock_alloc_change: def fake_change_placement_allocation(orig_policy,", "test_change_placement_allocation_no_original_allocation(self): qos1 = self._make_qos_policy() rule1_obj = self._make_qos_minbw_rule(qos1.id, min_kbps=500) qos1.rules =", "'policy': {'id': uuidutils.generate_uuid(), 'project_id': uuidutils.generate_uuid(), 'name': 'test-policy', 'description': 'Test policy", "'get_object') as get_object_mock: self.qos_plugin.get_policy_bandwidth_limit_rule( self.ctxt, self.rule.id, self.policy.id) get_object_mock.assert_called_once_with(self.ctxt, id=self.rule.id) def", "mock.patch.object( self.policy, \"get_bound_networks\" ), mock.patch.object( self.policy, \"get_bound_ports\" ): policy_ports =", "test_delete_policy_dscp_marking_rule(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy,", "mock_alloc_change: def fake_change_placement_allocation(orig_policy, policy, orig_port, port): port['binding:profile'] = {} mock_alloc_change.side_effect", "min_pps_rule_ingress = rule_object.QosMinimumPacketRateRule( self.ctxt, **min_pps_rule_ingress_data) ports = self._create_and_extend_ports( [self.min_bw_rule, min_bw_rule_ingress],", "= lib_constants.EGRESS_DIRECTION request_groups_uuids = ['fake_uuid0', 'fake_uuid1'] * 2 min_bw_rule_ingress_data =", "**self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", []) self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.update_policy_packet_rate_limit_rule,", "qos_consts.RULE_TYPE_PACKET_RATE_LIMIT) def test_create_min_pps_rule_on_bound_port(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.min_pps_rule]) segment", "port = self._prepare_port_for_placement_allocation( qos1, qos2, desired_min_kbps=1000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as", "return_value=_policy): setattr(_policy, \"rules\", [self.pps_rule]) self.qos_plugin.delete_policy_packet_rate_limit_rule( self.ctxt, self.pps_rule.id, self.policy.id) self._validate_driver_params('update_policy', self.ctxt)", "'shared': True, 'is_default': False}} self.rule_data = { 'bandwidth_limit_rule': {'id': uuidutils.generate_uuid(),", "self.qos_plugin.delete_policy_minimum_packet_rate_rule( self.ctxt, self.min_pps_rule.id, self.policy.id) self._validate_driver_params('update_policy', self.ctxt) def test_delete_policy_min_pps_rule_bad_policy(self): _policy =", "bw_limit_rule2 = rule_object.QosDscpMarkingRule(dscp_mark=18) qos1.rules = [bw_limit_rule1] qos2.rules = [bw_limit_rule2] orig_port", "= mock.call.driver.call( 'delete_policy', self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(policy_delete_mock_call) < mock_manager.mock_calls.index(delete_precommit_mock_call) <", "return port def _make_network(self, qos_policy_id=None): network = network_object.Network(self.context, qos_policy_id=qos_policy_id) network.create()", "_assert_pci_info(self, port): self.assertIn('pci_slot', port['binding:profile']) self.assertIn('pci_vendor_info', port['binding:profile']) self.assertIn('physical_network', port['binding:profile']) def test_change_placement_allocation_increase(self):", "states=(original_port, port))) mock_alloc_change.assert_called_once_with( qos1_obj, None, kwargs['original_port'], port) def test_check_port_for_placement_allocation_change_no_qos_update(self): qos1_obj", "with overwritten QoS policy self._make_port(network_id=network.id, qos_policy_id=port_qos.id, device_owner='compute:uu:id') ml2plugin_mock = mock.MagicMock()", "= 'd7bea120-1626-11ec-9148-c32debfcf0f6' QOS_MIN_PPS_RULE_ID = '6ac5db7e-1626-11ec-8c7f-0b70dbb8a8eb' # uuid -v5 f02f160e-1612-11ec-b2b8-bf60ab98186c #", "get_rule_mock_call = getattr( mock.call.QosPolicy.get_policy_obj().get_rule_by_id(), action)() # some actions construct rule", "-1000}}) self._assert_pci_info(port) def test_change_placement_allocation_decrease_min_pps(self): original_qos = self._make_qos_policy() desired_qos = self._make_qos_policy()", "'create_policy_bandwidth_limit_rules') def test_get_rule_type(self): admin_ctxt = context.get_admin_context() drivers_details = [{ 'name':", "{'create': [self.ctxt, rule_cls_mock, self.policy.id, {'fake_rule': {}}], 'update': [self.ctxt, rule_cls_mock, self.rule.id,", "self.policy.id) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id) def test_get_policy_bandwidth_limit_rules_for_policy_with_filters(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy):", "get_actions(self): return [] def get_request_extensions(self): return [] class QoSRuleAliasMinimumPacketRateTestExtensionManager(object): def", "def test_change_placement_allocation_new_policy_empty(self): qos1 = self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation(qos1, original_min_kbps=1000,", "= None if network_qos: qos_policy = net_qos_obj if qos_policy: mock_validate_policy.assert_called_once_with(", "port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={ self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': 500}}) def test_change_placement_allocation_decrease(self):", "'shared': True, 'is_default': False} with mock.patch('neutron.objects.qos.policy.QosPolicy') as QosMocked: self.qos_plugin.create_policy(self.ctxt, tenant_policy)", "test_create_policy_pps_rule_duplicates(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.pps_rule]) new_rule_data = {", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", [self.pps_rule]) self.qos_plugin.update_policy_packet_rate_limit_rule( self.ctxt, self.pps_rule.id, self.policy.id, self.rule_data)", "= self._make_qos_policy() qos2 = self._make_qos_policy() bw_limit_rule = rule_object.QosDscpMarkingRule(dscp_mark=16) orig_port, port", "device_owner=None): port_id = port_id if port_id else uuidutils.generate_uuid() base_mac =", "= {} if original_min_kbps: qos.rules += [self._make_qos_minbw_rule( qos.id, min_kbps=original_min_kbps, rule_id=TestQosPluginDB.QOS_MIN_BW_RULE_ID)]", "self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def test_update_policy_pps_rule_bad_policy(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy'])", "def _test_validate_update_port_callback(self, policy_id=None, original_policy_id=None): port_id = uuidutils.generate_uuid() kwargs = {", "mock.patch.object(self.qos_plugin, 'validate_policy_for_network') \\ as mock_validate_policy: self.qos_plugin._validate_create_network_callback( \"NETWORK\", \"precommit_create\", \"test_plugin\", payload=events.DBEventPayload(", "}, { 'minimum_packet_rate_rule': { 'id': uuidutils.generate_uuid(), 'min_kpps': 10, 'direction': 'egress'", "# Remove MissingAuthPlugin exception from logs self.patch_notifier = mock.patch( 'neutron.notifiers.batch_notifier.BatchNotifier._notify')", "test_get_policy_minimum_bandwidth_rules_for_policy_with_filters(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumBandwidthRule.' 'get_objects') as get_objects_mock:", "if port_qos: qos_policy = port_qos_obj elif network_qos: qos_policy = net_qos_obj", "def get_actions(self): return [] def get_request_extensions(self): return [] class TestQoSRuleAlias(test_db_base_plugin_v2.NeutronDbPluginV2TestCase):", "qos1, qos2, original_min_kbps=1000, desired_min_kbps=2000, original_min_kpps=500, desired_min_kpps=1000) for rule in qos2.rules:", "-1000}}) self._assert_pci_info(port) def test_change_placement_allocation_no_original_qos(self): qos1 = None qos2 = self._make_qos_policy()", "return_value=_policy): self.qos_plugin.update_policy_minimum_bandwidth_rule( self.ctxt, self.min_bw_rule.id, self.policy.id, self.rule_data) self.mock_qos_load_attr.assert_called_once_with('rules') self._validate_driver_params('update_policy', self.ctxt) self.rule_data['bandwidth_limit_rule']['max_kbps']", "self.rpc_push = mock.patch('neutron.api.rpc.handlers.resources_rpc' '.ResourcesPushRpcApi.push').start() self.context = context.get_admin_context() self.project_id = uuidutils.generate_uuid()", "test__extend_port_resource_request_bulk_min_pps_rule(self): ports = self._create_and_extend_ports([], [self.min_pps_rule]) for port in ports: self.assertEqual(", "or policy_id == original_policy_id: get_policy.assert_not_called() validate_policy_for_network.assert_not_called() get_ports.assert_not_called() validate_policy_for_ports.assert_not_called() else: get_policy.assert_called_once_with(admin_ctxt,", "neutron_lib.exceptions import qos as qos_exc from neutron_lib.objects import utils as", "= mock.call.driver.call( 'create_policy', self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(policy_mock_call) < mock_manager.mock_calls.index(create_precommit_mock_call) <", "[]) self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.update_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, self.policy.id, self.rule_data) @mock.patch.object(rule_object.QosBandwidthLimitRule, 'delete')", "False}} self.rule_data = { 'bandwidth_limit_rule': {'id': uuidutils.generate_uuid(), 'max_kbps': 100, 'max_burst_kbps':", "SERVICE_PLUGIN_KLASS = 'neutron.services.qos.qos_plugin.QoSPlugin' class TestQosPlugin(base.BaseQosTestCase): def setUp(self): super(TestQosPlugin, self).setUp() self.setup_coreplugin(load_plugins=False)", "network_object.Network( self.ctxt, segments=[segment]) port = ports_object.Port( self.ctxt, id=uuidutils.generate_uuid(), network_id=uuidutils.generate_uuid(), device_owner='')", "mock.patch('neutron.objects.qos.rule.' 'QosPacketRateLimitRule.' 'get_object') as get_object_mock: self.qos_plugin.get_policy_packet_rate_limit_rule( self.ctxt, self.pps_rule.id, self.policy.id) get_object_mock.assert_called_once_with(self.ctxt,", "self.ctxt, self.policy.id, self.rule_data) def test_update_policy_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound,", "test_change_placement_allocation_no_min_bw(self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() bw_limit_rule1 = rule_object.QosDscpMarkingRule(dscp_mark=16)", "lib_constants.EGRESS_DIRECTION port = self._create_and_extend_port([self.min_bw_rule], physical_network=None) self.assertIsNone(port.get('resource_request')) def test__extend_port_resource_request_mix_rules_non_provider_net(self): self.min_bw_rule.direction =", "self._prepare_port_for_placement_allocation( qos1, qos2, desired_min_kbps=1000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(qos1,", "self.assertEqual( {orc.NET_PACKET_RATE_KILOPACKET_PER_SEC: 10}, port['resource_request']['request_groups'][0]['resources'], ) self.assertEqual( ['fake_uuid'], port['resource_request']['same_subtree'], ) def", "self.rule_data) def test_delete_policy_packet_rate_limit_rule(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "def test_change_placement_allocation_increase_min_pps(self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() orig_port, port", "self.policy.id, self.rule_data) def _get_policy(self): return policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) def test_update_policy_rule_bad_policy(self):", "'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1, None, orig_port, port) mock_update_qos_alloc.assert_not_called() def", "_policy mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_rule_create, 'create') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() with", ") self.assertEqual( ['fake_uuid'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_min_pps_rule(self): port = self._create_and_extend_port([],", "= lib_constants.EGRESS_DIRECTION port = self._create_and_extend_port([self.min_bw_rule], physical_network=None) self.assertIsNone(port.get('resource_request')) def test__extend_port_resource_request_mix_rules_non_provider_net(self): self.min_bw_rule.direction", "'minimum_bandwidth_rule': {'min_kbps': 10} } def _update_rule(self, rule_type, rule_id, **kwargs): data", "rule_type data = self.rule_data[rule_data_name] rule = rule_object_class(self.ctxt, id=rule_id, qos_policy_id=self.qos_policy_id, **data)", "desired_min_kbps=2000, original_min_kpps=500, desired_min_kpps=1000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1,", "**rules_data[0]['minimum_packet_rate_rule']), rule_object.QosMinimumPacketRateRule( self.ctxt, **rules_data[1]['minimum_packet_rate_rule']), ] setattr(_policy, 'rules', rules) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "SERVICE_PLUGIN_KLASS} ext_mgr = QoSRuleAliasMinimumPacketRateTestExtensionManager() super(TestQoSRuleAlias, self).setUp(plugin=plugin, ext_mgr=ext_mgr, service_plugins=service_plugins) self.qos_plugin =", "min_pps_rule_ingress = rule_object.QosMinimumPacketRateRule( self.ctxt, **min_pps_rule_ingress_data) port = self._create_and_extend_port( [self.min_bw_rule, min_bw_rule_ingress],", "self.assertRaises( qos_exc.QoSRulesConflict, self.qos_plugin.create_policy_packet_rate_limit_rule, self.ctxt, _policy.id, new_rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_update_policy_packet_rate_limit_rule(self):", "test_get_policy_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy, self.ctxt, self.policy.id) def", "self.context, qos_policy, port) else: mock_validate_policy.assert_not_called() def test_validate_create_port_callback_policy_on_port(self): self._test_validate_create_port_callback(port_qos=True) def test_validate_create_port_callback_policy_on_port_and_network(self):", "qos2=desired_qos, qos_network_policy=qos_network) context = kwargs['context'] original_port = kwargs['original_port'] port =", "'network_id': network_id} } if has_qos_policy: self.port_data['port']['qos_policy_id'] = self.policy.id elif has_net_qos_policy:", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumBandwidthRule.' 'get_object') as get_object_mock: self.qos_plugin.get_policy_minimum_bandwidth_rule(", "port) def test_validate_policy_for_port_all_rules_valid(self): port = {'id': uuidutils.generate_uuid()} with mock.patch.object( self.qos_plugin.driver_manager,", "any_order=True) def test_show_non_existing_rule(self): for rule_type, rule_object_class in self.rule_objects.items(): rule_id =", "ports] ), mock.patch.object( self.policy, \"get_bound_networks\" ), mock.patch.object( self.policy, \"get_bound_ports\" ):", "'any' setattr(_policy, \"rules\", [self.min_pps_rule]) rules = [ { 'minimum_packet_rate_rule': {", "self.min_pps_rule.id, self.policy.id) def test_get_policy_min_pps_rule(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumPacketRateRule.'", "'neutron.objects.ports.Port.get_object', return_value=port_mock ) as get_port, mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=policy_mock ) as", "kwargs = self._prepare_for_port_placement_allocation_change( qos1=qos1_obj, qos2=qos1_obj) context = kwargs['context'] original_port =", "from neutron_lib.plugins import directory from neutron_lib.services.qos import constants as qos_consts", "port = self._prepare_port_for_placement_allocation( qos1, qos2, original_min_kbps=1000, desired_min_kbps=2000, original_min_kpps=500, desired_min_kpps=1000) for", "has_net_qos_policy: self.port_data['port']['qos_network_policy_id'] = self.policy.id self.port = ports_object.Port( self.ctxt, **self.port_data['port']) port_res", "some actions get rule from policy get_rule_mock_call = getattr( mock.call.QosPolicy.get_policy_obj().get_rule_by_id(),", "with mock.patch.object( self.qos_plugin.driver_manager, \"validate_rule_for_port\", return_value=True ): self.policy.rules = [self.rule] try:", "[] class QoSRuleAliasMinimumPacketRateTestExtensionManager(object): def get_resources(self): return qos_pps_minimum_rule_alias.Qos_pps_minimum_rule_alias.\\ get_resources() def get_actions(self):", "return_value=_policy): setattr(_policy, \"rules\", []) self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.delete_policy_packet_rate_limit_rule, self.ctxt, self.pps_rule.id, _policy.id)", "self._get_policy() policy.rules = [self.min_bw_rule] segment = network_object.NetworkSegment( physical_network='fake physnet') net", "'supported_parameters': [{ 'parameter_name': 'min_kpps', 'parameter_type': lib_constants.VALUES_TYPE_RANGE, 'parameter_range': {'start': 0, 'end':", "= '%s/alias-%s-rules' % (qos.ALIAS, rule_type.replace('_', '-')) request = self.new_delete_request(resource, rule_id,", "qos1.id if qos1 else None qos2_id = qos2.id if qos2", "ports: self.assertEqual( 2, len(port['resource_request']['request_groups']) ) self.assertIn( { 'id': 'fake_uuid0', 'required':", "**data) calls.append(mock.call(mock.ANY, rule_object_class, rule_id, self.qos_policy_id, {rule_data_name: data})) update_policy_rule_mock.assert_has_calls(calls, any_order=True) @mock.patch.object(qos_plugin.QoSPlugin,", ") def test__extend_port_resource_request_non_min_bw_or_min_pps_rule(self): port = self._create_and_extend_port([], []) self.assertIsNone(port.get('resource_request')) def test__extend_port_resource_request_min_bw_non_provider_net(self):", "self.assertRaises( lib_exc.NotAuthorized, self.qos_plugin.get_rule_type, self.ctxt, qos_consts.RULE_TYPE_PACKET_RATE_LIMIT) def test_create_min_pps_rule_on_bound_port(self): _policy = self._get_policy()", "return_value='fake_uuid', side_effect=request_groups_uuids): return qos_plugin.QoSPlugin._extend_port_resource_request( port_res, self.port) def _create_and_extend_ports(self, min_bw_rules, min_pps_rules=None,", "network_id=network_id) validate_policy_for_ports.assert_called_once_with( self.ctxt, policy_mock, [port_mock_without_own_policy]) def test_validate_update_network_callback_policy_changed(self): self._test_validate_update_network_callback( policy_id=uuidutils.generate_uuid()) def", "payload=events.DBEventPayload( self.context, states=(original_network, network))) self.assertEqual(ml2plugin_mock._make_port_dict.call_count, 1) mock_alloc_change_calls = [ mock.call(", "self.policy.id) def test_create_policy_dscp_marking_rule(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "mock_qos_get_obj: self.qos_plugin.create_policy_bandwidth_limit_rule( self.ctxt, _policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) self.mock_qos_load_attr.assert_called_once_with('rules') mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id)", "self.rule_objects.items(): rule_id = uuidutils.generate_uuid() with mock.patch('neutron.objects.qos.rule.QosRule.get_object', return_value=None): resource = '%s/alias-%s-rules'", "self.ctxt, _policy.id, new_rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_update_policy_packet_rate_limit_rule(self): _policy = policy_object.QosPolicy(", "_pager=mock.ANY, qos_policy_id=self.policy.id) def test_get_policy_minimum_bandwidth_rules_for_policy_with_filters(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumBandwidthRule.'", "policy_mock = mock.MagicMock(id=policy_id) admin_ctxt = mock.Mock() with mock.patch( 'neutron.objects.ports.Port.get_object', return_value=port_mock", "ports_object.Port( self.ctxt, id=uuidutils.generate_uuid(), network_id=uuidutils.generate_uuid(), device_owner='') with mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=policy), \\", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "return_value=port_mock ) as get_port, mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=policy_mock ) as get_policy,", "< mock_manager.mock_calls.index(delete_precommit_mock_call) < mock_manager.mock_calls.index(delete_mock_call)) @mock.patch.object(policy_object.QosPolicy, \"get_object\") @mock.patch.object(rule_object.QosBandwidthLimitRule, 'create') def test_create_policy_rule(self,", "qos1_obj = self._make_qos_policy() qos2_obj = self._make_qos_policy() kwargs = self._prepare_for_port_placement_allocation_change( qos1=qos1_obj,", "test_validate_update_network_callback_policy_removed(self): self._test_validate_update_network_callback( policy_id=None, original_policy_id=uuidutils.generate_uuid()) def test_validate_policy_for_port_rule_not_valid(self): port = {'id': uuidutils.generate_uuid()}", "with mock.patch('neutron.objects.qos.rule.' 'QosMinimumBandwidthRule.' 'get_object') as get_object_mock: self.qos_plugin.get_policy_minimum_bandwidth_rule( self.ctxt, self.rule.id, self.policy.id)", "mock_manager.reset_mock() method = getattr(self.qos_plugin, \"%s_policy_rule\" % action) method(*arguments) # some", "'NET_BW_IGR_KILOBIT_PER_SEC': -1000, 'NET_BW_EGR_KILOBIT_PER_SEC': 2000}}) def test_change_placement_allocation_change_dir_min_pps_ingress_to_any( self): qos1 = self._make_qos_policy()", "'.create_rbac_policy') @mock.patch.object(policy_object.QosPolicy, 'update') def test_update_policy(self, mock_qos_policy_update, mock_create_rbac_policy, mock_qos_policy_get): mock_qos_policy_get.return_value =", "'minimum_packet_rate': rule_object.QosMinimumPacketRateRule } self.qos_policy_id = uuidutils.generate_uuid() self.rule_data = { 'minimum_packet_rate_rule':", "= self._get_policy() setattr(_policy, \"rules\", [self.min_bw_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.update_policy_minimum_bandwidth_rule( self.ctxt,", "self.ctxt, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def test_update_policy_dscp_marking_rule(self): _policy = policy_object.QosPolicy(", "\"rules\", [self.pps_rule]) self.qos_plugin.update_policy_packet_rate_limit_rule( self.ctxt, self.pps_rule.id, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def", "exception from logs self.patch_notifier = mock.patch( 'neutron.notifiers.batch_notifier.BatchNotifier._notify') self.patch_notifier.start() plugin =", "'Test policy description', 'shared': True, 'is_default': False}} policy_details = {'id':", "qos2_id}} def test_check_port_for_placement_allocation_change_no_qos_change(self): qos1_obj = self._make_qos_policy() kwargs = self._prepare_for_port_placement_allocation_change( qos1=qos1_obj,", "self.ctxt, mock.ANY) update_mock_call = mock.call.driver.call( 'update_policy', self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(rule_delete_mock_call)", "{ 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': 1000}}) self._assert_pci_info(port) def test_change_placement_allocation_increase_min_pps_and_min_bw(self): qos1 = self._make_qos_policy() qos2", "'device_id': 'uu:id', 'id': '9416c220-160a-11ec-ba3d-474633eb825c', } port = {} with mock.patch.object(self.qos_plugin._placement_client,", "mock_qos_policy, mock_create_rbac_policy): mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_policy, 'QosPolicy') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock()", "= mock.call.driver.call( 'delete_policy_precommit', self.ctxt, mock.ANY) delete_mock_call = mock.call.driver.call( 'delete_policy', self.ctxt,", "else [] with mock.patch('neutron.objects.network.NetworkSegment.get_objects', return_value=[segment_mock]), \\ mock.patch( 'neutron.objects.qos.rule.QosMinimumBandwidthRule.' 'get_objects', return_value=min_bw_rules),", "qos as neutron_qos_exc from neutron.extensions import qos_pps_minimum_rule_alias from neutron.extensions import", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.update_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, self.policy.id, self.rule_data)", "qos_policy_id=self.policy.id) def test_get_policy_minimum_bandwidth_rules_for_policy_with_filters(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumBandwidthRule.' 'get_objects')", "device_owner='compute:fake-zone') with mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=policy), \\ mock.patch( 'neutron.objects.network.Network.get_object', return_value=net), \\", "qos_network = self._make_qos_policy() desired_qos = self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation(", "mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_policy_update, 'update') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() fields =", "self.policy.id) def test_verify_bad_method_call(self): self.assertRaises(AttributeError, getattr, self.qos_plugin, 'create_policy_bandwidth_limit_rules') def test_get_rule_type(self): admin_ctxt", "self.policy.id) get_object_mock.assert_called_once_with(self.ctxt, id=self.pps_rule.id) def test_get_policy_packet_rate_limit_rules_for_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.'", "ports_res = [ { \"resource_request\": { \"port_id\": uuidutils.generate_uuid(), \"qos_id\": self.policy.id,", "self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION self.min_bw_rule.qos_policy_id = self.policy.id port = self._create_and_extend_port([self.min_bw_rule], has_net_qos_policy=True)", "return_value=_policy) as mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.create_policy_minimum_bandwidth_rule, self.ctxt, self.policy.id, self.rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id)", "self.policy_data = { 'policy': {'id': uuidutils.generate_uuid(), 'project_id': uuidutils.generate_uuid(), 'name': 'test-policy',", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.create_policy_bandwidth_limit_rule, self.ctxt, self.policy.id, self.rule_data) def", "self._create_and_extend_port([], physical_network='public', has_qos_policy=False) self.assertIsNone(port.get('resource_request')) def test__extend_port_resource_request_min_bw_inherited_policy( self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION", "self.qos_plugin.update_policy_minimum_packet_rate_rule, self.ctxt, self.min_pps_rule.id, self.policy.id, self.rule_data) def test_delete_policy_min_pps_rule(self): _policy = self._get_policy()", "drivers_details, rule_type_details['drivers']) def test_get_min_pps_rule_type_as_user(self): self.assertRaises( lib_exc.NotAuthorized, self.qos_plugin.get_rule_type, self.ctxt, qos_consts.RULE_TYPE_MINIMUM_PACKET_RATE) class", "mock.Mock() with mock.patch( 'neutron.objects.ports.Port.get_objects', return_value=ports ) as get_ports, mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object',", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosBandwidthLimitRule.' 'get_objects') as get_objects_mock: self.qos_plugin.get_policy_bandwidth_limit_rules( self.ctxt,", "[self.min_pps_rule]) new_rule_data = { 'minimum_packet_rate_rule': { 'id': uuidutils.generate_uuid(), 'min_kpps': 1234,", "self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt, self.policy.id, self.rule_data) def test_update_policy_min_pps_rule(self): _policy = self._get_policy() setattr(_policy,", "self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.update_policy_minimum_packet_rate_rule, self.ctxt, self.min_pps_rule.id, self.policy.id, self.rule_data) def test_delete_policy_min_pps_rule(self): _policy", "[ { \"resource_request\": { \"port_id\": uuidutils.generate_uuid(), \"qos_id\": self.policy.id, \"network_id\": network_id,", ") return orig_port, kwargs['port'] def _assert_pci_info(self, port): self.assertIn('pci_slot', port['binding:profile']) self.assertIn('pci_vendor_info',", "self.assertEqual( 1, len(port['resource_request']['request_groups']) ) self.assertEqual( 'fake_uuid', port['resource_request']['request_groups'][0]['id'] ) self.assertEqual( ['CUSTOM_PHYSNET_PUBLIC',", "return_value=_policy): setattr(_policy, \"rules\", []) self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.update_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, self.policy.id,", "rules = [ { 'minimum_packet_rate_rule': { 'id': uuidutils.generate_uuid(), 'min_kpps': 10,", "= ['fake_uuid0', 'fake_uuid1'] * 2 min_bw_rule_ingress_data = { 'id': uuidutils.generate_uuid(),", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "'_get_ports_with_policy', return_value=[port]): self.assertRaises( NotImplementedError, self.qos_plugin.create_policy_minimum_bandwidth_rule, self.ctxt, policy.id, self.rule_data) def test_create_min_bw_rule_on_unbound_port(self):", "mock.MagicMock(id=port_id, qos_policy_id=policy_id) policy_mock = mock.MagicMock(id=policy_id) admin_ctxt = mock.Mock() with mock.patch(", "get_policy.assert_not_called() validate_policy_for_port.assert_not_called() else: get_port.assert_called_once_with(self.ctxt, id=port_id) get_policy.assert_called_once_with(admin_ctxt, id=policy_id) validate_policy_for_port.assert_called_once_with( self.ctxt, policy_mock,", "port = self._prepare_port_for_placement_allocation( qos1, qos2, desired_min_kbps=1000, original_min_kpps=500, desired_min_kpps=1000) with mock.patch.object(self.qos_plugin._placement_client,", "self.qos_plugin._change_placement_allocation( original_qos, desired_qos, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC':", "vif_type='fake_vif_type', profile={}) port1_binding.create() port1.bindings = [port1_binding] port1.update() port2 = self._make_port(", "mock_qos_policy_update, mock_create_rbac_policy, mock_qos_policy_get): mock_qos_policy_get.return_value = self.policy mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_policy_update,", "as get_object_mock: self.qos_plugin.get_policy_packet_rate_limit_rule( self.ctxt, self.pps_rule.id, self.policy.id) get_object_mock.assert_called_once_with(self.ctxt, id=self.pps_rule.id) def test_get_policy_packet_rate_limit_rules_for_policy(self):", "qos_exc.QosPolicyNotFound, self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt, self.policy.id, self.rule_data) def test_update_policy_min_pps_rule(self): _policy = self._get_policy()", "self.rule_data = { 'bandwidth_limit_rule': {'id': uuidutils.generate_uuid(), 'max_kbps': 100, 'max_burst_kbps': 150},", "} } port_mock = mock.MagicMock(id=port_id, qos_policy_id=policy_id) policy_mock = mock.MagicMock(id=policy_id) admin_ctxt", "\"original_port\": { \"id\": port.id, \"device_owner\": \"compute:uu:id\", \"qos_policy_id\": qos1_id, \"qos_network_policy_id\": qos_network_policy_id},", "test_delete_policy_min_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.delete_policy_minimum_packet_rate_rule, self.ctxt, self.min_pps_rule.id, self.policy.id)", "test_update_policy_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.update_policy_packet_rate_limit_rule, self.ctxt, self.pps_rule.id, self.policy.id,", ">= webob.exc.HTTPClientError.code: raise webob.exc.HTTPClientError(code=res.status_int) @mock.patch.object(qos_plugin.QoSPlugin, \"update_policy_rule\") def test_update_rule(self, update_policy_rule_mock): calls", "in self.rule_objects.items(): rule_id = uuidutils.generate_uuid() with mock.patch('neutron.objects.qos.rule.QosRule.get_object', return_value=None): resource =", "network = original_network ml2plugin_mock = mock.MagicMock() with mock.patch.object( self.qos_plugin, '_change_placement_allocation')", "): rule_type_details = self.qos_plugin.get_rule_type( admin_ctxt, qos_consts.RULE_TYPE_MINIMUM_PACKET_RATE) self.assertEqual( qos_consts.RULE_TYPE_MINIMUM_PACKET_RATE, rule_type_details['type']) self.assertEqual(", "is_sriov=True) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1, qos2, orig_port,", "ports_object.Port( self.ctxt, **self.port_data['port']) port_res = {\"binding:vnic_type\": \"normal\"} segment_mock = mock.MagicMock(network_id=network_id,", "qos = self._make_qos_policy() port_qos = self._make_qos_policy() original_network = self._make_network(original_qos.id) network", "mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_old_rule_not_min_bw(self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() bw_limit_rule", "< mock_manager.mock_calls.index(update_mock_call)) def test_update_policy_rule_check_rule_min_less_than_max(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.rule])", "return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosDscpMarkingRule.' 'get_objects') as get_objects_mock: self.qos_plugin.get_policy_dscp_marking_rules( self.ctxt, self.policy.id)", "request_groups_uuids=None): network_id = uuidutils.generate_uuid() self.port_data = { 'port': {'id': uuidutils.generate_uuid(),", "self.qos_plugin.update_policy_bandwidth_limit_rule( self.ctxt, self.rule.id, self.policy.id, self.rule_data) self.mock_qos_load_attr.assert_called_once_with('rules') self._validate_driver_params('update_policy', self.ctxt) self.rule_data['minimum_bandwidth_rule']['min_kbps'] =", "policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", [self.dscp_rule]) self.qos_plugin.update_policy_dscp_marking_rule(", "'dscp_mark': 16}, 'minimum_bandwidth_rule': { 'id': uuidutils.generate_uuid(), 'min_kbps': 10}, 'packet_rate_limit_rule': {", "original_min_kpps=1000, desired_min_kpps=2000, is_sriov=True) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1,", "qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_min_bw_dataplane_enforcement(self): qos1 = self._make_qos_policy()", "\"normal\"} segment_mock = mock.MagicMock(network_id=network_id, physical_network=physical_network) min_pps_rules = min_pps_rules if min_pps_rules", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.create_policy_minimum_packet_rate_rule( self.ctxt, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def", "orig_port, port = self._prepare_port_for_placement_allocation( qos1, qos2, desired_min_kbps=1000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation')", "qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_minimum_packet_rate_rule, self.ctxt, self.min_pps_rule.id, self.policy.id) def test_get_policy_min_pps_rules_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None):", "= kwargs['port'] with mock.patch.object( self.qos_plugin, '_change_placement_allocation') as mock_alloc_change: self.qos_plugin._check_port_for_placement_allocation_change( 'PORT',", "mock.call.driver.call( 'delete_policy', self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(policy_delete_mock_call) < mock_manager.mock_calls.index(delete_precommit_mock_call) < mock_manager.mock_calls.index(delete_mock_call))", "= {'filter': 'filter_id'} self.qos_plugin.get_policy_packet_rate_limit_rules( self.ctxt, self.policy.id, filters=filters) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY,", "mock.patch.object(self.qos_plugin, 'validate_policy_for_port') \\ as mock_validate_policy: self.qos_plugin._validate_create_port_callback( \"PORT\", \"precommit_create\", \"test_plugin\", payload=events.DBEventPayload(", "= self._prepare_port_for_placement_allocation( qos1, qos2, original_min_kpps=1000, desired_min_kpps=2000, is_sriov=True) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation')", "rule_create_mock_call = mock.call.create() update_precommit_mock_call = mock.call.driver.call( 'update_policy_precommit', self.ctxt, mock.ANY) update_mock_call", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, self.policy.id) def test_get_policy_bandwidth_limit_rules_for_nonexistent_policy(self):", "self.rule_data[rule_data_name] rule = rule_object_class(self.ctxt, id=rule_id, qos_policy_id=self.qos_policy_id, **data) with mock.patch( 'neutron.objects.qos.rule.QosRule.get_object',", "create_precommit_mock_call = mock.call.driver.call( 'create_policy_precommit', self.ctxt, mock.ANY) create_mock_call = mock.call.driver.call( 'create_policy',", "qos_policy_id=None): network = network_object.Network(self.context, qos_policy_id=qos_policy_id) network.create() return network def _test_validate_create_network_callback(self,", "_test_validate_update_network_callback(self, policy_id=None, original_policy_id=None): network_id = uuidutils.generate_uuid() kwargs = { \"context\":", "uuidutils.generate_uuid() ports_res = [ { \"resource_request\": { \"port_id\": uuidutils.generate_uuid(), \"qos_id\":", "self.assertRaises( lib_exc.NotAuthorized, self.qos_plugin.get_rule_type, self.ctxt, qos_consts.RULE_TYPE_BANDWIDTH_LIMIT) def test_get_rule_types(self): filters = {'type':", "self._get_policy() setattr(_policy, \"rules\", [self.pps_rule]) new_rule_data = { 'packet_rate_limit_rule': { 'max_kpps':", "self.context, states=(original_network, network))) self.assertEqual(ml2plugin_mock._make_port_dict.call_count, 1) mock_alloc_change_calls = [ mock.call( original_qos,", "def test_get_policy_dscp_marking_rules(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosDscpMarkingRule.' 'get_objects') as", "self.rule.id, self.policy.id) def test_get_policy_bandwidth_limit_rules_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_bandwidth_limit_rules,", "**self.rule_data['minimum_packet_rate_rule']) def _validate_driver_params(self, method_name, ctxt): call_args = self.qos_plugin.driver_manager.call.call_args[0] self.assertTrue(self.qos_plugin.driver_manager.call.called) self.assertEqual(call_args[0],", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.update_policy_bandwidth_limit_rule( self.ctxt, self.rule.id, self.policy.id, self.rule_data) self.mock_qos_load_attr.assert_called_once_with('rules') self._validate_driver_params('update_policy', self.ctxt)", "self.ctxt, **min_pps_rule_ingress_data) port = self._create_and_extend_port( [self.min_bw_rule, min_bw_rule_ingress], [self.min_pps_rule, min_pps_rule_ingress], request_groups_uuids=request_groups_uuids)", "'QosMinimumBandwidthRule.' 'get_objects') as get_objects_mock: filters = {'filter': 'filter_id'} self.qos_plugin.get_policy_minimum_bandwidth_rules( self.ctxt,", "500}, self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': 1000}}) def test_change_placement_allocation_change_direction_min_pps_and_min_bw( self): qos1 = self._make_qos_policy()", "mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_min_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.create_policy_minimum_packet_rate_rule,", "def _create_and_extend_port(self, min_bw_rules, min_pps_rules=None, physical_network='public', has_qos_policy=True, has_net_qos_policy=False, request_groups_uuids=None): network_id =", "return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_minimum_bandwidth_rule, self.ctxt, self.rule.id, self.policy.id) def test_get_policy_minimum_bandwidth_rules_for_nonexistent_policy(self): with", "new_rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_update_policy_packet_rate_limit_rule(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy'])", "self.policy.id, self.rule_data) def test_update_policy_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.update_policy_packet_rate_limit_rule,", "_make_port(self, network_id, qos_policy_id=None, port_id=None, qos_network_policy_id=None, device_owner=None): port_id = port_id if", "qos2.rules = [bw_limit_rule] orig_port, port = self._prepare_port_for_placement_allocation(qos1, original_min_kbps=1000) with mock.patch.object(self.qos_plugin._placement_client,", "= rule_object.QosMinimumBandwidthRule( self.ctxt, **min_bw_rule_ingress_data) min_pps_rule_ingress = rule_object.QosMinimumPacketRateRule( self.ctxt, **min_pps_rule_ingress_data) port", "return_value=drivers_details ): rule_type_details = self.qos_plugin.get_rule_type( admin_ctxt, qos_consts.RULE_TYPE_PACKET_RATE_LIMIT) self.assertEqual( qos_consts.RULE_TYPE_PACKET_RATE_LIMIT, rule_type_details['type'])", "return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.update_policy_minimum_packet_rate_rule, self.ctxt, self.min_pps_rule.id, self.policy.id, self.rule_data) def test_delete_policy_min_pps_rule(self):", "get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id, filter='filter_id') def test_get_policy_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None):", "return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_packet_rate_limit_rule, self.ctxt, self.pps_rule.id, self.policy.id) def test_get_policy_packet_rate_limit_rules_for_nonexistent_policy(self): with", "try: self.qos_plugin.validate_policy_for_port( self.ctxt, self.policy, port) except qos_exc.QosRuleNotSupported: self.fail(\"QosRuleNotSupported exception unexpectedly", "@mock.patch.object(rule_object.QosBandwidthLimitRule, 'delete') def test_delete_policy_rule(self, mock_qos_rule_delete): mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_rule_delete, 'delete')", "= mock.Mock() mock_manager.attach_mock(qos_policy_mock, 'QosPolicy') mock_manager.attach_mock(port_mock, 'Port') mock_manager.attach_mock(rule_cls_mock, 'RuleCls') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver')", "uuidutils.generate_uuid(), \"qos_id\": self.policy.id, \"network_id\": network_id, \"vnic_type\": \"normal\", } }, ]", "\"precommit_update\", \"test_plugin\", payload=events.DBEventPayload( self.ctxt, desired_state=kwargs['port'], states=(kwargs['original_port'],))) if policy_id is None", "self.rule.id, self.policy.id, self.rule_data) self.mock_qos_load_attr.assert_called_once_with('rules') self._validate_driver_params('update_policy', self.ctxt) self.rule_data['minimum_bandwidth_rule']['min_kbps'] = 1000 with", "self.rule_data) def test_update_policy_min_pps_rule(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.min_pps_rule]) with", "} self.policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) self.rule = rule_object.QosBandwidthLimitRule( self.ctxt,", "'id': uuidutils.generate_uuid(), 'min_kpps': 10, 'direction': 'egress' } }, ] self.rule_data['minimum_packet_rate_rule']['direction']", "}, } with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises( qos_exc.QoSRulesConflict, self.qos_plugin.create_policy_minimum_packet_rate_rule,", "self.rule_data) self.mock_qos_load_attr.assert_called_once_with('rules') self._validate_driver_params('update_policy', self.ctxt) self.rule_data['minimum_bandwidth_rule']['min_kbps'] = 1000 with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy):", "= lib_constants.EGRESS_DIRECTION port = self._create_and_extend_port([self.min_bw_rule]) self.assertEqual( 1, len(port['resource_request']['request_groups']) ) self.assertEqual(", "binding_prof, 'device_id': 'uu:id'} ) return orig_port, kwargs['port'] def _assert_pci_info(self, port):", "None) network = self._make_network(qos_policy_id=qos_network_policy_id) port = self._make_port( network.id, qos_policy_id=qos1_id, port_id=TestQosPluginDB.PORT_ID)", "self._get_policy() setattr(_policy, \"rules\", [self.min_bw_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.update_policy_minimum_bandwidth_rule( self.ctxt, self.min_bw_rule.id,", "{'filter': 'filter_id'} self.qos_plugin.get_policy_minimum_packet_rate_rules( self.ctxt, self.policy.id, filters=filters) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id,", "self.qos_plugin, \"validate_policy_for_network\" ) as validate_policy_for_network, mock.patch.object( self.qos_plugin, \"validate_policy_for_ports\" ) as", "'max_kbps': 5000, 'direction': self.rule.direction } } with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as", "\"validate_rule_for_port\", return_value=False ): self.policy.rules = [self.rule] self.assertRaises( qos_exc.QosRuleNotSupported, self.qos_plugin.validate_policy_for_port, self.ctxt,", "test_update_policy_rule_bad_policy(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy,", "} }, ] self.rule_data['minimum_packet_rate_rule']['direction'] = 'any' for rule_data in rules_data:", "new_rule_data in rules: with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.create_policy_minimum_packet_rate_rule,", "mock_manager.mock_calls.index(create_precommit_mock_call) < mock_manager.mock_calls.index(create_mock_call)) def test_add_policy_with_extra_tenant_keyword(self, *mocks): policy_id = uuidutils.generate_uuid() project_id", ") as validate_policy_for_ports, mock.patch.object( self.ctxt, \"elevated\", return_value=admin_ctxt ): self.qos_plugin._validate_update_network_callback( \"NETWORK\",", "as get_objects_mock: filters = {'filter': 'filter_id'} self.qos_plugin.get_policy_minimum_bandwidth_rules( self.ctxt, self.policy.id, filters=filters)", "\"rules\", [self.min_pps_rule]) rules = [ { 'minimum_packet_rate_rule': { 'id': uuidutils.generate_uuid(),", "self.ctxt, rule_data['minimum_packet_rate_rule']['id'], self.policy.id, self.rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_update_policy_min_pps_rule_bad_policy(self): _policy =", "orig_port, port = self._prepare_port_for_placement_allocation( qos1, qos2, original_min_kpps=1000, desired_min_kpps=2000, is_sriov=True) with", "if qos_policy: mock_validate_policy.assert_called_once_with( self.context, qos_policy, network.id) else: mock_validate_policy.assert_not_called() def test_validate_create_network_callback(self):", "= ports_object.PortBinding( self.context, port_id=port1.id, host='fake_host1', vnic_type='fake_vnic_type', vif_type='fake_vif_type', profile={}) port1_binding.create() port1.bindings", "with mock.patch('neutron.objects.qos.rule.' 'QosMinimumPacketRateRule.' 'get_objects') as get_objects_mock: self.qos_plugin.get_policy_minimum_packet_rate_rules( self.ctxt, self.policy.id) get_objects_mock.assert_called_once_with(", "qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() bw_limit_rule = rule_object.QosDscpMarkingRule(dscp_mark=16) qos2.rules", "consumer_uuid='uu:id', alloc_diff={self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': -1000}}) self._assert_pci_info(port) def test_change_placement_allocation_no_original_qos(self): qos1 =", "mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=policy), \\ mock.patch( 'neutron.objects.network.Network.get_object', return_value=net), \\ mock.patch.object( self.qos_plugin,", "= { 'pci_slot': '0000:42:41.0', 'pci_vendor_info': '8086:107ed', 'physical_network': 'sriov_phy' } binding_prof.update({'allocation':", "return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_packet_rate_limit_rules, self.ctxt, self.policy.id) def test_create_policy_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "the specific language governing permissions and limitations # under the", "_policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) self.mock_qos_load_attr.assert_called_once_with('rules') mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_rule_check_rule_bwlimit_less_than_minbw(self): _policy", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumPacketRateRule.' 'get_objects') as get_objects_mock: self.qos_plugin.get_policy_minimum_packet_rate_rules( self.ctxt,", "= self._make_port( network.id, qos_policy_id=qos1_id, port_id=TestQosPluginDB.PORT_ID) return {\"context\": self.context, \"original_port\": {", "= ['aa', 'bb', 'cc', 'dd', 'ee', 'ff'] mac = netaddr.EUI(next(net_utils.random_mac_generator(base_mac)))", "self.qos_plugin.update_policy_packet_rate_limit_rule, self.ctxt, self.pps_rule.id, self.policy.id, self.rule_data) def test_delete_policy_packet_rate_limit_rule(self): _policy = policy_object.QosPolicy(", "desired_min_kbps=1000, is_sriov=True) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( original_qos, desired_qos,", "'end': 100} }] }] with mock.patch.object( qos_plugin.QoSPlugin, \"supported_rule_type_details\", return_value=drivers_details ):", "under the Apache License, Version 2.0 (the \"License\"); you may", "self._get_policy() setattr(_policy, \"rules\", [self.rule]) new_rule_data = { 'bandwidth_limit_rule': { 'max_kbps':", "mock_alloc_change.assert_not_called() def test_check_port_for_placement_allocation_change_qos_network_policy( self): qos_network = self._make_qos_policy() desired_qos = self._make_qos_policy()", "orig_port = { 'binding:profile': {'allocation': { self.MIN_BW_REQUEST_GROUP_UUID: self.MIN_BW_RP}}, 'device_id': 'uu:id',", "def test_get_policy_packet_rate_limit_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_packet_rate_limit_rule, self.ctxt, self.pps_rule.id,", "mock.patch('neutron.objects.qos.rule.' 'QosBandwidthLimitRule.' 'get_objects') as get_objects_mock: self.qos_plugin.get_policy_bandwidth_limit_rules( self.ctxt, self.policy.id) get_objects_mock.assert_called_once_with( self.ctxt,", "except NotImplementedError: self.fail() def test_create_policy_rule_check_rule_min_pps_direction_conflict(self): _policy = self._get_policy() self.rule_data['minimum_packet_rate_rule']['direction'] =", "mock.patch( 'neutron.objects.ports.Port.get_object', return_value=port_mock ) as get_port, mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=policy_mock )", "{'min_kpps': 10, 'direction': 'any'} } class TestQosPluginDB(base.BaseQosTestCase): PORT_ID = 'f02f160e-1612-11ec-b2b8-bf60ab98186c'", "\\ mock.patch.object( self.qos_plugin, '_get_ports_with_policy', return_value=[port]): self.assertRaises( NotImplementedError, self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt, _policy.id,", "**self.port_data['port']) port_res = {\"binding:vnic_type\": \"normal\"} segment_mock = mock.MagicMock(network_id=network_id, physical_network=physical_network) min_pps_rules", "= directory.get_plugin(plugins_constants.QOS) self.qos_plugin.driver_manager = mock.Mock() self.rpc_push = mock.patch('neutron.api.rpc.handlers.resources_rpc' '.ResourcesPushRpcApi.push').start() self.context", "network = network_object.Network(self.context, qos_policy_id=qos_policy_id) network.create() return network def _test_validate_create_network_callback(self, network_qos=False):", "orig_port, port = self._prepare_port_for_placement_allocation( qos1, qos2, original_min_kbps=1000, desired_min_kbps=1000, original_min_kpps=1000, desired_min_kpps=1000)", "\"rules\", [self.rule]) self.qos_plugin.delete_policy_bandwidth_limit_rule( self.ctxt, self.rule.id, _policy.id) self._validate_driver_params('update_policy', self.ctxt) rule_delete_mock_call =", "get_policy_rule_mock.assert_has_calls(calls, any_order=True) @mock.patch.object(qos_plugin.QoSPlugin, \"delete_policy_rule\") def test_delete_rule(self, delete_policy_rule_mock): calls = []", "uuidutils.generate_uuid(), 'max_kpps': 20, 'max_burst_kpps': 130}, 'minimum_packet_rate_rule': { 'id': uuidutils.generate_uuid(), 'min_kpps':", "self.ctxt, **self.rule_data['packet_rate_limit_rule']) self.min_pps_rule = rule_object.QosMinimumPacketRateRule( self.ctxt, **self.rule_data['minimum_packet_rate_rule']) def _validate_driver_params(self, method_name,", "self.assertRaises( qos_exc.QoSRulesConflict, self.qos_plugin.create_policy_bandwidth_limit_rule, self.ctxt, _policy.id, new_rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) @mock.patch.object(rule_object.QosBandwidthLimitRule, 'update')", ") self.assertEqual( {orc.NET_PACKET_RATE_KILOPACKET_PER_SEC: 10}, port['resource_request']['request_groups'][0]['resources'], ) self.assertEqual( ['fake_uuid'], port['resource_request']['same_subtree'], )", "is None] expected_ports = ports + expected_network_ports with mock.patch( 'neutron.objects.ports.Port.get_objects',", "def test_delete_policy_rule(self, mock_qos_rule_delete): mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_rule_delete, 'delete') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver')", "construct rule from class reference rule_mock_call = getattr(mock.call.RuleCls(), action)() driver_mock_call", "import os_resource_classes as orc from oslo_config import cfg from oslo_utils", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "if policy_id is None or policy_id == original_policy_id: get_policy.assert_not_called() validate_policy_for_network.assert_not_called()", "if qos1 else None qos2_id = qos2.id if qos2 else", "_test_validate_create_network_callback(self, network_qos=False): net_qos_obj = self._make_qos_policy() net_qos_id = net_qos_obj.id if network_qos", "desired_min_kbps=2000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos_network, desired_qos, orig_port,", "self._validate_driver_params('update_policy', self.ctxt) def test_update_policy_rule_check_rule_bwlimit_less_than_minbw(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.rule])", "tenant_policy = { 'policy': {'id': policy_id, 'project_id': project_id, 'tenant_id': project_id,", "self.ctxt, self.dscp_rule.id, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def test_delete_policy_dscp_marking_rule(self): _policy =", "self._validate_driver_params('update_policy', self.ctxt) def test_update_policy_rule_check_rule_min_pps_direction_conflict(self): _policy = self._get_policy() rules_data = [", "network))) mock_alloc_change.assert_not_called() ml2plugin_mock._make_port_dict.assert_not_called() def test_check_network_for_placement_allocation_change_no_ports_to_update( self): original_qos = self._make_qos_policy() qos", "allocation.update( {TestQosPluginDB.MIN_BW_REQUEST_GROUP_UUID: TestQosPluginDB.MIN_BW_RP}) if original_min_kpps: qos.rules += [self._make_qos_minpps_rule( qos.id, min_kpps=original_min_kpps,", "self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation( qos1, qos2, original_min_kbps=1000, desired_min_kbps=2000, is_sriov=True)", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "10, orc.NET_BW_IGR_KILOBIT_PER_SEC: 20}, }, port['resource_request']['request_groups'] ) self.assertIn( { 'id': 'fake_uuid1',", "def test__extend_port_resource_request_mix_rules_non_provider_net(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION port = self._create_and_extend_port([self.min_bw_rule], [self.min_pps_rule], physical_network=None)", "drivers_details = [{ 'name': 'fake-driver', 'supported_parameters': [{ 'parameter_name': 'min_kpps', 'parameter_type':", "network_id=uuidutils.generate_uuid(), device_owner='') with mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=policy), \\ mock.patch( 'neutron.objects.network.Network.get_object', return_value=net),", "if desired_min_kpps: desired_qos.rules += [self._make_qos_minpps_rule( desired_qos.id, min_kpps=desired_min_kpps)] binding_prof = {}", "return_value=_policy): self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.update_policy_minimum_packet_rate_rule, self.ctxt, self.min_pps_rule.id, self.policy.id, self.rule_data) def test_update_policy_min_pps_rule_for_nonexistent_policy(self):", "= self._make_port(network.id, qos_policy_id=port_qos_id) kwargs = {\"context\": self.context, \"port\": {\"id\": port.id}}", "1000}, self.MIN_BW_RP: { 'NET_BW_IGR_KILOBIT_PER_SEC': -1000, 'NET_BW_EGR_KILOBIT_PER_SEC': 2000}}) def test_change_placement_allocation_change_dir_min_pps_ingress_to_any( self):", "qos_pps_minimum_rule_alias.Qos_pps_minimum_rule_alias.\\ get_resources() def get_actions(self): return [] def get_request_extensions(self): return []", "def test_get_policy_bandwidth_limit_rules_for_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosBandwidthLimitRule.' 'get_objects') as", "rule_cls_mock, self.policy.id, {'fake_rule': {}}], 'update': [self.ctxt, rule_cls_mock, self.rule.id, self.policy.id, {'fake_rule':", "\"qos_policy_id\": qos2_id}} def test_check_port_for_placement_allocation_change_no_qos_change(self): qos1_obj = self._make_qos_policy() kwargs = self._prepare_for_port_placement_allocation_change(", "qos_policy_id=self.policy.id) def test_get_policy_min_pps_rules_for_policy_with_filters(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumPacketRateRule.' 'get_objects')", "mock_alloc_change_calls = [ mock.call( original_qos, qos, {'id': port1.id, 'device_owner': 'compute:uu:id',", "as plugins_constants from neutron_lib.plugins import directory from neutron_lib.services.qos import constants", "self.ctxt, \"elevated\", return_value=admin_ctxt ): self.qos_plugin._validate_update_port_callback( \"PORT\", \"precommit_update\", \"test_plugin\", payload=events.DBEventPayload( self.ctxt,", "mock.patch( 'neutron.objects.qos.rule.QosRule.get_object', return_value=rule ), mock.patch.object(self.qos_plugin, 'get_policy_rule', return_value=rule.to_dict()): self._update_rule(rule_type, rule_id, **data)", "self.qos_plugin.create_policy_minimum_bandwidth_rule, self.ctxt, policy.id, self.rule_data) def test_create_min_bw_rule_on_unbound_port(self): policy = self._get_policy() policy.rules", "with mock.patch('neutron.objects.qos.rule.' 'QosMinimumPacketRateRule.' 'get_object') as get_object_mock: self.qos_plugin.get_policy_minimum_packet_rate_rule( self.ctxt, self.min_pps_rule.id, self.policy.id)", "= mock.Mock() with mock.patch( 'neutron.objects.ports.Port.get_objects', return_value=ports ) as get_ports, mock.patch(", "consumer_uuid='uu:id', alloc_diff={self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': -1000}}) self._assert_pci_info(port) def test_change_placement_allocation_decrease_min_pps(self): original_qos = self._make_qos_policy()", "'min_kbps': 20, 'direction': lib_constants.INGRESS_DIRECTION} min_pps_rule_ingress_data = { 'id': uuidutils.generate_uuid(), 'min_kpps':", "@mock.patch.object(qos_plugin.QoSPlugin, \"get_policy_rule\") def test_show_rule(self, get_policy_rule_mock): calls = [] for rule_type,", "self.mock_qos_load_attr = _mock_qos_load_attr.start() # We don't use real models as", "port in network_ports if port.qos_policy_id is None] expected_ports = ports", "required by applicable law or agreed to in writing, software", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.create_policy_bandwidth_limit_rule, self.ctxt, self.policy.id, self.rule_data)", "self._validate_driver_params('update_policy', self.ctxt) rule_delete_mock_call = mock.call.delete() update_precommit_mock_call = mock.call.driver.call( 'update_policy_precommit', self.ctxt,", "self.rule_data['minimum_bandwidth_rule']['min_kbps'] = 1000000 setattr(_policy, \"rules\", [self.rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as", "mock.Mock() mock_manager.attach_mock(mock_qos_rule_create, 'create') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() with mock.patch('neutron.objects.qos.qos_policy_validator' '.check_bandwidth_rule_conflict', return_value=None),", "self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", [self.pps_rule]) self.qos_plugin.create_policy_packet_rate_limit_rule( self.ctxt,", "self._create_and_extend_port([], []) self.assertIsNone(port.get('resource_request')) def test__extend_port_resource_request_min_bw_non_provider_net(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION port =", "'name': 'fake-driver', 'supported_parameters': [{ 'parameter_name': 'max_kbps', 'parameter_type': lib_constants.VALUES_TYPE_RANGE, 'parameter_range': {'start':", "self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': 1000}}) def test_change_placement_allocation_change_direction_min_pps_and_min_bw( self): qos1 = self._make_qos_policy() qos2", "for rule in qos2.rules: rule.direction = 'any' with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation')", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt, self.policy.id, self.rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt,", "calls = [] for rule_type, rule_object_class in self.rule_objects.items(): rule_id =", "**min_pps_rule_ingress_data) port = self._create_and_extend_port( [self.min_bw_rule, min_bw_rule_ingress], [self.min_pps_rule, min_pps_rule_ingress], request_groups_uuids=request_groups_uuids) self.assertEqual(", "'.create_rbac_policy') @mock.patch('neutron.objects.qos.policy.QosPolicy') def test_add_policy(self, mock_qos_policy, mock_create_rbac_policy): mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_policy,", "mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( original_qos, desired_qos, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC':", "res = request.get_response(self.ext_api) if res.status_int >= webob.exc.HTTPClientError.code: raise webob.exc.HTTPClientError(code=res.status_int) return", "mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={ self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': -1000}, self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': -2000}})", "return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.delete_policy_minimum_packet_rate_rule, self.ctxt, self.min_pps_rule.id, self.policy.id) def test_get_policy_min_pps_rule(self): with", "= self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation( qos1, qos2, original_min_kpps=1000, desired_min_kpps=2000,", "'neutron.objects.qos.rule.QosRule.get_object', return_value=rule ), mock.patch.object(self.qos_plugin, 'get_policy_rule', return_value=rule.to_dict()): self._update_rule(rule_type, rule_id, **data) calls.append(mock.call(mock.ANY,", "= self._make_qos_policy() rule2_obj = self._make_qos_minbw_rule(qos2.id, min_kbps=1000) qos2.rules = [rule2_obj] orig_port", "original_min_kpps=1000, desired_min_kpps=1000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1, qos2,", "def test_change_placement_allocation_no_original_qos(self): qos1 = None qos2 = self._make_qos_policy() rule2_obj =", "lib_constants.EGRESS_DIRECTION port = self._create_and_extend_port([self.min_bw_rule], [self.min_pps_rule], physical_network=None) self.assertEqual( 1, len(port['resource_request']['request_groups']) )", "self._assert_pci_info(port) def test_change_placement_allocation_increase_min_pps_and_min_bw(self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() orig_port,", "project_id = uuidutils.generate_uuid() tenant_policy = { 'policy': {'id': policy_id, 'project_id':", "policy_details = {'id': policy_id, 'project_id': project_id, 'name': 'test-policy', 'description': 'Test", "copy from unittest import mock from keystoneauth1 import exceptions as", "'update') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) setattr(_policy,", "physical_network='public', has_qos_policy=False) self.assertIsNone(port.get('resource_request')) def test__extend_port_resource_request_min_bw_inherited_policy( self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION self.min_bw_rule.qos_policy_id", "self._update_rule(rule_type, rule_id, **data) calls.append(mock.call(mock.ANY, rule_object_class, rule_id, self.qos_policy_id, {rule_data_name: data})) update_policy_rule_mock.assert_has_calls(calls,", "ml2plugin_mock._make_port_dict.assert_not_called() def test_check_network_for_placement_allocation_change_no_ports_to_update( self): original_qos = self._make_qos_policy() qos = self._make_qos_policy()", "qos, {'id': port1.id, 'device_owner': 'compute:uu:id', 'qos_policy_id': None, 'qos_network_policy_id': qos.id}, mock.ANY),", "policy_id }, \"original_port\": { \"id\": port_id, qos_consts.QOS_POLICY_ID: original_policy_id } }", "mock.call( original_qos, qos, {'id': port1.id, 'device_owner': 'compute:uu:id', 'qos_policy_id': None, 'qos_network_policy_id':", "qos_policy_id=self.policy.id) def test_get_policy_dscp_marking_rules_for_policy_with_filters(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosDscpMarkingRule.' 'get_objects')", "agreed to in writing, software # distributed under the License", "'CUSTOM_VNIC_TYPE_NORMAL'], 'resources': { orc.NET_BW_EGR_KILOBIT_PER_SEC: 10, orc.NET_BW_IGR_KILOBIT_PER_SEC: 20}, }, port['resource_request']['request_groups'] )", "network_ports if port.qos_policy_id is None] expected_ports = ports + expected_network_ports", "'network', 'after_update', ml2plugin_mock, payload=events.DBEventPayload( self.context, states=(original_network, network))) self.assertEqual(ml2plugin_mock._make_port_dict.call_count, 1) mock_alloc_change_calls", "profile={'allocation': 'fake_allocation'}) port1_binding.create() port1.bindings = [port1_binding] port1.update() with mock.patch.object( self.qos_plugin,", "@mock.patch.object(policy_object.QosPolicy, \"get_object\") @mock.patch.object(rule_object.QosBandwidthLimitRule, 'create') def test_create_policy_rule(self, mock_qos_rule_create, mock_qos_policy_get): _policy =", "policy, orig_port, port): port['binding:profile'] = {'allocation': 'fake_allocation'} mock_alloc_change.side_effect = fake_change_placement_allocation", "self.ctxt, **self.rule_data['bandwidth_limit_rule']) self.dscp_rule = rule_object.QosDscpMarkingRule( self.ctxt, **self.rule_data['dscp_marking_rule']) self.min_bw_rule = rule_object.QosMinimumBandwidthRule(", "distributed under the License is distributed on an \"AS IS\"", "'validate_policy_for_port') \\ as mock_validate_policy: self.qos_plugin._validate_create_port_callback( \"PORT\", \"precommit_create\", \"test_plugin\", payload=events.DBEventPayload( self.context,", "= self._make_qos_policy() qos2 = self._make_qos_policy() bw_limit_rule1 = rule_object.QosDscpMarkingRule(dscp_mark=16) bw_limit_rule2 =", "'get_objects') as get_objects_mock: filters = {'filter': 'filter_id'} self.qos_plugin.get_policy_bandwidth_limit_rules( self.ctxt, self.policy.id,", "'direction': self.rule.direction } } with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises(", "\"%s_policy_rule\" % action) method(*arguments) # some actions get rule from", "self.qos_plugin.get_policy_bandwidth_limit_rules( self.ctxt, self.policy.id) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id) def test_get_policy_bandwidth_limit_rules_for_policy_with_filters(self): with", "_policy = self._get_policy() rules_data = [ { 'minimum_packet_rate_rule': { 'id':", "id=port_id) port.create() return port def _make_network(self, qos_policy_id=None): network = network_object.Network(self.context,", "desired_min_kbps=1000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(qos1, qos2, orig_port, port)", "rule_object.QosMinimumBandwidthRule( self.ctxt, **min_bw_rule_ingress_data) min_pps_rule_ingress = rule_object.QosMinimumPacketRateRule( self.ctxt, **min_pps_rule_ingress_data) ports =", "CONDITIONS OF ANY KIND, either express or implied. See the", "{ \"id\": network_id, qos_consts.QOS_POLICY_ID: original_policy_id } } port_mock_with_own_policy = mock.MagicMock(", "port in expected_ports: self.assertIn(port, policy_ports) def _test_validate_update_port_callback(self, policy_id=None, original_policy_id=None): port_id", "}, port['resource_request']['request_groups'] ) self.assertEqual( ['fake_uuid0', 'fake_uuid1'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_no_qos_policy(self):", "self.ctxt, self.pps_rule.id, self.policy.id) def test_get_policy_packet_rate_limit_rules_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound,", "is_sriov=True) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( original_qos, desired_qos, orig_port,", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumPacketRateRule.' 'get_object') as get_object_mock: self.qos_plugin.get_policy_minimum_packet_rate_rule(", "rules = [self.rule, self.min_bw_rule] setattr(_policy, \"rules\", rules) self.mock_qos_load_attr.reset_mock() with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "network_qos else None network = self._make_network(qos_policy_id=net_qos_id) kwargs = {\"context\": self.context,", "= [ { \"resource_request\": { \"port_id\": uuidutils.generate_uuid(), \"qos_id\": self.policy.id, \"network_id\":", "ports as ports_object from neutron.objects.qos import policy as policy_object from", "test_change_placement_allocation_min_bw_dataplane_enforcement_with_pps( self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() orig_port, port", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", []) self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.update_policy_bandwidth_limit_rule, self.ctxt,", "'device_owner': 'compute:uu:id', 'qos_policy_id': None, 'qos_network_policy_id': None}, mock.ANY), ] mock_alloc_change.assert_has_calls(mock_alloc_change_calls, any_order=True)", "mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': 1000}}) self._assert_pci_info(port) def test_change_placement_allocation_increase_min_pps(self): qos1 =", "qos_exc.QosRuleNotFound, self.qos_plugin.update_policy_packet_rate_limit_rule, self.ctxt, self.pps_rule.id, self.policy.id, self.rule_data) def test_delete_policy_packet_rate_limit_rule(self): _policy =", "{'filter': 'filter_id'} self.qos_plugin.get_policy_dscp_marking_rules( self.ctxt, self.policy.id, filters=filters) get_objects_mock.assert_called_once_with( self.ctxt, qos_policy_id=self.policy.id, _pager=mock.ANY,", "rule_id, self.qos_policy_id)) get_policy_rule_mock.assert_has_calls(calls, any_order=True) @mock.patch.object(qos_plugin.QoSPlugin, \"delete_policy_rule\") def test_delete_rule(self, delete_policy_rule_mock): calls", "mock-out # methods that work with real data types mock.patch(", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt, self.policy.id, self.rule_data) def", "webob.exc from neutron.exceptions import qos as neutron_qos_exc from neutron.extensions import", "qos1_obj, None, kwargs['original_port'], port) def test_check_port_for_placement_allocation_change_no_qos_update(self): qos1_obj = self._make_qos_policy() kwargs", "original_min_kpps=1000, desired_min_kpps=1000) for rule in qos2.rules: rule.direction = 'any' with", "'fake_uuid0', 'required': ['CUSTOM_PHYSNET_PUBLIC', 'CUSTOM_VNIC_TYPE_NORMAL'], 'resources': { orc.NET_BW_EGR_KILOBIT_PER_SEC: 10, orc.NET_BW_IGR_KILOBIT_PER_SEC: 20},", "with mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=policy), \\ mock.patch( 'neutron.objects.network.Network.get_object', return_value=net), \\ mock.patch.object(", "as mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.create_policy_bandwidth_limit_rule, self.ctxt, self.policy.id, self.rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def", "+= [self._make_qos_minbw_rule( desired_qos.id, min_kbps=desired_min_kbps)] if desired_min_kpps: desired_qos.rules += [self._make_qos_minpps_rule( desired_qos.id,", "as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={ self.MIN_PPS_RP:", "port['resource_request']['request_groups'][0]['resources'], ) self.assertEqual( ['fake_uuid'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_min_pps_rule(self): port =", "types)) @mock.patch('neutron.objects.ports.Port') @mock.patch('neutron.objects.qos.policy.QosPolicy') def test_rule_notification_and_driver_ordering(self, qos_policy_mock, port_mock): rule_cls_mock = mock.Mock()", "[self.pps_rule]) new_rule_data = { 'packet_rate_limit_rule': { 'max_kpps': 400, 'direction': self.pps_rule.direction", "= uuidutils.generate_uuid() with mock.patch('neutron.objects.qos.rule.QosRule.get_object', return_value=None): resource = '%s/alias-%s-rules' % (qos.ALIAS,", "self.qos_plugin.driver_manager, \"validate_rule_for_network\", return_value=True ): self.policy.rules = [self.rule] try: self.qos_plugin.validate_policy_for_network( self.ctxt,", "request_groups_uuids=request_groups_uuids) self.assertEqual( 2, len(port['resource_request']['request_groups']) ) self.assertIn( { 'id': 'fake_uuid0', 'required':", "port['resource_request']['request_groups'] ) self.assertEqual( ['fake_uuid0', 'fake_uuid1'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_non_min_bw_or_min_pps_rule(self): port", "self.qos_plugin.create_policy_minimum_packet_rate_rule( self.ctxt, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def test_create_policy_min_pps_rule_duplicates(self): _policy =", "self.ctxt, self.min_pps_rule.id, self.policy.id) def test_get_policy_min_pps_rules_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound,", "'test_plugin', payload=events.DBEventPayload( context, states=(original_port, port))) mock_alloc_change.assert_called_once_with( qos_network, desired_qos, kwargs['original_port'], port)", "'qos_policy_id': port.qos_policy_id, 'qos_network_policy_id': port.qos_network_policy_id, } ml2plugin_mock._make_port_dict.side_effect = fake_make_port_dict port1 =", "orig_port, port): port['binding:profile'] = {'allocation': 'fake_allocation'} mock_alloc_change.side_effect = fake_change_placement_allocation self.qos_plugin._check_network_for_placement_allocation_change(", "min_pps_rules = min_pps_rules if min_pps_rules else [] with mock.patch('neutron.objects.network.NetworkSegment.get_objects', return_value=[segment_mock]),", "self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION port = self._create_and_extend_port([self.min_bw_rule], physical_network=None) self.assertIsNone(port.get('resource_request')) def test__extend_port_resource_request_mix_rules_non_provider_net(self):", "limitations # under the License. import copy from unittest import", "self._get_policy() setattr(_policy, \"rules\", [self.rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.qos_plugin.create_policy_minimum_bandwidth_rule(", "None port_qos_id = port_qos_obj.id if port_qos else None network =", "mock_manager.mock_calls.index(rule_mock_call) else: action_index = mock_manager.mock_calls.index( get_rule_mock_call) self.assertLess( action_index, mock_manager.mock_calls.index(driver_mock_call)) def", "'create') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() with mock.patch('neutron.objects.qos.qos_policy_validator' '.check_bandwidth_rule_conflict', return_value=None), \\ mock.patch(", "return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosPacketRateLimitRule.' 'get_object') as get_object_mock: self.qos_plugin.get_policy_packet_rate_limit_rule( self.ctxt, self.pps_rule.id,", "if is_sriov: binding_prof = { 'pci_slot': '0000:42:41.0', 'pci_vendor_info': '8086:107ed', 'physical_network':", "mock_update_qos_alloc: self.assertRaises(NotImplementedError, self.qos_plugin._change_placement_allocation, qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_min_bw_dataplane_enforcement(self):", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.delete_policy_minimum_packet_rate_rule( self.ctxt, self.min_pps_rule.id, self.policy.id) self._validate_driver_params('update_policy', self.ctxt) def", "\\ as mock_validate_policy: self.qos_plugin._validate_create_port_callback( \"PORT\", \"precommit_create\", \"test_plugin\", payload=events.DBEventPayload( self.context, resource_id=kwargs['port']['id'],))", "get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id) def test_get_policy_packet_rate_limit_rules_for_policy_with_filters(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with", "orig_port, port = self._prepare_port_for_placement_allocation(qos1, original_min_kbps=1000, original_min_kpps=2000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as", "'fake_uuid1'] min_bw_rule_ingress_data = { 'id': uuidutils.generate_uuid(), 'min_kbps': 20, 'direction': lib_constants.INGRESS_DIRECTION}", "'compute:uu:id', 'qos_policy_id': None, 'qos_network_policy_id': qos.id}, mock.ANY), mock.call( original_qos, qos, {'id':", "self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_minimum_packet_rate_rules, self.ctxt, self.policy.id) def test_get_min_pps_rule_type(self): admin_ctxt = context.get_admin_context()", ") self.assertEqual( ['fake_uuid'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_bulk_min_pps_rule(self): ports = self._create_and_extend_ports([],", "mock.patch('neutron.objects.db.api.delete_object').start() mock.patch('neutron.objects.db.api.get_object').start() _mock_qos_load_attr = mock.patch( 'neutron.objects.qos.policy.QosPolicy.obj_load_attr') self.mock_qos_load_attr = _mock_qos_load_attr.start() #", "self.ctxt) self.mock_qos_load_attr.assert_called_once_with('rules') mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_rule_check_rule_max_more_than_min(self): _policy = self._get_policy() setattr(_policy,", "{ 'minimum_packet_rate_rule': { 'id': uuidutils.generate_uuid(), 'min_kpps': 10, 'direction': 'ingress' }", "return qos_rule def _make_qos_minpps_rule(self, policy_id, direction='ingress', min_kpps=1000, rule_id=None): rule_id =", "else uuidutils.generate_uuid() qos_rule = rule_object.QosMinimumPacketRateRule( self.context, project_id=self.project_id, qos_policy_id=policy_id, direction=direction, min_kpps=min_kpps,", ") def test_get_ports_with_policy(self): network_ports = [ mock.MagicMock(qos_policy_id=None), mock.MagicMock(qos_policy_id=uuidutils.generate_uuid()), mock.MagicMock(qos_policy_id=None) ]", "uuidutils.generate_uuid(), 'min_kbps': 10}, 'packet_rate_limit_rule': { 'id': uuidutils.generate_uuid(), 'max_kpps': 20, 'max_burst_kpps':", "with mock.patch('neutron.objects.qos.policy.QosPolicy') as QosMocked: self.qos_plugin.create_policy(self.ctxt, tenant_policy) QosMocked.assert_called_once_with(self.ctxt, **policy_details) @mock.patch.object(policy_object.QosPolicy, \"get_object\")", "min_pps_rule_ingress_data = { 'id': uuidutils.generate_uuid(), 'min_kpps': 20, 'direction': lib_constants.INGRESS_DIRECTION} min_bw_rule_ingress", "self._validate_driver_params('update_policy', self.ctxt) self.mock_qos_load_attr.assert_called_once_with('rules') mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_rule_check_rule_max_more_than_min(self): _policy = self._get_policy()", "return_value=True ): self.policy.rules = [self.rule] try: self.qos_plugin.validate_policy_for_port( self.ctxt, self.policy, port)", "as get_objects_mock: self.qos_plugin.get_policy_dscp_marking_rules( self.ctxt, self.policy.id) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id) def", "= {\"binding:vnic_type\": \"normal\"} segment_mock = mock.MagicMock(network_id=network_id, physical_network=physical_network) min_pps_rules = min_pps_rules", "self.policy.id) def test_get_policy_minimum_bandwidth_rules_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_minimum_bandwidth_rules, self.ctxt,", "actions get rule from policy get_rule_mock_call = getattr( mock.call.QosPolicy.get_policy_obj().get_rule_by_id(), action)()", "\"normal\", } }, ] segment_mock = mock.MagicMock(network_id=network_id, physical_network=physical_network) min_pps_rules =", "for new_rule_data in rules: with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict,", "self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt, self.policy.id, self.rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_min_pps_rule(self): _policy =", "self).setUp() self.setup_coreplugin(load_plugins=False) cfg.CONF.set_override(\"core_plugin\", DB_PLUGIN_KLASS) cfg.CONF.set_override(\"service_plugins\", [\"qos\"]) manager.init() self.qos_plugin = directory.get_plugin(plugins_constants.QOS)", "**rules_data[1]['minimum_packet_rate_rule']), ] setattr(_policy, 'rules', rules) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj:", "self._prepare_port_for_placement_allocation( qos1, qos2, desired_min_kbps=1000, original_min_kpps=500, desired_min_kpps=1000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as", "drivers_details, rule_type_details['drivers']) def test_get_rule_type_as_user(self): self.assertRaises( lib_exc.NotAuthorized, self.qos_plugin.get_rule_type, self.ctxt, qos_consts.RULE_TYPE_BANDWIDTH_LIMIT) def", "\"validate_policy_for_network\" ) as validate_policy_for_network, mock.patch.object( self.qos_plugin, \"validate_policy_for_ports\" ) as validate_policy_for_ports,", "{'filter': 'filter_id'} self.qos_plugin.get_policy_bandwidth_limit_rules( self.ctxt, self.policy.id, filters=filters) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id,", "= self._get_policy() setattr(_policy, \"rules\", [self.rule]) new_rule_data = { 'bandwidth_limit_rule': {", "with mock.patch.object(qos_plugin.QoSPlugin, 'supported_rule_types', return_value=qos_consts.VALID_RULE_TYPES): types = self.qos_plugin.get_rule_types(self.ctxt, filters=filters) self.assertEqual(sorted(qos_consts.VALID_RULE_TYPES), sorted(type_['type']", "[self.min_pps_rule], physical_network=None) self.assertEqual( 1, len(port['resource_request']['request_groups']) ) self.assertEqual( 'fake_uuid', port['resource_request']['request_groups'][0]['id'] )", "return qos_policy def _make_qos_minbw_rule(self, policy_id, direction='ingress', min_kbps=1000, rule_id=None): rule_id =", "'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': 1000}}) self._assert_pci_info(port) def test_change_placement_allocation_increase_min_pps_and_min_bw(self): qos1 = self._make_qos_policy() qos2 =", "'neutron.objects.network.Network.get_object', return_value=net), \\ mock.patch.object( self.qos_plugin, '_get_ports_with_policy', return_value=[port]): self.assertRaises( NotImplementedError, self.qos_plugin.create_policy_minimum_bandwidth_rule,", "neutron.objects.qos import rule as rule_object from neutron.services.qos import qos_plugin from", "= self._make_qos_policy() original_network = self._make_network(original_qos.id) network = self._make_network() ml2plugin_mock =", "self.ctxt, self.min_pps_rule.id, self.policy.id, self.rule_data) def test_delete_policy_min_pps_rule(self): _policy = self._get_policy() setattr(_policy,", "return self.deserialize(self.fmt, res) def _show_rule(self, rule_type, rule_id): resource = '%s/alias-%s-rules'", "network as network_object from neutron.objects import ports as ports_object from", "{'id': policy_id, 'project_id': project_id, 'tenant_id': project_id, 'name': 'test-policy', 'description': 'Test", "self.pps_rule.id, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def test_update_policy_pps_rule_bad_policy(self): _policy = policy_object.QosPolicy(", "return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_dscp_marking_rule, self.ctxt, self.dscp_rule.id, self.policy.id) def test_get_policy_dscp_marking_rules_for_nonexistent_policy(self): with", "return_value=net), \\ mock.patch.object( self.qos_plugin, '_get_ports_with_policy', return_value=[port]): try: self.qos_plugin.create_policy_minimum_packet_rate_rule( self.ctxt, _policy.id,", "return qos_rule def _make_port(self, network_id, qos_policy_id=None, port_id=None, qos_network_policy_id=None, device_owner=None): port_id", "= qos1.id if qos1 else None qos2_id = qos2.id if", "def get_resources(self): return qos_pps_minimum_rule_alias.Qos_pps_minimum_rule_alias.\\ get_resources() def get_actions(self): return [] def", "if has_qos_policy: self.port_data['port']['qos_policy_id'] = self.policy.id elif has_net_qos_policy: self.port_data['port']['qos_network_policy_id'] = self.policy.id", "def _validate_driver_params(self, method_name, ctxt): call_args = self.qos_plugin.driver_manager.call.call_args[0] self.assertTrue(self.qos_plugin.driver_manager.call.called) self.assertEqual(call_args[0], method_name)", "port_mock_without_own_policy = mock.MagicMock( id=uuidutils.generate_uuid(), qos_policy_id=None) ports = [port_mock_with_own_policy, port_mock_without_own_policy] policy_mock", "self.assertTrue( mock_manager.mock_calls.index(rule_update_mock_call) < mock_manager.mock_calls.index(update_precommit_mock_call) < mock_manager.mock_calls.index(update_mock_call)) def test_update_policy_rule_check_rule_min_less_than_max(self): _policy =", "policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", [self.pps_rule]) self.qos_plugin.delete_policy_packet_rate_limit_rule(", "self.qos_plugin.get_policy_minimum_packet_rate_rule, self.ctxt, self.min_pps_rule.id, self.policy.id) def test_get_policy_min_pps_rules_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises(", "= self._make_qos_minbw_rule(qos2.id, min_kbps=1000) qos2.rules = [rule2_obj] orig_port = {'id': 'u:u',", "self.patch_notifier.start() plugin = 'ml2' service_plugins = {'qos_plugin_name': SERVICE_PLUGIN_KLASS} ext_mgr =", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", []) self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.delete_policy_bandwidth_limit_rule, self.ctxt,", "mock.patch.object( self.policy, \"get_bound_ports\" ): policy_ports = self.qos_plugin._get_ports_with_policy( self.ctxt, self.policy) self.assertEqual(", "qos2 = self._make_qos_policy() rule2_obj = self._make_qos_minbw_rule(qos2.id, min_kbps=1000) qos2.rules = [rule2_obj]", "self.rule_data['bandwidth_limit_rule']['max_kbps'] = 1 with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.assertRaises( qos_exc.QoSRuleParameterConflict, self.qos_plugin.update_policy_bandwidth_limit_rule, self.ctxt,", "port))) mock_alloc_change.assert_not_called() def test_check_port_for_placement_allocation_change(self): qos1_obj = self._make_qos_policy() qos2_obj = self._make_qos_policy()", ") def test__extend_port_resource_request_bulk_min_bw_and_pps_rule(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION self.min_pps_rule.direction = lib_constants.EGRESS_DIRECTION request_groups_uuids", "placement as pl_exc from neutron_lib.exceptions import qos as qos_exc from", "physical_network='fake physnet') net = network_object.Network( self.ctxt, segments=[segment]) port = ports_object.Port(", "response={'errors': [{'code': 'placement.concurrent_update'}]} ) self.assertRaises( neutron_qos_exc.QosPlacementAllocationUpdateConflict, self.qos_plugin._change_placement_allocation, qos1, qos2, orig_port,", "\"validate_policy_for_port\" ) as validate_policy_for_port, mock.patch.object( self.ctxt, \"elevated\", return_value=admin_ctxt ): self.qos_plugin._validate_update_port_callback(", "_test_validate_create_port_callback(self, port_qos=False, network_qos=False): net_qos_obj = self._make_qos_policy() port_qos_obj = self._make_qos_policy() net_qos_id", "policy_ports) def _test_validate_update_port_callback(self, policy_id=None, original_policy_id=None): port_id = uuidutils.generate_uuid() kwargs =", "with mock.patch( 'neutron.objects.ports.Port.get_object', return_value=port_mock ) as get_port, mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=policy_mock", "= mock.patch('neutron.api.rpc.handlers.resources_rpc' '.ResourcesPushRpcApi.push').start() self.context = context.get_admin_context() self.project_id = uuidutils.generate_uuid() def", "context, states=(original_port, port))) mock_alloc_change.assert_not_called() def test_check_port_for_placement_allocation_change_qos_network_policy( self): qos_network = self._make_qos_policy()", "original_min_kpps=500, desired_min_kpps=1000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(qos1, qos2, orig_port,", "'max_kbps': 100, 'max_burst_kbps': 150}, 'dscp_marking_rule': {'id': uuidutils.generate_uuid(), 'dscp_mark': 16}, 'minimum_bandwidth_rule':", "device_owner if device_owner else '3' port = ports_object.Port( self.context, network_id=network_id,", "self.ctxt, segments=[segment]) port = ports_object.Port( self.ctxt, id=uuidutils.generate_uuid(), network_id=uuidutils.generate_uuid(), device_owner='') with", "IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumPacketRateRule.' 'get_objects') as get_objects_mock: filters =", "'driver') mock_manager.reset_mock() self.qos_plugin.delete_policy(self.ctxt, self.policy.id) self._validate_driver_params('delete_policy', self.ctxt) policy_delete_mock_call = mock.call.delete() delete_precommit_mock_call", "] self.rule_data['minimum_packet_rate_rule']['direction'] = 'any' for rule_data in rules_data: rules =", "get_policy.assert_not_called() validate_policy_for_network.assert_not_called() get_ports.assert_not_called() validate_policy_for_ports.assert_not_called() else: get_policy.assert_called_once_with(admin_ctxt, id=policy_id) get_ports.assert_called_once_with(self.ctxt, network_id=network_id) validate_policy_for_ports.assert_called_once_with(", "cfg.CONF.set_override(\"service_plugins\", [\"qos\"]) manager.init() self.qos_plugin = directory.get_plugin(plugins_constants.QOS) self.qos_plugin.driver_manager = mock.Mock() self.rpc_push", "self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_minimum_packet_rate_rule, self.ctxt, self.min_pps_rule.id, self.policy.id) def test_get_policy_min_pps_rules_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "rule_id = rule_id if rule_id else uuidutils.generate_uuid() qos_rule = rule_object.QosMinimumBandwidthRule(", "self._make_port( network_id=network.id, qos_policy_id=None, device_owner='compute:uu:id') port1_binding = ports_object.PortBinding( self.context, port_id=port1.id, host='fake_host1',", "self._create_and_extend_port([self.min_bw_rule]) self.assertEqual( 1, len(port['resource_request']['request_groups']) ) self.assertEqual( 'fake_uuid', port['resource_request']['request_groups'][0]['id'] ) self.assertEqual(", "as get_objects_mock: self.qos_plugin.get_policy_minimum_packet_rate_rules( self.ctxt, self.policy.id) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id) def", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosPacketRateLimitRule.' 'get_object') as get_object_mock: self.qos_plugin.get_policy_packet_rate_limit_rule( self.ctxt,", "min_pps_rules=None, physical_network='public', has_qos_policy=True, has_net_qos_policy=False, request_groups_uuids=None): network_id = uuidutils.generate_uuid() self.port_data =", "port['binding:profile']) self.assertIn('pci_vendor_info', port['binding:profile']) self.assertIn('physical_network', port['binding:profile']) def test_change_placement_allocation_increase(self): qos1 = self._make_qos_policy()", ") as get_ports, mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=policy_mock ) as get_policy, mock.patch.object(", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises( qos_exc.QoSRulesConflict, self.qos_plugin.create_policy_bandwidth_limit_rule, self.ctxt, _policy.id,", "_mock_qos_load_attr = mock.patch( 'neutron.objects.qos.policy.QosPolicy.obj_load_attr') self.mock_qos_load_attr = _mock_qos_load_attr.start() # We don't", "self.ctxt, self.rule.id, self.policy.id) def test_get_policy_minimum_bandwidth_rules_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound,", "'fake_uuid1'] * 2 min_bw_rule_ingress_data = { 'id': uuidutils.generate_uuid(), 'min_kbps': 20,", "policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) def test_update_policy_rule_bad_policy(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy'])", "action)() # some actions construct rule from class reference rule_mock_call", "import utils as obj_utils from neutron_lib.plugins import constants as plugins_constants", "qos2=qos2_obj) context = kwargs['context'] original_port = kwargs['original_port'] port = kwargs['port']", "qos_policy = None if port_qos: qos_policy = port_qos_obj elif network_qos:", "self.new_update_request(resource, data, rule_id, self.fmt) res = request.get_response(self.ext_api) if res.status_int >=", "payload=events.DBEventPayload( context, states=(original_port, port))) mock_alloc_change.assert_called_once_with( qos1_obj, qos2_obj, kwargs['original_port'], port) def", "= {'type': 'type_id'} with mock.patch.object(qos_plugin.QoSPlugin, 'supported_rule_types', return_value=qos_consts.VALID_RULE_TYPES): types = self.qos_plugin.get_rule_types(self.ctxt,", "None) def test__extend_port_resource_request_min_bw_rule(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION port = self._create_and_extend_port([self.min_bw_rule]) self.assertEqual(", "'get_objects') as get_objects_mock: self.qos_plugin.get_policy_dscp_marking_rules( self.ctxt, self.policy.id) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id)", "= mock.patch( 'neutron.notifiers.batch_notifier.BatchNotifier._notify') self.patch_notifier.start() plugin = 'ml2' service_plugins = {'qos_plugin_name':", "constants as qos_consts from neutron_lib.utils import net as net_utils import", "See the # License for the specific language governing permissions", "rule_object.QosPacketRateLimitRule( self.ctxt, **self.rule_data['packet_rate_limit_rule']) self.min_pps_rule = rule_object.QosMinimumPacketRateRule( self.ctxt, **self.rule_data['minimum_packet_rate_rule']) def _validate_driver_params(self,", "setattr(_policy, \"rules\", [self.min_pps_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.delete_policy_minimum_packet_rate_rule( self.ctxt, self.min_pps_rule.id, self.policy.id)", "mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_no_original_allocation(self): qos1 = self._make_qos_policy() rule1_obj = self._make_qos_minbw_rule(qos1.id, min_kbps=500)", "exception unexpectedly raised\") def test_validate_policy_for_network(self): network = uuidutils.generate_uuid() with mock.patch.object(", "vnic_type='fake_vnic_type', vif_type='fake_vif_type', profile={'allocation': 'fake_allocation'}) port1_binding.create() port1.bindings = [port1_binding] port1.update() with", "= self._prepare_port_for_placement_allocation( None, desired_qos, qos_network_policy=qos_network, original_min_kbps=1000, desired_min_kbps=2000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation')", "'get_objects', return_value=min_bw_rules), \\ mock.patch( 'neutron.objects.qos.rule.QosMinimumPacketRateRule.' 'get_objects', return_value=min_pps_rules), \\ mock.patch( 'uuid.uuid5',", "new_rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_min_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound,", "= { 'policy': {'id': policy_id, 'project_id': project_id, 'tenant_id': project_id, 'name':", "'before_update', 'test_plugin', payload=events.DBEventPayload( context, states=(original_port, port))) mock_alloc_change.assert_called_once_with( qos1_obj, None, kwargs['original_port'],", "\"rules\", []) mock_qos_policy_get.return_value = _policy mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_rule_create, 'create')", "self.assertTrue(self.qos_plugin.driver_manager.call.called) self.assertEqual(call_args[0], method_name) self.assertEqual(call_args[1], ctxt) self.assertIsInstance(call_args[2], policy_object.QosPolicy) def _create_and_extend_port(self, min_bw_rules,", "self.qos_plugin.create_policy_minimum_bandwidth_rule( self.ctxt, policy.id, self.rule_data) except NotImplementedError: self.fail() @mock.patch( 'neutron.objects.rbac_db.RbacNeutronDbObjectMixin' '.create_rbac_policy')", "return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.delete_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, self.policy.id) def test_verify_bad_method_call(self): self.assertRaises(AttributeError,", "original_policy_id=policy_id) def test_validate_update_port_callback_policy_removed(self): self._test_validate_update_port_callback( policy_id=None, original_policy_id=uuidutils.generate_uuid()) def _test_validate_update_network_callback(self, policy_id=None, original_policy_id=None):", "{ 'id': uuidutils.generate_uuid(), 'min_kpps': 1234, 'direction': self.min_pps_rule.direction, }, } with", "get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id, filter='filter_id') def test_get_policy_min_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None):", "for rule_type, rule_object_class in self.rule_objects.items(): rule_id = uuidutils.generate_uuid() with mock.patch('neutron.objects.qos.rule.QosRule.get_object',", "desired_qos.rules += [self._make_qos_minbw_rule( desired_qos.id, min_kbps=desired_min_kbps)] if desired_min_kpps: desired_qos.rules += [self._make_qos_minpps_rule(", "self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() orig_port, port =", "ports = self._create_and_extend_ports( [self.min_bw_rule, min_bw_rule_ingress], [self.min_pps_rule, min_pps_rule_ingress], request_groups_uuids=request_groups_uuids) for port", "mock.Mock() mock_manager.attach_mock(mock_qos_policy, 'QosPolicy') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() self.qos_plugin.create_policy(self.ctxt, self.policy_data) policy_mock_call =", "self.mock_qos_load_attr.assert_called_once_with('rules') mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_rule_check_rule_bwlimit_less_than_minbw(self): _policy = self._get_policy() self.rule_data['bandwidth_limit_rule']['max_kbps'] =", "self.assertEqual(sorted(qos_consts.VALID_RULE_TYPES), sorted(type_['type'] for type_ in types)) @mock.patch('neutron.objects.ports.Port') @mock.patch('neutron.objects.qos.policy.QosPolicy') def test_rule_notification_and_driver_ordering(self,", "consumer_uuid='uu:id', alloc_diff={ self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': 500}}) def test_change_placement_allocation_decrease(self): original_qos =", "self.ctxt) def test_create_policy_min_pps_rule_duplicates(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.min_pps_rule]) new_rule_data", "self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id) def test_get_policy_minimum_bandwidth_rules_for_policy_with_filters(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.'", "= rule_object.QosMinimumPacketRateRule( self.ctxt, **min_pps_rule_ingress_data) port = self._create_and_extend_port( [self.min_bw_rule, min_bw_rule_ingress], [self.min_pps_rule,", "\"original_network\": { \"id\": network_id, qos_consts.QOS_POLICY_ID: original_policy_id } } port_mock_with_own_policy =", "self.ctxt) def test_get_policy_dscp_marking_rules(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosDscpMarkingRule.' 'get_objects')", "rule_object.QosDscpMarkingRule(dscp_mark=16) bw_limit_rule2 = rule_object.QosDscpMarkingRule(dscp_mark=18) qos1.rules = [bw_limit_rule1] qos2.rules = [bw_limit_rule2]", "self.rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_update_policy_min_pps_rule_bad_policy(self): _policy = self._get_policy() setattr(_policy, \"rules\",", "'e16161f4-1626-11ec-a5a2-1fc9396e27cc' def setUp(self): super(TestQosPluginDB, self).setUp() self.setup_coreplugin(load_plugins=False) cfg.CONF.set_override(\"core_plugin\", DB_PLUGIN_KLASS) cfg.CONF.set_override(\"service_plugins\", [\"qos\"])", "self.fail() @mock.patch( 'neutron.objects.rbac_db.RbacNeutronDbObjectMixin' '.create_rbac_policy') @mock.patch('neutron.objects.qos.policy.QosPolicy') def test_add_policy(self, mock_qos_policy, mock_create_rbac_policy): mock_manager", "port2.bindings[0].profile, {'allocation': 'fake_allocation'}) def _prepare_port_for_placement_allocation(self, original_qos, desired_qos=None, qos_network_policy=None, original_min_kbps=None, desired_min_kbps=None,", "law or agreed to in writing, software # distributed under", "\"get_bound_networks\" ), mock.patch.object( self.policy, \"get_bound_ports\" ): policy_ports = self.qos_plugin._get_ports_with_policy( self.ctxt,", "1 self.qos_plugin.update_policy_bandwidth_limit_rule( self.ctxt, self.rule.id, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) rule_update_mock_call =", "qos1=qos1_obj, qos2=qos1_obj) context = kwargs['context'] original_port = kwargs['original_port'] port =", "orig_port, port = self._prepare_port_for_placement_allocation( original_qos, desired_qos, original_min_kbps=2000, desired_min_kbps=1000, is_sriov=True) with", "return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumBandwidthRule.' 'get_objects') as get_objects_mock: self.qos_plugin.get_policy_minimum_bandwidth_rules( self.ctxt, self.policy.id)", "self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt, self.policy.id, self.rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_min_pps_rule(self): _policy", "= self._make_qos_policy() qos2 = self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation( qos1,", "mock_manager.attach_mock(rule_cls_mock, 'RuleCls') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') for action, arguments in rule_actions.items(): mock_manager.reset_mock()", "'get_objects') as get_objects_mock: self.qos_plugin.get_policy_minimum_bandwidth_rules( self.ctxt, self.policy.id) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id)", "'minimum_bandwidth_rule': { 'id': uuidutils.generate_uuid(), 'min_kbps': 10}, 'packet_rate_limit_rule': { 'id': uuidutils.generate_uuid(),", "= qos2.id if qos2 else None qos_network_policy_id = ( qos_network_policy.id", "= port_qos_obj elif network_qos: qos_policy = net_qos_obj if qos_policy: mock_validate_policy.assert_called_once_with(", "mock_alloc_change_calls = [ mock.call( original_qos, None, {'id': port1.id, 'device_owner': 'compute:uu:id',", "def test__extend_port_resource_request_min_bw_and_pps_rule(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION self.min_pps_rule.direction = lib_constants.EGRESS_DIRECTION request_groups_uuids =", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", [self.pps_rule]) self.qos_plugin.create_policy_packet_rate_limit_rule( self.ctxt, self.policy.id, self.rule_data)", "= None qos2 = self._make_qos_policy() rule2_obj = self._make_qos_minbw_rule(qos2.id, min_kbps=1000) qos2.rules", "self._make_qos_policy() bw_limit_rule1 = rule_object.QosDscpMarkingRule(dscp_mark=16) bw_limit_rule2 = rule_object.QosDscpMarkingRule(dscp_mark=18) qos1.rules = [bw_limit_rule1]", "rule_id if rule_id else uuidutils.generate_uuid() qos_rule = rule_object.QosMinimumPacketRateRule( self.context, project_id=self.project_id,", "port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={ self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': -500, 'NET_PACKET_RATE_EGR_KILOPACKET_PER_SEC': 1000},", "qos = original_qos or qos_network_policy qos.rules = [] allocation =", "self._make_network(qos_policy_id=net_qos_id) port = self._make_port(network.id, qos_policy_id=port_qos_id) kwargs = {\"context\": self.context, \"port\":", "qos1 = self._make_qos_policy() rule1_obj = self._make_qos_minbw_rule(qos1.id, min_kbps=500) qos1.rules = [rule1_obj]", "policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) self.rule = rule_object.QosBandwidthLimitRule( self.ctxt, **self.rule_data['bandwidth_limit_rule']) self.dscp_rule =", "'uuid.uuid5', return_value='fake_uuid', side_effect=request_groups_uuids): return qos_plugin.QoSPlugin._extend_port_resource_request_bulk( ports_res, None) def test__extend_port_resource_request_min_bw_rule(self): self.min_bw_rule.direction", "10, orc.NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC: 20, }, }, port['resource_request']['request_groups'] ) self.assertEqual( ['fake_uuid0', 'fake_uuid1'],", "self.qos_plugin.get_policy_minimum_packet_rate_rules, self.ctxt, self.policy.id) def test_get_min_pps_rule_type(self): admin_ctxt = context.get_admin_context() drivers_details =", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_minimum_packet_rate_rules, self.ctxt, self.policy.id) def test_get_min_pps_rule_type(self):", "mock.patch('neutron.objects.qos.rule.' 'QosBandwidthLimitRule.' 'get_object') as get_object_mock: self.qos_plugin.get_policy_bandwidth_limit_rule( self.ctxt, self.rule.id, self.policy.id) get_object_mock.assert_called_once_with(self.ctxt,", "self.context, states=(original_network, network))) mock_alloc_change.assert_not_called() ml2plugin_mock._make_port_dict.assert_not_called() def test_check_network_for_placement_allocation_change_no_ports_to_update( self): original_qos =", "port2_binding.create() port2.bindings = [port2_binding] port2.update() with mock.patch.object( self.qos_plugin, '_change_placement_allocation') as", "port2.id, 'device_owner': 'compute:uu:id', 'qos_policy_id': None, 'qos_network_policy_id': qos.id}, mock.ANY)] mock_alloc_change.assert_has_calls(mock_alloc_change_calls, any_order=True)", "self.assertRaises( qos_exc.QoSRuleParameterConflict, self.qos_plugin.update_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, self.policy.id, self.rule_data) def _get_policy(self): return", "with mock.patch('neutron.objects.qos.rule.' 'QosDscpMarkingRule.' 'get_objects') as get_objects_mock: self.qos_plugin.get_policy_dscp_marking_rules( self.ctxt, self.policy.id) get_objects_mock.assert_called_once_with(", "qos1.rules = [rule1_obj] qos2 = self._make_qos_policy() rule2_obj = self._make_qos_minbw_rule(qos2.id, min_kbps=1000)", "mac_address=mac, id=port_id) port.create() return port def _make_network(self, qos_policy_id=None): network =", "id=_policy.id) def test_create_policy_rule_duplicates(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.rule]) new_rule_data", "shared=False, is_default=False) qos_policy.create() return qos_policy def _make_qos_minbw_rule(self, policy_id, direction='ingress', min_kbps=1000,", "qos_policy_id=port_qos.id, device_owner='compute:uu:id') ml2plugin_mock = mock.MagicMock() with mock.patch.object( self.qos_plugin, '_change_placement_allocation') as", "policy.id, self.rule_data) def test_create_min_bw_rule_on_unbound_port(self): policy = self._get_policy() policy.rules = [self.min_bw_rule]", "qos2, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': 1000}}) self._assert_pci_info(port)", "[self.min_bw_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.create_policy_bandwidth_limit_rule, self.ctxt, self.policy.id,", "mock.patch( 'neutron.objects.ports.Port.get_objects', return_value=ports ) as get_ports, mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=policy_mock )", "network = self._make_network(qos_policy_id=net_qos_id) port = self._make_port(network.id, qos_policy_id=port_qos_id) kwargs = {\"context\":", "self._make_qos_policy() qos2 = self._make_qos_policy() bw_limit_rule = rule_object.QosDscpMarkingRule(dscp_mark=16) orig_port, port =", "'-')) request = self.new_show_request(resource, rule_id, self.fmt) res = request.get_response(self.ext_api) if", "= context.Context('fake_user', 'fake_tenant') self.rule_objects = { 'bandwidth_limit': rule_object.QosBandwidthLimitRule, 'dscp_marking': rule_object.QosDscpMarkingRule,", "{ 'bandwidth_limit_rule': {'id': uuidutils.generate_uuid(), 'max_kbps': 100, 'max_burst_kbps': 150}, 'dscp_marking_rule': {'id':", "'ff'] mac = netaddr.EUI(next(net_utils.random_mac_generator(base_mac))) device_owner = device_owner if device_owner else", "port_qos else None network = self._make_network(qos_policy_id=net_qos_id) port = self._make_port(network.id, qos_policy_id=port_qos_id)", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.assertRaises( qos_exc.QoSRuleParameterConflict, self.qos_plugin.update_policy_minimum_bandwidth_rule, self.ctxt, self.min_bw_rule.id, self.policy.id, self.rule_data) def", "allocation = {} if original_min_kbps: qos.rules += [self._make_qos_minbw_rule( qos.id, min_kbps=original_min_kbps,", ") self.assertEqual( ['fake_uuid'], port['resource_request']['same_subtree'], ) def test_get_ports_with_policy(self): network_ports = [", "desired_qos.rules += [self._make_qos_minpps_rule( desired_qos.id, min_kpps=desired_min_kpps)] binding_prof = {} if is_sriov:", "as neutron_qos_exc from neutron.extensions import qos_pps_minimum_rule_alias from neutron.extensions import qos_rules_alias", "uuidutils.generate_uuid(), 'min_kpps': 10, 'direction': 'any'}, } self.policy = policy_object.QosPolicy( self.ctxt,", "qos_exc.QosRuleNotFound, self.qos_plugin.update_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, self.policy.id, self.rule_data) @mock.patch.object(rule_object.QosBandwidthLimitRule, 'delete') def test_delete_policy_rule(self,", "port.id, \"device_owner\": \"compute:uu:id\", \"qos_policy_id\": qos1_id, \"qos_network_policy_id\": qos_network_policy_id}, \"port\": {\"id\": port.id,", "mock.patch('neutron.objects.qos.policy.QosPolicy') as QosMocked: self.qos_plugin.create_policy(self.ctxt, tenant_policy) QosMocked.assert_called_once_with(self.ctxt, **policy_details) @mock.patch.object(policy_object.QosPolicy, \"get_object\") @mock.patch(", "mock.patch('neutron.objects.qos.rule.get_rules', return_value=[self.rule]), mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.rule_data['bandwidth_limit_rule']['max_kbps'] = 1 self.qos_plugin.update_policy_bandwidth_limit_rule( self.ctxt,", "self.qos_plugin.get_policy_bandwidth_limit_rule( self.ctxt, self.rule.id, self.policy.id) get_object_mock.assert_called_once_with(self.ctxt, id=self.rule.id) def test_get_policy_bandwidth_limit_rules_for_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "['fake_uuid0', 'fake_uuid1'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_no_qos_policy(self): port = self._create_and_extend_port([], physical_network='public',", "get_port, mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=policy_mock ) as get_policy, mock.patch.object( self.qos_plugin, \"validate_policy_for_port\"", "self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", [self.pps_rule]) self.qos_plugin.delete_policy_packet_rate_limit_rule( self.ctxt,", "self.rule_data) def test_delete_policy_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.delete_policy_packet_rate_limit_rule, self.ctxt,", "ports_object.Port( self.ctxt, id=uuidutils.generate_uuid(), network_id=uuidutils.generate_uuid(), device_owner='') with mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy), \\", "**rule_data['minimum_packet_rate_rule']) setattr(_policy, \"rules\", [min_pps_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict,", ") def test__extend_port_resource_request_min_bw_and_pps_rule(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION self.min_pps_rule.direction = lib_constants.EGRESS_DIRECTION request_groups_uuids", "}, port['resource_request']['request_groups'] ) self.assertEqual( ['fake_uuid0', 'fake_uuid1'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_non_min_bw_or_min_pps_rule(self):", "port = self._prepare_port_for_placement_allocation( qos1, qos2, original_min_kpps=1000, desired_min_kpps=2000, is_sriov=True) with mock.patch.object(self.qos_plugin._placement_client,", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.qos_plugin.create_policy_minimum_bandwidth_rule( self.ctxt, _policy.id, self.rule_data) self._validate_driver_params('update_policy',", ") self.assertRaises( neutron_qos_exc.QosPlacementAllocationUpdateConflict, self.qos_plugin._change_placement_allocation, qos1, qos2, orig_port, port) def test_change_placement_allocation_update_generation_conflict(self):", "except NotImplementedError: self.fail() @mock.patch( 'neutron.objects.rbac_db.RbacNeutronDbObjectMixin' '.create_rbac_policy') @mock.patch('neutron.objects.qos.policy.QosPolicy') def test_add_policy(self, mock_qos_policy,", "= original_network ml2plugin_mock = mock.MagicMock() with mock.patch.object( self.qos_plugin, '_change_placement_allocation') as", "ks_exc.Conflict( response={'errors': [{'code': 'placement.concurrent_update'}]} ) self.assertRaises( neutron_qos_exc.QosPlacementAllocationUpdateConflict, self.qos_plugin._change_placement_allocation, qos1, qos2,", "mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_rule_delete, 'delete') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() _policy =", "= self._get_policy() setattr(_policy, \"rules\", [self.min_pps_rule]) new_rule_data = { 'minimum_packet_rate_rule': {", "request = self.new_show_request(resource, rule_id, self.fmt) res = request.get_response(self.ext_api) if res.status_int", "self.ctxt, id=uuidutils.generate_uuid(), network_id=uuidutils.generate_uuid(), device_owner='') with mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy), \\ mock.patch(", "in ports: self.assertEqual( 2, len(port['resource_request']['request_groups']) ) self.assertIn( { 'id': 'fake_uuid0',", "'neutron.db.db_base_plugin_v2.NeutronDbPluginV2' SERVICE_PLUGIN_KLASS = 'neutron.services.qos.qos_plugin.QoSPlugin' class TestQosPlugin(base.BaseQosTestCase): def setUp(self): super(TestQosPlugin, self).setUp()", "'fake_uuid1'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_no_qos_policy(self): port = self._create_and_extend_port([], physical_network='public', has_qos_policy=False)", "self.qos_plugin.get_policy_minimum_bandwidth_rule, self.ctxt, self.rule.id, self.policy.id) def test_get_policy_minimum_bandwidth_rules_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises(", "'min_kpps': 10, 'direction': 'ingress' } }, { 'minimum_packet_rate_rule': { 'id':", "is None or policy_id == original_policy_id: get_port.assert_not_called() get_policy.assert_not_called() validate_policy_for_port.assert_not_called() else:", "test_delete_policy_min_pps_rule(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.min_pps_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy):", "return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumPacketRateRule.' 'get_objects') as get_objects_mock: self.qos_plugin.get_policy_minimum_packet_rate_rules( self.ctxt, self.policy.id)", "[{ 'parameter_name': 'min_kpps', 'parameter_type': lib_constants.VALUES_TYPE_RANGE, 'parameter_range': {'start': 0, 'end': 100}", "mock_update_qos_alloc.side_effect = ks_exc.Conflict( response={'errors': [{'code': 'placement.concurrent_update'}]} ) self.assertRaises( neutron_qos_exc.QosPlacementAllocationUpdateConflict, self.qos_plugin._change_placement_allocation,", "mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_min_bw_dataplane_enforcement(self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() orig_port,", "QOS_MIN_PPS_RULE_ID = '6ac5db7e-1626-11ec-8c7f-0b70dbb8a8eb' # uuid -v5 f02f160e-1612-11ec-b2b8-bf60ab98186c # 6ac5db7e-1626-11ec-8c7f-0b70dbb8a8eb MIN_PPS_REQUEST_GROUP_UUID", "): self.policy.rules = [self.rule] self.assertRaises( qos_exc.QosRuleNotSupported, self.qos_plugin.validate_policy_for_port, self.ctxt, self.policy, port)", "binding_prof = { 'pci_slot': '0000:42:41.0', 'pci_vendor_info': '8086:107ed', 'physical_network': 'sriov_phy' }", "= self._prepare_for_port_placement_allocation_change( qos1=qos1_obj, qos2=qos1_obj) context = kwargs['context'] original_port = kwargs['original_port']", "= self._create_and_extend_port([self.min_bw_rule]) self.assertEqual( 1, len(port['resource_request']['request_groups']) ) self.assertEqual( 'fake_uuid', port['resource_request']['request_groups'][0]['id'] )", "self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.delete_policy_minimum_packet_rate_rule, self.ctxt, self.min_pps_rule.id, _policy.id) def test_delete_policy_min_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "def test_change_placement_allocation_min_bw_dataplane_enforcement(self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() orig_port, port", "test_validate_create_network_callback_no_qos(self): self._test_validate_create_network_callback(network_qos=False) def _test_validate_create_port_callback(self, port_qos=False, network_qos=False): net_qos_obj = self._make_qos_policy() port_qos_obj", "as obj_utils from neutron_lib.plugins import constants as plugins_constants from neutron_lib.plugins", "qos_policy def _make_qos_minbw_rule(self, policy_id, direction='ingress', min_kbps=1000, rule_id=None): rule_id = rule_id", "self.qos_plugin.create_policy_bandwidth_limit_rule, self.ctxt, self.policy.id, self.rule_data) def test_update_policy_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises(", "= '%s_rule' % rule_type data = self.rule_data[rule_data_name] rule = rule_object_class(self.ctxt,", "webob.exc.HTTPClientError.code: raise webob.exc.HTTPClientError(code=res.status_int) return self.deserialize(self.fmt, res) def _show_rule(self, rule_type, rule_id):", "self.rule_data) except NotImplementedError: self.fail() @mock.patch( 'neutron.objects.rbac_db.RbacNeutronDbObjectMixin' '.create_rbac_policy') @mock.patch('neutron.objects.qos.policy.QosPolicy') def test_add_policy(self,", "mock.patch.object( self.qos_plugin, '_change_placement_allocation') as mock_alloc_change: self.qos_plugin._check_network_for_placement_allocation_change( 'network', 'after_update', ml2plugin_mock, payload=events.DBEventPayload(", "original_qos, qos, {'id': port1.id, 'device_owner': 'compute:uu:id', 'qos_policy_id': None, 'qos_network_policy_id': qos.id},", "= [ port for port in network_ports if port.qos_policy_id is", "= mock.MagicMock() with mock.patch.object( self.qos_plugin, '_change_placement_allocation') as mock_alloc_change: self.qos_plugin._check_network_for_placement_allocation_change( 'network',", "@mock.patch.object(qos_plugin.QoSPlugin, \"delete_policy_rule\") def test_delete_rule(self, delete_policy_rule_mock): calls = [] for rule_type,", "mock.Mock() mock_manager.attach_mock(mock_qos_rule_delete, 'delete') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() _policy = policy_object.QosPolicy( self.ctxt,", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.qos_plugin.create_policy_bandwidth_limit_rule( self.ctxt, _policy.id, self.rule_data) self._validate_driver_params('update_policy',", "self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_dscp_marking_rules, self.ctxt, self.policy.id) def test_get_policy_minimum_bandwidth_rule(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy):", "self.qos_plugin, '_get_ports_with_policy', return_value=[port]): try: self.qos_plugin.create_policy_minimum_packet_rate_rule( self.ctxt, _policy.id, self.rule_data) except NotImplementedError:", "self.ctxt, qos_consts.RULE_TYPE_PACKET_RATE_LIMIT) def test_create_min_pps_rule_on_bound_port(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.min_pps_rule])", "mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt, self.policy.id, self.rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_min_pps_rule(self):", "test_check_port_for_placement_allocation_change(self): qos1_obj = self._make_qos_policy() qos2_obj = self._make_qos_policy() kwargs = self._prepare_for_port_placement_allocation_change(", "qos1, qos2, qos_network_policy=None): qos1_id = qos1.id if qos1 else None", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumBandwidthRule.' 'get_object') as get_object_mock: self.qos_plugin.get_policy_minimum_bandwidth_rule( self.ctxt,", "def test__extend_port_resource_request_non_min_bw_or_min_pps_rule(self): port = self._create_and_extend_port([], []) self.assertIsNone(port.get('resource_request')) def test__extend_port_resource_request_min_bw_non_provider_net(self): self.min_bw_rule.direction", "self._make_port(network_id=network.id, qos_policy_id=port_qos.id, device_owner='compute:uu:id') ml2plugin_mock = mock.MagicMock() with mock.patch.object( self.qos_plugin, '_change_placement_allocation')", "in self.rule_objects.items(): rule_id = uuidutils.generate_uuid() rule_data_name = '%s_rule' % rule_type", "project_id, 'tenant_id': project_id, 'name': 'test-policy', 'description': 'Test policy description', 'shared':", "webob.exc.HTTPClientError(code=res.status_int) @mock.patch.object(qos_plugin.QoSPlugin, \"update_policy_rule\") def test_update_rule(self, update_policy_rule_mock): calls = [] for", "5000, 'direction': self.rule.direction } } with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj:", "'direction': lib_constants.INGRESS_DIRECTION} min_bw_rule_ingress = rule_object.QosMinimumBandwidthRule( self.ctxt, **min_bw_rule_ingress_data) min_pps_rule_ingress = rule_object.QosMinimumPacketRateRule(", "{ 'id': 'fake_uuid0', 'required': ['CUSTOM_PHYSNET_PUBLIC', 'CUSTOM_VNIC_TYPE_NORMAL'], 'resources': { orc.NET_BW_EGR_KILOBIT_PER_SEC: 10,", "self.ctxt, self.dscp_rule.id, self.policy.id) self._validate_driver_params('update_policy', self.ctxt) def test_get_policy_dscp_marking_rules(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy):", "= network_object.Network(self.context, qos_policy_id=qos_policy_id) network.create() return network def _test_validate_create_network_callback(self, network_qos=False): net_qos_obj", "port1.update() port2.update() self.assertDictEqual( port1.bindings[0].profile, {'allocation': 'fake_allocation'}) self.assertDictEqual( port2.bindings[0].profile, {'allocation': 'fake_allocation'})", "self.ctxt, self.rule.id, self.policy.id, self.rule_data) def _get_policy(self): return policy_object.QosPolicy( self.ctxt, **self.policy_data['policy'])", "ctxt): call_args = self.qos_plugin.driver_manager.call.call_args[0] self.assertTrue(self.qos_plugin.driver_manager.call.called) self.assertEqual(call_args[0], method_name) self.assertEqual(call_args[1], ctxt) self.assertIsInstance(call_args[2],", "{orc.NET_PACKET_RATE_KILOPACKET_PER_SEC: 10}, port['resource_request']['request_groups'][0]['resources'], ) self.assertEqual( ['fake_uuid'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_bulk_min_bw_rule(self):", "self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(policy_delete_mock_call) < mock_manager.mock_calls.index(delete_precommit_mock_call) < mock_manager.mock_calls.index(delete_mock_call)) @mock.patch.object(policy_object.QosPolicy, \"get_object\")", "setattr(_policy, \"rules\", [self.rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.create_policy_minimum_bandwidth_rule,", "self.policy.id) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id) def test_get_policy_packet_rate_limit_rules_for_policy_with_filters(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy):", "**self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", [self.pps_rule]) self.qos_plugin.create_policy_packet_rate_limit_rule( self.ctxt, self.policy.id,", "self._make_port( network.id, qos_policy_id=qos1_id, port_id=TestQosPluginDB.PORT_ID) return {\"context\": self.context, \"original_port\": { \"id\":", "direction=direction, min_kpps=min_kpps, id=rule_id) qos_rule.create() return qos_rule def _make_port(self, network_id, qos_policy_id=None,", "mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_min_pps_rule(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.min_pps_rule])", "*mocks): policy_id = uuidutils.generate_uuid() project_id = uuidutils.generate_uuid() tenant_policy = {", "mock_manager.mock_calls.index(update_mock_call)) @mock.patch('neutron.objects.db.api.get_object', return_value=None) @mock.patch.object(policy_object.QosPolicy, 'delete') def test_delete_policy(self, mock_qos_policy_delete, mock_api_get_policy): mock_manager", "with mock.patch('neutron.objects.qos.rule.' 'QosPacketRateLimitRule.' 'get_objects') as get_objects_mock: filters = {'filter': 'filter_id'}", "['fake_uuid'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_bulk_min_pps_rule(self): ports = self._create_and_extend_ports([], [self.min_pps_rule]) for", "rule_delete_mock_call = mock.call.delete() update_precommit_mock_call = mock.call.driver.call( 'update_policy_precommit', self.ctxt, mock.ANY) update_mock_call", "def test_create_policy_rule_check_rule_min_less_than_max(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "[{ 'parameter_name': 'max_kbps', 'parameter_type': lib_constants.VALUES_TYPE_RANGE, 'parameter_range': {'start': 0, 'end': 100}", "def _show_rule(self, rule_type, rule_id): resource = '%s/alias-%s-rules' % (qos.ALIAS, rule_type.replace('_',", "port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': 1000}}) self._assert_pci_info(port) def test_change_placement_allocation_increase_min_pps(self): qos1", "plugins_constants from neutron_lib.plugins import directory from neutron_lib.services.qos import constants as", "self).setUp() self.setup_coreplugin(load_plugins=False) mock.patch('neutron.objects.db.api.create_object').start() mock.patch('neutron.objects.db.api.update_object').start() mock.patch('neutron.objects.db.api.delete_object').start() mock.patch('neutron.objects.db.api.get_object').start() _mock_qos_load_attr = mock.patch( 'neutron.objects.qos.policy.QosPolicy.obj_load_attr')", "webob.exc.HTTPClientError.code: raise webob.exc.HTTPClientError(code=res.status_int) return self.deserialize(self.fmt, res) def _delete_rule(self, rule_type, rule_id):", "oslo_config import cfg from oslo_utils import uuidutils import webob.exc from", "= mock_manager.mock_calls.index(rule_mock_call) else: action_index = mock_manager.mock_calls.index( get_rule_mock_call) self.assertLess( action_index, mock_manager.mock_calls.index(driver_mock_call))", "test_change_placement_allocation_change_dir_min_pps_ingress_to_any( self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() orig_port, port", "@mock.patch.object(rule_object.QosBandwidthLimitRule, 'update') def test_update_policy_rule(self, mock_qos_rule_update): mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_rule_update, 'update')", "'uuid.uuid5', return_value='fake_uuid', side_effect=request_groups_uuids): return qos_plugin.QoSPlugin._extend_port_resource_request( port_res, self.port) def _create_and_extend_ports(self, min_bw_rules,", "min_pps_rules=None, physical_network='public', request_groups_uuids=None): network_id = uuidutils.generate_uuid() ports_res = [ {", "policy description', 'shared': True, 'is_default': False}} policy_details = {'id': policy_id,", "self.policy.id) self._validate_driver_params('update_policy', self.ctxt) def test_get_policy_dscp_marking_rules(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.'", "device_owner='compute:uu:id') port2_binding = ports_object.PortBinding( self.context, port_id=port2.id, host='fake_host2', vnic_type='fake_vnic_type', vif_type='fake_vif_type', profile={})", "**self.policy_data['policy']) def test_update_policy_rule_bad_policy(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "self.qos_plugin._check_port_for_placement_allocation_change( 'PORT', 'before_update', 'test_plugin', payload=events.DBEventPayload( context, states=(original_port, port))) mock_alloc_change.assert_called_once_with( qos1_obj,", "None qos2_id = qos2.id if qos2 else None qos_network_policy_id =", "context.Context('fake_user', 'fake_tenant') self.rule_objects = { 'minimum_packet_rate': rule_object.QosMinimumPacketRateRule } self.qos_policy_id =", "qos_pps_minimum_rule_alias from neutron.extensions import qos_rules_alias from neutron import manager from", "_policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) setattr(_policy, \"rules\", [self.rule]) with mock.patch('neutron.objects.qos.rule.get_rules',", "rule_object.QosMinimumPacketRateRule( self.ctxt, **self.rule_data['minimum_packet_rate_rule']) def _validate_driver_params(self, method_name, ctxt): call_args = self.qos_plugin.driver_manager.call.call_args[0]", "try: self.qos_plugin.create_policy_minimum_packet_rate_rule( self.ctxt, _policy.id, self.rule_data) except NotImplementedError: self.fail() def test_create_policy_rule_check_rule_min_pps_direction_conflict(self):", "'validate_policy_for_network') \\ as mock_validate_policy: self.qos_plugin._validate_create_network_callback( \"NETWORK\", \"precommit_create\", \"test_plugin\", payload=events.DBEventPayload( self.context,", "_policy.id, self.rule_data) def test_create_min_pps_rule_on_unbound_port(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.min_pps_rule])", "False}} policy_details = {'id': policy_id, 'project_id': project_id, 'name': 'test-policy', 'description':", "qos_exc.QosPolicyNotFound, self.qos_plugin.delete_policy_packet_rate_limit_rule, self.ctxt, self.pps_rule.id, self.policy.id) def test_get_pps_rule_type(self): admin_ctxt = context.get_admin_context()", "self.ctxt) rule_delete_mock_call = mock.call.delete() update_precommit_mock_call = mock.call.driver.call( 'update_policy_precommit', self.ctxt, mock.ANY)", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", []) self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.update_policy_packet_rate_limit_rule, self.ctxt, self.pps_rule.id,", "with mock.patch.object( self.qos_plugin.driver_manager, \"validate_rule_for_network\", return_value=True ): self.policy.rules = [self.rule] try:", "rule_object_class, rule_id, self.qos_policy_id)) get_policy_rule_mock.assert_has_calls(calls, any_order=True) @mock.patch.object(qos_plugin.QoSPlugin, \"delete_policy_rule\") def test_delete_rule(self, delete_policy_rule_mock):", "mock_manager.mock_calls.index(update_mock_call)) def test_delete_policy_rule_bad_policy(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "(qos.ALIAS, rule_type.replace('_', '-')) request = self.new_update_request(resource, data, rule_id, self.fmt) res", "mock_validate_policy.assert_called_once_with( self.context, qos_policy, network.id) else: mock_validate_policy.assert_not_called() def test_validate_create_network_callback(self): self._test_validate_create_network_callback(network_qos=True) def", "None, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={ self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': -1000}, self.MIN_PPS_RP:", "on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS", "consumer_uuid='uu:id', alloc_diff={self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': 1000}}) self._assert_pci_info(port) def test_change_placement_allocation_increase_min_pps_and_min_bw(self): qos1 =", "= [self.rule] try: self.qos_plugin.validate_policy_for_port( self.ctxt, self.policy, port) except qos_exc.QosRuleNotSupported: self.fail(\"QosRuleNotSupported", "['fake_uuid'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_min_pps_rule(self): port = self._create_and_extend_port([], [self.min_pps_rule]) self.assertEqual(", "with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1, None, orig_port, port)", "as mock_update_qos_alloc: mock_update_qos_alloc.side_effect = ks_exc.Conflict( response={'errors': [{'code': 'placement.concurrent_update'}]} ) self.assertRaises(", "'fake_allocation'}) def _prepare_port_for_placement_allocation(self, original_qos, desired_qos=None, qos_network_policy=None, original_min_kbps=None, desired_min_kbps=None, original_min_kpps=None, desired_min_kpps=None,", "+= [self._make_qos_minbw_rule( qos.id, min_kbps=original_min_kbps, rule_id=TestQosPluginDB.QOS_MIN_BW_RULE_ID)] allocation.update( {TestQosPluginDB.MIN_BW_REQUEST_GROUP_UUID: TestQosPluginDB.MIN_BW_RP}) if original_min_kpps:", "policy_id }, \"original_network\": { \"id\": network_id, qos_consts.QOS_POLICY_ID: original_policy_id } }", "setattr(_policy, \"rules\", [self.min_pps_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.update_policy_minimum_packet_rate_rule( self.ctxt, self.min_pps_rule.id, self.policy.id,", "self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_packet_rate_limit_rule, self.ctxt, self.pps_rule.id, self.policy.id) def test_get_policy_packet_rate_limit_rules_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "vnic_type='fake_vnic_type', vif_type='fake_vif_type', profile={}) port2_binding.create() port2.bindings = [port2_binding] port2.update() with mock.patch.object(", "'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': 500}}) def test_change_placement_allocation_decrease(self): original_qos = self._make_qos_policy() desired_qos = self._make_qos_policy()", "self._test_validate_create_port_callback(port_qos=True) def test_validate_create_port_callback_policy_on_port_and_network(self): self._test_validate_create_port_callback(port_qos=True, network_qos=True) def test_validate_create_port_callback_policy_on_network(self): self._test_validate_create_port_callback(network_qos=True) def test_validate_create_port_callback_no_policy(self):", "] for new_rule_data in rules: with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj:", "self.rule.id, self.policy.id) get_object_mock.assert_called_once_with(self.ctxt, id=self.rule.id) def test_get_policy_minimum_bandwidth_rules_for_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with", "rule_object_class, rule_id, self.qos_policy_id)) delete_policy_rule_mock.assert_has_calls(calls, any_order=True) def test_show_non_existing_rule(self): for rule_type, rule_object_class", "* 2 min_bw_rule_ingress_data = { 'id': uuidutils.generate_uuid(), 'min_kbps': 20, 'direction':", "= [self.rule, self.min_bw_rule] setattr(_policy, \"rules\", rules) self.mock_qos_load_attr.reset_mock() with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy):", "'fake_allocation'}) self.assertDictEqual( port2.bindings[0].profile, {'allocation': 'fake_allocation'}) def _prepare_port_for_placement_allocation(self, original_qos, desired_qos=None, qos_network_policy=None,", "neutron.extensions import qos_rules_alias from neutron import manager from neutron.objects import", ") as get_policy, mock.patch.object( self.qos_plugin, \"validate_policy_for_port\" ) as validate_policy_for_port, mock.patch.object(", "test_create_policy_rule(self, mock_qos_rule_create, mock_qos_policy_get): _policy = copy.copy(self.policy) setattr(_policy, \"rules\", []) mock_qos_policy_get.return_value", "= self._create_and_extend_port([], physical_network='public', has_qos_policy=False) self.assertIsNone(port.get('resource_request')) def test__extend_port_resource_request_min_bw_inherited_policy( self): self.min_bw_rule.direction =", "self._get_policy() setattr(_policy, \"rules\", [self.min_pps_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.update_policy_minimum_packet_rate_rule( self.ctxt, self.min_pps_rule.id,", "get_request_extensions(self): return [] class QoSRuleAliasMinimumPacketRateTestExtensionManager(object): def get_resources(self): return qos_pps_minimum_rule_alias.Qos_pps_minimum_rule_alias.\\ get_resources()", "True, 'is_default': False}} self.rule_data = { 'bandwidth_limit_rule': {'id': uuidutils.generate_uuid(), 'max_kbps':", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.update_policy_minimum_packet_rate_rule( self.ctxt, self.min_pps_rule.id, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def", "return_value=[port]): try: self.qos_plugin.create_policy_minimum_bandwidth_rule( self.ctxt, policy.id, self.rule_data) except NotImplementedError: self.fail() @mock.patch(", "qos_plugin.QoSPlugin._extend_port_resource_request( port_res, self.port) def _create_and_extend_ports(self, min_bw_rules, min_pps_rules=None, physical_network='public', request_groups_uuids=None): network_id", "\"validate_rule_for_port\", return_value=True ): self.policy.rules = [self.rule] try: self.qos_plugin.validate_policy_for_port( self.ctxt, self.policy,", "= self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation( qos1, qos2, desired_min_kbps=1000) with", "policy_object.QosPolicy) def _create_and_extend_port(self, min_bw_rules, min_pps_rules=None, physical_network='public', has_qos_policy=True, has_net_qos_policy=False, request_groups_uuids=None): network_id", "< mock_manager.mock_calls.index(create_precommit_mock_call) < mock_manager.mock_calls.index(create_mock_call)) def test_add_policy_with_extra_tenant_keyword(self, *mocks): policy_id = uuidutils.generate_uuid()", "return_value=_policy) as mock_qos_get_obj: self.assertRaises( qos_exc.QoSRulesConflict, self.qos_plugin.create_policy_bandwidth_limit_rule, self.ctxt, _policy.id, new_rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt,", "qos_exc.QoSRuleParameterConflict, self.qos_plugin.update_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, self.policy.id, self.rule_data) def _get_policy(self): return policy_object.QosPolicy(", "self.assertEqual( ['fake_uuid0', 'fake_uuid1'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_non_min_bw_or_min_pps_rule(self): port = self._create_and_extend_port([],", "= {'filter': 'filter_id'} self.qos_plugin.get_policy_bandwidth_limit_rules( self.ctxt, self.policy.id, filters=filters) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY,", "def test_change_placement_allocation_no_original_allocation(self): qos1 = self._make_qos_policy() rule1_obj = self._make_qos_minbw_rule(qos1.id, min_kbps=500) qos1.rules", "rule_id, self.qos_policy_id)) delete_policy_rule_mock.assert_has_calls(calls, any_order=True) def test_show_non_existing_rule(self): for rule_type, rule_object_class in", "in types)) @mock.patch('neutron.objects.ports.Port') @mock.patch('neutron.objects.qos.policy.QosPolicy') def test_rule_notification_and_driver_ordering(self, qos_policy_mock, port_mock): rule_cls_mock =", "Licensed under the Apache License, Version 2.0 (the \"License\"); you", "\\ mock.patch.object( self.qos_plugin, '_get_ports_with_policy', return_value=[port]): try: self.qos_plugin.create_policy_minimum_bandwidth_rule( self.ctxt, policy.id, self.rule_data)", "[self.min_bw_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.qos_plugin.create_policy_bandwidth_limit_rule( self.ctxt, _policy.id, self.rule_data)", "qos_exc.QosPolicyNotFound, self.qos_plugin.delete_policy_minimum_packet_rate_rule, self.ctxt, self.min_pps_rule.id, self.policy.id) def test_get_policy_min_pps_rule(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy):", "= self._prepare_for_port_placement_allocation_change( qos1=qos1_obj, qos2=qos2_obj) context = kwargs['context'] original_port = kwargs['original_port']", "self.assertTrue( mock_manager.mock_calls.index(policy_mock_call) < mock_manager.mock_calls.index(create_precommit_mock_call) < mock_manager.mock_calls.index(create_mock_call)) def test_add_policy_with_extra_tenant_keyword(self, *mocks): policy_id", "consumer_uuid='uu:id', alloc_diff={self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': 1000}}) self._assert_pci_info(port) def test_change_placement_allocation_increase_min_pps(self): qos1 = self._make_qos_policy()", "network_id, qos_consts.QOS_POLICY_ID: policy_id }, \"original_network\": { \"id\": network_id, qos_consts.QOS_POLICY_ID: original_policy_id", "get_objects_mock: filters = {'filter': 'filter_id'} self.qos_plugin.get_policy_packet_rate_limit_rules( self.ctxt, self.policy.id, filters=filters) get_objects_mock.assert_called_once_with(", "[{ 'parameter_name': 'max_kpps', 'parameter_type': lib_constants.VALUES_TYPE_RANGE, 'parameter_range': {'start': 0, 'end': 100}", "self): qos_network = self._make_qos_policy() desired_qos = self._make_qos_policy() kwargs = self._prepare_for_port_placement_allocation_change(", "self._make_qos_policy() rule1_obj = self._make_qos_minbw_rule(qos1.id, min_kbps=500) qos1.rules = [rule1_obj] qos2 =", "-2000}}) def test_change_placement_allocation_no_min_bw(self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() bw_limit_rule1", "['aa', 'bb', 'cc', 'dd', 'ee', 'ff'] mac = netaddr.EUI(next(net_utils.random_mac_generator(base_mac))) device_owner", "def test_change_placement_allocation_update_conflict(self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() orig_port, port", "mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': -1000}}) self._assert_pci_info(port) def test_change_placement_allocation_decrease_min_pps(self): original_qos =", "kwargs['original_port'] qos = original_qos or qos_network_policy qos.rules = [] allocation", "qos2 = self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation( qos1, qos2, original_min_kpps=1000,", "policy self._make_port(network_id=network.id, qos_policy_id=port_qos.id, device_owner='compute:uu:id') ml2plugin_mock = mock.MagicMock() with mock.patch.object( self.qos_plugin,", "def test__extend_port_resource_request_bulk_min_bw_rule(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION ports = self._create_and_extend_ports([self.min_bw_rule]) for port", "as mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.create_policy_minimum_bandwidth_rule, self.ctxt, self.policy.id, self.rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def", "mock_manager.reset_mock() self.qos_plugin.delete_policy(self.ctxt, self.policy.id) self._validate_driver_params('delete_policy', self.ctxt) policy_delete_mock_call = mock.call.delete() delete_precommit_mock_call =", "mock.ANY) create_mock_call = mock.call.driver.call( 'create_policy', self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(policy_mock_call) <", "self.ctxt, self.rule.id, self.policy.id, self.rule_data) @mock.patch.object(rule_object.QosBandwidthLimitRule, 'delete') def test_delete_policy_rule(self, mock_qos_rule_delete): mock_manager", "\"NETWORK\", \"precommit_update\", \"test_plugin\", payload=events.DBEventPayload( self.ctxt, desired_state=kwargs['network'], states=(kwargs['original_network'],))) if policy_id is", "self._test_validate_update_network_callback( policy_id=policy_id, original_policy_id=policy_id) def test_validate_update_network_callback_policy_removed(self): self._test_validate_update_network_callback( policy_id=None, original_policy_id=uuidutils.generate_uuid()) def test_validate_policy_for_port_rule_not_valid(self):", "= mock.call.create() update_precommit_mock_call = mock.call.driver.call( 'update_policy_precommit', self.ctxt, mock.ANY) update_mock_call =", "get_resources(self): return qos_pps_minimum_rule_alias.Qos_pps_minimum_rule_alias.\\ get_resources() def get_actions(self): return [] def get_request_extensions(self):", "= [bw_limit_rule1] qos2.rules = [bw_limit_rule2] orig_port = { 'binding:profile': {'allocation':", "= self._make_port( network_id=network.id, qos_policy_id=None, device_owner='compute:uu:id') port1_binding = ports_object.PortBinding( self.context, port_id=port1.id,", "if rule_mock_call in mock_manager.mock_calls: action_index = mock_manager.mock_calls.index(rule_mock_call) else: action_index =", "= [bw_limit_rule] orig_port, port = self._prepare_port_for_placement_allocation(qos1, original_min_kbps=1000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation')", "'unset_default').start() mock.patch.object(policy_object.QosPolicy, 'set_default').start() cfg.CONF.set_override(\"core_plugin\", DB_PLUGIN_KLASS) cfg.CONF.set_override(\"service_plugins\", [\"qos\"]) manager.init() self.qos_plugin =", "rule_cls_mock, self.rule.id, self.policy.id]} mock_manager = mock.Mock() mock_manager.attach_mock(qos_policy_mock, 'QosPolicy') mock_manager.attach_mock(port_mock, 'Port')", "def test_create_policy_min_pps_rule(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.min_pps_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "port = self._prepare_port_for_placement_allocation( original_qos, desired_qos, original_min_kbps=2000, desired_min_kbps=1000, is_sriov=True) with mock.patch.object(self.qos_plugin._placement_client,", "\"rules\", [self.min_pps_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.update_policy_minimum_packet_rate_rule( self.ctxt, self.min_pps_rule.id, self.policy.id, self.rule_data)", "qos1, None, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={ self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': -1000},", "test_create_policy_rule_check_rule_minbw_gr_than_bwlimit(self): _policy = self._get_policy() self.rule_data['minimum_bandwidth_rule']['min_kbps'] = 1000000 setattr(_policy, \"rules\", [self.rule])", "self.ctxt, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) rule_create_mock_call = mock.call.create() update_precommit_mock_call =", "qos_consts.RULE_TYPE_PACKET_RATE_LIMIT) self.assertEqual( qos_consts.RULE_TYPE_PACKET_RATE_LIMIT, rule_type_details['type']) self.assertEqual( drivers_details, rule_type_details['drivers']) def test_get_pps_rule_type_as_user(self): self.assertRaises(", "self.policy.id, \"network_id\": network_id, \"vnic_type\": \"normal\", } }, { \"resource_request\": {", "def test_get_min_pps_rule_type_as_user(self): self.assertRaises( lib_exc.NotAuthorized, self.qos_plugin.get_rule_type, self.ctxt, qos_consts.RULE_TYPE_MINIMUM_PACKET_RATE) class QoSRuleAliasTestExtensionManager(object): def", "qos2.rules: rule.direction = 'any' with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.assertRaises(NotImplementedError,", "port = self._prepare_port_for_placement_allocation( original_qos, desired_qos, original_min_kpps=2000, desired_min_kpps=1000, is_sriov=True) with mock.patch.object(self.qos_plugin._placement_client,", "desired_min_kpps=1000, is_sriov=True) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( original_qos, desired_qos,", "400, 'direction': self.pps_rule.direction } } with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj:", "'egress' } }, ] self.rule_data['minimum_packet_rate_rule']['direction'] = 'any' for rule_data in", "\"context\": self.ctxt, \"network\": { \"id\": network_id, qos_consts.QOS_POLICY_ID: policy_id }, \"original_network\":", ").start() mock.patch.object(policy_object.QosPolicy, 'unset_default').start() mock.patch.object(policy_object.QosPolicy, 'set_default').start() cfg.CONF.set_override(\"core_plugin\", DB_PLUGIN_KLASS) cfg.CONF.set_override(\"service_plugins\", [\"qos\"]) manager.init()", "self.qos_plugin._check_port_for_placement_allocation_change( 'PORT', 'before_update', 'test_plugin', payload=events.DBEventPayload( context, states=(original_port, port))) mock_alloc_change.assert_not_called() def", "as orc from oslo_config import cfg from oslo_utils import uuidutils", "self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation( qos1, qos2, desired_min_kbps=1000, original_min_kpps=500, desired_min_kpps=1000)", "return_value=None): self.qos_plugin.create_policy_bandwidth_limit_rule( self.ctxt, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) rule_create_mock_call = mock.call.create()", "as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_min_bw_dataplane_enforcement_with_pps( self):", "'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={", "rule_object.QosBandwidthLimitRule( self.ctxt, **self.rule_data['bandwidth_limit_rule']) self.dscp_rule = rule_object.QosDscpMarkingRule( self.ctxt, **self.rule_data['dscp_marking_rule']) self.min_bw_rule =", "'project_id': project_id, 'name': 'test-policy', 'description': 'Test policy description', 'shared': True,", "self.qos_plugin.update_policy_minimum_bandwidth_rule( self.ctxt, self.min_bw_rule.id, self.policy.id, self.rule_data) self.mock_qos_load_attr.assert_called_once_with('rules') self._validate_driver_params('update_policy', self.ctxt) self.rule_data['bandwidth_limit_rule']['max_kbps'] =", "import cfg from oslo_utils import uuidutils import webob.exc from neutron.exceptions", "TestQosPluginDB(base.BaseQosTestCase): PORT_ID = 'f02f160e-1612-11ec-b2b8-bf60ab98186c' QOS_MIN_BW_RULE_ID = '8bf8eb46-160e-11ec-8024-9f96be32099d' # uuid -v5", "'c8bc1b27-59a1-5135-aa33-aeecad6093f4' MIN_BW_RP = 'd7bea120-1626-11ec-9148-c32debfcf0f6' QOS_MIN_PPS_RULE_ID = '6ac5db7e-1626-11ec-8c7f-0b70dbb8a8eb' # uuid -v5", "with mock.patch('neutron.objects.qos.rule.' 'QosBandwidthLimitRule.' 'get_object') as get_object_mock: self.qos_plugin.get_policy_bandwidth_limit_rule( self.ctxt, self.rule.id, self.policy.id)", "original_network = self._make_network(original_qos.id) network = self._make_network(qos.id) ml2plugin_mock = mock.MagicMock() def", "as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( original_qos, desired_qos, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_BW_RP:", "desired_qos, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': -1000}}) self._assert_pci_info(port) def", "self.ctxt, policy.id, self.rule_data) def test_create_min_bw_rule_on_unbound_port(self): policy = self._get_policy() policy.rules =", "{'id': policy_id, 'project_id': project_id, 'name': 'test-policy', 'description': 'Test policy description',", "as get_object_mock: self.qos_plugin.get_policy_minimum_bandwidth_rule( self.ctxt, self.rule.id, self.policy.id) get_object_mock.assert_called_once_with(self.ctxt, id=self.rule.id) def test_get_policy_minimum_bandwidth_rules_for_policy(self):", "fake_make_port_dict(port): return { 'id': port.id, 'device_owner': port.device_owner, 'qos_policy_id': port.qos_policy_id, 'qos_network_policy_id':", "} }, ] segment_mock = mock.MagicMock(network_id=network_id, physical_network=physical_network) min_pps_rules = min_pps_rules", "port.qos_policy_id is None] expected_ports = ports + expected_network_ports with mock.patch(", "min_kbps=1000) qos2.rules = [rule2_obj] orig_port = {'id': 'u:u', 'device_id': 'i:d',", "description', 'shared': True, 'is_default': False}} self.rule_data = { 'bandwidth_limit_rule': {'id':", "'id': port.id, 'device_owner': port.device_owner, 'qos_policy_id': port.qos_policy_id, 'qos_network_policy_id': port.qos_network_policy_id, } ml2plugin_mock._make_port_dict.side_effect", "self.port_data['port']['qos_network_policy_id'] = self.policy.id self.port = ports_object.Port( self.ctxt, **self.port_data['port']) port_res =", "def test_change_placement_allocation_no_min_bw(self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() bw_limit_rule1 =", "< mock_manager.mock_calls.index(update_mock_call)) def test_create_policy_rule_check_rule_min_less_than_max(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.rule])", "= { 'id': uuidutils.generate_uuid(), 'min_kbps': 20, 'direction': lib_constants.INGRESS_DIRECTION} min_pps_rule_ingress_data =", "self.ctxt, self.policy.id, self.rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_min_pps_rule(self): _policy = self._get_policy()", "port2_binding = ports_object.PortBinding( self.context, port_id=port2.id, host='fake_host2', vnic_type='fake_vnic_type', vif_type='fake_vif_type', profile={}) port2_binding.create()", "mock.patch('neutron.objects.qos.rule.' 'QosPacketRateLimitRule.' 'get_objects') as get_objects_mock: self.qos_plugin.get_policy_packet_rate_limit_rules( self.ctxt, self.policy.id) get_objects_mock.assert_called_once_with( self.ctxt,", "mock.patch.object( self.qos_plugin, \"validate_policy_for_port\" ) as validate_policy_for_port, mock.patch.object( self.ctxt, \"elevated\", return_value=admin_ctxt", "self.ctxt, \"elevated\", return_value=admin_ctxt ): self.qos_plugin._validate_update_network_callback( \"NETWORK\", \"precommit_update\", \"test_plugin\", payload=events.DBEventPayload( self.ctxt,", "self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION port = self._create_and_extend_port([self.min_bw_rule]) self.assertEqual( 1, len(port['resource_request']['request_groups']) )", "return_value=ports ) as get_ports, mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=policy_mock ) as get_policy,", "lib_constants.VALUES_TYPE_RANGE, 'parameter_range': {'start': 0, 'end': 100} }] }] with mock.patch.object(", "as get_objects_mock: self.qos_plugin.get_policy_minimum_bandwidth_rules( self.ctxt, self.policy.id) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id) def", "= self._prepare_port_for_placement_allocation( original_qos, desired_qos, original_min_kbps=2000, desired_min_kbps=1000, is_sriov=True) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation')", "[self.rule]) self.qos_plugin.delete_policy_bandwidth_limit_rule( self.ctxt, self.rule.id, _policy.id) self._validate_driver_params('update_policy', self.ctxt) rule_delete_mock_call = mock.call.delete()", "return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosBandwidthLimitRule.' 'get_objects') as get_objects_mock: filters = {'filter':", "desired_qos, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': -1000}}) self._assert_pci_info(port)", "self.ctxt, self.rule.id, self.policy.id, self.rule_data) def test_delete_policy_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises(", "self.assertEqual( 2, len(port['resource_request']['request_groups']) ) self.assertIn( { 'id': 'fake_uuid0', 'required': ['CUSTOM_PHYSNET_PUBLIC',", "self.policy.id) def test_create_policy_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.create_policy_bandwidth_limit_rule, self.ctxt,", "self._validate_driver_params('update_policy', self.ctxt) def test_update_policy_pps_rule_bad_policy(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with", "rule_object.QosDscpMarkingRule(dscp_mark=16) qos2.rules = [bw_limit_rule] orig_port, port = self._prepare_port_for_placement_allocation(qos1, original_min_kbps=1000) with", "self.ctxt, self.policy.id) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id) def test_get_policy_dscp_marking_rules_for_policy_with_filters(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "port1.update() self.assertDictEqual(port1.bindings[0].profile, {}) def test_check_network_for_placement_allocation_change(self): original_qos = self._make_qos_policy() qos =", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.update_policy_minimum_packet_rate_rule( self.ctxt, self.min_pps_rule.id, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt)", "qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_dscp_marking_rules, self.ctxt, self.policy.id) def test_get_policy_minimum_bandwidth_rule(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with", "= ports_object.PortBinding( self.context, port_id=port2.id, host='fake_host2', vnic_type='fake_vnic_type', vif_type='fake_vif_type', profile={}) port2_binding.create() port2.bindings", "request = self.new_show_request(resource, rule_id, self.fmt) res = request.get_response(self.ext_api) self.assertEqual(webob.exc.HTTPNotFound.code, res.status_int)", "and limitations # under the License. import copy from unittest", "{ 'id': uuidutils.generate_uuid(), 'min_kbps': 10}, 'packet_rate_limit_rule': { 'id': uuidutils.generate_uuid(), 'max_kpps':", "\"resource_request\": { \"port_id\": uuidutils.generate_uuid(), \"qos_id\": self.policy.id, \"network_id\": network_id, \"vnic_type\": \"normal\",", "qos_exc.QosRuleNotSupportedByNetwork: self.fail(\"QosRuleNotSupportedByNetwork \" \"exception unexpectedly raised\") def test_create_min_bw_rule_on_bound_port(self): policy =", "test_create_policy_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.create_policy_bandwidth_limit_rule, self.ctxt, self.policy.id, self.rule_data)", "self.qos_plugin.get_policy_minimum_packet_rate_rules( self.ctxt, self.policy.id) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id) def test_get_policy_min_pps_rules_for_policy_with_filters(self): with", "**policy_details) @mock.patch.object(policy_object.QosPolicy, \"get_object\") @mock.patch( 'neutron.objects.rbac_db.RbacNeutronDbObjectMixin' '.create_rbac_policy') @mock.patch.object(policy_object.QosPolicy, 'update') def test_update_policy(self,", "mock.patch( 'neutron.objects.network.Network.get_object', return_value=net), \\ mock.patch.object( self.qos_plugin, '_get_ports_with_policy', return_value=[port]): self.assertRaises( NotImplementedError,", "setattr(_policy, 'rules', rules) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.update_policy_minimum_packet_rate_rule,", "self.ctxt, mock.ANY) create_mock_call = mock.call.driver.call( 'create_policy', self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(policy_mock_call)", "self.qos_plugin._check_network_for_placement_allocation_change( 'network', 'after_update', ml2plugin_mock, payload=events.DBEventPayload( self.context, states=(original_network, network))) mock_alloc_change.assert_not_called() ml2plugin_mock._make_port_dict.assert_not_called()", "qos2_obj = self._make_qos_policy() kwargs = self._prepare_for_port_placement_allocation_change( qos1=qos1_obj, qos2=qos2_obj) context =", "return_value=_policy) as mock_qos_get_obj: self.qos_plugin.create_policy_bandwidth_limit_rule( self.ctxt, _policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) self.mock_qos_load_attr.assert_called_once_with('rules')", "self._validate_driver_params('update_policy', self.ctxt) self.mock_qos_load_attr.assert_called_once_with('rules') mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_rule_check_rule_bwlimit_less_than_minbw(self): _policy = self._get_policy()", "**self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", []) self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.delete_policy_packet_rate_limit_rule,", "# some actions get rule from policy get_rule_mock_call = getattr(", "self.qos_plugin.create_policy_packet_rate_limit_rule, self.ctxt, _policy.id, new_rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_update_policy_packet_rate_limit_rule(self): _policy =", "'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_new_policy_empty(self):", "\"supported_rule_type_details\", return_value=drivers_details ): rule_type_details = self.qos_plugin.get_rule_type( admin_ctxt, qos_consts.RULE_TYPE_MINIMUM_PACKET_RATE) self.assertEqual( qos_consts.RULE_TYPE_MINIMUM_PACKET_RATE,", "self.qos_policy_id = uuidutils.generate_uuid() self.rule_data = { 'bandwidth_limit_rule': {'max_kbps': 100, 'max_burst_kbps':", "from neutron.objects import network as network_object from neutron.objects import ports", "original_min_kpps=2000, desired_min_kpps=1000, is_sriov=True) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( original_qos,", "mock.patch.object( self.qos_plugin, '_change_placement_allocation') as mock_alloc_change: def fake_change_placement_allocation(orig_policy, policy, orig_port, port):", "} with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises( qos_exc.QoSRulesConflict, self.qos_plugin.create_policy_bandwidth_limit_rule, self.ctxt,", "any_order=True) @mock.patch.object(qos_plugin.QoSPlugin, \"delete_policy_rule\") def test_delete_rule(self, delete_policy_rule_mock): calls = [] for", "] segment_mock = mock.MagicMock(network_id=network_id, physical_network=physical_network) min_pps_rules = min_pps_rules if min_pps_rules", "'update_policy', self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(rule_update_mock_call) < mock_manager.mock_calls.index(update_precommit_mock_call) < mock_manager.mock_calls.index(update_mock_call)) def", "self.rule_data) def test_delete_policy_min_pps_rule(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.min_pps_rule]) with", "'after_update', ml2plugin_mock, payload=events.DBEventPayload( self.context, states=(original_network, network))) self.assertEqual(ml2plugin_mock._make_port_dict.call_count, 1) mock_alloc_change_calls =", "raise webob.exc.HTTPClientError(code=res.status_int) @mock.patch.object(qos_plugin.QoSPlugin, \"update_policy_rule\") def test_update_rule(self, update_policy_rule_mock): calls = []", "test_validate_policy_for_network(self): network = uuidutils.generate_uuid() with mock.patch.object( self.qos_plugin.driver_manager, \"validate_rule_for_network\", return_value=True ):", "network_qos: qos_policy = net_qos_obj if qos_policy: mock_validate_policy.assert_called_once_with( self.context, qos_policy, port)", "data = self.rule_data[rule_data_name] rule = rule_object_class(self.ctxt, id=rule_id, qos_policy_id=self.qos_policy_id, **data) with", "calls.append(mock.call(mock.ANY, rule_object_class, rule_id, self.qos_policy_id)) delete_policy_rule_mock.assert_has_calls(calls, any_order=True) def test_show_non_existing_rule(self): for rule_type,", "_policy = self._get_policy() setattr(_policy, \"rules\", [self.rule]) new_rule_data = { 'bandwidth_limit_rule':", "qos_exc.QosRuleNotFound, self.qos_plugin.delete_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, _policy.id) def test_get_policy_bandwidth_limit_rule(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy):", "self.policy.id, \"network_id\": network_id, \"vnic_type\": \"normal\", } }, ] segment_mock =", "self.qos_plugin.get_policy_packet_rate_limit_rule, self.ctxt, self.pps_rule.id, self.policy.id) def test_get_policy_packet_rate_limit_rules_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises(", "self.setup_coreplugin(load_plugins=False) mock.patch('neutron.objects.db.api.create_object').start() mock.patch('neutron.objects.db.api.update_object').start() mock.patch('neutron.objects.db.api.delete_object').start() mock.patch('neutron.objects.db.api.get_object').start() _mock_qos_load_attr = mock.patch( 'neutron.objects.qos.policy.QosPolicy.obj_load_attr') self.mock_qos_load_attr", "= [port1_binding] port1.update() port2 = self._make_port( network_id=network.id, qos_policy_id=None, device_owner='compute:uu:id') port2_binding", "pl_exc.PlacementAllocationGenerationConflict( consumer=self.MIN_BW_RP)) self.assertRaises( pl_exc.PlacementAllocationGenerationConflict, self.qos_plugin._change_placement_allocation, qos1, qos2, orig_port, port) def", "self.qos_plugin.update_policy_packet_rate_limit_rule( self.ctxt, self.pps_rule.id, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def test_update_policy_pps_rule_bad_policy(self): _policy", "mock_create_rbac_policy, mock_qos_policy_get): mock_qos_policy_get.return_value = self.policy mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_policy_update, 'update')", "self.project_id = uuidutils.generate_uuid() def _make_qos_policy(self): qos_policy = policy_object.QosPolicy( self.context, project_id=self.project_id,", "**data) with mock.patch( 'neutron.objects.qos.rule.QosRule.get_object', return_value=rule ), mock.patch.object(self.qos_plugin, 'get_policy_rule', return_value=rule.to_dict()): self._delete_rule(rule_type,", "\"network\": network} with mock.patch.object(self.qos_plugin, 'validate_policy_for_network') \\ as mock_validate_policy: self.qos_plugin._validate_create_network_callback( \"NETWORK\",", "mock_validate_policy: self.qos_plugin._validate_create_network_callback( \"NETWORK\", \"precommit_create\", \"test_plugin\", payload=events.DBEventPayload( self.context, resource_id=kwargs['network']['id'],)) qos_policy =", "self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation(qos1, original_min_kbps=1000, original_min_kpps=2000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation')", "def test_get_policy_min_pps_rules_for_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumPacketRateRule.' 'get_objects') as", "'rules', rules) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.update_policy_minimum_packet_rate_rule, self.ctxt,", "return_value=None) @mock.patch.object(policy_object.QosPolicy, 'delete') def test_delete_policy(self, mock_qos_policy_delete, mock_api_get_policy): mock_manager = mock.Mock()", "original_qos, qos, {'id': port2.id, 'device_owner': 'compute:uu:id', 'qos_policy_id': None, 'qos_network_policy_id': qos.id},", "from neutron_lib import exceptions as lib_exc from neutron_lib.exceptions import placement", "mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_PPS_RP: {", "'qos_network_policy_id': qos.id}, mock.ANY), mock.call( original_qos, qos, {'id': port2.id, 'device_owner': 'compute:uu:id',", "= mock.call.driver.call( 'update_policy', self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(rule_delete_mock_call) < mock_manager.mock_calls.index(update_precommit_mock_call) <", "id=uuidutils.generate_uuid(), network_id=uuidutils.generate_uuid(), device_owner='compute:fake-zone') with mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=policy), \\ mock.patch( 'neutron.objects.network.Network.get_object',", "filter='filter_id') def test_get_policy_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy, self.ctxt,", "original_min_kpps: qos.rules += [self._make_qos_minpps_rule( qos.id, min_kpps=original_min_kpps, rule_id=TestQosPluginDB.QOS_MIN_PPS_RULE_ID)] allocation.update( {TestQosPluginDB.MIN_PPS_REQUEST_GROUP_UUID: TestQosPluginDB.MIN_PPS_RP})", "self.policy.rules = [self.rule] try: self.qos_plugin.validate_policy_for_port( self.ctxt, self.policy, port) except qos_exc.QosRuleNotSupported:", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", [self.pps_rule]) self.qos_plugin.delete_policy_packet_rate_limit_rule( self.ctxt, self.pps_rule.id, self.policy.id) self._validate_driver_params('update_policy',", "_policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\",", "mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos_network, desired_qos, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC':", "def test_change_placement_allocation_new_rule_not_min_bw(self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() bw_limit_rule =", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", [self.rule]) self.qos_plugin.delete_policy_bandwidth_limit_rule( self.ctxt, self.rule.id, _policy.id) self._validate_driver_params('update_policy',", "policy_id is None or policy_id == original_policy_id: get_port.assert_not_called() get_policy.assert_not_called() validate_policy_for_port.assert_not_called()", "= mock.MagicMock(id=policy_id) admin_ctxt = mock.Mock() with mock.patch( 'neutron.objects.ports.Port.get_objects', return_value=ports )", "'shared': True, 'is_default': False}} policy_details = {'id': policy_id, 'project_id': project_id,", "MIN_PPS_REQUEST_GROUP_UUID = '995008f4-f120-547a-b051-428b89076067' MIN_PPS_RP = 'e16161f4-1626-11ec-a5a2-1fc9396e27cc' def setUp(self): super(TestQosPluginDB, self).setUp()", "'delete') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() self.qos_plugin.delete_policy(self.ctxt, self.policy.id) self._validate_driver_params('delete_policy', self.ctxt) policy_delete_mock_call =", "self.qos_plugin.delete_policy_packet_rate_limit_rule, self.ctxt, self.pps_rule.id, _policy.id) def test_get_policy_packet_rate_limit_rule(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with", "get rule from policy get_rule_mock_call = getattr( mock.call.QosPolicy.get_policy_obj().get_rule_by_id(), action)() #", "len(port['resource_request']['request_groups']) ) self.assertIn( { 'id': 'fake_uuid0', 'required': ['CUSTOM_PHYSNET_PUBLIC', 'CUSTOM_VNIC_TYPE_NORMAL'], 'resources':", "self.policy.id, self.rule_data) @mock.patch.object(rule_object.QosBandwidthLimitRule, 'delete') def test_delete_policy_rule(self, mock_qos_rule_delete): mock_manager = mock.Mock()", "= self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation( qos1, qos2, original_min_kbps=1000, desired_min_kbps=2000)", "test_create_policy_packet_rate_limit_rule(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy,", "return_value=_policy) as mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.create_policy_bandwidth_limit_rule, self.ctxt, self.policy.id, self.rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id)", "return qos_plugin.QoSPlugin._extend_port_resource_request( port_res, self.port) def _create_and_extend_ports(self, min_bw_rules, min_pps_rules=None, physical_network='public', request_groups_uuids=None):", "uuidutils.generate_uuid() self._test_validate_update_network_callback( policy_id=policy_id, original_policy_id=policy_id) def test_validate_update_network_callback_policy_removed(self): self._test_validate_update_network_callback( policy_id=None, original_policy_id=uuidutils.generate_uuid()) def", "new_rule_data = { 'packet_rate_limit_rule': { 'max_kpps': 400, 'direction': self.pps_rule.direction }", "setattr(_policy, \"rules\", rules) self.mock_qos_load_attr.reset_mock() with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.update_policy_minimum_bandwidth_rule( self.ctxt, self.min_bw_rule.id,", "network_id=network) except qos_exc.QosRuleNotSupportedByNetwork: self.fail(\"QosRuleNotSupportedByNetwork \" \"exception unexpectedly raised\") def test_create_min_bw_rule_on_bound_port(self):", "= policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", [self.dscp_rule])", "self.dscp_rule.id, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def test_delete_policy_dscp_marking_rule(self): _policy = policy_object.QosPolicy(", "qos2, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': -1000}}) def test_change_placement_allocation_equal_minkbps_and_minkpps(self):", "request = self.new_delete_request(resource, rule_id, self.fmt) res = request.get_response(self.ext_api) if res.status_int", "self._validate_driver_params('update_policy', self.ctxt) self.rule_data['bandwidth_limit_rule']['max_kbps'] = 1 with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.assertRaises( qos_exc.QoSRuleParameterConflict,", "for port in ports: self.assertEqual( 2, len(port['resource_request']['request_groups']) ) self.assertIn( {", "mock_alloc_change.assert_has_calls(mock_alloc_change_calls, any_order=True) port1.update() self.assertDictEqual(port1.bindings[0].profile, {}) def test_check_network_for_placement_allocation_change(self): original_qos = self._make_qos_policy()", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.qos_plugin.create_policy_minimum_bandwidth_rule( self.ctxt, _policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt)", "{ \"id\": port_id, qos_consts.QOS_POLICY_ID: original_policy_id } } port_mock = mock.MagicMock(id=port_id,", "ports = [port_mock_with_own_policy, port_mock_without_own_policy] policy_mock = mock.MagicMock(id=policy_id) admin_ctxt = mock.Mock()", "'test_plugin', payload=events.DBEventPayload( context, states=(original_port, port))) mock_alloc_change.assert_called_once_with( qos1_obj, None, kwargs['original_port'], port)", "= self._make_qos_policy() bw_limit_rule = rule_object.QosDscpMarkingRule(dscp_mark=16) qos2.rules = [bw_limit_rule] orig_port, port", "network_object.NetworkSegment( physical_network='fake physnet') net = network_object.Network( self.ctxt, segments=[segment]) port =", "< mock_manager.mock_calls.index(update_precommit_mock_call) < mock_manager.mock_calls.index(update_mock_call)) @mock.patch('neutron.objects.db.api.get_object', return_value=None) @mock.patch.object(policy_object.QosPolicy, 'delete') def test_delete_policy(self,", "self.assertEqual( qos_consts.RULE_TYPE_MINIMUM_PACKET_RATE, rule_type_details['type']) self.assertEqual( drivers_details, rule_type_details['drivers']) def test_get_min_pps_rule_type_as_user(self): self.assertRaises( lib_exc.NotAuthorized,", "id=_policy.id) def test_create_policy_rule_check_rule_minbw_gr_than_bwlimit(self): _policy = self._get_policy() self.rule_data['minimum_bandwidth_rule']['min_kbps'] = 1000000 setattr(_policy,", "\"rules\", [self.pps_rule]) self.qos_plugin.create_policy_packet_rate_limit_rule( self.ctxt, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def test_create_policy_pps_rule_duplicates(self):", "} } with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises( qos_exc.QoSRulesConflict, self.qos_plugin.create_policy_bandwidth_limit_rule,", "test_get_min_pps_rule_type(self): admin_ctxt = context.get_admin_context() drivers_details = [{ 'name': 'fake-driver', 'supported_parameters':", "'before_update', 'test_plugin', payload=events.DBEventPayload( context, states=(original_port, port))) mock_alloc_change.assert_not_called() def test_check_port_for_placement_allocation_change_qos_network_policy( self):", "id=port_id) get_policy.assert_called_once_with(admin_ctxt, id=policy_id) validate_policy_for_port.assert_called_once_with( self.ctxt, policy_mock, port_mock) def test_validate_update_port_callback_policy_changed(self): self._test_validate_update_port_callback(", "mock_manager.mock_calls.index(policy_mock_call) < mock_manager.mock_calls.index(create_precommit_mock_call) < mock_manager.mock_calls.index(create_mock_call)) def test_add_policy_with_extra_tenant_keyword(self, *mocks): policy_id =", "mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) @mock.patch.object(rule_object.QosBandwidthLimitRule, 'update') def test_update_policy_rule(self, mock_qos_rule_update): mock_manager = mock.Mock()", "return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosBandwidthLimitRule.' 'get_object') as get_object_mock: self.qos_plugin.get_policy_bandwidth_limit_rule( self.ctxt, self.rule.id,", "return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.create_policy_bandwidth_limit_rule, self.ctxt, self.policy.id, self.rule_data) def test_update_policy_rule_for_nonexistent_policy(self): with", "network_object.Network( self.ctxt, segments=[segment]) port = ports_object.Port( self.ctxt, id=uuidutils.generate_uuid(), network_id=uuidutils.generate_uuid(), device_owner='compute:fake-zone')", "context, states=(original_port, port))) mock_alloc_change.assert_called_once_with( qos_network, desired_qos, kwargs['original_port'], port) def test_check_network_for_placement_allocation_change_no_qos_change(self):", "{ 'packet_rate_limit_rule': { 'max_kpps': 400, 'direction': self.pps_rule.direction } } with", "= [ mock.MagicMock(qos_policy_id=self.policy.id), ] expected_network_ports = [ port for port", "as validate_policy_for_network, mock.patch.object( self.qos_plugin, \"validate_policy_for_ports\" ) as validate_policy_for_ports, mock.patch.object( self.ctxt,", "self.policy.id) get_object_mock.assert_called_once_with(self.ctxt, id=self.rule.id) def test_get_policy_bandwidth_limit_rules_for_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.'", "= self.policy.id self.port = ports_object.Port( self.ctxt, **self.port_data['port']) port_res = {\"binding:vnic_type\":", "self._create_and_extend_ports([self.min_bw_rule]) for port in ports: self.assertEqual( 1, len(port['resource_request']['request_groups']) ) self.assertEqual(", "'RuleCls') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') for action, arguments in rule_actions.items(): mock_manager.reset_mock() method", "orc.NET_PACKET_RATE_EGR_KILOPACKET_PER_SEC: 10, orc.NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC: 20, }, }, port['resource_request']['request_groups'] ) self.assertEqual( ['fake_uuid0',", "OF ANY KIND, either express or implied. See the #", "get_objects_mock: self.qos_plugin.get_policy_packet_rate_limit_rules( self.ctxt, self.policy.id) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id) def test_get_policy_packet_rate_limit_rules_for_policy_with_filters(self):", "get_objects_mock: self.qos_plugin.get_policy_dscp_marking_rules( self.ctxt, self.policy.id) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id) def test_get_policy_dscp_marking_rules_for_policy_with_filters(self):", "port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={ self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': 500}, self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC':", "= net_qos_obj if qos_policy: mock_validate_policy.assert_called_once_with( self.context, qos_policy, network.id) else: mock_validate_policy.assert_not_called()", "} binding_prof.update({'allocation': allocation}) orig_port.update( {'binding:profile': binding_prof, 'device_id': 'uu:id'} ) return", "We also need to mock-out # methods that work with", "['fake_uuid'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_min_bw_and_pps_rule(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION self.min_pps_rule.direction =", "qos2_obj, kwargs['original_port'], port) def test_check_port_for_placement_allocation_change_no_new_policy(self): qos1_obj = self._make_qos_policy() kwargs =", "'driver') mock_manager.reset_mock() self.qos_plugin.create_policy(self.ctxt, self.policy_data) policy_mock_call = mock.call.QosPolicy().create() create_precommit_mock_call = mock.call.driver.call(", "ctxt) self.assertIsInstance(call_args[2], policy_object.QosPolicy) def _create_and_extend_port(self, min_bw_rules, min_pps_rules=None, physical_network='public', has_qos_policy=True, has_net_qos_policy=False,", "def test_change_placement_allocation_decrease_min_pps(self): original_qos = self._make_qos_policy() desired_qos = self._make_qos_policy() orig_port, port", "in writing, software # distributed under the License is distributed", "port = self._make_port( network.id, qos_policy_id=qos1_id, port_id=TestQosPluginDB.PORT_ID) return {\"context\": self.context, \"original_port\":", "[] def get_request_extensions(self): return [] class TestQoSRuleAlias(test_db_base_plugin_v2.NeutronDbPluginV2TestCase): def setUp(self): #", "min_bw_rules, min_pps_rules=None, physical_network='public', has_qos_policy=True, has_net_qos_policy=False, request_groups_uuids=None): network_id = uuidutils.generate_uuid() self.port_data", "'get_objects', return_value=min_pps_rules), \\ mock.patch( 'uuid.uuid5', return_value='fake_uuid', side_effect=request_groups_uuids): return qos_plugin.QoSPlugin._extend_port_resource_request( port_res,", "qos_policy_id=self.policy.id) def test_get_policy_bandwidth_limit_rules_for_policy_with_filters(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosBandwidthLimitRule.' 'get_objects')", "qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy, self.ctxt, self.policy.id) def test_get_policy_bandwidth_limit_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises(", "< mock_manager.mock_calls.index(create_mock_call)) def test_add_policy_with_extra_tenant_keyword(self, *mocks): policy_id = uuidutils.generate_uuid() project_id =", "def test_rule_notification_and_driver_ordering(self, qos_policy_mock, port_mock): rule_cls_mock = mock.Mock() rule_cls_mock.rule_type = 'fake'", "mac = netaddr.EUI(next(net_utils.random_mac_generator(base_mac))) device_owner = device_owner if device_owner else '3'", "\"device_owner\": \"compute:uu:id\", \"qos_policy_id\": qos1_id, \"qos_network_policy_id\": qos_network_policy_id}, \"port\": {\"id\": port.id, \"qos_policy_id\":", "self.port_data = { 'port': {'id': uuidutils.generate_uuid(), 'network_id': network_id} } if", "filters = {'filter': 'filter_id'} self.qos_plugin.get_policy_dscp_marking_rules( self.ctxt, self.policy.id, filters=filters) get_objects_mock.assert_called_once_with( self.ctxt,", "f02f160e-1612-11ec-b2b8-bf60ab98186c # 6ac5db7e-1626-11ec-8c7f-0b70dbb8a8eb MIN_PPS_REQUEST_GROUP_UUID = '995008f4-f120-547a-b051-428b89076067' MIN_PPS_RP = 'e16161f4-1626-11ec-a5a2-1fc9396e27cc' def", "kwargs = self._prepare_for_port_placement_allocation_change( original_qos, desired_qos, qos_network_policy=qos_network_policy) orig_port = kwargs['original_port'] qos", "= rule_object.QosDscpMarkingRule(dscp_mark=16) bw_limit_rule2 = rule_object.QosDscpMarkingRule(dscp_mark=18) qos1.rules = [bw_limit_rule1] qos2.rules =", "self._get_policy() setattr(_policy, \"rules\", [self.rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.update_policy_bandwidth_limit_rule( self.ctxt, self.rule.id,", "= self._prepare_port_for_placement_allocation( qos1, qos2, desired_min_kbps=1000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc:", "self.ctxt) def test_update_policy_pps_rule_bad_policy(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "= [ mock.MagicMock(qos_policy_id=None), mock.MagicMock(qos_policy_id=uuidutils.generate_uuid()), mock.MagicMock(qos_policy_id=None) ] ports = [ mock.MagicMock(qos_policy_id=self.policy.id),", "self.rule_data) self._validate_driver_params('update_policy', self.ctxt) rule_update_mock_call = mock.call.update() update_precommit_mock_call = mock.call.driver.call( 'update_policy_precommit',", "actions construct rule from class reference rule_mock_call = getattr(mock.call.RuleCls(), action)()", "cfg.CONF.set_override(\"core_plugin\", DB_PLUGIN_KLASS) cfg.CONF.set_override(\"service_plugins\", [\"qos\"]) manager.init() self.qos_plugin = directory.get_plugin(plugins_constants.QOS) self.qos_plugin.driver_manager =", "uuidutils.generate_uuid() base_mac = ['aa', 'bb', 'cc', 'dd', 'ee', 'ff'] mac", "qos2 = self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation( qos1, qos2, desired_min_kbps=1000)", "'f02f160e-1612-11ec-b2b8-bf60ab98186c' QOS_MIN_BW_RULE_ID = '8bf8eb46-160e-11ec-8024-9f96be32099d' # uuid -v5 f02f160e-1612-11ec-b2b8-bf60ab98186c # 8bf8eb46-160e-11ec-8024-9f96be32099d", "= { 'minimum_packet_rate': rule_object.QosMinimumPacketRateRule } self.qos_policy_id = uuidutils.generate_uuid() self.rule_data =", "self._make_network(original_qos.id) network = self._make_network(qos.id) ml2plugin_mock = mock.MagicMock() def fake_make_port_dict(port): return", "orig_port, port) def test_change_placement_allocation_update_generation_conflict(self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy()", "self.ctxt, segments=[segment]) port = ports_object.Port( self.ctxt, id=uuidutils.generate_uuid(), network_id=uuidutils.generate_uuid(), device_owner='compute:fake-zone') with", "qos1, qos2, desired_min_kbps=1000, original_min_kpps=500, desired_min_kpps=1000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc:", "mock_manager.reset_mock() fields = obj_utils.get_updatable_fields( policy_object.QosPolicy, self.policy_data['policy']) self.qos_plugin.update_policy( self.ctxt, self.policy.id, {'policy':", "self.qos_plugin._change_placement_allocation, qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_min_bw_dataplane_enforcement(self): qos1 =", "def test_check_network_for_placement_allocation_change_no_ports_to_update( self): original_qos = self._make_qos_policy() qos = self._make_qos_policy() port_qos", "desired_qos = self._make_qos_policy() kwargs = self._prepare_for_port_placement_allocation_change( qos1=None, qos2=desired_qos, qos_network_policy=qos_network) context", "self.assertRaises( pl_exc.PlacementAllocationGenerationConflict, self.qos_plugin._change_placement_allocation, qos1, qos2, orig_port, port) def test_change_placement_allocation_qos_network_policy(self): qos_network", "self._prepare_port_for_placement_allocation( qos1, qos2, original_min_kpps=1000, desired_min_kpps=2000, is_sriov=True) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as", "as QosMocked: self.qos_plugin.create_policy(self.ctxt, tenant_policy) QosMocked.assert_called_once_with(self.ctxt, **policy_details) @mock.patch.object(policy_object.QosPolicy, \"get_object\") @mock.patch( 'neutron.objects.rbac_db.RbacNeutronDbObjectMixin'", "self.ctxt, mock.ANY) if rule_mock_call in mock_manager.mock_calls: action_index = mock_manager.mock_calls.index(rule_mock_call) else:", "self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt, self.policy.id, self.rule_data) def test_update_policy_min_pps_rule(self): _policy =", "self.ctxt, self.min_bw_rule.id, self.policy.id, self.rule_data) def test_update_policy_rule_check_rule_minbw_gr_than_bwlimit(self): _policy = self._get_policy() setattr(_policy,", "mock_qos_rule_create, mock_qos_policy_get): _policy = copy.copy(self.policy) setattr(_policy, \"rules\", []) mock_qos_policy_get.return_value =", "desired_min_kbps=2000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: mock_update_qos_alloc.side_effect = ks_exc.Conflict( response={'errors':", "self.ctxt, self.rule.id, self.policy.id) def test_verify_bad_method_call(self): self.assertRaises(AttributeError, getattr, self.qos_plugin, 'create_policy_bandwidth_limit_rules') def", "} with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises( qos_exc.QoSRulesConflict, self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt,", "mock.call.driver.call( 'update_policy', self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(rule_update_mock_call) < mock_manager.mock_calls.index(update_precommit_mock_call) < mock_manager.mock_calls.index(update_mock_call))", "with mock.patch( 'neutron.objects.ports.Port.get_objects', return_value=ports ) as get_ports, mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=policy_mock", "mock.patch( 'neutron.objects.network.Network.get_object', return_value=net), \\ mock.patch.object( self.qos_plugin, '_get_ports_with_policy', return_value=[port]): try: self.qos_plugin.create_policy_minimum_bandwidth_rule(", "@mock.patch('neutron.objects.qos.policy.QosPolicy') def test_add_policy(self, mock_qos_policy, mock_create_rbac_policy): mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_policy, 'QosPolicy')", "qos_exc.QosPolicyNotFound, self.qos_plugin.update_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, self.policy.id, self.rule_data) def test_delete_policy_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "0, 'end': 100} }] }] with mock.patch.object( qos_plugin.QoSPlugin, \"supported_rule_type_details\", return_value=drivers_details", "mock_qos_get_obj: self.assertRaises( qos_exc.QoSRulesConflict, self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt, _policy.id, new_rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def", "with mock.patch('neutron.objects.network.NetworkSegment.get_objects', return_value=[segment_mock]), \\ mock.patch( 'neutron.objects.qos.rule.QosMinimumBandwidthRule.' 'get_objects', return_value=min_bw_rules), \\ mock.patch(", "'neutron.notifiers.batch_notifier.BatchNotifier._notify') self.patch_notifier.start() plugin = 'ml2' service_plugins = {'qos_plugin_name': SERVICE_PLUGIN_KLASS} ext_mgr", "= self._make_qos_policy() kwargs = self._prepare_for_port_placement_allocation_change( qos1=qos1_obj, qos2=qos2_obj) context = kwargs['context']", "[self.min_pps_rule]) segment = network_object.NetworkSegment( physical_network='fake physnet') net = network_object.Network( self.ctxt,", "as get_policy, mock.patch.object( self.qos_plugin, \"validate_policy_for_network\" ) as validate_policy_for_network, mock.patch.object( self.qos_plugin,", "min_pps_rules else [] with mock.patch('neutron.objects.network.NetworkSegment.get_objects', return_value=[segment_mock]), \\ mock.patch( 'neutron.objects.qos.rule.QosMinimumBandwidthRule.' 'get_objects',", "1000000 setattr(_policy, \"rules\", [self.rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict,", "filters = {'filter': 'filter_id'} self.qos_plugin.get_policy_bandwidth_limit_rules( self.ctxt, self.policy.id, filters=filters) get_objects_mock.assert_called_once_with( self.ctxt,", "port.device_owner, 'qos_policy_id': port.qos_policy_id, 'qos_network_policy_id': port.qos_network_policy_id, } ml2plugin_mock._make_port_dict.side_effect = fake_make_port_dict port1", "network_id, \"vnic_type\": \"normal\", } }, ] segment_mock = mock.MagicMock(network_id=network_id, physical_network=physical_network)", "calls.append(mock.call(mock.ANY, rule_object_class, rule_id, self.qos_policy_id, {rule_data_name: data})) update_policy_rule_mock.assert_has_calls(calls, any_order=True) @mock.patch.object(qos_plugin.QoSPlugin, \"get_policy_rule\")", "port in ports: self.assertEqual( 2, len(port['resource_request']['request_groups']) ) self.assertIn( { 'id':", "= uuidutils.generate_uuid() def _make_qos_policy(self): qos_policy = policy_object.QosPolicy( self.context, project_id=self.project_id, shared=False,", "kwargs['port'].pop('qos_policy_id') context = kwargs['context'] original_port = kwargs['original_port'] port = kwargs['port']", "self.min_bw_rule.id, self.policy.id, self.rule_data) self.mock_qos_load_attr.assert_called_once_with('rules') self._validate_driver_params('update_policy', self.ctxt) self.rule_data['bandwidth_limit_rule']['max_kbps'] = 1 with", "self.ctxt, self.rule.id, _policy.id) self._validate_driver_params('update_policy', self.ctxt) rule_delete_mock_call = mock.call.delete() update_precommit_mock_call =", "qos1 else None qos2_id = qos2.id if qos2 else None", "mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_rule_check_rule_max_more_than_min(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.min_bw_rule])", "self.ctxt, self.rule.id, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) rule_update_mock_call = mock.call.update() update_precommit_mock_call", "= mock.call.QosPolicy().create() create_precommit_mock_call = mock.call.driver.call( 'create_policy_precommit', self.ctxt, mock.ANY) create_mock_call =", "self.pps_rule = rule_object.QosPacketRateLimitRule( self.ctxt, **self.rule_data['packet_rate_limit_rule']) self.min_pps_rule = rule_object.QosMinimumPacketRateRule( self.ctxt, **self.rule_data['minimum_packet_rate_rule'])", "with the License. You may obtain # a copy of", "orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={ self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': -1000}, self.MIN_PPS_RP: {", "'neutron.objects.qos.rule.QosRule.get_object', return_value=rule ), mock.patch.object(self.qos_plugin, 'get_policy_rule', return_value=rule.to_dict()): self._delete_rule(rule_type, rule_id) calls.append(mock.call(mock.ANY, rule_object_class,", "port) def test_change_placement_allocation_qos_network_policy(self): qos_network = self._make_qos_policy() desired_qos = self._make_qos_policy() orig_port,", "self.assertEqual(ml2plugin_mock._make_port_dict.call_count, 1) mock_alloc_change_calls = [ mock.call( original_qos, None, {'id': port1.id,", "{'max_kbps': 100, 'max_burst_kbps': 150}, 'dscp_marking_rule': {'dscp_mark': 16}, 'minimum_bandwidth_rule': {'min_kbps': 10}", "qos_policy_id=self.qos_policy_id, **data) with mock.patch( 'neutron.objects.qos.rule.QosRule.get_object', return_value=rule ), mock.patch.object(self.qos_plugin, 'get_policy_rule', return_value=rule.to_dict()):", "mock.MagicMock(id=policy_id) admin_ctxt = mock.Mock() with mock.patch( 'neutron.objects.ports.Port.get_object', return_value=port_mock ) as", "qos_consts.QOS_POLICY_ID: policy_id }, \"original_port\": { \"id\": port_id, qos_consts.QOS_POLICY_ID: original_policy_id }", "@mock.patch('neutron.objects.db.api.get_object', return_value=None) @mock.patch.object(policy_object.QosPolicy, 'delete') def test_delete_policy(self, mock_qos_policy_delete, mock_api_get_policy): mock_manager =", "DB_PLUGIN_KLASS = 'neutron.db.db_base_plugin_v2.NeutronDbPluginV2' SERVICE_PLUGIN_KLASS = 'neutron.services.qos.qos_plugin.QoSPlugin' class TestQosPlugin(base.BaseQosTestCase): def setUp(self):", "self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", []) self.assertRaises( qos_exc.QosRuleNotFound,", "port): port['binding:profile'] = {} mock_alloc_change.side_effect = fake_change_placement_allocation self.qos_plugin._check_network_for_placement_allocation_change( 'network', 'after_update',", "return_value=[port]): self.assertRaises( NotImplementedError, self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt, _policy.id, self.rule_data) def test_create_min_pps_rule_on_unbound_port(self): _policy", "governing permissions and limitations # under the License. import copy", "self.min_bw_rule.qos_policy_id = self.policy.id port = self._create_and_extend_port([self.min_bw_rule], has_net_qos_policy=True) self.assertEqual( 1, len(port['resource_request']['request_groups'])", "'minimum_packet_rate_rule': { 'id': uuidutils.generate_uuid(), 'min_kpps': 1234, 'direction': self.min_pps_rule.direction, }, }", "self.assertIn('physical_network', port['binding:profile']) def test_change_placement_allocation_increase(self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy()", "test__extend_port_resource_request_mix_rules_non_provider_net(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION port = self._create_and_extend_port([self.min_bw_rule], [self.min_pps_rule], physical_network=None) self.assertEqual(", "self.policy.id, new_rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) for rule_data in rules: min_pps_rule =", "test_create_min_pps_rule_on_bound_port(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.min_pps_rule]) segment = network_object.NetworkSegment(", "desired_qos.rules = [] if desired_min_kbps: desired_qos.rules += [self._make_qos_minbw_rule( desired_qos.id, min_kbps=desired_min_kbps)]", "port.id, 'device_owner': port.device_owner, 'qos_policy_id': port.qos_policy_id, 'qos_network_policy_id': port.qos_network_policy_id, } ml2plugin_mock._make_port_dict.side_effect =", "port_id else uuidutils.generate_uuid() base_mac = ['aa', 'bb', 'cc', 'dd', 'ee',", "self.ctxt, self.min_pps_rule.id, self.policy.id) self._validate_driver_params('update_policy', self.ctxt) def test_delete_policy_min_pps_rule_bad_policy(self): _policy = self._get_policy()", "consumer_uuid='uu:id', alloc_diff={self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': -1000}}) def test_change_placement_allocation_equal_minkbps_and_minkpps(self): qos1 = self._make_qos_policy() qos2", "return_value=_policy): self.rule_data['bandwidth_limit_rule']['max_kbps'] = 1 self.qos_plugin.update_policy_bandwidth_limit_rule( self.ctxt, self.rule.id, self.policy.id, self.rule_data) self._validate_driver_params('update_policy',", "test_get_policy_min_pps_rules_for_policy_with_filters(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumPacketRateRule.' 'get_objects') as get_objects_mock:", "] mock_alloc_change.assert_has_calls(mock_alloc_change_calls, any_order=True) port1.update() self.assertDictEqual(port1.bindings[0].profile, {}) def test_check_network_for_placement_allocation_change(self): original_qos =", "alloc_diff={self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': -1000}}) def test_change_placement_allocation_equal_minkbps_and_minkpps(self): qos1 = self._make_qos_policy() qos2 =", "= policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) self.rule = rule_object.QosBandwidthLimitRule( self.ctxt, **self.rule_data['bandwidth_limit_rule']) self.dscp_rule", "{} with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1, None, orig_port,", "self.ctxt, desired_state=kwargs['port'], states=(kwargs['original_port'],))) if policy_id is None or policy_id ==", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "uuidutils.generate_uuid() kwargs = { \"port\": { \"id\": port_id, qos_consts.QOS_POLICY_ID: policy_id", "self.qos_plugin.update_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, self.policy.id, self.rule_data) @mock.patch.object(rule_object.QosBandwidthLimitRule, 'delete') def test_delete_policy_rule(self, mock_qos_rule_delete):", "qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_packet_rate_limit_rules, self.ctxt, self.policy.id) def test_create_policy_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises(", "self.rule.id, _policy.id) self._validate_driver_params('update_policy', self.ctxt) rule_delete_mock_call = mock.call.delete() update_precommit_mock_call = mock.call.driver.call(", "( qos_network_policy.id if qos_network_policy else None) network = self._make_network(qos_policy_id=qos_network_policy_id) port", "self.mock_qos_load_attr.assert_called_once_with('rules') self._validate_driver_params('update_policy', self.ctxt) self.rule_data['bandwidth_limit_rule']['max_kbps'] = 1 with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.assertRaises(", "mock.patch.object( self.ctxt, \"elevated\", return_value=admin_ctxt ): self.qos_plugin._validate_update_network_callback( \"NETWORK\", \"precommit_update\", \"test_plugin\", payload=events.DBEventPayload(", "return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumPacketRateRule.' 'get_object') as get_object_mock: self.qos_plugin.get_policy_minimum_packet_rate_rule( self.ctxt, self.min_pps_rule.id,", "qos_policy_id=qos_policy_id, qos_network_policy_id=qos_network_policy_id, mac_address=mac, id=port_id) port.create() return port def _make_network(self, qos_policy_id=None):", "is not compute bound self._make_port(network_id=network.id, qos_policy_id=None, device_owner='uu:id') # Port with", "validate_policy_for_network, mock.patch.object( self.qos_plugin, \"validate_policy_for_ports\" ) as validate_policy_for_ports, mock.patch.object( self.ctxt, \"elevated\",", "mock.MagicMock( id=uuidutils.generate_uuid(), qos_policy_id=uuidutils.generate_uuid()) port_mock_without_own_policy = mock.MagicMock( id=uuidutils.generate_uuid(), qos_policy_id=None) ports =", "'uu:id', 'id': '9416c220-160a-11ec-ba3d-474633eb825c', } port = {} with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation')", "def test_create_policy_rule_check_rule_bwlimit_less_than_minbw(self): _policy = self._get_policy() self.rule_data['bandwidth_limit_rule']['max_kbps'] = 1 setattr(_policy, \"rules\",", "qos1, qos2, original_min_kbps=1000, desired_min_kbps=2000, is_sriov=True) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc:", "= lib_constants.EGRESS_DIRECTION port = self._create_and_extend_port([self.min_bw_rule], [self.min_pps_rule], physical_network=None) self.assertEqual( 1, len(port['resource_request']['request_groups'])", "_policy = copy.copy(self.policy) setattr(_policy, \"rules\", []) mock_qos_policy_get.return_value = _policy mock_manager", "get_objects_mock: self.qos_plugin.get_policy_bandwidth_limit_rules( self.ctxt, self.policy.id) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id) def test_get_policy_bandwidth_limit_rules_for_policy_with_filters(self):", "self.rule.direction } } with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises( qos_exc.QoSRulesConflict,", "def test_get_policy_minimum_bandwidth_rules_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_minimum_bandwidth_rules, self.ctxt, self.policy.id)", "'type_id'} with mock.patch.object(qos_plugin.QoSPlugin, 'supported_rule_types', return_value=qos_consts.VALID_RULE_TYPES): types = self.qos_plugin.get_rule_types(self.ctxt, filters=filters) self.assertEqual(sorted(qos_consts.VALID_RULE_TYPES),", "= getattr(mock.call.RuleCls(), action)() driver_mock_call = mock.call.driver.call('update_policy', self.ctxt, mock.ANY) if rule_mock_call", "with mock.patch.object( self.qos_plugin, '_change_placement_allocation') as mock_alloc_change: def fake_change_placement_allocation(orig_policy, policy, orig_port,", "[self.rule] try: self.qos_plugin.validate_policy_for_port( self.ctxt, self.policy, port) except qos_exc.QosRuleNotSupported: self.fail(\"QosRuleNotSupported exception", "'after_update', ml2plugin_mock, payload=events.DBEventPayload( self.context, states=(original_network, network))) self.assertEqual(ml2plugin_mock._make_port_dict.call_count, 2) mock_alloc_change_calls =", "neutron_lib import context from neutron_lib import exceptions as lib_exc from", "def _create_and_extend_ports(self, min_bw_rules, min_pps_rules=None, physical_network='public', request_groups_uuids=None): network_id = uuidutils.generate_uuid() ports_res", "test_check_network_for_placement_allocation_change(self): original_qos = self._make_qos_policy() qos = self._make_qos_policy() original_network = self._make_network(original_qos.id)", "mock.call.delete() delete_precommit_mock_call = mock.call.driver.call( 'delete_policy_precommit', self.ctxt, mock.ANY) delete_mock_call = mock.call.driver.call(", "project_id=self.project_id, qos_policy_id=policy_id, direction=direction, min_kpps=min_kpps, id=rule_id) qos_rule.create() return qos_rule def _make_port(self,", "mock_manager.mock_calls.index(create_mock_call)) def test_add_policy_with_extra_tenant_keyword(self, *mocks): policy_id = uuidutils.generate_uuid() project_id = uuidutils.generate_uuid()", "unittest import mock from keystoneauth1 import exceptions as ks_exc import", "= getattr( mock.call.QosPolicy.get_policy_obj().get_rule_by_id(), action)() # some actions construct rule from", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "rule_object from neutron.services.qos import qos_plugin from neutron.tests.unit.db import test_db_base_plugin_v2 from", "rule_object.QosBandwidthLimitRule, 'dscp_marking': rule_object.QosDscpMarkingRule, 'minimum_bandwidth': rule_object.QosMinimumBandwidthRule } self.qos_policy_id = uuidutils.generate_uuid() self.rule_data", "self.qos_plugin._change_placement_allocation(qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_no_original_allocation(self): qos1 = self._make_qos_policy()", "mock_manager.reset_mock() _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy,", "port['resource_request']['request_groups'][0]['resources'], ) self.assertEqual( ['fake_uuid'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_bulk_min_bw_and_pps_rule(self): self.min_bw_rule.direction =", "'QosDscpMarkingRule.' 'get_objects') as get_objects_mock: self.qos_plugin.get_policy_dscp_marking_rules( self.ctxt, self.policy.id) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY,", "request_groups_uuids=request_groups_uuids) for port in ports: self.assertEqual( 2, len(port['resource_request']['request_groups']) ) self.assertIn(", "test__extend_port_resource_request_non_min_bw_or_min_pps_rule(self): port = self._create_and_extend_port([], []) self.assertIsNone(port.get('resource_request')) def test__extend_port_resource_request_min_bw_non_provider_net(self): self.min_bw_rule.direction =", "self.policy.id) def test_get_min_pps_rule_type(self): admin_ctxt = context.get_admin_context() drivers_details = [{ 'name':", "_mock_qos_load_attr.start() # We don't use real models as per mocks", "port['binding:profile']) def test_change_placement_allocation_increase(self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() orig_port,", "\"rules\", []) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.delete_policy_minimum_packet_rate_rule, self.ctxt, self.min_pps_rule.id,", "def test_create_policy_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.create_policy_bandwidth_limit_rule, self.ctxt, self.policy.id,", "getattr(mock.call.RuleCls(), action)() driver_mock_call = mock.call.driver.call('update_policy', self.ctxt, mock.ANY) if rule_mock_call in", "direction='ingress', min_kbps=1000, rule_id=None): rule_id = rule_id if rule_id else uuidutils.generate_uuid()", "device_owner = device_owner if device_owner else '3' port = ports_object.Port(", "kwargs['port'] def _assert_pci_info(self, port): self.assertIn('pci_slot', port['binding:profile']) self.assertIn('pci_vendor_info', port['binding:profile']) self.assertIn('physical_network', port['binding:profile'])", "= ks_exc.Conflict( response={'errors': [{'code': 'placement.concurrent_update'}]} ) self.assertRaises( neutron_qos_exc.QosPlacementAllocationUpdateConflict, self.qos_plugin._change_placement_allocation, qos1,", "in rules: min_pps_rule = rule_object.QosMinimumPacketRateRule( self.ctxt, **rule_data['minimum_packet_rate_rule']) setattr(_policy, \"rules\", [min_pps_rule])", "= self._make_qos_policy() original_network = self._make_network(qos1.id) network = original_network ml2plugin_mock =", "mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos_network, desired_qos, orig_port, port) mock_update_qos_alloc.assert_called_once_with(", "'placement.concurrent_update'}]} ) self.assertRaises( neutron_qos_exc.QosPlacementAllocationUpdateConflict, self.qos_plugin._change_placement_allocation, qos1, qos2, orig_port, port) def", "QosMocked.assert_called_once_with(self.ctxt, **policy_details) @mock.patch.object(policy_object.QosPolicy, \"get_object\") @mock.patch( 'neutron.objects.rbac_db.RbacNeutronDbObjectMixin' '.create_rbac_policy') @mock.patch.object(policy_object.QosPolicy, 'update') def", "self.pps_rule.id, self.policy.id, self.rule_data) def test_delete_policy_packet_rate_limit_rule(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy'])", "qos2, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={ self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': 500}})", "{'fake_rule': {}}], 'update': [self.ctxt, rule_cls_mock, self.rule.id, self.policy.id, {'fake_rule': {}}], 'delete':", "self.qos_plugin.update_policy_packet_rate_limit_rule, self.ctxt, self.pps_rule.id, self.policy.id, self.rule_data) def test_delete_policy_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None):", "neutron_lib.utils import net as net_utils import os_resource_classes as orc from", "except in compliance with the License. You may obtain #", "has_qos_policy: self.port_data['port']['qos_policy_id'] = self.policy.id elif has_net_qos_policy: self.port_data['port']['qos_network_policy_id'] = self.policy.id self.port", "mock.ANY) self.assertTrue( mock_manager.mock_calls.index(policy_delete_mock_call) < mock_manager.mock_calls.index(delete_precommit_mock_call) < mock_manager.mock_calls.index(delete_mock_call)) @mock.patch.object(policy_object.QosPolicy, \"get_object\") @mock.patch.object(rule_object.QosBandwidthLimitRule,", "payload=events.DBEventPayload( self.context, resource_id=kwargs['network']['id'],)) qos_policy = None if network_qos: qos_policy =", "self.qos_plugin.get_rule_type, self.ctxt, qos_consts.RULE_TYPE_PACKET_RATE_LIMIT) def test_create_min_pps_rule_on_bound_port(self): _policy = self._get_policy() setattr(_policy, \"rules\",", "mock.call( original_qos, qos, {'id': port2.id, 'device_owner': 'compute:uu:id', 'qos_policy_id': None, 'qos_network_policy_id':", "qos2, orig_port, port) def test_change_placement_allocation_update_generation_conflict(self): qos1 = self._make_qos_policy() qos2 =", "= rule_object.QosMinimumPacketRateRule( self.context, project_id=self.project_id, qos_policy_id=policy_id, direction=direction, min_kpps=min_kpps, id=rule_id) qos_rule.create() return", "self._make_network(qos_policy_id=net_qos_id) kwargs = {\"context\": self.context, \"network\": network} with mock.patch.object(self.qos_plugin, 'validate_policy_for_network')", "= self._make_qos_policy() net_qos_id = net_qos_obj.id if network_qos else None port_qos_id", "self.policy.rules = [self.rule] try: self.qos_plugin.validate_policy_for_network( self.ctxt, self.policy, network_id=network) except qos_exc.QosRuleNotSupportedByNetwork:", "'test-policy', 'description': 'Test policy description', 'shared': True, 'is_default': False}} policy_details", "'QosPacketRateLimitRule.' 'get_objects') as get_objects_mock: self.qos_plugin.get_policy_packet_rate_limit_rules( self.ctxt, self.policy.id) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY,", "qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_minimum_packet_rate_rules, self.ctxt, self.policy.id) def test_get_min_pps_rule_type(self): admin_ctxt = context.get_admin_context() drivers_details", "\"vnic_type\": \"normal\", } }, { \"resource_request\": { \"port_id\": uuidutils.generate_uuid(), \"qos_id\":", "setattr(_policy, \"rules\", [self.dscp_rule]) self.qos_plugin.update_policy_dscp_marking_rule( self.ctxt, self.dscp_rule.id, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt)", "mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_min_bw_dataplane_enforcement_with_pps( self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy()", "self.qos_plugin.create_policy_minimum_bandwidth_rule, self.ctxt, self.policy.id, self.rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_rule_duplicates(self): _policy =", "rule_type.replace('_', '-')) request = self.new_delete_request(resource, rule_id, self.fmt) res = request.get_response(self.ext_api)", "min_kbps=min_kbps, id=rule_id) qos_rule.create() return qos_rule def _make_qos_minpps_rule(self, policy_id, direction='ingress', min_kpps=1000,", "self.rule = rule_object.QosBandwidthLimitRule( self.ctxt, **self.rule_data['bandwidth_limit_rule']) self.dscp_rule = rule_object.QosDscpMarkingRule( self.ctxt, **self.rule_data['dscp_marking_rule'])", "return_value=min_pps_rules), \\ mock.patch( 'uuid.uuid5', return_value='fake_uuid', side_effect=request_groups_uuids): return qos_plugin.QoSPlugin._extend_port_resource_request( port_res, self.port)", "mock_manager.mock_calls.index(rule_update_mock_call) < mock_manager.mock_calls.index(update_precommit_mock_call) < mock_manager.mock_calls.index(update_mock_call)) def test_update_policy_rule_check_rule_min_less_than_max(self): _policy = self._get_policy()", "{\"context\": self.context, \"port\": {\"id\": port.id}} with mock.patch.object(self.qos_plugin, 'validate_policy_for_port') \\ as", "os_resource_classes as orc from oslo_config import cfg from oslo_utils import", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.delete_policy_minimum_packet_rate_rule, self.ctxt, self.min_pps_rule.id, self.policy.id) def", "def _make_qos_minpps_rule(self, policy_id, direction='ingress', min_kpps=1000, rule_id=None): rule_id = rule_id if", "segment_mock = mock.MagicMock(network_id=network_id, physical_network=physical_network) min_pps_rules = min_pps_rules if min_pps_rules else", "-1000}, self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': -2000}}) def test_change_placement_allocation_no_min_bw(self): qos1 = self._make_qos_policy()", "# distributed under the License is distributed on an \"AS", "return qos_plugin.QoSPlugin._extend_port_resource_request_bulk( ports_res, None) def test__extend_port_resource_request_min_bw_rule(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION port", "'neutron.objects.qos.rule.QosMinimumPacketRateRule.' 'get_objects', return_value=min_pps_rules), \\ mock.patch( 'uuid.uuid5', return_value='fake_uuid', side_effect=request_groups_uuids): return qos_plugin.QoSPlugin._extend_port_resource_request_bulk(", "= ports_object.Port( self.ctxt, id=uuidutils.generate_uuid(), network_id=uuidutils.generate_uuid(), device_owner='compute:fake-zone') with mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy),", "# Unless required by applicable law or agreed to in", "def setUp(self): super(TestQosPluginDB, self).setUp() self.setup_coreplugin(load_plugins=False) cfg.CONF.set_override(\"core_plugin\", DB_PLUGIN_KLASS) cfg.CONF.set_override(\"service_plugins\", [\"qos\"]) manager.init()", "if qos_policy: mock_validate_policy.assert_called_once_with( self.context, qos_policy, port) else: mock_validate_policy.assert_not_called() def test_validate_create_port_callback_policy_on_port(self):", "mock.call.driver.call( 'update_policy_precommit', self.ctxt, mock.ANY) update_mock_call = mock.call.driver.call( 'update_policy', self.ctxt, mock.ANY)", "def _make_network(self, qos_policy_id=None): network = network_object.Network(self.context, qos_policy_id=qos_policy_id) network.create() return network", "any_order=True) port1.update() port2.update() self.assertDictEqual( port1.bindings[0].profile, {'allocation': 'fake_allocation'}) self.assertDictEqual( port2.bindings[0].profile, {'allocation':", "self._make_qos_minbw_rule(qos2.id, min_kbps=1000) qos2.rules = [rule2_obj] orig_port = {'id': 'u:u', 'device_id':", "False} with mock.patch('neutron.objects.qos.policy.QosPolicy') as QosMocked: self.qos_plugin.create_policy(self.ctxt, tenant_policy) QosMocked.assert_called_once_with(self.ctxt, **policy_details) @mock.patch.object(policy_object.QosPolicy,", "policy.rules = [self.min_bw_rule] segment = network_object.NetworkSegment( physical_network='fake physnet') net =", "arguments in rule_actions.items(): mock_manager.reset_mock() method = getattr(self.qos_plugin, \"%s_policy_rule\" % action)", "self.context, states=(original_network, network))) mock_alloc_change.assert_not_called() ml2plugin_mock._make_port_dict.assert_not_called() def test_check_network_for_placement_allocation_change_remove_qos(self): original_qos = self._make_qos_policy()", ") self.assertEqual( ['fake_uuid'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_bulk_min_bw_and_pps_rule(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION", "'max_kpps', 'parameter_type': lib_constants.VALUES_TYPE_RANGE, 'parameter_range': {'start': 0, 'end': 100} }] }]", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.update_policy_bandwidth_limit_rule( self.ctxt, self.rule.id, self.policy.id, self.rule_data) self.mock_qos_load_attr.assert_called_once_with('rules') self._validate_driver_params('update_policy',", "is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES", "= [{ 'name': 'fake-driver', 'supported_parameters': [{ 'parameter_name': 'max_kbps', 'parameter_type': lib_constants.VALUES_TYPE_RANGE,", "= mock.call.delete() update_precommit_mock_call = mock.call.driver.call( 'update_policy_precommit', self.ctxt, mock.ANY) update_mock_call =", "test_db_base_plugin_v2 from neutron.tests.unit.services.qos import base DB_PLUGIN_KLASS = 'neutron.db.db_base_plugin_v2.NeutronDbPluginV2' SERVICE_PLUGIN_KLASS =", "self.pps_rule.id, _policy.id) def test_get_policy_packet_rate_limit_rule(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosPacketRateLimitRule.'", "'min_kpps', 'parameter_type': lib_constants.VALUES_TYPE_RANGE, 'parameter_range': {'start': 0, 'end': 100} }] }]", "self.pps_rule.id, self.policy.id, self.rule_data) def test_delete_policy_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound,", "orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_old_rule_not_min_bw(self): qos1 = self._make_qos_policy() qos2 =", "qos1_obj = self._make_qos_policy() kwargs = self._prepare_for_port_placement_allocation_change( qos1=qos1_obj, qos2=None) kwargs['port'].pop('qos_policy_id') context", "class TestQoSRuleAlias(test_db_base_plugin_v2.NeutronDbPluginV2TestCase): def setUp(self): # Remove MissingAuthPlugin exception from logs", "mock.call.update() update_precommit_mock_call = mock.call.driver.call( 'update_policy_precommit', self.ctxt, mock.ANY) update_mock_call = mock.call.driver.call(", "self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.update_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, self.policy.id, self.rule_data) def test_delete_policy_rule_for_nonexistent_policy(self): with", "rule_data in rules: min_pps_rule = rule_object.QosMinimumPacketRateRule( self.ctxt, **rule_data['minimum_packet_rate_rule']) setattr(_policy, \"rules\",", "['fake_uuid0', 'fake_uuid1'] * 2 min_bw_rule_ingress_data = { 'id': uuidutils.generate_uuid(), 'min_kbps':", "self.assertEqual( ['fake_uuid0', 'fake_uuid1'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_no_qos_policy(self): port = self._create_and_extend_port([],", "test_validate_create_port_callback_policy_on_network(self): self._test_validate_create_port_callback(network_qos=True) def test_validate_create_port_callback_no_policy(self): self._test_validate_create_port_callback() def _prepare_for_port_placement_allocation_change(self, qos1, qos2, qos_network_policy=None):", "def test_update_policy_pps_rule_bad_policy(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy):", "test_validate_create_port_callback_policy_on_port(self): self._test_validate_create_port_callback(port_qos=True) def test_validate_create_port_callback_policy_on_port_and_network(self): self._test_validate_create_port_callback(port_qos=True, network_qos=True) def test_validate_create_port_callback_policy_on_network(self): self._test_validate_create_port_callback(network_qos=True) def", "qos1, qos2, original_min_kbps=1000, desired_min_kbps=1000, original_min_kpps=1000, desired_min_kpps=1000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as", "description', 'shared': True, 'is_default': False} with mock.patch('neutron.objects.qos.policy.QosPolicy') as QosMocked: self.qos_plugin.create_policy(self.ctxt,", "get_objects_mock: filters = {'filter': 'filter_id'} self.qos_plugin.get_policy_minimum_packet_rate_rules( self.ctxt, self.policy.id, filters=filters) get_objects_mock.assert_called_once_with(", "neutron_lib.exceptions import placement as pl_exc from neutron_lib.exceptions import qos as", "as rule_object from neutron.services.qos import qos_plugin from neutron.tests.unit.db import test_db_base_plugin_v2", "'d7bea120-1626-11ec-9148-c32debfcf0f6' QOS_MIN_PPS_RULE_ID = '6ac5db7e-1626-11ec-8c7f-0b70dbb8a8eb' # uuid -v5 f02f160e-1612-11ec-b2b8-bf60ab98186c # 6ac5db7e-1626-11ec-8c7f-0b70dbb8a8eb", "[self.rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.create_policy_minimum_bandwidth_rule, self.ctxt, self.policy.id,", "= {'id': uuidutils.generate_uuid()} with mock.patch.object( self.qos_plugin.driver_manager, \"validate_rule_for_port\", return_value=True ): self.policy.rules", "policy_id, direction='ingress', min_kpps=1000, rule_id=None): rule_id = rule_id if rule_id else", "elif network_qos: qos_policy = net_qos_obj if qos_policy: mock_validate_policy.assert_called_once_with( self.context, qos_policy,", "[min_pps_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt, self.policy.id,", "'max_burst_kbps': 150}, 'dscp_marking_rule': {'dscp_mark': 16}, 'minimum_bandwidth_rule': {'min_kbps': 10} } def", "self._test_validate_create_port_callback() def _prepare_for_port_placement_allocation_change(self, qos1, qos2, qos_network_policy=None): qos1_id = qos1.id if", "'get_object') as get_object_mock: self.qos_plugin.get_policy_packet_rate_limit_rule( self.ctxt, self.pps_rule.id, self.policy.id) get_object_mock.assert_called_once_with(self.ctxt, id=self.pps_rule.id) def", "self._make_qos_policy() qos2_obj = self._make_qos_policy() kwargs = self._prepare_for_port_placement_allocation_change( qos1=qos1_obj, qos2=qos2_obj) context", "return_value=rule ), mock.patch.object(self.qos_plugin, 'get_policy_rule', return_value=rule.to_dict()): self._update_rule(rule_type, rule_id, **data) calls.append(mock.call(mock.ANY, rule_object_class,", "'qos_network_policy_id': qos.id}, mock.ANY)] mock_alloc_change.assert_has_calls(mock_alloc_change_calls, any_order=True) port1.update() port2.update() self.assertDictEqual( port1.bindings[0].profile, {'allocation':", "self.ctxt, qos_consts.RULE_TYPE_MINIMUM_PACKET_RATE) class QoSRuleAliasTestExtensionManager(object): def get_resources(self): return qos_rules_alias.Qos_rules_alias.get_resources() def get_actions(self):", "port_qos_obj elif network_qos: qos_policy = net_qos_obj if qos_policy: mock_validate_policy.assert_called_once_with( self.context,", "{'binding:profile': binding_prof, 'device_id': 'uu:id'} ) return orig_port, kwargs['port'] def _assert_pci_info(self,", "self._create_and_extend_port([self.min_bw_rule], [self.min_pps_rule], physical_network=None) self.assertEqual( 1, len(port['resource_request']['request_groups']) ) self.assertEqual( 'fake_uuid', port['resource_request']['request_groups'][0]['id']", "mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) setattr(_policy, \"rules\",", "**self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", [self.dscp_rule]) self.qos_plugin.delete_policy_dscp_marking_rule( self.ctxt, self.dscp_rule.id,", "self.policy.id port = self._create_and_extend_port([self.min_bw_rule], has_net_qos_policy=True) self.assertEqual( 1, len(port['resource_request']['request_groups']) ) self.assertEqual(", "policy_id == original_policy_id: get_policy.assert_not_called() validate_policy_for_network.assert_not_called() get_ports.assert_not_called() validate_policy_for_ports.assert_not_called() else: get_policy.assert_called_once_with(admin_ctxt, id=policy_id)", "\"rules\", [self.rule]) with mock.patch('neutron.objects.qos.rule.get_rules', return_value=[self.rule]), mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.rule_data['bandwidth_limit_rule']['max_kbps'] =", "states=(kwargs['original_network'],))) if policy_id is None or policy_id == original_policy_id: get_policy.assert_not_called()", "= self._create_and_extend_port([self.min_bw_rule], [self.min_pps_rule], physical_network=None) self.assertEqual( 1, len(port['resource_request']['request_groups']) ) self.assertEqual( 'fake_uuid',", "self.assertEqual(webob.exc.HTTPNotFound.code, res.status_int) class TestQoSRuleAliasMinimumPacketRate(TestQoSRuleAlias): def setUp(self): # Remove MissingAuthPlugin exception", "= mock.Mock() mock_manager.attach_mock(mock_qos_policy_delete, 'delete') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() self.qos_plugin.delete_policy(self.ctxt, self.policy.id) self._validate_driver_params('delete_policy',", "if device_owner else '3' port = ports_object.Port( self.context, network_id=network_id, device_owner=device_owner,", "resource_id=kwargs['port']['id'],)) qos_policy = None if port_qos: qos_policy = port_qos_obj elif", "payload=events.DBEventPayload( context, states=(original_port, port))) mock_alloc_change.assert_called_once_with( qos_network, desired_qos, kwargs['original_port'], port) def", "test_update_policy_dscp_marking_rule(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy,", "request_groups_uuids=None): network_id = uuidutils.generate_uuid() ports_res = [ { \"resource_request\": {", "else: mock_validate_policy.assert_not_called() def test_validate_create_port_callback_policy_on_port(self): self._test_validate_create_port_callback(port_qos=True) def test_validate_create_port_callback_policy_on_port_and_network(self): self._test_validate_create_port_callback(port_qos=True, network_qos=True) def", "port = self._create_and_extend_port([], physical_network='public', has_qos_policy=False) self.assertIsNone(port.get('resource_request')) def test__extend_port_resource_request_min_bw_inherited_policy( self): self.min_bw_rule.direction", "qos1=None, qos2=desired_qos, qos_network_policy=qos_network) context = kwargs['context'] original_port = kwargs['original_port'] port", "port))) mock_alloc_change.assert_called_once_with( qos1_obj, qos2_obj, kwargs['original_port'], port) def test_check_port_for_placement_allocation_change_no_new_policy(self): qos1_obj =", "vnic_type='fake_vnic_type', vif_type='fake_vif_type', profile={}) port1_binding.create() port1.bindings = [port1_binding] port1.update() port2 =", "= policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) setattr(_policy, \"rules\", [self.rule]) with mock.patch('neutron.objects.qos.rule.get_rules', return_value=[self.rule]),", "return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.update_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, self.policy.id, self.rule_data) def test_delete_policy_rule_for_nonexistent_policy(self):", "self.ctxt, self.policy.id) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id) def test_get_policy_bandwidth_limit_rules_for_policy_with_filters(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def test_update_policy_rule_check_rule_min_pps_direction_conflict(self): _policy = self._get_policy() rules_data =", "'resources': { orc.NET_PACKET_RATE_EGR_KILOPACKET_PER_SEC: 10, orc.NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC: 20, }, }, port['resource_request']['request_groups'] )", "orig_port, port) def test_change_placement_allocation_qos_network_policy(self): qos_network = self._make_qos_policy() desired_qos = self._make_qos_policy()", "self._validate_driver_params('delete_policy', self.ctxt) policy_delete_mock_call = mock.call.delete() delete_precommit_mock_call = mock.call.driver.call( 'delete_policy_precommit', self.ctxt,", "_pager=mock.ANY, qos_policy_id=self.policy.id) def test_get_policy_packet_rate_limit_rules_for_policy_with_filters(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosPacketRateLimitRule.'", "= min_pps_rules if min_pps_rules else [] with mock.patch('neutron.objects.network.NetworkSegment.get_objects', return_value=[segment_mock]), \\", "data types mock.patch( 'neutron.objects.base.NeutronDbObject.modify_fields_from_db' ).start() mock.patch.object(policy_object.QosPolicy, 'unset_default').start() mock.patch.object(policy_object.QosPolicy, 'set_default').start() cfg.CONF.set_override(\"core_plugin\",", "sorted(type_['type'] for type_ in types)) @mock.patch('neutron.objects.ports.Port') @mock.patch('neutron.objects.qos.policy.QosPolicy') def test_rule_notification_and_driver_ordering(self, qos_policy_mock,", "= fake_make_port_dict port1 = self._make_port( network_id=network.id, qos_policy_id=None, device_owner='compute:uu:id') port1_binding =", "network_id} } if has_qos_policy: self.port_data['port']['qos_policy_id'] = self.policy.id elif has_net_qos_policy: self.port_data['port']['qos_network_policy_id']", "neutron import manager from neutron.objects import network as network_object from", "test_validate_update_network_callback_policy_not_changed(self): policy_id = uuidutils.generate_uuid() self._test_validate_update_network_callback( policy_id=policy_id, original_policy_id=policy_id) def test_validate_update_network_callback_policy_removed(self): self._test_validate_update_network_callback(", "qos_network, desired_qos, kwargs['original_port'], port) def test_check_network_for_placement_allocation_change_no_qos_change(self): qos1 = self._make_qos_policy() original_network", "alloc_diff={self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': -1000}}) self._assert_pci_info(port) def test_change_placement_allocation_decrease_min_pps(self): original_qos = self._make_qos_policy() desired_qos", "device_owner='uu:id') # Port with overwritten QoS policy self._make_port(network_id=network.id, qos_policy_id=port_qos.id, device_owner='compute:uu:id')", "self.assertIn( { 'id': 'fake_uuid0', 'required': ['CUSTOM_PHYSNET_PUBLIC', 'CUSTOM_VNIC_TYPE_NORMAL'], 'resources': { orc.NET_BW_EGR_KILOBIT_PER_SEC:", "self.qos_plugin._change_placement_allocation( qos1, None, orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_old_rule_not_min_bw(self): qos1 =", ">= webob.exc.HTTPClientError.code: raise webob.exc.HTTPClientError(code=res.status_int) return self.deserialize(self.fmt, res) def _show_rule(self, rule_type,", "qos_policy: mock_validate_policy.assert_called_once_with( self.context, qos_policy, port) else: mock_validate_policy.assert_not_called() def test_validate_create_port_callback_policy_on_port(self): self._test_validate_create_port_callback(port_qos=True)", "qos_network_policy=qos_network, original_min_kbps=1000, desired_min_kbps=2000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos_network,", "self.qos_plugin.update_policy_dscp_marking_rule( self.ctxt, self.dscp_rule.id, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def test_delete_policy_dscp_marking_rule(self): _policy", "self.port = ports_object.Port( self.ctxt, **self.port_data['port']) port_res = {\"binding:vnic_type\": \"normal\"} segment_mock", "[ mock.MagicMock(qos_policy_id=self.policy.id), ] expected_network_ports = [ port for port in", "self.rule_data) def test_create_min_pps_rule_on_unbound_port(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.min_pps_rule]) segment", "'minimum_packet_rate_rule': {'min_kpps': 10, 'direction': 'any'} } class TestQosPluginDB(base.BaseQosTestCase): PORT_ID =", "test_validate_create_port_callback_policy_on_port_and_network(self): self._test_validate_create_port_callback(port_qos=True, network_qos=True) def test_validate_create_port_callback_policy_on_network(self): self._test_validate_create_port_callback(network_qos=True) def test_validate_create_port_callback_no_policy(self): self._test_validate_create_port_callback() def", "self.qos_plugin.driver_manager = mock.Mock() self.rpc_push = mock.patch('neutron.api.rpc.handlers.resources_rpc' '.ResourcesPushRpcApi.push').start() self.context = context.get_admin_context()", "self.qos_plugin.get_policy_dscp_marking_rules( self.ctxt, self.policy.id) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id) def test_get_policy_dscp_marking_rules_for_policy_with_filters(self): with", "specific language governing permissions and limitations # under the License.", "desired_min_kpps=None, is_sriov=False): kwargs = self._prepare_for_port_placement_allocation_change( original_qos, desired_qos, qos_network_policy=qos_network_policy) orig_port =", "with mock.patch('neutron.objects.qos.rule.' 'QosMinimumPacketRateRule.' 'get_objects') as get_objects_mock: filters = {'filter': 'filter_id'}", "_validate_driver_params(self, method_name, ctxt): call_args = self.qos_plugin.driver_manager.call.call_args[0] self.assertTrue(self.qos_plugin.driver_manager.call.called) self.assertEqual(call_args[0], method_name) self.assertEqual(call_args[1],", "# not use this file except in compliance with the", "network = self._make_network() ml2plugin_mock = mock.MagicMock() def fake_make_port_dict(port): return {", "as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos_network, desired_qos, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_BW_RP:", "if network_qos else None port_qos_id = port_qos_obj.id if port_qos else", "qos_network_policy=None, original_min_kbps=None, desired_min_kbps=None, original_min_kpps=None, desired_min_kpps=None, is_sriov=False): kwargs = self._prepare_for_port_placement_allocation_change( original_qos,", "= self._make_qos_policy() desired_qos = self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation( None,", "from oslo_utils import uuidutils import webob.exc from neutron.exceptions import qos", "'any' for rule_data in rules_data: rules = [ rule_object.QosMinimumPacketRateRule( self.ctxt,", "mock_manager.attach_mock(mock_qos_policy_update, 'update') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() fields = obj_utils.get_updatable_fields( policy_object.QosPolicy, self.policy_data['policy'])", "\"rules\", [self.min_pps_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.create_policy_minimum_packet_rate_rule( self.ctxt, self.policy.id, self.rule_data) self._validate_driver_params('update_policy',", "mock.patch('neutron.objects.qos.qos_policy_validator' '.check_bandwidth_rule_conflict', return_value=None), \\ mock.patch( 'neutron.objects.qos.qos_policy_validator' '.check_min_pps_rule_conflict', return_value=None): self.qos_plugin.create_policy_bandwidth_limit_rule( self.ctxt,", "{ \"port\": { \"id\": port_id, qos_consts.QOS_POLICY_ID: policy_id }, \"original_port\": {", "self.ctxt, self.policy.id, self.rule_data) def test_update_policy_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound,", "from policy get_rule_mock_call = getattr( mock.call.QosPolicy.get_policy_obj().get_rule_by_id(), action)() # some actions", "'max_burst_kpps': 130}, 'minimum_packet_rate_rule': { 'id': uuidutils.generate_uuid(), 'min_kpps': 10, 'direction': 'any'},", "in expected_ports: self.assertIn(port, policy_ports) def _test_validate_update_port_callback(self, policy_id=None, original_policy_id=None): port_id =", "'network', 'after_update', ml2plugin_mock, payload=events.DBEventPayload( self.context, states=(original_network, network))) mock_alloc_change.assert_not_called() ml2plugin_mock._make_port_dict.assert_not_called() def", "rule_type_details['drivers']) def test_get_pps_rule_type_as_user(self): self.assertRaises( lib_exc.NotAuthorized, self.qos_plugin.get_rule_type, self.ctxt, qos_consts.RULE_TYPE_PACKET_RATE_LIMIT) def test_create_min_pps_rule_on_bound_port(self):", "port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_min_bw_dataplane_enforcement(self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy()", "test_get_policy_packet_rate_limit_rule(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosPacketRateLimitRule.' 'get_object') as get_object_mock:", "= lib_constants.EGRESS_DIRECTION request_groups_uuids = ['fake_uuid0', 'fake_uuid1'] min_bw_rule_ingress_data = { 'id':", "self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", [self.dscp_rule]) self.qos_plugin.update_policy_dscp_marking_rule( self.ctxt,", "'update_policy', self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(rule_create_mock_call) < mock_manager.mock_calls.index(update_precommit_mock_call) < mock_manager.mock_calls.index(update_mock_call)) def", "min_kbps=original_min_kbps, rule_id=TestQosPluginDB.QOS_MIN_BW_RULE_ID)] allocation.update( {TestQosPluginDB.MIN_BW_REQUEST_GROUP_UUID: TestQosPluginDB.MIN_BW_RP}) if original_min_kpps: qos.rules += [self._make_qos_minpps_rule(", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", [self.pps_rule]) self.qos_plugin.delete_policy_packet_rate_limit_rule( self.ctxt, self.pps_rule.id, self.policy.id)", "self.assertIsNone(port.get('resource_request')) def test__extend_port_resource_request_mix_rules_non_provider_net(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION port = self._create_and_extend_port([self.min_bw_rule], [self.min_pps_rule],", "'QosMinimumPacketRateRule.' 'get_objects') as get_objects_mock: self.qos_plugin.get_policy_minimum_packet_rate_rules( self.ctxt, self.policy.id) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY,", "if qos_network_policy else None) network = self._make_network(qos_policy_id=qos_network_policy_id) port = self._make_port(", "test_delete_policy_packet_rate_limit_rule(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy,", "= self.qos_plugin.get_rule_type( admin_ctxt, qos_consts.RULE_TYPE_MINIMUM_PACKET_RATE) self.assertEqual( qos_consts.RULE_TYPE_MINIMUM_PACKET_RATE, rule_type_details['type']) self.assertEqual( drivers_details, rule_type_details['drivers'])", "} } port_mock_with_own_policy = mock.MagicMock( id=uuidutils.generate_uuid(), qos_policy_id=uuidutils.generate_uuid()) port_mock_without_own_policy = mock.MagicMock(", "from neutron_lib.objects import utils as obj_utils from neutron_lib.plugins import constants", "mocks above. We also need to mock-out # methods that", "self.assertIsNone(port.get('resource_request')) def test__extend_port_resource_request_min_bw_inherited_policy( self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION self.min_bw_rule.qos_policy_id = self.policy.id", "+ expected_network_ports with mock.patch( 'neutron.objects.ports.Port.get_objects', side_effect=[network_ports, ports] ), mock.patch.object( self.policy,", "def test_update_policy(self, mock_qos_policy_update, mock_create_rbac_policy, mock_qos_policy_get): mock_qos_policy_get.return_value = self.policy mock_manager =", "port_mock_with_own_policy = mock.MagicMock( id=uuidutils.generate_uuid(), qos_policy_id=uuidutils.generate_uuid()) port_mock_without_own_policy = mock.MagicMock( id=uuidutils.generate_uuid(), qos_policy_id=None)", "'get_objects') as get_objects_mock: filters = {'filter': 'filter_id'} self.qos_plugin.get_policy_minimum_bandwidth_rules( self.ctxt, self.policy.id,", "qos_exc.QosRuleNotFound, self.qos_plugin.delete_policy_packet_rate_limit_rule, self.ctxt, self.pps_rule.id, _policy.id) def test_get_policy_packet_rate_limit_rule(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy):", "with mock.patch.object(self.qos_plugin, 'validate_policy_for_port') \\ as mock_validate_policy: self.qos_plugin._validate_create_port_callback( \"PORT\", \"precommit_create\", \"test_plugin\",", "test_change_placement_allocation_decrease(self): original_qos = self._make_qos_policy() desired_qos = self._make_qos_policy() orig_port, port =", "self.ctxt) policy_update_mock_call = mock.call.update() update_precommit_mock_call = mock.call.driver.call( 'update_policy_precommit', self.ctxt, mock.ANY)", "\"test_plugin\", payload=events.DBEventPayload( self.context, resource_id=kwargs['network']['id'],)) qos_policy = None if network_qos: qos_policy", "'minimum_packet_rate_rule': { 'id': uuidutils.generate_uuid(), 'min_kpps': 10, 'direction': 'egress' } },", "def test_validate_update_network_callback_policy_removed(self): self._test_validate_update_network_callback( policy_id=None, original_policy_id=uuidutils.generate_uuid()) def test_validate_policy_for_port_rule_not_valid(self): port = {'id':", "self.qos_plugin._change_placement_allocation( qos_network, desired_qos, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': 1000}})", "return_value=_policy): self.assertRaises( qos_exc.QoSRuleParameterConflict, self.qos_plugin.update_policy_minimum_bandwidth_rule, self.ctxt, self.min_bw_rule.id, self.policy.id, self.rule_data) def test_update_policy_rule_check_rule_minbw_gr_than_bwlimit(self):", "'get_object') as get_object_mock: self.qos_plugin.get_policy_minimum_packet_rate_rule( self.ctxt, self.min_pps_rule.id, self.policy.id) get_object_mock.assert_called_once_with( self.ctxt, id=self.min_pps_rule.id)", "filter='filter_id') def test_get_policy_min_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_minimum_packet_rate_rule, self.ctxt,", "mock_alloc_change.assert_not_called() ml2plugin_mock._make_port_dict.assert_not_called() def test_check_network_for_placement_allocation_change_no_ports_to_update( self): original_qos = self._make_qos_policy() qos =", "'max_kpps': 20, 'max_burst_kpps': 130}, 'minimum_packet_rate_rule': { 'id': uuidutils.generate_uuid(), 'min_kpps': 10,", "test_update_policy(self, mock_qos_policy_update, mock_create_rbac_policy, mock_qos_policy_get): mock_qos_policy_get.return_value = self.policy mock_manager = mock.Mock()", "'ingress' } }, { 'minimum_packet_rate_rule': { 'id': uuidutils.generate_uuid(), 'min_kpps': 10,", "as network_object from neutron.objects import ports as ports_object from neutron.objects.qos", "get_policy, mock.patch.object( self.qos_plugin, \"validate_policy_for_network\" ) as validate_policy_for_network, mock.patch.object( self.qos_plugin, \"validate_policy_for_ports\"", "self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(policy_update_mock_call) < mock_manager.mock_calls.index(update_precommit_mock_call) < mock_manager.mock_calls.index(update_mock_call)) @mock.patch('neutron.objects.db.api.get_object', return_value=None)", "self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def test_create_policy_pps_rule_duplicates(self): _policy = self._get_policy() setattr(_policy, \"rules\",", "= kwargs['context'] original_port = kwargs['original_port'] port = kwargs['port'] with mock.patch.object(", "[]) self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.delete_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, _policy.id) def test_get_policy_bandwidth_limit_rule(self): with", "get_objects_mock: filters = {'filter': 'filter_id'} self.qos_plugin.get_policy_bandwidth_limit_rules( self.ctxt, self.policy.id, filters=filters) get_objects_mock.assert_called_once_with(", "self.policy.id) self._validate_driver_params('update_policy', self.ctxt) def test_delete_policy_pps_rule_bad_policy(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy'])", "except qos_exc.QosRuleNotSupported: self.fail(\"QosRuleNotSupported exception unexpectedly raised\") def test_validate_policy_for_network(self): network =", "self.pps_rule.id, self.policy.id) get_object_mock.assert_called_once_with(self.ctxt, id=self.pps_rule.id) def test_get_policy_packet_rate_limit_rules_for_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with", "% (qos.ALIAS, rule_type.replace('_', '-')) request = self.new_delete_request(resource, rule_id, self.fmt) res", "mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() self.qos_plugin.delete_policy(self.ctxt, self.policy.id) self._validate_driver_params('delete_policy', self.ctxt) policy_delete_mock_call = mock.call.delete()", "{\"id\": port.id}} with mock.patch.object(self.qos_plugin, 'validate_policy_for_port') \\ as mock_validate_policy: self.qos_plugin._validate_create_port_callback( \"PORT\",", "kwargs['original_port'], port) def test_check_port_for_placement_allocation_change_no_qos_update(self): qos1_obj = self._make_qos_policy() kwargs = self._prepare_for_port_placement_allocation_change(", "def test_check_network_for_placement_allocation_change_remove_qos(self): original_qos = self._make_qos_policy() original_network = self._make_network(original_qos.id) network =", "under the License is distributed on an \"AS IS\" BASIS,", "mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={ self.MIN_PPS_RP:", "1000}}) def test_change_placement_allocation_change_direction_min_pps_and_min_bw( self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy()", "return_value=rule.to_dict()): self._update_rule(rule_type, rule_id, **data) calls.append(mock.call(mock.ANY, rule_object_class, rule_id, self.qos_policy_id, {rule_data_name: data}))", "self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", [self.dscp_rule]) self.qos_plugin.delete_policy_dscp_marking_rule( self.ctxt,", "def test__extend_port_resource_request_min_bw_inherited_policy( self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION self.min_bw_rule.qos_policy_id = self.policy.id port", "None, kwargs['original_port'], port) def test_check_port_for_placement_allocation_change_no_qos_update(self): qos1_obj = self._make_qos_policy() kwargs =", "def test_validate_update_port_callback_policy_removed(self): self._test_validate_update_port_callback( policy_id=None, original_policy_id=uuidutils.generate_uuid()) def _test_validate_update_network_callback(self, policy_id=None, original_policy_id=None): network_id", "'compute:uu:id', 'qos_policy_id': None, 'qos_network_policy_id': None}, mock.ANY), ] mock_alloc_change.assert_has_calls(mock_alloc_change_calls, any_order=True) port1.update()", "qos.id, min_kpps=original_min_kpps, rule_id=TestQosPluginDB.QOS_MIN_PPS_RULE_ID)] allocation.update( {TestQosPluginDB.MIN_PPS_REQUEST_GROUP_UUID: TestQosPluginDB.MIN_PPS_RP}) if desired_qos: desired_qos.rules =", "self.qos_plugin._change_placement_allocation( qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': 1000}})", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.update_policy_minimum_packet_rate_rule, self.ctxt, rule_data['minimum_packet_rate_rule']['id'], self.policy.id,", "desired_qos.id, min_kpps=desired_min_kpps)] binding_prof = {} if is_sriov: binding_prof = {", "self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id) def test_get_policy_dscp_marking_rules_for_policy_with_filters(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.'", "def test_get_policy_minimum_bandwidth_rules_for_policy_with_filters(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumBandwidthRule.' 'get_objects') as", "mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.create_policy_minimum_bandwidth_rule, self.ctxt, self.policy.id, self.rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_rule_duplicates(self):", "binding_prof = {} if is_sriov: binding_prof = { 'pci_slot': '0000:42:41.0',", "self.qos_plugin._change_placement_allocation( qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC':", "self.ctxt, self.policy.id) def test_get_policy_minimum_bandwidth_rule(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumBandwidthRule.'", "self.policy.id, {'fake_rule': {}}], 'delete': [self.ctxt, rule_cls_mock, self.rule.id, self.policy.id]} mock_manager =", "self._get_policy() setattr(_policy, \"rules\", [self.min_pps_rule]) segment = network_object.NetworkSegment( physical_network='fake physnet') net", "self._create_and_extend_port([self.min_bw_rule], physical_network=None) self.assertIsNone(port.get('resource_request')) def test__extend_port_resource_request_mix_rules_non_provider_net(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION port =", "mock.call( original_qos, None, {'id': port1.id, 'device_owner': 'compute:uu:id', 'qos_policy_id': None, 'qos_network_policy_id':", "[self.rule]) with mock.patch('neutron.objects.qos.rule.get_rules', return_value=[self.rule]), mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.rule_data['bandwidth_limit_rule']['max_kbps'] = 1", "this file except in compliance with the License. You may", "port['resource_request']['request_groups'][0]['resources'], ) self.assertEqual( ['fake_uuid'], port['resource_request']['same_subtree'], ) def test_get_ports_with_policy(self): network_ports =", "self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id, filter='filter_id') def test_get_policy_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises(", "'bandwidth_limit_rule': { 'max_kbps': 5000, 'direction': self.rule.direction } } with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "mock_alloc_change: self.qos_plugin._check_port_for_placement_allocation_change( 'PORT', 'before_update', 'test_plugin', payload=events.DBEventPayload( context, states=(original_port, port))) mock_alloc_change.assert_not_called()", "ports_object.PortBinding( self.context, port_id=port1.id, host='fake_host1', vnic_type='fake_vnic_type', vif_type='fake_vif_type', profile={'allocation': 'fake_allocation'}) port1_binding.create() port1.bindings", "'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': -2000}}) def test_change_placement_allocation_no_min_bw(self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy()", "{'NET_BW_IGR_KILOBIT_PER_SEC': 1000}}) self._assert_pci_info(port) def test_change_placement_allocation_increase_min_pps(self): qos1 = self._make_qos_policy() qos2 =", "return_value=_policy): setattr(_policy, \"rules\", [self.dscp_rule]) self.qos_plugin.create_policy_dscp_marking_rule( self.ctxt, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt)", "'_get_ports_with_policy', return_value=[port]): try: self.qos_plugin.create_policy_minimum_packet_rate_rule( self.ctxt, _policy.id, self.rule_data) except NotImplementedError: self.fail()", "port['resource_request']['same_subtree'], ) def test_get_ports_with_policy(self): network_ports = [ mock.MagicMock(qos_policy_id=None), mock.MagicMock(qos_policy_id=uuidutils.generate_uuid()), mock.MagicMock(qos_policy_id=None)", "test_check_port_for_placement_allocation_change_no_new_policy(self): qos1_obj = self._make_qos_policy() kwargs = self._prepare_for_port_placement_allocation_change( qos1=qos1_obj, qos2=None) context", "= QoSRuleAliasTestExtensionManager() super(TestQoSRuleAlias, self).setUp(plugin=plugin, ext_mgr=ext_mgr, service_plugins=service_plugins) self.qos_plugin = directory.get_plugin(plugins_constants.QOS) self.ctxt", "None network = self._make_network(qos_policy_id=net_qos_id) port = self._make_port(network.id, qos_policy_id=port_qos_id) kwargs =", "policy_id=policy_id, original_policy_id=policy_id) def test_validate_update_network_callback_policy_removed(self): self._test_validate_update_network_callback( policy_id=None, original_policy_id=uuidutils.generate_uuid()) def test_validate_policy_for_port_rule_not_valid(self): port", "qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': 1000}}) self._assert_pci_info(port)", "def test_delete_rule(self, delete_policy_rule_mock): calls = [] for rule_type, rule_object_class in", "self.policy.id) def test_get_policy_bandwidth_limit_rules_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_bandwidth_limit_rules, self.ctxt,", "TestQosPlugin(base.BaseQosTestCase): def setUp(self): super(TestQosPlugin, self).setUp() self.setup_coreplugin(load_plugins=False) mock.patch('neutron.objects.db.api.create_object').start() mock.patch('neutron.objects.db.api.update_object').start() mock.patch('neutron.objects.db.api.delete_object').start() mock.patch('neutron.objects.db.api.get_object').start()", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.update_policy_minimum_packet_rate_rule, self.ctxt, rule_data['minimum_packet_rate_rule']['id'], self.policy.id, self.rule_data)", "port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': 1000}}) self._assert_pci_info(port) def test_change_placement_allocation_increase_min_pps_and_min_bw(self):", "mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_new_policy_empty(self): qos1 =", "res.status_int >= webob.exc.HTTPClientError.code: raise webob.exc.HTTPClientError(code=res.status_int) return self.deserialize(self.fmt, res) def _show_rule(self,", "port2 = self._make_port( network_id=network.id, qos_policy_id=None, device_owner='compute:uu:id') port2_binding = ports_object.PortBinding( self.context,", "self.rule_data) def test_update_policy_min_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.update_policy_minimum_packet_rate_rule, self.ctxt,", "'_change_placement_allocation') as mock_alloc_change: self.qos_plugin._check_network_for_placement_allocation_change( 'network', 'after_update', ml2plugin_mock, payload=events.DBEventPayload( self.context, states=(original_network,", "{ 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': -500, 'NET_PACKET_RATE_EGR_KILOPACKET_PER_SEC': 1000}, self.MIN_BW_RP: { 'NET_BW_IGR_KILOBIT_PER_SEC': -1000, 'NET_BW_EGR_KILOBIT_PER_SEC':", "mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: mock_update_qos_alloc.side_effect = ( pl_exc.PlacementAllocationGenerationConflict( consumer=self.MIN_BW_RP)) self.assertRaises(", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_minimum_bandwidth_rules, self.ctxt, self.policy.id) def test_create_policy_rule_for_nonexistent_policy(self): with", "uuidutils.generate_uuid() self.rule_data = { 'minimum_packet_rate_rule': {'min_kpps': 10, 'direction': 'any'} }", "orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={ self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': 500}, self.MIN_BW_RP:", "= self._create_and_extend_port([self.min_bw_rule], physical_network=None) self.assertIsNone(port.get('resource_request')) def test__extend_port_resource_request_mix_rules_non_provider_net(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION port", "self.policy.id, filters=filters) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id, filter='filter_id') def test_get_policy_packet_rate_limit_rule_for_nonexistent_policy(self): with", "port1_binding.create() port1.bindings = [port1_binding] port1.update() port2 = self._make_port( network_id=network.id, qos_policy_id=None,", "def test_update_policy_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.update_policy_bandwidth_limit_rule, self.ctxt, self.rule.id,", "mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_new_policy_empty(self): qos1 = self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation(qos1,", "neutron_lib.plugins import directory from neutron_lib.services.qos import constants as qos_consts from", "self.rule_data) def test_update_policy_rule_check_rule_minbw_gr_than_bwlimit(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.min_bw_rule]) with", "def _prepare_for_port_placement_allocation_change(self, qos1, qos2, qos_network_policy=None): qos1_id = qos1.id if qos1", "return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_minimum_packet_rate_rule, self.ctxt, self.min_pps_rule.id, self.policy.id) def test_get_policy_min_pps_rules_for_nonexistent_policy(self): with", "Port which is not compute bound self._make_port(network_id=network.id, qos_policy_id=None, device_owner='uu:id') #", "We don't use real models as per mocks above. We", "real models as per mocks above. We also need to", "\"precommit_update\", \"test_plugin\", payload=events.DBEventPayload( self.ctxt, desired_state=kwargs['network'], states=(kwargs['original_network'],))) if policy_id is None", "(qos.ALIAS, rule_type.replace('_', '-')) request = self.new_show_request(resource, rule_id, self.fmt) res =", "self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(rule_delete_mock_call) < mock_manager.mock_calls.index(update_precommit_mock_call) < mock_manager.mock_calls.index(update_mock_call)) def test_delete_policy_rule_bad_policy(self):", "def test__extend_port_resource_request_bulk_min_pps_rule(self): ports = self._create_and_extend_ports([], [self.min_pps_rule]) for port in ports:", "\"network\": { \"id\": network_id, qos_consts.QOS_POLICY_ID: policy_id }, \"original_network\": { \"id\":", "lib_exc.NotAuthorized, self.qos_plugin.get_rule_type, self.ctxt, qos_consts.RULE_TYPE_BANDWIDTH_LIMIT) def test_get_rule_types(self): filters = {'type': 'type_id'}", "method = getattr(self.qos_plugin, \"%s_policy_rule\" % action) method(*arguments) # some actions", "uuidutils.generate_uuid(), 'min_kpps': 10, 'direction': 'ingress' } }, { 'minimum_packet_rate_rule': {", "file except in compliance with the License. You may obtain", "res = request.get_response(self.ext_api) self.assertEqual(webob.exc.HTTPNotFound.code, res.status_int) class TestQoSRuleAliasMinimumPacketRate(TestQoSRuleAlias): def setUp(self): #", "qos_policy = None if network_qos: qos_policy = net_qos_obj if qos_policy:", "orig_port.update( {'binding:profile': binding_prof, 'device_id': 'uu:id'} ) return orig_port, kwargs['port'] def", "self.ctxt, self.rule.id, self.policy.id, self.rule_data) self.mock_qos_load_attr.assert_called_once_with('rules') self._validate_driver_params('update_policy', self.ctxt) rules = [self.rule,", "port_mock): rule_cls_mock = mock.Mock() rule_cls_mock.rule_type = 'fake' rule_actions = {'create':", "{ 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': -1000}}) self._assert_pci_info(port) def test_change_placement_allocation_no_original_qos(self): qos1 = None qos2", "payload=events.DBEventPayload( self.context, states=(original_network, network))) self.assertEqual(ml2plugin_mock._make_port_dict.call_count, 2) mock_alloc_change_calls = [ mock.call(", "[self.pps_rule]) self.qos_plugin.create_policy_packet_rate_limit_rule( self.ctxt, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def test_create_policy_pps_rule_duplicates(self): _policy", "\"get_object\") @mock.patch.object(rule_object.QosBandwidthLimitRule, 'create') def test_create_policy_rule(self, mock_qos_rule_create, mock_qos_policy_get): _policy = copy.copy(self.policy)", "= uuidutils.generate_uuid() ports_res = [ { \"resource_request\": { \"port_id\": uuidutils.generate_uuid(),", "_pager=mock.ANY, qos_policy_id=self.policy.id) def test_get_policy_bandwidth_limit_rules_for_policy_with_filters(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosBandwidthLimitRule.'", "= rule_object_class(self.ctxt, id=rule_id, qos_policy_id=self.qos_policy_id, **data) with mock.patch( 'neutron.objects.qos.rule.QosRule.get_object', return_value=rule ),", "), mock.patch.object( self.policy, \"get_bound_networks\" ), mock.patch.object( self.policy, \"get_bound_ports\" ): policy_ports", "test_get_policy_dscp_marking_rules(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosDscpMarkingRule.' 'get_objects') as get_objects_mock:", "def test_validate_update_network_callback_policy_not_changed(self): policy_id = uuidutils.generate_uuid() self._test_validate_update_network_callback( policy_id=policy_id, original_policy_id=policy_id) def test_validate_update_network_callback_policy_removed(self):", "= self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation( qos1, qos2, original_min_kpps=1000, desired_min_kpps=1000)", "OR CONDITIONS OF ANY KIND, either express or implied. See", "port['binding:profile']) self.assertIn('physical_network', port['binding:profile']) def test_change_placement_allocation_increase(self): qos1 = self._make_qos_policy() qos2 =", "mock.MagicMock(qos_policy_id=self.policy.id), ] expected_network_ports = [ port for port in network_ports", "as mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.update_policy_minimum_packet_rate_rule, self.ctxt, rule_data['minimum_packet_rate_rule']['id'], self.policy.id, self.rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id)", "lib_constants.EGRESS_DIRECTION self.min_pps_rule.direction = lib_constants.EGRESS_DIRECTION request_groups_uuids = ['fake_uuid0', 'fake_uuid1'] * 2", "self.min_pps_rule.direction = lib_constants.EGRESS_DIRECTION request_groups_uuids = ['fake_uuid0', 'fake_uuid1'] * 2 min_bw_rule_ingress_data", "data})) update_policy_rule_mock.assert_has_calls(calls, any_order=True) @mock.patch.object(qos_plugin.QoSPlugin, \"get_policy_rule\") def test_show_rule(self, get_policy_rule_mock): calls =", "10}, port['resource_request']['request_groups'][0]['resources'], ) self.assertEqual( ['fake_uuid'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_min_bw_and_pps_rule(self): self.min_bw_rule.direction", "\"supported_rule_type_details\", return_value=drivers_details ): rule_type_details = self.qos_plugin.get_rule_type( admin_ctxt, qos_consts.RULE_TYPE_PACKET_RATE_LIMIT) self.assertEqual( qos_consts.RULE_TYPE_PACKET_RATE_LIMIT,", "= rule_object.QosMinimumBandwidthRule( self.ctxt, **self.rule_data['minimum_bandwidth_rule']) self.pps_rule = rule_object.QosPacketRateLimitRule( self.ctxt, **self.rule_data['packet_rate_limit_rule']) self.min_pps_rule", "}, { \"resource_request\": { \"port_id\": uuidutils.generate_uuid(), \"qos_id\": self.policy.id, \"network_id\": network_id,", "{} if is_sriov: binding_prof = { 'pci_slot': '0000:42:41.0', 'pci_vendor_info': '8086:107ed',", "@mock.patch.object(policy_object.QosPolicy, 'update') def test_update_policy(self, mock_qos_policy_update, mock_create_rbac_policy, mock_qos_policy_get): mock_qos_policy_get.return_value = self.policy", "def test_add_policy(self, mock_qos_policy, mock_create_rbac_policy): mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_policy, 'QosPolicy') mock_manager.attach_mock(self.qos_plugin.driver_manager,", "self.policy.id, {'policy': fields}) self._validate_driver_params('update_policy', self.ctxt) policy_update_mock_call = mock.call.update() update_precommit_mock_call =", "service_plugins = {'qos_plugin_name': SERVICE_PLUGIN_KLASS} ext_mgr = QoSRuleAliasMinimumPacketRateTestExtensionManager() super(TestQoSRuleAlias, self).setUp(plugin=plugin, ext_mgr=ext_mgr,", "network_id, qos_policy_id=None, port_id=None, qos_network_policy_id=None, device_owner=None): port_id = port_id if port_id", "qos_network_policy_id}, \"port\": {\"id\": port.id, \"qos_policy_id\": qos2_id}} def test_check_port_for_placement_allocation_change_no_qos_change(self): qos1_obj =", "= self._prepare_for_port_placement_allocation_change( original_qos, desired_qos, qos_network_policy=qos_network_policy) orig_port = kwargs['original_port'] qos =", "self.rule_data) def test_delete_policy_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.delete_policy_bandwidth_limit_rule, self.ctxt,", "port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_no_original_allocation(self): qos1 = self._make_qos_policy() rule1_obj = self._make_qos_minbw_rule(qos1.id,", "self.rule_data) self.mock_qos_load_attr.assert_called_once_with('rules') self._validate_driver_params('update_policy', self.ctxt) rules = [self.rule, self.min_bw_rule] setattr(_policy, \"rules\",", "self.rule_data['minimum_packet_rate_rule']['direction'] = 'any' for rule_data in rules_data: rules = [", "qos2, original_min_kbps=1000, desired_min_kbps=2000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: mock_update_qos_alloc.side_effect =", "\"rules\", [self.dscp_rule]) self.qos_plugin.create_policy_dscp_marking_rule( self.ctxt, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def test_update_policy_dscp_marking_rule(self):", "if desired_min_kbps: desired_qos.rules += [self._make_qos_minbw_rule( desired_qos.id, min_kbps=desired_min_kbps)] if desired_min_kpps: desired_qos.rules", "self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id, filter='filter_id') def test_get_policy_min_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises(", "desired_min_kbps=2000, original_min_kpps=500, desired_min_kpps=1000) for rule in qos2.rules: rule.direction = 'egress'", "self.assertEqual( ['fake_uuid'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_min_bw_and_pps_rule(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION self.min_pps_rule.direction", "mock.call.QosPolicy.get_policy_obj().get_rule_by_id(), action)() # some actions construct rule from class reference", "port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': -1000}}) self._assert_pci_info(port) def test_change_placement_allocation_decrease_min_pps(self): original_qos", "from neutron_lib.services.qos import constants as qos_consts from neutron_lib.utils import net", "original_network = self._make_network(qos1.id) network = original_network ml2plugin_mock = mock.MagicMock() with", "}, ] self.rule_data['minimum_packet_rate_rule']['direction'] = 'any' for rule_data in rules_data: rules", "self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation( qos1, qos2, original_min_kbps=1000, desired_min_kbps=2000, original_min_kpps=500,", "'fake-driver', 'supported_parameters': [{ 'parameter_name': 'min_kpps', 'parameter_type': lib_constants.VALUES_TYPE_RANGE, 'parameter_range': {'start': 0,", "{ 'binding:profile': {'allocation': { self.MIN_BW_REQUEST_GROUP_UUID: self.MIN_BW_RP}}, 'device_id': 'uu:id', 'id': '9416c220-160a-11ec-ba3d-474633eb825c',", "self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation( qos1, qos2, original_min_kbps=1000, desired_min_kbps=1000, original_min_kpps=1000,", "'PORT', 'before_update', 'test_plugin', payload=events.DBEventPayload( context, states=(original_port, port))) mock_alloc_change.assert_called_once_with( qos_network, desired_qos,", "self.qos_plugin._change_placement_allocation, qos1, qos2, orig_port, port) def test_change_placement_allocation_update_generation_conflict(self): qos1 = self._make_qos_policy()", "'neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy), \\ mock.patch( 'neutron.objects.network.Network.get_object', return_value=net), \\ mock.patch.object( self.qos_plugin, '_get_ports_with_policy',", "'fake_uuid', port['resource_request']['request_groups'][0]['id'] ) self.assertEqual( ['CUSTOM_PHYSNET_PUBLIC', 'CUSTOM_VNIC_TYPE_NORMAL'], port['resource_request']['request_groups'][0]['required'] ) self.assertEqual( {orc.NET_BW_EGR_KILOBIT_PER_SEC:", "self._prepare_port_for_placement_allocation( qos1, qos2, original_min_kbps=1000, desired_min_kbps=2000, original_min_kpps=500, desired_min_kpps=1000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation')", "self.patch_notifier = mock.patch( 'neutron.notifiers.batch_notifier.BatchNotifier._notify') self.patch_notifier.start() plugin = 'ml2' service_plugins =", "self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': -500, 'NET_PACKET_RATE_EGR_KILOPACKET_PER_SEC': 1000}, self.MIN_BW_RP: { 'NET_BW_IGR_KILOBIT_PER_SEC': -1000,", "physical_network='public', request_groups_uuids=None): network_id = uuidutils.generate_uuid() ports_res = [ { \"resource_request\":", "'resources': { orc.NET_BW_EGR_KILOBIT_PER_SEC: 10, orc.NET_BW_IGR_KILOBIT_PER_SEC: 20}, }, port['resource_request']['request_groups'] ) self.assertIn(", "setattr(_policy, \"rules\", [self.rule]) new_rule_data = { 'bandwidth_limit_rule': { 'max_kbps': 5000,", "= self._get_policy() setattr(_policy, \"rules\", [self.min_pps_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.create_policy_minimum_packet_rate_rule( self.ctxt,", "None if port_qos: qos_policy = port_qos_obj elif network_qos: qos_policy =", "'bandwidth_limit_rule': {'max_kbps': 100, 'max_burst_kbps': 150}, 'dscp_marking_rule': {'dscp_mark': 16}, 'minimum_bandwidth_rule': {'min_kbps':", "unexpectedly raised\") def test_create_min_bw_rule_on_bound_port(self): policy = self._get_policy() policy.rules = [self.min_bw_rule]", "mock_manager.mock_calls.index(delete_mock_call)) @mock.patch.object(policy_object.QosPolicy, \"get_object\") @mock.patch.object(rule_object.QosBandwidthLimitRule, 'create') def test_create_policy_rule(self, mock_qos_rule_create, mock_qos_policy_get): _policy", "orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': 1000}}) self._assert_pci_info(port) def", "qos_network_policy_id = ( qos_network_policy.id if qos_network_policy else None) network =", "self.policy.id) def test_create_policy_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.create_policy_packet_rate_limit_rule, self.ctxt,", "min_kpps=min_kpps, id=rule_id) qos_rule.create() return qos_rule def _make_port(self, network_id, qos_policy_id=None, port_id=None,", "mock_qos_rule_update): mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_rule_update, 'update') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() _policy", "import copy from unittest import mock from keystoneauth1 import exceptions", "rule_mock_call in mock_manager.mock_calls: action_index = mock_manager.mock_calls.index(rule_mock_call) else: action_index = mock_manager.mock_calls.index(", "or qos_network_policy qos.rules = [] allocation = {} if original_min_kbps:", "self.policy.id, self.rule_data) self.mock_qos_load_attr.assert_called_once_with('rules') self._validate_driver_params('update_policy', self.ctxt) rules = [self.rule, self.min_bw_rule] setattr(_policy,", "network_id = uuidutils.generate_uuid() self.port_data = { 'port': {'id': uuidutils.generate_uuid(), 'network_id':", "setattr(_policy, \"rules\", []) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.update_policy_minimum_packet_rate_rule, self.ctxt,", "= 1 self.qos_plugin.update_policy_bandwidth_limit_rule( self.ctxt, self.rule.id, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) rule_update_mock_call", "mock.ANY) self.assertTrue( mock_manager.mock_calls.index(rule_create_mock_call) < mock_manager.mock_calls.index(update_precommit_mock_call) < mock_manager.mock_calls.index(update_mock_call)) def test_create_policy_rule_check_rule_min_less_than_max(self): _policy", "def test_get_policy_packet_rate_limit_rule(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosPacketRateLimitRule.' 'get_object') as", "rule_id if rule_id else uuidutils.generate_uuid() qos_rule = rule_object.QosMinimumBandwidthRule( self.context, project_id=self.project_id,", "= {'allocation': 'fake_allocation'} mock_alloc_change.side_effect = fake_change_placement_allocation self.qos_plugin._check_network_for_placement_allocation_change( 'network', 'after_update', ml2plugin_mock,", "_pager=mock.ANY, qos_policy_id=self.policy.id, filter='filter_id') def test_get_policy_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound,", "self.ctxt, mock.ANY) update_mock_call = mock.call.driver.call( 'update_policy', self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(policy_update_mock_call)", "qos2, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': 1000}}) self._assert_pci_info(port) def", "lib_constants.EGRESS_DIRECTION request_groups_uuids = ['fake_uuid0', 'fake_uuid1'] * 2 min_bw_rule_ingress_data = {", "self.qos_plugin.get_policy_minimum_packet_rate_rule( self.ctxt, self.min_pps_rule.id, self.policy.id) get_object_mock.assert_called_once_with( self.ctxt, id=self.min_pps_rule.id) def test_get_policy_min_pps_rules_for_policy(self): with", "= { 'bandwidth_limit_rule': {'id': uuidutils.generate_uuid(), 'max_kbps': 100, 'max_burst_kbps': 150}, 'dscp_marking_rule':", "directory.get_plugin(plugins_constants.QOS) self.ctxt = context.Context('fake_user', 'fake_tenant') self.rule_objects = { 'minimum_packet_rate': rule_object.QosMinimumPacketRateRule", "} class TestQosPluginDB(base.BaseQosTestCase): PORT_ID = 'f02f160e-1612-11ec-b2b8-bf60ab98186c' QOS_MIN_BW_RULE_ID = '8bf8eb46-160e-11ec-8024-9f96be32099d' #", "[port1_binding] port1.update() port2 = self._make_port( network_id=network.id, qos_policy_id=None, device_owner='compute:uu:id') port2_binding =", "neutron.objects.qos import policy as policy_object from neutron.objects.qos import rule as", "'min_kpps': 20, 'direction': lib_constants.INGRESS_DIRECTION} min_bw_rule_ingress = rule_object.QosMinimumBandwidthRule( self.ctxt, **min_bw_rule_ingress_data) min_pps_rule_ingress", "as get_objects_mock: filters = {'filter': 'filter_id'} self.qos_plugin.get_policy_minimum_packet_rate_rules( self.ctxt, self.policy.id, filters=filters)", "mock_alloc_change.assert_has_calls(mock_alloc_change_calls, any_order=True) port1.update() port2.update() self.assertDictEqual( port1.bindings[0].profile, {'allocation': 'fake_allocation'}) self.assertDictEqual( port2.bindings[0].profile,", "'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1, None, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id',", "test_delete_policy_rule_bad_policy(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy,", "class TestQosPlugin(base.BaseQosTestCase): def setUp(self): super(TestQosPlugin, self).setUp() self.setup_coreplugin(load_plugins=False) mock.patch('neutron.objects.db.api.create_object').start() mock.patch('neutron.objects.db.api.update_object').start() mock.patch('neutron.objects.db.api.delete_object').start()", "return_value=rule.to_dict()): self._delete_rule(rule_type, rule_id) calls.append(mock.call(mock.ANY, rule_object_class, rule_id, self.qos_policy_id)) delete_policy_rule_mock.assert_has_calls(calls, any_order=True) def", "self._validate_driver_params('update_policy', self.ctxt) rules = [self.rule, self.min_bw_rule] setattr(_policy, \"rules\", rules) self.mock_qos_load_attr.reset_mock()", "network_qos else None port_qos_id = port_qos_obj.id if port_qos else None", "self.context, port_id=port1.id, host='fake_host1', vnic_type='fake_vnic_type', vif_type='fake_vif_type', profile={}) port1_binding.create() port1.bindings = [port1_binding]", "'update_policy', self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(rule_delete_mock_call) < mock_manager.mock_calls.index(update_precommit_mock_call) < mock_manager.mock_calls.index(update_mock_call)) def", "'get_objects') as get_objects_mock: self.qos_plugin.get_policy_minimum_packet_rate_rules( self.ctxt, self.policy.id) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id)", "**self.policy_data['policy']) self.rule = rule_object.QosBandwidthLimitRule( self.ctxt, **self.rule_data['bandwidth_limit_rule']) self.dscp_rule = rule_object.QosDscpMarkingRule( self.ctxt,", "self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': -2000}}) def test_change_placement_allocation_no_min_bw(self): qos1 = self._make_qos_policy() qos2", "+= [self._make_qos_minpps_rule( qos.id, min_kpps=original_min_kpps, rule_id=TestQosPluginDB.QOS_MIN_PPS_RULE_ID)] allocation.update( {TestQosPluginDB.MIN_PPS_REQUEST_GROUP_UUID: TestQosPluginDB.MIN_PPS_RP}) if desired_qos:", "return_value=_policy): setattr(_policy, \"rules\", []) self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.update_policy_packet_rate_limit_rule, self.ctxt, self.pps_rule.id, self.policy.id,", "[self.rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.update_policy_bandwidth_limit_rule( self.ctxt, self.rule.id, self.policy.id, self.rule_data) self.mock_qos_load_attr.assert_called_once_with('rules')", "mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( original_qos, desired_qos, orig_port, port) mock_update_qos_alloc.assert_called_once_with(", "{ \"port_id\": uuidutils.generate_uuid(), \"qos_id\": self.policy.id, \"network_id\": network_id, \"vnic_type\": \"normal\", }", "import netaddr from neutron_lib.api.definitions import qos from neutron_lib.callbacks import events", "mock.patch.object( self.qos_plugin, '_get_ports_with_policy', return_value=[port]): try: self.qos_plugin.create_policy_minimum_bandwidth_rule( self.ctxt, policy.id, self.rule_data) except", "{'allocation': 'fake_allocation'}) def _prepare_port_for_placement_allocation(self, original_qos, desired_qos=None, qos_network_policy=None, original_min_kbps=None, desired_min_kbps=None, original_min_kpps=None,", "as mock_update_qos_alloc: self.assertRaises(NotImplementedError, self.qos_plugin._change_placement_allocation, qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_not_called() def", "base DB_PLUGIN_KLASS = 'neutron.db.db_base_plugin_v2.NeutronDbPluginV2' SERVICE_PLUGIN_KLASS = 'neutron.services.qos.qos_plugin.QoSPlugin' class TestQosPlugin(base.BaseQosTestCase): def", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_minimum_packet_rate_rules, self.ctxt, self.policy.id) def test_get_min_pps_rule_type(self): admin_ctxt", "return_value=_policy) as mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.update_policy_minimum_packet_rate_rule, self.ctxt, rule_data['minimum_packet_rate_rule']['id'], self.policy.id, self.rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt,", "# uuid -v5 f02f160e-1612-11ec-b2b8-bf60ab98186c # 8bf8eb46-160e-11ec-8024-9f96be32099d MIN_BW_REQUEST_GROUP_UUID = 'c8bc1b27-59a1-5135-aa33-aeecad6093f4' MIN_BW_RP", "ports_object from neutron.objects.qos import policy as policy_object from neutron.objects.qos import", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy, self.ctxt, self.policy.id) def test_get_policy_bandwidth_limit_rule_for_nonexistent_policy(self):", "test_create_min_pps_rule_on_unbound_port(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.min_pps_rule]) segment = network_object.NetworkSegment(", "20, 'max_burst_kpps': 130}, 'minimum_packet_rate_rule': { 'id': uuidutils.generate_uuid(), 'min_kpps': 10, 'direction':", "qos2=qos1_obj) context = kwargs['context'] original_port = kwargs['original_port'] port = kwargs['port']", "] expected_network_ports = [ port for port in network_ports if", "policy_id, 'project_id': project_id, 'tenant_id': project_id, 'name': 'test-policy', 'description': 'Test policy", "rule_id = rule_id if rule_id else uuidutils.generate_uuid() qos_rule = rule_object.QosMinimumPacketRateRule(", "[] def get_request_extensions(self): return [] class QoSRuleAliasMinimumPacketRateTestExtensionManager(object): def get_resources(self): return", "): self.policy.rules = [self.rule] try: self.qos_plugin.validate_policy_for_port( self.ctxt, self.policy, port) except", "self.policy.id, self.rule_data) self.mock_qos_load_attr.assert_called_once_with('rules') self._validate_driver_params('update_policy', self.ctxt) self.rule_data['bandwidth_limit_rule']['max_kbps'] = 1 with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "self._test_validate_update_network_callback( policy_id=None, original_policy_id=uuidutils.generate_uuid()) def test_validate_policy_for_port_rule_not_valid(self): port = {'id': uuidutils.generate_uuid()} with", "= { 'policy': {'id': uuidutils.generate_uuid(), 'project_id': uuidutils.generate_uuid(), 'name': 'test-policy', 'description':", "mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: mock_update_qos_alloc.side_effect = ks_exc.Conflict( response={'errors': [{'code': 'placement.concurrent_update'}]}", "qos_consts.QOS_POLICY_ID: original_policy_id } } port_mock = mock.MagicMock(id=port_id, qos_policy_id=policy_id) policy_mock =", "\"id\": network_id, qos_consts.QOS_POLICY_ID: policy_id }, \"original_network\": { \"id\": network_id, qos_consts.QOS_POLICY_ID:", "self.context, network_id=network_id, device_owner=device_owner, project_id=self.project_id, admin_state_up=True, status='DOWN', device_id='2', qos_policy_id=qos_policy_id, qos_network_policy_id=qos_network_policy_id, mac_address=mac,", "qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_packet_rate_limit_rule, self.ctxt, self.pps_rule.id, self.policy.id) def test_get_policy_packet_rate_limit_rules_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None):", "self.qos_plugin._validate_update_port_callback( \"PORT\", \"precommit_update\", \"test_plugin\", payload=events.DBEventPayload( self.ctxt, desired_state=kwargs['port'], states=(kwargs['original_port'],))) if policy_id", "True, 'is_default': False}} policy_details = {'id': policy_id, 'project_id': project_id, 'name':", "device_owner='compute:uu:id') ml2plugin_mock = mock.MagicMock() with mock.patch.object( self.qos_plugin, '_change_placement_allocation') as mock_alloc_change:", "qos_policy_id=None, device_owner='compute:uu:id') port2_binding = ports_object.PortBinding( self.context, port_id=port2.id, host='fake_host2', vnic_type='fake_vnic_type', vif_type='fake_vif_type',", "bw_limit_rule = rule_object.QosDscpMarkingRule(dscp_mark=16) orig_port, port = self._prepare_port_for_placement_allocation( qos1, qos2, desired_min_kbps=2000)", "= mock.call.driver.call( 'update_policy', self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(policy_update_mock_call) < mock_manager.mock_calls.index(update_precommit_mock_call) <", "def test_get_policy_dscp_marking_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_dscp_marking_rule, self.ctxt, self.dscp_rule.id,", "rules: min_pps_rule = rule_object.QosMinimumPacketRateRule( self.ctxt, **rule_data['minimum_packet_rate_rule']) setattr(_policy, \"rules\", [min_pps_rule]) with", "for action, arguments in rule_actions.items(): mock_manager.reset_mock() method = getattr(self.qos_plugin, \"%s_policy_rule\"", "from oslo_config import cfg from oslo_utils import uuidutils import webob.exc", "original_policy_id } } port_mock_with_own_policy = mock.MagicMock( id=uuidutils.generate_uuid(), qos_policy_id=uuidutils.generate_uuid()) port_mock_without_own_policy =", "context.get_admin_context() self.policy_data = { 'policy': {'id': uuidutils.generate_uuid(), 'project_id': uuidutils.generate_uuid(), 'name':", "self.policy.id) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id) def test_get_policy_minimum_bandwidth_rules_for_policy_with_filters(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy):", "fields = obj_utils.get_updatable_fields( policy_object.QosPolicy, self.policy_data['policy']) self.qos_plugin.update_policy( self.ctxt, self.policy.id, {'policy': fields})", "import placement as pl_exc from neutron_lib.exceptions import qos as qos_exc", "self.dscp_rule.id, self.policy.id) self._validate_driver_params('update_policy', self.ctxt) def test_get_policy_dscp_marking_rules(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with", "rule_type: kwargs} resource = '%s/alias-%s-rules' % (qos.ALIAS, rule_type.replace('_', '-')) request", "qos_network_policy=qos_network) context = kwargs['context'] original_port = kwargs['original_port'] port = kwargs['port']", "qos2, original_min_kpps=1000, desired_min_kpps=2000, is_sriov=True) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(", "writing, software # distributed under the License is distributed on", "\\ mock.patch( 'neutron.objects.qos.rule.QosMinimumPacketRateRule.' 'get_objects', return_value=min_pps_rules), \\ mock.patch( 'uuid.uuid5', return_value='fake_uuid', side_effect=request_groups_uuids):", "test_validate_update_port_callback_policy_not_changed(self): policy_id = uuidutils.generate_uuid() self._test_validate_update_port_callback( policy_id=policy_id, original_policy_id=policy_id) def test_validate_update_port_callback_policy_removed(self): self._test_validate_update_port_callback(", "= directory.get_plugin(plugins_constants.QOS) self.ctxt = context.Context('fake_user', 'fake_tenant') self.rule_objects = { 'minimum_packet_rate':", "self.ctxt, _policy.id, self.rule_data) except NotImplementedError: self.fail() def test_create_policy_rule_check_rule_min_pps_direction_conflict(self): _policy =", "self.min_pps_rule.direction = lib_constants.EGRESS_DIRECTION request_groups_uuids = ['fake_uuid0', 'fake_uuid1'] min_bw_rule_ingress_data = {", "self.assertLess( action_index, mock_manager.mock_calls.index(driver_mock_call)) def test_create_policy_packet_rate_limit_rule(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy'])", "rule_object_class(self.ctxt, id=rule_id, qos_policy_id=self.qos_policy_id, **data) with mock.patch('neutron.objects.qos.rule.QosRule.get_object', return_value=rule): self._show_rule(rule_type, rule_id) calls.append(mock.call(mock.ANY,", "\"test_plugin\", payload=events.DBEventPayload( self.context, resource_id=kwargs['port']['id'],)) qos_policy = None if port_qos: qos_policy", "= self._prepare_port_for_placement_allocation( original_qos, desired_qos, original_min_kpps=2000, desired_min_kpps=1000, is_sriov=True) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation')", "setattr(_policy, \"rules\", [self.rule]) self.qos_plugin.delete_policy_bandwidth_limit_rule( self.ctxt, self.rule.id, _policy.id) self._validate_driver_params('update_policy', self.ctxt) rule_delete_mock_call", "mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_min_bw_dataplane_enforcement_with_pps( self): qos1", "setattr(_policy, \"rules\", [self.min_pps_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.create_policy_minimum_packet_rate_rule( self.ctxt, self.policy.id, self.rule_data)", "return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy, self.ctxt, self.policy.id) def test_get_policy_bandwidth_limit_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "setUp(self): # Remove MissingAuthPlugin exception from logs self.patch_notifier = mock.patch(", "uuidutils.generate_uuid() qos_rule = rule_object.QosMinimumBandwidthRule( self.context, project_id=self.project_id, qos_policy_id=policy_id, direction=direction, min_kbps=min_kbps, id=rule_id)", "qos_policy, network.id) else: mock_validate_policy.assert_not_called() def test_validate_create_network_callback(self): self._test_validate_create_network_callback(network_qos=True) def test_validate_create_network_callback_no_qos(self): self._test_validate_create_network_callback(network_qos=False)", "self.rule.id, self.policy.id) def test_verify_bad_method_call(self): self.assertRaises(AttributeError, getattr, self.qos_plugin, 'create_policy_bandwidth_limit_rules') def test_get_rule_type(self):", "the License. You may obtain # a copy of the", "10}, 'packet_rate_limit_rule': { 'id': uuidutils.generate_uuid(), 'max_kpps': 20, 'max_burst_kpps': 130}, 'minimum_packet_rate_rule':", "in network_ports if port.qos_policy_id is None] expected_ports = ports +", "new_rule_data = { 'minimum_packet_rate_rule': { 'id': uuidutils.generate_uuid(), 'min_kpps': 1234, 'direction':", "self.ctxt = context.Context('fake_user', 'fake_tenant') self.rule_objects = { 'minimum_packet_rate': rule_object.QosMinimumPacketRateRule }", "use this file except in compliance with the License. You", "rule_data in rules_data: rules = [ rule_object.QosMinimumPacketRateRule( self.ctxt, **rules_data[0]['minimum_packet_rate_rule']), rule_object.QosMinimumPacketRateRule(", "\"test_plugin\", payload=events.DBEventPayload( self.ctxt, desired_state=kwargs['network'], states=(kwargs['original_network'],))) if policy_id is None or", "self.ctxt) def test_delete_policy_dscp_marking_rule(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "None, 'qos_network_policy_id': qos.id}, mock.ANY), mock.call( original_qos, qos, {'id': port2.id, 'device_owner':", "self._prepare_for_port_placement_allocation_change( qos1=qos1_obj, qos2=qos1_obj) context = kwargs['context'] original_port = kwargs['original_port'] port", "= uuidutils.generate_uuid() kwargs = { \"context\": self.ctxt, \"network\": { \"id\":", "allocation.update( {TestQosPluginDB.MIN_PPS_REQUEST_GROUP_UUID: TestQosPluginDB.MIN_PPS_RP}) if desired_qos: desired_qos.rules = [] if desired_min_kbps:", "10} } def _update_rule(self, rule_type, rule_id, **kwargs): data = {'alias_%s_rule'", "states=(original_port, port))) mock_alloc_change.assert_called_once_with( qos1_obj, qos2_obj, kwargs['original_port'], port) def test_check_port_for_placement_allocation_change_no_new_policy(self): qos1_obj", "id=_policy.id) def test_update_policy_packet_rate_limit_rule(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "self.ctxt, policy.id, self.rule_data) except NotImplementedError: self.fail() @mock.patch( 'neutron.objects.rbac_db.RbacNeutronDbObjectMixin' '.create_rbac_policy') @mock.patch('neutron.objects.qos.policy.QosPolicy')", "mock_qos_rule_delete): mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_rule_delete, 'delete') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() _policy", "get_object_mock.assert_called_once_with(self.ctxt, id=self.rule.id) def test_get_policy_minimum_bandwidth_rules_for_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumBandwidthRule.'", "= rule_object.QosMinimumPacketRateRule( self.ctxt, **min_pps_rule_ingress_data) ports = self._create_and_extend_ports( [self.min_bw_rule, min_bw_rule_ingress], [self.min_pps_rule,", "len(port['resource_request']['request_groups']) ) self.assertEqual( 'fake_uuid', port['resource_request']['request_groups'][0]['id'] ) self.assertEqual( ['CUSTOM_PHYSNET_PUBLIC', 'CUSTOM_VNIC_TYPE_NORMAL'], port['resource_request']['request_groups'][0]['required']", "self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.update_policy_minimum_packet_rate_rule, self.ctxt, rule_data['minimum_packet_rate_rule']['id'], self.policy.id, self.rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_update_policy_min_pps_rule_bad_policy(self):", "net = network_object.Network( self.ctxt, segments=[segment]) port = ports_object.Port( self.ctxt, id=uuidutils.generate_uuid(),", "uuidutils.generate_uuid() def _make_qos_policy(self): qos_policy = policy_object.QosPolicy( self.context, project_id=self.project_id, shared=False, is_default=False)", "as mock_alloc_change: def fake_change_placement_allocation(orig_policy, policy, orig_port, port): port['binding:profile'] = {}", "original_qos, desired_qos, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': -1000}})", "orig_port, port = self._prepare_port_for_placement_allocation(qos1, original_min_kbps=1000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc:", "ports = [ mock.MagicMock(qos_policy_id=self.policy.id), ] expected_network_ports = [ port for", "def test_validate_create_network_callback(self): self._test_validate_create_network_callback(network_qos=True) def test_validate_create_network_callback_no_qos(self): self._test_validate_create_network_callback(network_qos=False) def _test_validate_create_port_callback(self, port_qos=False, network_qos=False):", "port1.bindings = [port1_binding] port1.update() with mock.patch.object( self.qos_plugin, '_change_placement_allocation') as mock_alloc_change:", "self.assertDictEqual( port1.bindings[0].profile, {'allocation': 'fake_allocation'}) self.assertDictEqual( port2.bindings[0].profile, {'allocation': 'fake_allocation'}) def _prepare_port_for_placement_allocation(self,", "bw_limit_rule1 = rule_object.QosDscpMarkingRule(dscp_mark=16) bw_limit_rule2 = rule_object.QosDscpMarkingRule(dscp_mark=18) qos1.rules = [bw_limit_rule1] qos2.rules", "= mock.Mock() mock_manager.attach_mock(mock_qos_policy, 'QosPolicy') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() self.qos_plugin.create_policy(self.ctxt, self.policy_data) policy_mock_call", "-v5 f02f160e-1612-11ec-b2b8-bf60ab98186c # 6ac5db7e-1626-11ec-8c7f-0b70dbb8a8eb MIN_PPS_REQUEST_GROUP_UUID = '995008f4-f120-547a-b051-428b89076067' MIN_PPS_RP = 'e16161f4-1626-11ec-a5a2-1fc9396e27cc'", "[self._make_qos_minpps_rule( desired_qos.id, min_kpps=desired_min_kpps)] binding_prof = {} if is_sriov: binding_prof =", "get_object_mock.assert_called_once_with(self.ctxt, id=self.rule.id) def test_get_policy_bandwidth_limit_rules_for_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosBandwidthLimitRule.'", "policy, orig_port, port): port['binding:profile'] = {} mock_alloc_change.side_effect = fake_change_placement_allocation self.qos_plugin._check_network_for_placement_allocation_change(", "that work with real data types mock.patch( 'neutron.objects.base.NeutronDbObject.modify_fields_from_db' ).start() mock.patch.object(policy_object.QosPolicy,", "\\ mock.patch( 'neutron.objects.qos.qos_policy_validator' '.check_min_pps_rule_conflict', return_value=None): self.qos_plugin.create_policy_bandwidth_limit_rule( self.ctxt, self.policy.id, self.rule_data) self._validate_driver_params('update_policy',", "'get_objects') as get_objects_mock: self.qos_plugin.get_policy_bandwidth_limit_rules( self.ctxt, self.policy.id) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id)", "= self._make_network(qos1.id) network = original_network ml2plugin_mock = mock.MagicMock() with mock.patch.object(", "qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_dscp_marking_rule, self.ctxt, self.dscp_rule.id, self.policy.id) def test_get_policy_dscp_marking_rules_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None):", "self._validate_driver_params('update_policy', self.ctxt) policy_update_mock_call = mock.call.update() update_precommit_mock_call = mock.call.driver.call( 'update_policy_precommit', self.ctxt,", "{ \"id\": network_id, qos_consts.QOS_POLICY_ID: policy_id }, \"original_network\": { \"id\": network_id,", "return_value=[port]): self.assertRaises( NotImplementedError, self.qos_plugin.create_policy_minimum_bandwidth_rule, self.ctxt, policy.id, self.rule_data) def test_create_min_bw_rule_on_unbound_port(self): policy", "rule_object.QosMinimumPacketRateRule( self.ctxt, **rule_data['minimum_packet_rate_rule']) setattr(_policy, \"rules\", [min_pps_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as", "setattr(_policy, \"rules\", []) self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.delete_policy_packet_rate_limit_rule, self.ctxt, self.pps_rule.id, _policy.id) def", "self._get_policy() rules_data = [ { 'minimum_packet_rate_rule': { 'id': uuidutils.generate_uuid(), 'min_kpps':", "'create_policy_precommit', self.ctxt, mock.ANY) create_mock_call = mock.call.driver.call( 'create_policy', self.ctxt, mock.ANY) self.assertTrue(", "also need to mock-out # methods that work with real", "= context.get_admin_context() drivers_details = [{ 'name': 'fake-driver', 'supported_parameters': [{ 'parameter_name':", "uuidutils.generate_uuid() self.rule_data = { 'bandwidth_limit_rule': {'max_kbps': 100, 'max_burst_kbps': 150}, 'dscp_marking_rule':", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.create_policy_minimum_bandwidth_rule, self.ctxt, self.policy.id, self.rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt,", "alloc_diff={ self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': -1000}, self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': -2000}}) def test_change_placement_allocation_no_min_bw(self):", "= mock_manager.mock_calls.index( get_rule_mock_call) self.assertLess( action_index, mock_manager.mock_calls.index(driver_mock_call)) def test_create_policy_packet_rate_limit_rule(self): _policy =", "_policy = self._get_policy() setattr(_policy, \"rules\", [self.min_pps_rule]) segment = network_object.NetworkSegment( physical_network='fake", "ports_object.PortBinding( self.context, port_id=port2.id, host='fake_host2', vnic_type='fake_vnic_type', vif_type='fake_vif_type', profile={}) port2_binding.create() port2.bindings =", "self.mock_qos_load_attr.assert_called_once_with('rules') self._validate_driver_params('update_policy', self.ctxt) rules = [self.rule, self.min_bw_rule] setattr(_policy, \"rules\", rules)", "mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={ self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': -500, 'NET_PACKET_RATE_EGR_KILOPACKET_PER_SEC': 1000}, self.MIN_BW_RP:", "mock_validate_policy.assert_called_once_with( self.context, qos_policy, port) else: mock_validate_policy.assert_not_called() def test_validate_create_port_callback_policy_on_port(self): self._test_validate_create_port_callback(port_qos=True) def", "logs self.patch_notifier = mock.patch( 'neutron.notifiers.batch_notifier.BatchNotifier._notify') self.patch_notifier.start() plugin = 'ml2' service_plugins", "rule_object.QosMinimumPacketRateRule } self.qos_policy_id = uuidutils.generate_uuid() self.rule_data = { 'minimum_packet_rate_rule': {'min_kpps':", "neutron.extensions import qos_pps_minimum_rule_alias from neutron.extensions import qos_rules_alias from neutron import", "self._create_and_extend_port( [self.min_bw_rule, min_bw_rule_ingress], [self.min_pps_rule, min_pps_rule_ingress], request_groups_uuids=request_groups_uuids) self.assertEqual( 2, len(port['resource_request']['request_groups']) )", "policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", [self.pps_rule]) self.qos_plugin.update_policy_packet_rate_limit_rule(", "[ mock.MagicMock(qos_policy_id=None), mock.MagicMock(qos_policy_id=uuidutils.generate_uuid()), mock.MagicMock(qos_policy_id=None) ] ports = [ mock.MagicMock(qos_policy_id=self.policy.id), ]", "'neutron.objects.network.Network.get_object', return_value=net), \\ mock.patch.object( self.qos_plugin, '_get_ports_with_policy', return_value=[port]): try: self.qos_plugin.create_policy_minimum_packet_rate_rule( self.ctxt,", "get_policy, mock.patch.object( self.qos_plugin, \"validate_policy_for_port\" ) as validate_policy_for_port, mock.patch.object( self.ctxt, \"elevated\",", "get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id, filter='filter_id') def test_get_policy_packet_rate_limit_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None):", "'any' with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.assertRaises(NotImplementedError, self.qos_plugin._change_placement_allocation, qos1, qos2,", "action)() driver_mock_call = mock.call.driver.call('update_policy', self.ctxt, mock.ANY) if rule_mock_call in mock_manager.mock_calls:", "port_id=TestQosPluginDB.PORT_ID) return {\"context\": self.context, \"original_port\": { \"id\": port.id, \"device_owner\": \"compute:uu:id\",", "'device_owner': 'compute:uu:id', 'qos_policy_id': None, 'qos_network_policy_id': qos.id}, mock.ANY)] mock_alloc_change.assert_has_calls(mock_alloc_change_calls, any_order=True) port1.update()", "_policy = self._get_policy() setattr(_policy, \"rules\", [self.rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as", "qos_exc.QosPolicyNotFound, self.qos_plugin.create_policy_bandwidth_limit_rule, self.ctxt, self.policy.id, self.rule_data) def test_update_policy_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None):", "policy_id=uuidutils.generate_uuid()) def test_validate_update_network_callback_policy_not_changed(self): policy_id = uuidutils.generate_uuid() self._test_validate_update_network_callback( policy_id=policy_id, original_policy_id=policy_id) def", "states=(kwargs['original_port'],))) if policy_id is None or policy_id == original_policy_id: get_port.assert_not_called()", "return_value=False ): self.policy.rules = [self.rule] self.assertRaises( qos_exc.QosRuleNotSupported, self.qos_plugin.validate_policy_for_port, self.ctxt, self.policy,", "net_qos_id = net_qos_obj.id if network_qos else None port_qos_id = port_qos_obj.id", "} ml2plugin_mock._make_port_dict.side_effect = fake_make_port_dict port1 = self._make_port( network_id=network.id, qos_policy_id=None, device_owner='compute:uu:id')", "rule_object.QosDscpMarkingRule(dscp_mark=18) qos1.rules = [bw_limit_rule1] qos2.rules = [bw_limit_rule2] orig_port = {", "{} mock_alloc_change.side_effect = fake_change_placement_allocation self.qos_plugin._check_network_for_placement_allocation_change( 'network', 'after_update', ml2plugin_mock, payload=events.DBEventPayload( self.context,", "= directory.get_plugin(plugins_constants.QOS) self.ctxt = context.Context('fake_user', 'fake_tenant') self.rule_objects = { 'bandwidth_limit':", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt, self.policy.id, new_rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt,", "QosMocked: self.qos_plugin.create_policy(self.ctxt, tenant_policy) QosMocked.assert_called_once_with(self.ctxt, **policy_details) @mock.patch.object(policy_object.QosPolicy, \"get_object\") @mock.patch( 'neutron.objects.rbac_db.RbacNeutronDbObjectMixin' '.create_rbac_policy')", "self.ctxt, self.policy.id) def test_create_policy_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.create_policy_packet_rate_limit_rule,", "original_network = self._make_network(original_qos.id) network = self._make_network() ml2plugin_mock = mock.MagicMock() def", "rule_object.QosMinimumPacketRateRule( self.ctxt, **rules_data[0]['minimum_packet_rate_rule']), rule_object.QosMinimumPacketRateRule( self.ctxt, **rules_data[1]['minimum_packet_rate_rule']), ] setattr(_policy, 'rules', rules)", "None or policy_id == original_policy_id: get_policy.assert_not_called() validate_policy_for_network.assert_not_called() get_ports.assert_not_called() validate_policy_for_ports.assert_not_called() else:", "express or implied. See the # License for the specific", "port1.update() with mock.patch.object( self.qos_plugin, '_change_placement_allocation') as mock_alloc_change: def fake_change_placement_allocation(orig_policy, policy,", "rule_object_class in self.rule_objects.items(): rule_id = uuidutils.generate_uuid() rule_data_name = '%s_rule' %", "desired_min_kpps=1000) for rule in qos2.rules: rule.direction = 'egress' with mock.patch.object(self.qos_plugin._placement_client,", "[self.dscp_rule]) self.qos_plugin.update_policy_dscp_marking_rule( self.ctxt, self.dscp_rule.id, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def test_delete_policy_dscp_marking_rule(self):", "type_ in types)) @mock.patch('neutron.objects.ports.Port') @mock.patch('neutron.objects.qos.policy.QosPolicy') def test_rule_notification_and_driver_ordering(self, qos_policy_mock, port_mock): rule_cls_mock", "qos2 = self._make_qos_policy() bw_limit_rule1 = rule_object.QosDscpMarkingRule(dscp_mark=16) bw_limit_rule2 = rule_object.QosDscpMarkingRule(dscp_mark=18) qos1.rules", "self._make_qos_policy() kwargs = self._prepare_for_port_placement_allocation_change( qos1=qos1_obj, qos2=qos2_obj) context = kwargs['context'] original_port", "network = self._make_network(qos.id) ml2plugin_mock = mock.MagicMock() def fake_make_port_dict(port): return {", "if port_qos else None network = self._make_network(qos_policy_id=net_qos_id) port = self._make_port(network.id,", "the Apache License, Version 2.0 (the \"License\"); you may #", "mock.patch('neutron.objects.network.NetworkSegment.get_objects', return_value=[segment_mock]), \\ mock.patch( 'neutron.objects.qos.rule.QosMinimumBandwidthRule.' 'get_objects', return_value=min_bw_rules), \\ mock.patch( 'neutron.objects.qos.rule.QosMinimumPacketRateRule.'", "): self.qos_plugin._validate_update_port_callback( \"PORT\", \"precommit_update\", \"test_plugin\", payload=events.DBEventPayload( self.ctxt, desired_state=kwargs['port'], states=(kwargs['original_port'],))) if", "return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.delete_policy_packet_rate_limit_rule, self.ctxt, self.pps_rule.id, self.policy.id) def test_get_pps_rule_type(self): admin_ctxt", "status='DOWN', device_id='2', qos_policy_id=qos_policy_id, qos_network_policy_id=qos_network_policy_id, mac_address=mac, id=port_id) port.create() return port def", "self.qos_plugin.get_rule_type, self.ctxt, qos_consts.RULE_TYPE_MINIMUM_PACKET_RATE) class QoSRuleAliasTestExtensionManager(object): def get_resources(self): return qos_rules_alias.Qos_rules_alias.get_resources() def", "payload=events.DBEventPayload( context, states=(original_port, port))) mock_alloc_change.assert_not_called() def test_check_port_for_placement_allocation_change_qos_network_policy( self): qos_network =", "'device_id': 'uu:id'} ) return orig_port, kwargs['port'] def _assert_pci_info(self, port): self.assertIn('pci_slot',", "test_change_placement_allocation_increase(self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() orig_port, port =", "mock_manager.mock_calls.index(delete_precommit_mock_call) < mock_manager.mock_calls.index(delete_mock_call)) @mock.patch.object(policy_object.QosPolicy, \"get_object\") @mock.patch.object(rule_object.QosBandwidthLimitRule, 'create') def test_create_policy_rule(self, mock_qos_rule_create,", "qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={ self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC':", "self.rule_data) def test_create_min_bw_rule_on_unbound_port(self): policy = self._get_policy() policy.rules = [self.min_bw_rule] segment", "work with real data types mock.patch( 'neutron.objects.base.NeutronDbObject.modify_fields_from_db' ).start() mock.patch.object(policy_object.QosPolicy, 'unset_default').start()", "= uuidutils.generate_uuid() kwargs = { \"port\": { \"id\": port_id, qos_consts.QOS_POLICY_ID:", "= mock.MagicMock(network_id=network_id, physical_network=physical_network) min_pps_rules = min_pps_rules if min_pps_rules else []", "if res.status_int >= webob.exc.HTTPClientError.code: raise webob.exc.HTTPClientError(code=res.status_int) @mock.patch.object(qos_plugin.QoSPlugin, \"update_policy_rule\") def test_update_rule(self,", "'pci_slot': '0000:42:41.0', 'pci_vendor_info': '8086:107ed', 'physical_network': 'sriov_phy' } binding_prof.update({'allocation': allocation}) orig_port.update(", "def test_create_policy_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.create_policy_packet_rate_limit_rule, self.ctxt, self.policy.id,", "lib_constants.INGRESS_DIRECTION} min_bw_rule_ingress = rule_object.QosMinimumBandwidthRule( self.ctxt, **min_bw_rule_ingress_data) min_pps_rule_ingress = rule_object.QosMinimumPacketRateRule( self.ctxt,", "return_value=_policy): setattr(_policy, \"rules\", []) self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.delete_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, _policy.id)", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_dscp_marking_rule, self.ctxt, self.dscp_rule.id, self.policy.id) def", "webob.exc.HTTPClientError.code: raise webob.exc.HTTPClientError(code=res.status_int) @mock.patch.object(qos_plugin.QoSPlugin, \"update_policy_rule\") def test_update_rule(self, update_policy_rule_mock): calls =", "self.policy.id, filters=filters) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id, filter='filter_id') def test_get_policy_minimum_bandwidth_rule_for_nonexistent_policy(self): with", "qos_exc.QoSRuleParameterConflict, self.qos_plugin.update_policy_minimum_bandwidth_rule, self.ctxt, self.min_bw_rule.id, self.policy.id, self.rule_data) def test_update_policy_rule_check_rule_minbw_gr_than_bwlimit(self): _policy =", "_policy.id, self.rule_data) except NotImplementedError: self.fail() def test_create_policy_rule_check_rule_min_pps_direction_conflict(self): _policy = self._get_policy()", "as mock_qos_get_obj: self.assertRaises( qos_exc.QoSRulesConflict, self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt, _policy.id, new_rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id)", "[bw_limit_rule] orig_port, port = self._prepare_port_for_placement_allocation(qos1, original_min_kbps=1000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as", "return_value=_policy): self.qos_plugin.update_policy_bandwidth_limit_rule( self.ctxt, self.rule.id, self.policy.id, self.rule_data) self.mock_qos_load_attr.assert_called_once_with('rules') self._validate_driver_params('update_policy', self.ctxt) rules", "port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={ self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': -1000}, self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC':", "port_id = uuidutils.generate_uuid() kwargs = { \"port\": { \"id\": port_id,", "= self._make_network(qos_policy_id=net_qos_id) port = self._make_port(network.id, qos_policy_id=port_qos_id) kwargs = {\"context\": self.context,", "self.policy.id, filters=filters) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id, filter='filter_id') def test_get_policy_for_nonexistent_policy(self): with", "network_id=uuidutils.generate_uuid(), device_owner='') with mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy), \\ mock.patch( 'neutron.objects.network.Network.get_object', return_value=net),", "def test_change_placement_allocation_qos_network_policy(self): qos_network = self._make_qos_policy() desired_qos = self._make_qos_policy() orig_port, port", "min_pps_rules if min_pps_rules else [] with mock.patch('neutron.objects.network.NetworkSegment.get_objects', return_value=[segment_mock]), \\ mock.patch(", "= _mock_qos_load_attr.start() # We don't use real models as per", "mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_policy, 'QosPolicy') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() self.qos_plugin.create_policy(self.ctxt, self.policy_data)", "'delete') def test_delete_policy(self, mock_qos_policy_delete, mock_api_get_policy): mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_policy_delete, 'delete')", "return_value=policy_mock ) as get_policy, mock.patch.object( self.qos_plugin, \"validate_policy_for_port\" ) as validate_policy_for_port,", "qos_policy_id=self.policy.id, filter='filter_id') def test_get_policy_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy,", "uuidutils.generate_uuid(), 'min_kpps': 1234, 'direction': self.min_pps_rule.direction, }, } with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy)", "self._prepare_for_port_placement_allocation_change( qos1=None, qos2=desired_qos, qos_network_policy=qos_network) context = kwargs['context'] original_port = kwargs['original_port']", "self.assertIn(port, policy_ports) def _test_validate_update_port_callback(self, policy_id=None, original_policy_id=None): port_id = uuidutils.generate_uuid() kwargs", "'fake_uuid', port['resource_request']['request_groups'][0]['id'] ) self.assertEqual( ['CUSTOM_VNIC_TYPE_NORMAL'], port['resource_request']['request_groups'][0]['required'] ) self.assertEqual( {orc.NET_PACKET_RATE_KILOPACKET_PER_SEC: 10},", "self.ctxt, self.pps_rule.id, self.policy.id) def test_get_pps_rule_type(self): admin_ctxt = context.get_admin_context() drivers_details =", "orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_min_bw_dataplane_enforcement_with_pps( self): qos1 = self._make_qos_policy() qos2", "update_mock_call = mock.call.driver.call( 'update_policy', self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(rule_update_mock_call) < mock_manager.mock_calls.index(update_precommit_mock_call)", "def test_validate_update_port_callback_policy_changed(self): self._test_validate_update_port_callback( policy_id=uuidutils.generate_uuid()) def test_validate_update_port_callback_policy_not_changed(self): policy_id = uuidutils.generate_uuid() self._test_validate_update_port_callback(", "as validate_policy_for_port, mock.patch.object( self.ctxt, \"elevated\", return_value=admin_ctxt ): self.qos_plugin._validate_update_port_callback( \"PORT\", \"precommit_update\",", "\\ mock.patch.object( self.qos_plugin, '_get_ports_with_policy', return_value=[port]): try: self.qos_plugin.create_policy_minimum_packet_rate_rule( self.ctxt, _policy.id, self.rule_data)", "def test_update_policy_min_pps_rule(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.min_pps_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "qos_exc.QosRuleNotFound, self.qos_plugin.delete_policy_minimum_packet_rate_rule, self.ctxt, self.min_pps_rule.id, _policy.id) def test_delete_policy_min_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None):", "qos_rules_alias.Qos_rules_alias.get_resources() def get_actions(self): return [] def get_request_extensions(self): return [] class", "self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.delete_policy_packet_rate_limit_rule, self.ctxt, self.pps_rule.id, self.policy.id) def test_get_pps_rule_type(self): admin_ctxt =", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosDscpMarkingRule.' 'get_objects') as get_objects_mock: self.qos_plugin.get_policy_dscp_marking_rules( self.ctxt,", "{'id': uuidutils.generate_uuid(), 'network_id': network_id} } if has_qos_policy: self.port_data['port']['qos_policy_id'] = self.policy.id", "segment = network_object.NetworkSegment( physical_network='fake physnet') net = network_object.Network( self.ctxt, segments=[segment])", "self.qos_plugin.get_policy_packet_rate_limit_rules( self.ctxt, self.policy.id, filters=filters) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id, filter='filter_id') def", "{ 'bandwidth_limit_rule': {'max_kbps': 100, 'max_burst_kbps': 150}, 'dscp_marking_rule': {'dscp_mark': 16}, 'minimum_bandwidth_rule':", "mock.ANY), mock.call( original_qos, qos, {'id': port2.id, 'device_owner': 'compute:uu:id', 'qos_policy_id': None,", "rule_type_details['type']) self.assertEqual( drivers_details, rule_type_details['drivers']) def test_get_min_pps_rule_type_as_user(self): self.assertRaises( lib_exc.NotAuthorized, self.qos_plugin.get_rule_type, self.ctxt,", "min_kpps=1000, rule_id=None): rule_id = rule_id if rule_id else uuidutils.generate_uuid() qos_rule", "mock.MagicMock() def fake_make_port_dict(port): return { 'id': port.id, 'device_owner': port.device_owner, 'qos_policy_id':", "test_get_policy_minimum_bandwidth_rules_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_minimum_bandwidth_rules, self.ctxt, self.policy.id) def", "= ( qos_network_policy.id if qos_network_policy else None) network = self._make_network(qos_policy_id=qos_network_policy_id)", "}, ] segment_mock = mock.MagicMock(network_id=network_id, physical_network=physical_network) min_pps_rules = min_pps_rules if", "= self._make_network(qos.id) ml2plugin_mock = mock.MagicMock() def fake_make_port_dict(port): return { 'id':", "= self._make_qos_policy() kwargs = self._prepare_for_port_placement_allocation_change( qos1=qos1_obj, qos2=qos1_obj) context = kwargs['context']", "orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_min_bw_dataplane_enforcement(self): qos1 = self._make_qos_policy() qos2 =", "self.ctxt, _policy.id, self.rule_data) def test_create_min_pps_rule_on_unbound_port(self): _policy = self._get_policy() setattr(_policy, \"rules\",", "def test_validate_create_port_callback_policy_on_port(self): self._test_validate_create_port_callback(port_qos=True) def test_validate_create_port_callback_policy_on_port_and_network(self): self._test_validate_create_port_callback(port_qos=True, network_qos=True) def test_validate_create_port_callback_policy_on_network(self): self._test_validate_create_port_callback(network_qos=True)", "has_qos_policy=True, has_net_qos_policy=False, request_groups_uuids=None): network_id = uuidutils.generate_uuid() self.port_data = { 'port':", "validate_policy_for_port, mock.patch.object( self.ctxt, \"elevated\", return_value=admin_ctxt ): self.qos_plugin._validate_update_port_callback( \"PORT\", \"precommit_update\", \"test_plugin\",", "uuidutils.generate_uuid() with mock.patch.object( self.qos_plugin.driver_manager, \"validate_rule_for_network\", return_value=True ): self.policy.rules = [self.rule]", "filter='filter_id') def test_get_policy_minimum_bandwidth_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_minimum_bandwidth_rule, self.ctxt,", "lib_exc.NotAuthorized, self.qos_plugin.get_rule_type, self.ctxt, qos_consts.RULE_TYPE_MINIMUM_PACKET_RATE) class QoSRuleAliasTestExtensionManager(object): def get_resources(self): return qos_rules_alias.Qos_rules_alias.get_resources()", "\"PORT\", \"precommit_create\", \"test_plugin\", payload=events.DBEventPayload( self.context, resource_id=kwargs['port']['id'],)) qos_policy = None if", "'Port') mock_manager.attach_mock(rule_cls_mock, 'RuleCls') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') for action, arguments in rule_actions.items():", "port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_min_pps_rule(self): port = self._create_and_extend_port([], [self.min_pps_rule]) self.assertEqual( 1,", "qos_policy_id=self.policy.id, filter='filter_id') def test_get_policy_minimum_bandwidth_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_minimum_bandwidth_rule,", "mock_manager.mock_calls.index(update_mock_call)) def test_create_policy_rule_check_rule_min_less_than_max(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.rule]) with", "self._get_policy() self.rule_data['minimum_bandwidth_rule']['min_kbps'] = 1000000 setattr(_policy, \"rules\", [self.rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy)", "self.ctxt) def test_create_policy_pps_rule_duplicates(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.pps_rule]) new_rule_data", "[ rule_object.QosMinimumPacketRateRule( self.ctxt, **rules_data[0]['minimum_packet_rate_rule']), rule_object.QosMinimumPacketRateRule( self.ctxt, **rules_data[1]['minimum_packet_rate_rule']), ] setattr(_policy, 'rules',", "mock.ANY) update_mock_call = mock.call.driver.call( 'update_policy', self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(rule_create_mock_call) <", "from neutron.objects.qos import rule as rule_object from neutron.services.qos import qos_plugin", "id=self.min_pps_rule.id) def test_get_policy_min_pps_rules_for_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumPacketRateRule.' 'get_objects')", "self.qos_plugin.validate_policy_for_port( self.ctxt, self.policy, port) except qos_exc.QosRuleNotSupported: self.fail(\"QosRuleNotSupported exception unexpectedly raised\")", "[self.min_pps_rule]) rules = [ { 'minimum_packet_rate_rule': { 'id': uuidutils.generate_uuid(), 'min_kpps':", "policy_id is None or policy_id == original_policy_id: get_policy.assert_not_called() validate_policy_for_network.assert_not_called() get_ports.assert_not_called()", "as mock_update_qos_alloc: mock_update_qos_alloc.side_effect = ( pl_exc.PlacementAllocationGenerationConflict( consumer=self.MIN_BW_RP)) self.assertRaises( pl_exc.PlacementAllocationGenerationConflict, self.qos_plugin._change_placement_allocation,", "= [ { 'minimum_packet_rate_rule': { 'id': uuidutils.generate_uuid(), 'min_kpps': 10, 'direction':", "self.ctxt, self.min_pps_rule.id, self.policy.id) def test_get_policy_min_pps_rule(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.'", "setUp(self): super(TestQosPlugin, self).setUp() self.setup_coreplugin(load_plugins=False) mock.patch('neutron.objects.db.api.create_object').start() mock.patch('neutron.objects.db.api.update_object').start() mock.patch('neutron.objects.db.api.delete_object').start() mock.patch('neutron.objects.db.api.get_object').start() _mock_qos_load_attr =", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosBandwidthLimitRule.' 'get_object') as get_object_mock: self.qos_plugin.get_policy_bandwidth_limit_rule( self.ctxt,", "payload=events.DBEventPayload( self.ctxt, desired_state=kwargs['port'], states=(kwargs['original_port'],))) if policy_id is None or policy_id", "mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.create_policy_bandwidth_limit_rule, self.ctxt, self.policy.id, self.rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_rule_check_rule_minbw_gr_than_bwlimit(self):", "def test_get_policy_min_pps_rules_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_minimum_packet_rate_rules, self.ctxt, self.policy.id)", "rule.direction = 'any' with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.assertRaises(NotImplementedError, self.qos_plugin._change_placement_allocation,", "with mock.patch('neutron.objects.qos.rule.get_rules', return_value=[self.rule]), mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.rule_data['bandwidth_limit_rule']['max_kbps'] = 1 self.qos_plugin.update_policy_bandwidth_limit_rule(", "in rule_actions.items(): mock_manager.reset_mock() method = getattr(self.qos_plugin, \"%s_policy_rule\" % action) method(*arguments)", "original_policy_id=None): port_id = uuidutils.generate_uuid() kwargs = { \"port\": { \"id\":", "'update_qos_allocation') as mock_update_qos_alloc: mock_update_qos_alloc.side_effect = ks_exc.Conflict( response={'errors': [{'code': 'placement.concurrent_update'}]} )", "{'id': uuidutils.generate_uuid(), 'max_kbps': 100, 'max_burst_kbps': 150}, 'dscp_marking_rule': {'id': uuidutils.generate_uuid(), 'dscp_mark':", "TestQosPluginDB.MIN_PPS_RP}) if desired_qos: desired_qos.rules = [] if desired_min_kbps: desired_qos.rules +=", "self.policy mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_policy_update, 'update') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() fields", "test__extend_port_resource_request_min_bw_non_provider_net(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION port = self._create_and_extend_port([self.min_bw_rule], physical_network=None) self.assertIsNone(port.get('resource_request')) def", "MIN_BW_RP = 'd7bea120-1626-11ec-9148-c32debfcf0f6' QOS_MIN_PPS_RULE_ID = '6ac5db7e-1626-11ec-8c7f-0b70dbb8a8eb' # uuid -v5 f02f160e-1612-11ec-b2b8-bf60ab98186c", "original_min_kbps=1000, desired_min_kbps=2000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: mock_update_qos_alloc.side_effect = ks_exc.Conflict(", "project_id=self.project_id, admin_state_up=True, status='DOWN', device_id='2', qos_policy_id=qos_policy_id, qos_network_policy_id=qos_network_policy_id, mac_address=mac, id=port_id) port.create() return", "10, 'direction': 'any'}, } self.policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) self.rule", "= uuidutils.generate_uuid() self.port_data = { 'port': {'id': uuidutils.generate_uuid(), 'network_id': network_id}", "neutron_lib.api.definitions import qos from neutron_lib.callbacks import events from neutron_lib import", "self._make_qos_policy() rule2_obj = self._make_qos_minbw_rule(qos2.id, min_kbps=1000) qos2.rules = [rule2_obj] orig_port =", "self.ctxt, self.rule.id, self.policy.id) get_object_mock.assert_called_once_with(self.ctxt, id=self.rule.id) def test_get_policy_minimum_bandwidth_rules_for_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy):", "self.assertEqual( 'fake_uuid', port['resource_request']['request_groups'][0]['id'] ) self.assertEqual( ['CUSTOM_VNIC_TYPE_NORMAL'], port['resource_request']['request_groups'][0]['required'] ) self.assertEqual( {orc.NET_PACKET_RATE_KILOPACKET_PER_SEC:", "test_delete_rule(self, delete_policy_rule_mock): calls = [] for rule_type, rule_object_class in self.rule_objects.items():", "= [bw_limit_rule2] orig_port = { 'binding:profile': {'allocation': { self.MIN_BW_REQUEST_GROUP_UUID: self.MIN_BW_RP}},", "port['resource_request']['request_groups'][0]['resources'], ) self.assertEqual( ['fake_uuid'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_min_bw_and_pps_rule(self): self.min_bw_rule.direction =", "mock.Mock() mock_manager.attach_mock(mock_qos_policy_update, 'update') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() fields = obj_utils.get_updatable_fields( policy_object.QosPolicy,", "mock_manager.mock_calls.index(rule_create_mock_call) < mock_manager.mock_calls.index(update_precommit_mock_call) < mock_manager.mock_calls.index(update_mock_call)) def test_create_policy_rule_check_rule_min_less_than_max(self): _policy = self._get_policy()", "= uuidutils.generate_uuid() tenant_policy = { 'policy': {'id': policy_id, 'project_id': project_id,", "self._make_qos_policy() port_qos_obj = self._make_qos_policy() net_qos_id = net_qos_obj.id if network_qos else", "fake_change_placement_allocation self.qos_plugin._check_network_for_placement_allocation_change( 'network', 'after_update', ml2plugin_mock, payload=events.DBEventPayload( self.context, states=(original_network, network))) self.assertEqual(ml2plugin_mock._make_port_dict.call_count,", "self.policy) self.assertEqual( len(expected_ports), len(policy_ports)) for port in expected_ports: self.assertIn(port, policy_ports)", "'neutron.objects.network.Network.get_object', return_value=net), \\ mock.patch.object( self.qos_plugin, '_get_ports_with_policy', return_value=[port]): try: self.qos_plugin.create_policy_minimum_bandwidth_rule( self.ctxt,", "to mock-out # methods that work with real data types", "= self._make_network(original_qos.id) network = self._make_network(qos.id) ml2plugin_mock = mock.MagicMock() def fake_make_port_dict(port):", "= {'create': [self.ctxt, rule_cls_mock, self.policy.id, {'fake_rule': {}}], 'update': [self.ctxt, rule_cls_mock,", "return_value=None): resource = '%s/alias-%s-rules' % (qos.ALIAS, rule_type.replace('_', '-')) request =", "expected_ports = ports + expected_network_ports with mock.patch( 'neutron.objects.ports.Port.get_objects', side_effect=[network_ports, ports]", "alloc_diff={self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': 1000}}) self._assert_pci_info(port) def test_change_placement_allocation_increase_min_pps(self): qos1 = self._make_qos_policy() qos2", "{'id': uuidutils.generate_uuid(), 'dscp_mark': 16}, 'minimum_bandwidth_rule': { 'id': uuidutils.generate_uuid(), 'min_kbps': 10},", "don't use real models as per mocks above. We also", "ports + expected_network_ports with mock.patch( 'neutron.objects.ports.Port.get_objects', side_effect=[network_ports, ports] ), mock.patch.object(", "driver_mock_call = mock.call.driver.call('update_policy', self.ctxt, mock.ANY) if rule_mock_call in mock_manager.mock_calls: action_index", "'ee', 'ff'] mac = netaddr.EUI(next(net_utils.random_mac_generator(base_mac))) device_owner = device_owner if device_owner", "def test_validate_create_port_callback_no_policy(self): self._test_validate_create_port_callback() def _prepare_for_port_placement_allocation_change(self, qos1, qos2, qos_network_policy=None): qos1_id =", "_prepare_for_port_placement_allocation_change(self, qos1, qos2, qos_network_policy=None): qos1_id = qos1.id if qos1 else", "def get_resources(self): return qos_rules_alias.Qos_rules_alias.get_resources() def get_actions(self): return [] def get_request_extensions(self):", "states=(original_port, port))) mock_alloc_change.assert_not_called() def test_check_port_for_placement_allocation_change(self): qos1_obj = self._make_qos_policy() qos2_obj =", "self.assertEqual( qos_consts.RULE_TYPE_BANDWIDTH_LIMIT, rule_type_details['type']) self.assertEqual( drivers_details, rule_type_details['drivers']) def test_get_rule_type_as_user(self): self.assertRaises( lib_exc.NotAuthorized,", "with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: mock_update_qos_alloc.side_effect = ( pl_exc.PlacementAllocationGenerationConflict( consumer=self.MIN_BW_RP))", "original_min_kbps=1000, desired_min_kbps=2000, original_min_kpps=500, desired_min_kpps=1000) for rule in qos2.rules: rule.direction =", "update_policy_rule_mock): calls = [] for rule_type, rule_object_class in self.rule_objects.items(): rule_id", "% (qos.ALIAS, rule_type.replace('_', '-')) request = self.new_update_request(resource, data, rule_id, self.fmt)", "return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_dscp_marking_rules, self.ctxt, self.policy.id) def test_get_policy_minimum_bandwidth_rule(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "self.pps_rule.direction } } with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises( qos_exc.QoSRulesConflict,", "= context.get_admin_context() self.policy_data = { 'policy': {'id': uuidutils.generate_uuid(), 'project_id': uuidutils.generate_uuid(),", "original_qos = self._make_qos_policy() qos = self._make_qos_policy() original_network = self._make_network(original_qos.id) network", "setattr(_policy, \"rules\", [min_pps_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.create_policy_minimum_packet_rate_rule,", "self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': 500}, self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': 1000}}) def test_change_placement_allocation_change_direction_min_pps_and_min_bw( self):", "self._prepare_port_for_placement_allocation( qos1, qos2, original_min_kbps=1000, desired_min_kbps=1000, original_min_kpps=1000, desired_min_kpps=1000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation')", "self._make_qos_policy() desired_qos = self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation( original_qos, desired_qos,", "= uuidutils.generate_uuid() self._test_validate_update_network_callback( policy_id=policy_id, original_policy_id=policy_id) def test_validate_update_network_callback_policy_removed(self): self._test_validate_update_network_callback( policy_id=None, original_policy_id=uuidutils.generate_uuid())", "mock.patch( 'neutron.objects.ports.Port.get_objects', side_effect=[network_ports, ports] ), mock.patch.object( self.policy, \"get_bound_networks\" ), mock.patch.object(", "self._test_validate_update_port_callback( policy_id=uuidutils.generate_uuid()) def test_validate_update_port_callback_policy_not_changed(self): policy_id = uuidutils.generate_uuid() self._test_validate_update_port_callback( policy_id=policy_id, original_policy_id=policy_id)", "self.qos_plugin.create_policy_packet_rate_limit_rule, self.ctxt, self.policy.id, self.rule_data) def test_update_policy_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises(", "= QoSRuleAliasMinimumPacketRateTestExtensionManager() super(TestQoSRuleAlias, self).setUp(plugin=plugin, ext_mgr=ext_mgr, service_plugins=service_plugins) self.qos_plugin = directory.get_plugin(plugins_constants.QOS) self.ctxt", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "'ml2' service_plugins = {'qos_plugin_name': SERVICE_PLUGIN_KLASS} ext_mgr = QoSRuleAliasMinimumPacketRateTestExtensionManager() super(TestQoSRuleAlias, self).setUp(plugin=plugin,", "rule_object.QosMinimumPacketRateRule( self.context, project_id=self.project_id, qos_policy_id=policy_id, direction=direction, min_kpps=min_kpps, id=rule_id) qos_rule.create() return qos_rule", "port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': -1000}}) def test_change_placement_allocation_equal_minkbps_and_minkpps(self): qos1 =", "calls.append(mock.call(mock.ANY, rule_object_class, rule_id, self.qos_policy_id)) get_policy_rule_mock.assert_has_calls(calls, any_order=True) @mock.patch.object(qos_plugin.QoSPlugin, \"delete_policy_rule\") def test_delete_rule(self,", "action_index = mock_manager.mock_calls.index( get_rule_mock_call) self.assertLess( action_index, mock_manager.mock_calls.index(driver_mock_call)) def test_create_policy_packet_rate_limit_rule(self): _policy", "), mock.patch.object( self.policy, \"get_bound_ports\" ): policy_ports = self.qos_plugin._get_ports_with_policy( self.ctxt, self.policy)", "def test_get_rule_type_as_user(self): self.assertRaises( lib_exc.NotAuthorized, self.qos_plugin.get_rule_type, self.ctxt, qos_consts.RULE_TYPE_BANDWIDTH_LIMIT) def test_get_rule_types(self): filters", "'any'}, } self.policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) self.rule = rule_object.QosBandwidthLimitRule(", "self.qos_plugin.create_policy_minimum_packet_rate_rule( self.ctxt, _policy.id, self.rule_data) except NotImplementedError: self.fail() def test_create_policy_rule_check_rule_min_pps_direction_conflict(self): _policy", "setattr(_policy, \"rules\", [self.rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.update_policy_bandwidth_limit_rule( self.ctxt, self.rule.id, self.policy.id,", "return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_minimum_packet_rate_rules, self.ctxt, self.policy.id) def test_get_min_pps_rule_type(self): admin_ctxt =", "% rule_type data = self.rule_data[rule_data_name] rule = rule_object_class(self.ctxt, id=rule_id, qos_policy_id=self.qos_policy_id,", "self._get_policy() setattr(_policy, \"rules\", [self.min_pps_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.create_policy_minimum_packet_rate_rule( self.ctxt, self.policy.id,", "qos_policy, port) else: mock_validate_policy.assert_not_called() def test_validate_create_port_callback_policy_on_port(self): self._test_validate_create_port_callback(port_qos=True) def test_validate_create_port_callback_policy_on_port_and_network(self): self._test_validate_create_port_callback(port_qos=True,", "manager from neutron.objects import network as network_object from neutron.objects import", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.update_policy_minimum_bandwidth_rule( self.ctxt, self.min_bw_rule.id, self.policy.id, self.rule_data) self.mock_qos_load_attr.assert_called_once_with('rules') self._validate_driver_params('update_policy',", "self.qos_plugin.get_policy_minimum_bandwidth_rules, self.ctxt, self.policy.id) def test_create_policy_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound,", "under the License. import copy from unittest import mock from", "self.qos_plugin.delete_policy(self.ctxt, self.policy.id) self._validate_driver_params('delete_policy', self.ctxt) policy_delete_mock_call = mock.call.delete() delete_precommit_mock_call = mock.call.driver.call(", "filters=filters) self.assertEqual(sorted(qos_consts.VALID_RULE_TYPES), sorted(type_['type'] for type_ in types)) @mock.patch('neutron.objects.ports.Port') @mock.patch('neutron.objects.qos.policy.QosPolicy') def", "setattr(_policy, \"rules\", [self.min_bw_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.qos_plugin.create_policy_bandwidth_limit_rule( self.ctxt,", "_pager=mock.ANY, qos_policy_id=self.policy.id, filter='filter_id') def test_get_policy_minimum_bandwidth_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound,", "self._prepare_port_for_placement_allocation( qos1, qos2, original_min_kpps=1000, desired_min_kpps=1000) for rule in qos2.rules: rule.direction", "def test_get_pps_rule_type(self): admin_ctxt = context.get_admin_context() drivers_details = [{ 'name': 'fake-driver',", "super(TestQosPlugin, self).setUp() self.setup_coreplugin(load_plugins=False) mock.patch('neutron.objects.db.api.create_object').start() mock.patch('neutron.objects.db.api.update_object').start() mock.patch('neutron.objects.db.api.delete_object').start() mock.patch('neutron.objects.db.api.get_object').start() _mock_qos_load_attr = mock.patch(", "test_update_policy_min_pps_rule(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.min_pps_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy):", "payload=events.DBEventPayload( context, states=(original_port, port))) mock_alloc_change.assert_called_once_with( qos1_obj, None, kwargs['original_port'], port) def", "= [port_mock_with_own_policy, port_mock_without_own_policy] policy_mock = mock.MagicMock(id=policy_id) admin_ctxt = mock.Mock() with", "\"port_id\": uuidutils.generate_uuid(), \"qos_id\": self.policy.id, \"network_id\": network_id, \"vnic_type\": \"normal\", } },", "] ports = [ mock.MagicMock(qos_policy_id=self.policy.id), ] expected_network_ports = [ port", "self.qos_plugin.create_policy_bandwidth_limit_rule( self.ctxt, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) rule_create_mock_call = mock.call.create() update_precommit_mock_call", "id=uuidutils.generate_uuid(), network_id=uuidutils.generate_uuid(), device_owner='') with mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy), \\ mock.patch( 'neutron.objects.network.Network.get_object',", "self.assertEqual( ['fake_uuid'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_bulk_min_pps_rule(self): ports = self._create_and_extend_ports([], [self.min_pps_rule])", "self.assertEqual( ['fake_uuid'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_bulk_min_bw_and_pps_rule(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION self.min_pps_rule.direction", "qos_consts.RULE_TYPE_BANDWIDTH_LIMIT) def test_get_rule_types(self): filters = {'type': 'type_id'} with mock.patch.object(qos_plugin.QoSPlugin, 'supported_rule_types',", "net_qos_obj if qos_policy: mock_validate_policy.assert_called_once_with( self.context, qos_policy, network.id) else: mock_validate_policy.assert_not_called() def", "with real data types mock.patch( 'neutron.objects.base.NeutronDbObject.modify_fields_from_db' ).start() mock.patch.object(policy_object.QosPolicy, 'unset_default').start() mock.patch.object(policy_object.QosPolicy,", "\"delete_policy_rule\") def test_delete_rule(self, delete_policy_rule_mock): calls = [] for rule_type, rule_object_class", "self.ctxt, id=uuidutils.generate_uuid(), network_id=uuidutils.generate_uuid(), device_owner='compute:fake-zone') with mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy), \\ mock.patch(", "= uuidutils.generate_uuid() self.rule_data = { 'bandwidth_limit_rule': {'max_kbps': 100, 'max_burst_kbps': 150},", "= self.rule_data[rule_data_name] rule = rule_object_class(self.ctxt, id=rule_id, qos_policy_id=self.qos_policy_id, **data) with mock.patch(", "port_id=None, qos_network_policy_id=None, device_owner=None): port_id = port_id if port_id else uuidutils.generate_uuid()", "NotImplementedError, self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt, _policy.id, self.rule_data) def test_create_min_pps_rule_on_unbound_port(self): _policy = self._get_policy()", "self.ctxt, self.policy.id, filters=filters) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id, filter='filter_id') def test_get_policy_for_nonexistent_policy(self):", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", [self.dscp_rule]) self.qos_plugin.delete_policy_dscp_marking_rule( self.ctxt, self.dscp_rule.id, self.policy.id)", "mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_not_called() def", "return [] def get_request_extensions(self): return [] class TestQoSRuleAlias(test_db_base_plugin_v2.NeutronDbPluginV2TestCase): def setUp(self):", "self.ctxt, mock.ANY) update_mock_call = mock.call.driver.call( 'update_policy', self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(rule_create_mock_call)", "[self.min_pps_rule]) for port in ports: self.assertEqual( 1, len(port['resource_request']['request_groups']) ) self.assertEqual(", "policy_object.QosPolicy, self.policy_data['policy']) self.qos_plugin.update_policy( self.ctxt, self.policy.id, {'policy': fields}) self._validate_driver_params('update_policy', self.ctxt) policy_update_mock_call", "[{ 'name': 'fake-driver', 'supported_parameters': [{ 'parameter_name': 'max_kbps', 'parameter_type': lib_constants.VALUES_TYPE_RANGE, 'parameter_range':", "qos2=None) context = kwargs['context'] original_port = kwargs['original_port'] port = kwargs['port']", "'0000:42:41.0', 'pci_vendor_info': '8086:107ed', 'physical_network': 'sriov_phy' } binding_prof.update({'allocation': allocation}) orig_port.update( {'binding:profile':", "License for the specific language governing permissions and limitations #", "self.fail() def test_create_policy_rule_check_rule_min_pps_direction_conflict(self): _policy = self._get_policy() self.rule_data['minimum_packet_rate_rule']['direction'] = 'any' setattr(_policy,", "policy_id = uuidutils.generate_uuid() self._test_validate_update_network_callback( policy_id=policy_id, original_policy_id=policy_id) def test_validate_update_network_callback_policy_removed(self): self._test_validate_update_network_callback( policy_id=None,", "{ 'policy': {'id': policy_id, 'project_id': project_id, 'tenant_id': project_id, 'name': 'test-policy',", "consumer_uuid='uu:id', alloc_diff={ self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': -1000}, self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': -2000}}) def", "admin_ctxt = context.get_admin_context() drivers_details = [{ 'name': 'fake-driver', 'supported_parameters': [{", "mock from keystoneauth1 import exceptions as ks_exc import netaddr from", "= [rule1_obj] qos2 = self._make_qos_policy() rule2_obj = self._make_qos_minbw_rule(qos2.id, min_kbps=1000) qos2.rules", "= rule_object.QosDscpMarkingRule(dscp_mark=16) qos2.rules = [bw_limit_rule] orig_port, port = self._prepare_port_for_placement_allocation(qos1, original_min_kbps=1000)", "\"get_bound_ports\" ): policy_ports = self.qos_plugin._get_ports_with_policy( self.ctxt, self.policy) self.assertEqual( len(expected_ports), len(policy_ports))", "self._test_validate_update_port_callback( policy_id=None, original_policy_id=uuidutils.generate_uuid()) def _test_validate_update_network_callback(self, policy_id=None, original_policy_id=None): network_id = uuidutils.generate_uuid()", "{ 'max_kbps': 5000, 'direction': self.rule.direction } } with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy)", "self.rule_data) self._validate_driver_params('update_policy', self.ctxt) rule_create_mock_call = mock.call.create() update_precommit_mock_call = mock.call.driver.call( 'update_policy_precommit',", "= self._make_network(original_qos.id) network = self._make_network(qos.id) # Port which is not", "\"test_plugin\", payload=events.DBEventPayload( self.ctxt, desired_state=kwargs['port'], states=(kwargs['original_port'],))) if policy_id is None or", "'id': 'fake_uuid0', 'required': ['CUSTOM_PHYSNET_PUBLIC', 'CUSTOM_VNIC_TYPE_NORMAL'], 'resources': { orc.NET_BW_EGR_KILOBIT_PER_SEC: 10, orc.NET_BW_IGR_KILOBIT_PER_SEC:", "port1.id, 'device_owner': 'compute:uu:id', 'qos_policy_id': None, 'qos_network_policy_id': None}, mock.ANY), ] mock_alloc_change.assert_has_calls(mock_alloc_change_calls,", "mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_update_conflict(self): qos1", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "policy_ports = self.qos_plugin._get_ports_with_policy( self.ctxt, self.policy) self.assertEqual( len(expected_ports), len(policy_ports)) for port", "update_mock_call = mock.call.driver.call( 'update_policy', self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(policy_update_mock_call) < mock_manager.mock_calls.index(update_precommit_mock_call)", "[\"qos\"]) manager.init() self.qos_plugin = directory.get_plugin(plugins_constants.QOS) self.qos_plugin.driver_manager = mock.Mock() self.rpc_push =", "_policy = self._get_policy() setattr(_policy, \"rules\", [self.min_bw_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as", "self.rule.id, _policy.id) def test_get_policy_bandwidth_limit_rule(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosBandwidthLimitRule.'", "self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def test_create_policy_pps_rule_duplicates(self): _policy = self._get_policy() setattr(_policy,", "rule_id else uuidutils.generate_uuid() qos_rule = rule_object.QosMinimumBandwidthRule( self.context, project_id=self.project_id, qos_policy_id=policy_id, direction=direction,", "def test_validate_create_port_callback_policy_on_port_and_network(self): self._test_validate_create_port_callback(port_qos=True, network_qos=True) def test_validate_create_port_callback_policy_on_network(self): self._test_validate_create_port_callback(network_qos=True) def test_validate_create_port_callback_no_policy(self): self._test_validate_create_port_callback()", "mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': 1000}}) self._assert_pci_info(port) def test_change_placement_allocation_increase_min_pps_and_min_bw(self): qos1", "from neutron_lib.exceptions import qos as qos_exc from neutron_lib.objects import utils", "'is_default': False}} self.rule_data = { 'bandwidth_limit_rule': {'id': uuidutils.generate_uuid(), 'max_kbps': 100,", "as mock_qos_get_obj: self.assertRaises( qos_exc.QoSRulesConflict, self.qos_plugin.create_policy_packet_rate_limit_rule, self.ctxt, _policy.id, new_rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id)", "qos_rule def _make_qos_minpps_rule(self, policy_id, direction='ingress', min_kpps=1000, rule_id=None): rule_id = rule_id", "def test_get_rule_types(self): filters = {'type': 'type_id'} with mock.patch.object(qos_plugin.QoSPlugin, 'supported_rule_types', return_value=qos_consts.VALID_RULE_TYPES):", "qos1.rules = [bw_limit_rule] with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(qos1, qos2,", "qos2, orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_new_rule_not_min_bw(self): qos1 = self._make_qos_policy() qos2", "'before_update', 'test_plugin', payload=events.DBEventPayload( context, states=(original_port, port))) mock_alloc_change.assert_called_once_with( qos_network, desired_qos, kwargs['original_port'],", "= self._create_and_extend_port([], [self.min_pps_rule]) self.assertEqual( 1, len(port['resource_request']['request_groups']) ) self.assertEqual( 'fake_uuid', port['resource_request']['request_groups'][0]['id']", "rule as rule_object from neutron.services.qos import qos_plugin from neutron.tests.unit.db import", "mock.call.driver.call( 'update_policy', self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(policy_update_mock_call) < mock_manager.mock_calls.index(update_precommit_mock_call) < mock_manager.mock_calls.index(update_mock_call))", "rule_id=None): rule_id = rule_id if rule_id else uuidutils.generate_uuid() qos_rule =", "mock.patch.object( qos_plugin.QoSPlugin, \"supported_rule_type_details\", return_value=drivers_details ): rule_type_details = self.qos_plugin.get_rule_type( admin_ctxt, qos_consts.RULE_TYPE_PACKET_RATE_LIMIT)", "qos_policy.create() return qos_policy def _make_qos_minbw_rule(self, policy_id, direction='ingress', min_kbps=1000, rule_id=None): rule_id", "above. We also need to mock-out # methods that work", "import mock from keystoneauth1 import exceptions as ks_exc import netaddr", "= self._create_and_extend_port([self.min_bw_rule], has_net_qos_policy=True) self.assertEqual( 1, len(port['resource_request']['request_groups']) ) self.assertEqual( 'fake_uuid', port['resource_request']['request_groups'][0]['id']", "self.ctxt, self.policy.id) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id) def test_get_policy_min_pps_rules_for_policy_with_filters(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( original_qos, desired_qos, orig_port, port)", "self.qos_plugin, 'create_policy_bandwidth_limit_rules') def test_get_rule_type(self): admin_ctxt = context.get_admin_context() drivers_details = [{", "qos_policy: mock_validate_policy.assert_called_once_with( self.context, qos_policy, network.id) else: mock_validate_policy.assert_not_called() def test_validate_create_network_callback(self): self._test_validate_create_network_callback(network_qos=True)", "orig_port, port = self._prepare_port_for_placement_allocation( original_qos, desired_qos, original_min_kpps=2000, desired_min_kpps=1000, is_sriov=True) with", "mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=policy_mock ) as get_policy, mock.patch.object( self.qos_plugin, \"validate_policy_for_port\" )", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosDscpMarkingRule.' 'get_objects') as get_objects_mock: self.qos_plugin.get_policy_dscp_marking_rules(", "test_create_min_bw_rule_on_unbound_port(self): policy = self._get_policy() policy.rules = [self.min_bw_rule] segment = network_object.NetworkSegment(", "get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id, filter='filter_id') def test_get_policy_minimum_bandwidth_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None):", "profile={}) port2_binding.create() port2.bindings = [port2_binding] port2.update() with mock.patch.object( self.qos_plugin, '_change_placement_allocation')", "qos1_obj = self._make_qos_policy() kwargs = self._prepare_for_port_placement_allocation_change( qos1=qos1_obj, qos2=qos1_obj) context =", "qos1, qos2, desired_min_kbps=2000) qos1.rules = [bw_limit_rule] with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as", "[self.pps_rule]) self.qos_plugin.update_policy_packet_rate_limit_rule( self.ctxt, self.pps_rule.id, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def test_update_policy_pps_rule_bad_policy(self):", "device_owner else '3' port = ports_object.Port( self.context, network_id=network_id, device_owner=device_owner, project_id=self.project_id,", "self.policy.id self.port = ports_object.Port( self.ctxt, **self.port_data['port']) port_res = {\"binding:vnic_type\": \"normal\"}", "{TestQosPluginDB.MIN_BW_REQUEST_GROUP_UUID: TestQosPluginDB.MIN_BW_RP}) if original_min_kpps: qos.rules += [self._make_qos_minpps_rule( qos.id, min_kpps=original_min_kpps, rule_id=TestQosPluginDB.QOS_MIN_PPS_RULE_ID)]", "test_update_policy_rule(self, mock_qos_rule_update): mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_rule_update, 'update') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock()", "as get_objects_mock: filters = {'filter': 'filter_id'} self.qos_plugin.get_policy_bandwidth_limit_rules( self.ctxt, self.policy.id, filters=filters)", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_packet_rate_limit_rules, self.ctxt, self.policy.id) def test_create_policy_pps_rule_for_nonexistent_policy(self):", "mock.patch.object( self.qos_plugin, \"validate_policy_for_ports\" ) as validate_policy_for_ports, mock.patch.object( self.ctxt, \"elevated\", return_value=admin_ctxt", "self._make_qos_policy() original_network = self._make_network(original_qos.id) network = self._make_network(qos.id) # Port which", "qos_consts from neutron_lib.utils import net as net_utils import os_resource_classes as", "== original_policy_id: get_policy.assert_not_called() validate_policy_for_network.assert_not_called() get_ports.assert_not_called() validate_policy_for_ports.assert_not_called() else: get_policy.assert_called_once_with(admin_ctxt, id=policy_id) get_ports.assert_called_once_with(self.ctxt,", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises( qos_exc.QoSRulesConflict, self.qos_plugin.create_policy_packet_rate_limit_rule, self.ctxt, _policy.id, new_rule_data)", "'id': '9416c220-160a-11ec-ba3d-474633eb825c', } port = {} with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as", "mock.Mock() mock_manager.attach_mock(mock_qos_rule_update, 'update') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() _policy = policy_object.QosPolicy( self.ctxt,", "self.ctxt, **min_pps_rule_ingress_data) ports = self._create_and_extend_ports( [self.min_bw_rule, min_bw_rule_ingress], [self.min_pps_rule, min_pps_rule_ingress], request_groups_uuids=request_groups_uuids)", "self.policy.id elif has_net_qos_policy: self.port_data['port']['qos_network_policy_id'] = self.policy.id self.port = ports_object.Port( self.ctxt,", "def test__extend_port_resource_request_no_qos_policy(self): port = self._create_and_extend_port([], physical_network='public', has_qos_policy=False) self.assertIsNone(port.get('resource_request')) def test__extend_port_resource_request_min_bw_inherited_policy(", "permissions and limitations # under the License. import copy from", "network} with mock.patch.object(self.qos_plugin, 'validate_policy_for_network') \\ as mock_validate_policy: self.qos_plugin._validate_create_network_callback( \"NETWORK\", \"precommit_create\",", "self.ctxt) rule_update_mock_call = mock.call.update() update_precommit_mock_call = mock.call.driver.call( 'update_policy_precommit', self.ctxt, mock.ANY)", "self.qos_plugin.get_rule_type( admin_ctxt, qos_consts.RULE_TYPE_BANDWIDTH_LIMIT) self.assertEqual( qos_consts.RULE_TYPE_BANDWIDTH_LIMIT, rule_type_details['type']) self.assertEqual( drivers_details, rule_type_details['drivers']) def", "'neutron.objects.base.NeutronDbObject.modify_fields_from_db' ).start() mock.patch.object(policy_object.QosPolicy, 'unset_default').start() mock.patch.object(policy_object.QosPolicy, 'set_default').start() cfg.CONF.set_override(\"core_plugin\", DB_PLUGIN_KLASS) cfg.CONF.set_override(\"service_plugins\", [\"qos\"])", "mock_manager.attach_mock(mock_qos_policy_delete, 'delete') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() self.qos_plugin.delete_policy(self.ctxt, self.policy.id) self._validate_driver_params('delete_policy', self.ctxt) policy_delete_mock_call", "return [] class TestQoSRuleAlias(test_db_base_plugin_v2.NeutronDbPluginV2TestCase): def setUp(self): # Remove MissingAuthPlugin exception", "return_value=rule ), mock.patch.object(self.qos_plugin, 'get_policy_rule', return_value=rule.to_dict()): self._delete_rule(rule_type, rule_id) calls.append(mock.call(mock.ANY, rule_object_class, rule_id,", "test_validate_create_network_callback(self): self._test_validate_create_network_callback(network_qos=True) def test_validate_create_network_callback_no_qos(self): self._test_validate_create_network_callback(network_qos=False) def _test_validate_create_port_callback(self, port_qos=False, network_qos=False): net_qos_obj", "return {\"context\": self.context, \"original_port\": { \"id\": port.id, \"device_owner\": \"compute:uu:id\", \"qos_policy_id\":", "kwargs = self._prepare_for_port_placement_allocation_change( qos1=qos1_obj, qos2=qos2_obj) context = kwargs['context'] original_port =", "= 1000 with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.assertRaises( qos_exc.QoSRuleParameterConflict, self.qos_plugin.update_policy_minimum_bandwidth_rule, self.ctxt, self.min_bw_rule.id,", "'minimum_packet_rate_rule': { 'id': uuidutils.generate_uuid(), 'min_kpps': 10, 'direction': 'ingress' } },", "mock.patch.object( self.qos_plugin.driver_manager, \"validate_rule_for_port\", return_value=True ): self.policy.rules = [self.rule] try: self.qos_plugin.validate_policy_for_port(", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_dscp_marking_rules, self.ctxt, self.policy.id) def test_get_policy_minimum_bandwidth_rule(self): with", "self.deserialize(self.fmt, res) def _show_rule(self, rule_type, rule_id): resource = '%s/alias-%s-rules' %", "compute bound self._make_port(network_id=network.id, qos_policy_id=None, device_owner='uu:id') # Port with overwritten QoS", "self.ctxt, _policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) self.mock_qos_load_attr.assert_called_once_with('rules') mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_rule_check_rule_bwlimit_less_than_minbw(self):", "qos1=qos1_obj, qos2=qos2_obj) context = kwargs['context'] original_port = kwargs['original_port'] port =", "test_create_policy_rule_duplicates(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.rule]) new_rule_data = {", "expected_network_ports with mock.patch( 'neutron.objects.ports.Port.get_objects', side_effect=[network_ports, ports] ), mock.patch.object( self.policy, \"get_bound_networks\"", "qos2 = self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation( qos1, qos2, desired_min_kbps=1000,", "_make_qos_minpps_rule(self, policy_id, direction='ingress', min_kpps=1000, rule_id=None): rule_id = rule_id if rule_id", "'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos_network, desired_qos, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id',", "qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': -1000}}) def", "= self._create_and_extend_ports( [self.min_bw_rule, min_bw_rule_ingress], [self.min_pps_rule, min_pps_rule_ingress], request_groups_uuids=request_groups_uuids) for port in", "port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_min_bw_and_pps_rule(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION self.min_pps_rule.direction = lib_constants.EGRESS_DIRECTION", "original_qos, desired_qos, qos_network_policy=qos_network_policy) orig_port = kwargs['original_port'] qos = original_qos or", "port) def test_change_placement_allocation_update_generation_conflict(self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() orig_port,", ") def test__extend_port_resource_request_no_qos_policy(self): port = self._create_and_extend_port([], physical_network='public', has_qos_policy=False) self.assertIsNone(port.get('resource_request')) def", "\"rules\", [self.rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.update_policy_bandwidth_limit_rule( self.ctxt, self.rule.id, self.policy.id, self.rule_data)", "rules_data: rules = [ rule_object.QosMinimumPacketRateRule( self.ctxt, **rules_data[0]['minimum_packet_rate_rule']), rule_object.QosMinimumPacketRateRule( self.ctxt, **rules_data[1]['minimum_packet_rate_rule']),", "rule in qos2.rules: rule.direction = 'egress' with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as", "mock.call.QosPolicy().create() create_precommit_mock_call = mock.call.driver.call( 'create_policy_precommit', self.ctxt, mock.ANY) create_mock_call = mock.call.driver.call(", "qos.id}, mock.ANY), mock.call( original_qos, qos, {'id': port2.id, 'device_owner': 'compute:uu:id', 'qos_policy_id':", "self._prepare_port_for_placement_allocation(qos1, original_min_kbps=1000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1, qos2,", "-1000}}) def test_change_placement_allocation_equal_minkbps_and_minkpps(self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() orig_port,", "keystoneauth1 import exceptions as ks_exc import netaddr from neutron_lib.api.definitions import", "mock.patch.object( qos_plugin.QoSPlugin, \"supported_rule_type_details\", return_value=drivers_details ): rule_type_details = self.qos_plugin.get_rule_type( admin_ctxt, qos_consts.RULE_TYPE_MINIMUM_PACKET_RATE)", "= { 'minimum_packet_rate_rule': { 'id': uuidutils.generate_uuid(), 'min_kpps': 1234, 'direction': self.min_pps_rule.direction,", "'parameter_name': 'min_kpps', 'parameter_type': lib_constants.VALUES_TYPE_RANGE, 'parameter_range': {'start': 0, 'end': 100} }]", "None, orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_old_rule_not_min_bw(self): qos1 = self._make_qos_policy() qos2", "return_value=_policy), \\ mock.patch( 'neutron.objects.network.Network.get_object', return_value=net), \\ mock.patch.object( self.qos_plugin, '_get_ports_with_policy', return_value=[port]):", "self.qos_plugin.delete_policy_dscp_marking_rule( self.ctxt, self.dscp_rule.id, self.policy.id) self._validate_driver_params('update_policy', self.ctxt) def test_get_policy_dscp_marking_rules(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "ext_mgr = QoSRuleAliasTestExtensionManager() super(TestQoSRuleAlias, self).setUp(plugin=plugin, ext_mgr=ext_mgr, service_plugins=service_plugins) self.qos_plugin = directory.get_plugin(plugins_constants.QOS)", "return qos_rules_alias.Qos_rules_alias.get_resources() def get_actions(self): return [] def get_request_extensions(self): return []", "mock.patch( 'neutron.objects.qos.qos_policy_validator' '.check_min_pps_rule_conflict', return_value=None): self.qos_plugin.create_policy_bandwidth_limit_rule( self.ctxt, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt)", "'get_objects') as get_objects_mock: filters = {'filter': 'filter_id'} self.qos_plugin.get_policy_packet_rate_limit_rules( self.ctxt, self.policy.id,", "self.ctxt, _policy.id, new_rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_min_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None):", "'NET_BW_EGR_KILOBIT_PER_SEC': 2000}}) def test_change_placement_allocation_change_dir_min_pps_ingress_to_any( self): qos1 = self._make_qos_policy() qos2 =", "None, desired_qos, qos_network_policy=qos_network, original_min_kbps=1000, desired_min_kbps=2000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc:", "self.qos_plugin, \"validate_policy_for_ports\" ) as validate_policy_for_ports, mock.patch.object( self.ctxt, \"elevated\", return_value=admin_ctxt ):", "the # License for the specific language governing permissions and", "def test_validate_update_network_callback_policy_changed(self): self._test_validate_update_network_callback( policy_id=uuidutils.generate_uuid()) def test_validate_update_network_callback_policy_not_changed(self): policy_id = uuidutils.generate_uuid() self._test_validate_update_network_callback(", "= {'filter': 'filter_id'} self.qos_plugin.get_policy_dscp_marking_rules( self.ctxt, self.policy.id, filters=filters) get_objects_mock.assert_called_once_with( self.ctxt, qos_policy_id=self.policy.id,", "= {\"context\": self.context, \"port\": {\"id\": port.id}} with mock.patch.object(self.qos_plugin, 'validate_policy_for_port') \\", "desired_min_kbps=2000) qos1.rules = [bw_limit_rule] with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(qos1,", "get_object_mock.assert_called_once_with( self.ctxt, id=self.min_pps_rule.id) def test_get_policy_min_pps_rules_for_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.'", "original_policy_id=uuidutils.generate_uuid()) def _test_validate_update_network_callback(self, policy_id=None, original_policy_id=None): network_id = uuidutils.generate_uuid() kwargs =", "mock.patch('neutron.objects.qos.rule.QosRule.get_object', return_value=rule): self._show_rule(rule_type, rule_id) calls.append(mock.call(mock.ANY, rule_object_class, rule_id, self.qos_policy_id)) get_policy_rule_mock.assert_has_calls(calls, any_order=True)", "device_owner='compute:uu:id') port1_binding = ports_object.PortBinding( self.context, port_id=port1.id, host='fake_host1', vnic_type='fake_vnic_type', vif_type='fake_vif_type', profile={'allocation':", "mock_manager.attach_mock(mock_qos_rule_create, 'create') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() with mock.patch('neutron.objects.qos.qos_policy_validator' '.check_bandwidth_rule_conflict', return_value=None), \\", "drivers_details = [{ 'name': 'fake-driver', 'supported_parameters': [{ 'parameter_name': 'max_kbps', 'parameter_type':", "= mock.patch( 'neutron.objects.qos.policy.QosPolicy.obj_load_attr') self.mock_qos_load_attr = _mock_qos_load_attr.start() # We don't use", "mock.patch( 'neutron.objects.qos.rule.QosRule.get_object', return_value=rule ), mock.patch.object(self.qos_plugin, 'get_policy_rule', return_value=rule.to_dict()): self._delete_rule(rule_type, rule_id) calls.append(mock.call(mock.ANY,", "'direction': 'any'} } class TestQosPluginDB(base.BaseQosTestCase): PORT_ID = 'f02f160e-1612-11ec-b2b8-bf60ab98186c' QOS_MIN_BW_RULE_ID =", "mock.ANY) self.assertTrue( mock_manager.mock_calls.index(rule_update_mock_call) < mock_manager.mock_calls.index(update_precommit_mock_call) < mock_manager.mock_calls.index(update_mock_call)) def test_update_policy_rule_check_rule_min_less_than_max(self): _policy", "@mock.patch.object(rule_object.QosBandwidthLimitRule, 'create') def test_create_policy_rule(self, mock_qos_rule_create, mock_qos_policy_get): _policy = copy.copy(self.policy) setattr(_policy,", "self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.update_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, self.policy.id, self.rule_data) @mock.patch.object(rule_object.QosBandwidthLimitRule, 'delete') def", "mock.MagicMock(qos_policy_id=None) ] ports = [ mock.MagicMock(qos_policy_id=self.policy.id), ] expected_network_ports = [", "delete_policy_rule_mock): calls = [] for rule_type, rule_object_class in self.rule_objects.items(): rule_id", "ks_exc import netaddr from neutron_lib.api.definitions import qos from neutron_lib.callbacks import", "def test_add_policy_with_extra_tenant_keyword(self, *mocks): policy_id = uuidutils.generate_uuid() project_id = uuidutils.generate_uuid() tenant_policy", "rule_type_details['type']) self.assertEqual( drivers_details, rule_type_details['drivers']) def test_get_pps_rule_type_as_user(self): self.assertRaises( lib_exc.NotAuthorized, self.qos_plugin.get_rule_type, self.ctxt,", "as get_objects_mock: self.qos_plugin.get_policy_packet_rate_limit_rules( self.ctxt, self.policy.id) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id) def", "mock_validate_policy.assert_not_called() def test_validate_create_port_callback_policy_on_port(self): self._test_validate_create_port_callback(port_qos=True) def test_validate_create_port_callback_policy_on_port_and_network(self): self._test_validate_create_port_callback(port_qos=True, network_qos=True) def test_validate_create_port_callback_policy_on_network(self):", "qos1_id, \"qos_network_policy_id\": qos_network_policy_id}, \"port\": {\"id\": port.id, \"qos_policy_id\": qos2_id}} def test_check_port_for_placement_allocation_change_no_qos_change(self):", "from neutron.objects.qos import policy as policy_object from neutron.objects.qos import rule", "self.min_pps_rule.id, self.policy.id) self._validate_driver_params('update_policy', self.ctxt) def test_delete_policy_min_pps_rule_bad_policy(self): _policy = self._get_policy() setattr(_policy,", "def test_get_policy_bandwidth_limit_rules_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_bandwidth_limit_rules, self.ctxt, self.policy.id)", "policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", [self.rule]) self.qos_plugin.delete_policy_bandwidth_limit_rule(", "def test_get_policy_bandwidth_limit_rule(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosBandwidthLimitRule.' 'get_object') as", "self.min_pps_rule = rule_object.QosMinimumPacketRateRule( self.ctxt, **self.rule_data['minimum_packet_rate_rule']) def _validate_driver_params(self, method_name, ctxt): call_args", "self.assertEqual( len(expected_ports), len(policy_ports)) for port in expected_ports: self.assertIn(port, policy_ports) def", "policy_id = uuidutils.generate_uuid() project_id = uuidutils.generate_uuid() tenant_policy = { 'policy':", "'test-policy', 'description': 'Test policy description', 'shared': True, 'is_default': False}} self.rule_data", "self.assertEqual(call_args[0], method_name) self.assertEqual(call_args[1], ctxt) self.assertIsInstance(call_args[2], policy_object.QosPolicy) def _create_and_extend_port(self, min_bw_rules, min_pps_rules=None,", "test_show_rule(self, get_policy_rule_mock): calls = [] for rule_type, rule_object_class in self.rule_objects.items():", "states=(original_port, port))) mock_alloc_change.assert_not_called() def test_check_port_for_placement_allocation_change_qos_network_policy( self): qos_network = self._make_qos_policy() desired_qos", "host='fake_host1', vnic_type='fake_vnic_type', vif_type='fake_vif_type', profile={'allocation': 'fake_allocation'}) port1_binding.create() port1.bindings = [port1_binding] port1.update()", "_prepare_port_for_placement_allocation(self, original_qos, desired_qos=None, qos_network_policy=None, original_min_kbps=None, desired_min_kbps=None, original_min_kpps=None, desired_min_kpps=None, is_sriov=False): kwargs", "self.context, states=(original_network, network))) self.assertEqual(ml2plugin_mock._make_port_dict.call_count, 2) mock_alloc_change_calls = [ mock.call( original_qos,", "'description': 'Test policy description', 'shared': True, 'is_default': False}} self.rule_data =", "netaddr from neutron_lib.api.definitions import qos from neutron_lib.callbacks import events from", "id=rule_id, qos_policy_id=self.qos_policy_id, **data) with mock.patch('neutron.objects.qos.rule.QosRule.get_object', return_value=rule): self._show_rule(rule_type, rule_id) calls.append(mock.call(mock.ANY, rule_object_class,", "port.create() return port def _make_network(self, qos_policy_id=None): network = network_object.Network(self.context, qos_policy_id=qos_policy_id)", "'id': uuidutils.generate_uuid(), 'min_kbps': 20, 'direction': lib_constants.INGRESS_DIRECTION} min_pps_rule_ingress_data = { 'id':", "'id': uuidutils.generate_uuid(), 'max_kpps': 20, 'max_burst_kpps': 130}, 'minimum_packet_rate_rule': { 'id': uuidutils.generate_uuid(),", "{'id': uuidutils.generate_uuid()} with mock.patch.object( self.qos_plugin.driver_manager, \"validate_rule_for_port\", return_value=False ): self.policy.rules =", "return_value=admin_ctxt ): self.qos_plugin._validate_update_port_callback( \"PORT\", \"precommit_update\", \"test_plugin\", payload=events.DBEventPayload( self.ctxt, desired_state=kwargs['port'], states=(kwargs['original_port'],)))", "oslo_utils import uuidutils import webob.exc from neutron.exceptions import qos as", "is_default=False) qos_policy.create() return qos_policy def _make_qos_minbw_rule(self, policy_id, direction='ingress', min_kbps=1000, rule_id=None):", "lib_constants from neutron_lib import context from neutron_lib import exceptions as", "qos1_id = qos1.id if qos1 else None qos2_id = qos2.id", "admin_ctxt, qos_consts.RULE_TYPE_PACKET_RATE_LIMIT) self.assertEqual( qos_consts.RULE_TYPE_PACKET_RATE_LIMIT, rule_type_details['type']) self.assertEqual( drivers_details, rule_type_details['drivers']) def test_get_pps_rule_type_as_user(self):", "'description': 'Test policy description', 'shared': True, 'is_default': False} with mock.patch('neutron.objects.qos.policy.QosPolicy')", "'QosPacketRateLimitRule.' 'get_object') as get_object_mock: self.qos_plugin.get_policy_packet_rate_limit_rule( self.ctxt, self.pps_rule.id, self.policy.id) get_object_mock.assert_called_once_with(self.ctxt, id=self.pps_rule.id)", "admin_ctxt, qos_consts.RULE_TYPE_BANDWIDTH_LIMIT) self.assertEqual( qos_consts.RULE_TYPE_BANDWIDTH_LIMIT, rule_type_details['type']) self.assertEqual( drivers_details, rule_type_details['drivers']) def test_get_rule_type_as_user(self):", "mock.MagicMock() with mock.patch.object( self.qos_plugin, '_change_placement_allocation') as mock_alloc_change: self.qos_plugin._check_network_for_placement_allocation_change( 'network', 'after_update',", "import uuidutils import webob.exc from neutron.exceptions import qos as neutron_qos_exc", "2, len(port['resource_request']['request_groups']) ) self.assertIn( { 'id': 'fake_uuid0', 'required': ['CUSTOM_PHYSNET_PUBLIC', 'CUSTOM_VNIC_TYPE_NORMAL'],", "policy_mock, [port_mock_without_own_policy]) def test_validate_update_network_callback_policy_changed(self): self._test_validate_update_network_callback( policy_id=uuidutils.generate_uuid()) def test_validate_update_network_callback_policy_not_changed(self): policy_id =", "def test_get_policy_packet_rate_limit_rules_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_packet_rate_limit_rules, self.ctxt, self.policy.id)", "self.assertEqual( drivers_details, rule_type_details['drivers']) def test_get_pps_rule_type_as_user(self): self.assertRaises( lib_exc.NotAuthorized, self.qos_plugin.get_rule_type, self.ctxt, qos_consts.RULE_TYPE_PACKET_RATE_LIMIT)", "): rule_type_details = self.qos_plugin.get_rule_type( admin_ctxt, qos_consts.RULE_TYPE_PACKET_RATE_LIMIT) self.assertEqual( qos_consts.RULE_TYPE_PACKET_RATE_LIMIT, rule_type_details['type']) self.assertEqual(", "self.qos_plugin.get_policy_packet_rate_limit_rules, self.ctxt, self.policy.id) def test_create_policy_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound,", "[self._make_qos_minbw_rule( desired_qos.id, min_kbps=desired_min_kbps)] if desired_min_kpps: desired_qos.rules += [self._make_qos_minpps_rule( desired_qos.id, min_kpps=desired_min_kpps)]", "= ports_object.Port( self.ctxt, id=uuidutils.generate_uuid(), network_id=uuidutils.generate_uuid(), device_owner='') with mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy),", "self.ctxt, self.min_pps_rule.id, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def test_update_policy_rule_check_rule_min_pps_direction_conflict(self): _policy =", ") self.assertEqual( ['fake_uuid0', 'fake_uuid1'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_no_qos_policy(self): port =", "qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() bw_limit_rule = rule_object.QosDscpMarkingRule(dscp_mark=16) orig_port,", "def test_get_policy_minimum_bandwidth_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_minimum_bandwidth_rule, self.ctxt, self.rule.id,", "_policy.id) def test_get_policy_bandwidth_limit_rule(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosBandwidthLimitRule.' 'get_object')", "segments=[segment]) port = ports_object.Port( self.ctxt, id=uuidutils.generate_uuid(), network_id=uuidutils.generate_uuid(), device_owner='') with mock.patch(", "id=_policy.id) @mock.patch.object(rule_object.QosBandwidthLimitRule, 'update') def test_update_policy_rule(self, mock_qos_rule_update): mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_rule_update,", "network_id=uuidutils.generate_uuid(), device_owner='compute:fake-zone') with mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy), \\ mock.patch( 'neutron.objects.network.Network.get_object', return_value=net),", "network_id=network.id, qos_policy_id=None, device_owner='compute:uu:id') port1_binding = ports_object.PortBinding( self.context, port_id=port1.id, host='fake_host1', vnic_type='fake_vnic_type',", "**self.rule_data['bandwidth_limit_rule']) self.dscp_rule = rule_object.QosDscpMarkingRule( self.ctxt, **self.rule_data['dscp_marking_rule']) self.min_bw_rule = rule_object.QosMinimumBandwidthRule( self.ctxt,", "port['resource_request']['request_groups'][0]['id'] ) self.assertEqual( ['CUSTOM_VNIC_TYPE_NORMAL'], port['resource_request']['request_groups'][0]['required'] ) self.assertEqual( {orc.NET_PACKET_RATE_KILOPACKET_PER_SEC: 10}, port['resource_request']['request_groups'][0]['resources'],", "expected_ports: self.assertIn(port, policy_ports) def _test_validate_update_port_callback(self, policy_id=None, original_policy_id=None): port_id = uuidutils.generate_uuid()", "def fake_change_placement_allocation(orig_policy, policy, orig_port, port): port['binding:profile'] = {'allocation': 'fake_allocation'} mock_alloc_change.side_effect", "_policy = self._get_policy() self.rule_data['bandwidth_limit_rule']['max_kbps'] = 1 setattr(_policy, \"rules\", [self.min_bw_rule]) with", "context.get_admin_context() self.project_id = uuidutils.generate_uuid() def _make_qos_policy(self): qos_policy = policy_object.QosPolicy( self.context,", "= ports_object.PortBinding( self.context, port_id=port1.id, host='fake_host1', vnic_type='fake_vnic_type', vif_type='fake_vif_type', profile={'allocation': 'fake_allocation'}) port1_binding.create()", "port): self.assertIn('pci_slot', port['binding:profile']) self.assertIn('pci_vendor_info', port['binding:profile']) self.assertIn('physical_network', port['binding:profile']) def test_change_placement_allocation_increase(self): qos1", "original_qos, desired_qos, original_min_kbps=2000, desired_min_kbps=1000, is_sriov=True) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc:", "} } with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises( qos_exc.QoSRulesConflict, self.qos_plugin.create_policy_packet_rate_limit_rule,", "qos_policy = port_qos_obj elif network_qos: qos_policy = net_qos_obj if qos_policy:", "test_get_policy_min_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_minimum_packet_rate_rule, self.ctxt, self.min_pps_rule.id, self.policy.id)", "is_sriov=False): kwargs = self._prepare_for_port_placement_allocation_change( original_qos, desired_qos, qos_network_policy=qos_network_policy) orig_port = kwargs['original_port']", "MIN_BW_REQUEST_GROUP_UUID = 'c8bc1b27-59a1-5135-aa33-aeecad6093f4' MIN_BW_RP = 'd7bea120-1626-11ec-9148-c32debfcf0f6' QOS_MIN_PPS_RULE_ID = '6ac5db7e-1626-11ec-8c7f-0b70dbb8a8eb' #", "DB_PLUGIN_KLASS) cfg.CONF.set_override(\"service_plugins\", [\"qos\"]) manager.init() self.qos_plugin = directory.get_plugin(plugins_constants.QOS) self.qos_plugin.driver_manager = mock.Mock()", "get_objects_mock: filters = {'filter': 'filter_id'} self.qos_plugin.get_policy_dscp_marking_rules( self.ctxt, self.policy.id, filters=filters) get_objects_mock.assert_called_once_with(", "self.rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_min_pps_rule(self): _policy = self._get_policy() setattr(_policy, \"rules\",", "= self._make_qos_policy() bw_limit_rule = rule_object.QosDscpMarkingRule(dscp_mark=16) orig_port, port = self._prepare_port_for_placement_allocation( qos1,", "{rule_data_name: data})) update_policy_rule_mock.assert_has_calls(calls, any_order=True) @mock.patch.object(qos_plugin.QoSPlugin, \"get_policy_rule\") def test_show_rule(self, get_policy_rule_mock): calls", "mock.ANY) delete_mock_call = mock.call.driver.call( 'delete_policy', self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(policy_delete_mock_call) <", "port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': -1000}}) self._assert_pci_info(port) def test_change_placement_allocation_no_original_qos(self):", "test_validate_policy_for_port_rule_not_valid(self): port = {'id': uuidutils.generate_uuid()} with mock.patch.object( self.qos_plugin.driver_manager, \"validate_rule_for_port\", return_value=False", "network_qos=False): net_qos_obj = self._make_qos_policy() net_qos_id = net_qos_obj.id if network_qos else", "import qos_pps_minimum_rule_alias from neutron.extensions import qos_rules_alias from neutron import manager", "'bb', 'cc', 'dd', 'ee', 'ff'] mac = netaddr.EUI(next(net_utils.random_mac_generator(base_mac))) device_owner =", "test_change_placement_allocation_increase_min_pps_and_min_bw(self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() orig_port, port =", "{'allocation': { self.MIN_BW_REQUEST_GROUP_UUID: self.MIN_BW_RP}}, 'device_id': 'uu:id', 'id': '9416c220-160a-11ec-ba3d-474633eb825c', } port", "orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_new_rule_not_min_bw(self): qos1 = self._make_qos_policy() qos2 =", "self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def test_update_policy_rule_check_rule_min_pps_direction_conflict(self): _policy = self._get_policy() rules_data", "\"rules\", []) self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.delete_policy_packet_rate_limit_rule, self.ctxt, self.pps_rule.id, _policy.id) def test_get_policy_packet_rate_limit_rule(self):", "rule_data['minimum_packet_rate_rule']['id'], self.policy.id, self.rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_update_policy_min_pps_rule_bad_policy(self): _policy = self._get_policy()", "-1000, 'NET_BW_EGR_KILOBIT_PER_SEC': 2000}}) def test_change_placement_allocation_change_dir_min_pps_ingress_to_any( self): qos1 = self._make_qos_policy() qos2", "rule_type_details = self.qos_plugin.get_rule_type( admin_ctxt, qos_consts.RULE_TYPE_BANDWIDTH_LIMIT) self.assertEqual( qos_consts.RULE_TYPE_BANDWIDTH_LIMIT, rule_type_details['type']) self.assertEqual( drivers_details,", "**self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", [self.dscp_rule]) self.qos_plugin.update_policy_dscp_marking_rule( self.ctxt, self.dscp_rule.id,", "= {'filter': 'filter_id'} self.qos_plugin.get_policy_minimum_packet_rate_rules( self.ctxt, self.policy.id, filters=filters) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY,", "test_get_policy_dscp_marking_rules_for_policy_with_filters(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosDscpMarkingRule.' 'get_objects') as get_objects_mock:", ") self.assertIn( { 'id': 'fake_uuid1', 'required': ['CUSTOM_VNIC_TYPE_NORMAL'], 'resources': { orc.NET_PACKET_RATE_EGR_KILOPACKET_PER_SEC:", "test_create_policy_rule_check_rule_max_more_than_min(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.min_bw_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy)", "= 'fake' rule_actions = {'create': [self.ctxt, rule_cls_mock, self.policy.id, {'fake_rule': {}}],", ") self.assertEqual( 'fake_uuid', port['resource_request']['request_groups'][0]['id'] ) self.assertEqual( ['CUSTOM_VNIC_TYPE_NORMAL'], port['resource_request']['request_groups'][0]['required'] ) self.assertEqual(", "setattr(_policy, \"rules\", [self.pps_rule]) new_rule_data = { 'packet_rate_limit_rule': { 'max_kpps': 400,", "def get_request_extensions(self): return [] class QoSRuleAliasMinimumPacketRateTestExtensionManager(object): def get_resources(self): return qos_pps_minimum_rule_alias.Qos_pps_minimum_rule_alias.\\", "self.qos_plugin._validate_create_network_callback( \"NETWORK\", \"precommit_create\", \"test_plugin\", payload=events.DBEventPayload( self.context, resource_id=kwargs['network']['id'],)) qos_policy = None", "self.assertEqual(ml2plugin_mock._make_port_dict.call_count, 2) mock_alloc_change_calls = [ mock.call( original_qos, qos, {'id': port1.id,", "\"rules\", [self.rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.qos_plugin.create_policy_minimum_bandwidth_rule( self.ctxt, _policy.id,", "= rule_object.QosDscpMarkingRule(dscp_mark=18) qos1.rules = [bw_limit_rule1] qos2.rules = [bw_limit_rule2] orig_port =", "for rule_type, rule_object_class in self.rule_objects.items(): rule_id = uuidutils.generate_uuid() rule_data_name =", "mock.Mock() with mock.patch( 'neutron.objects.ports.Port.get_object', return_value=port_mock ) as get_port, mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object',", "context from neutron_lib import exceptions as lib_exc from neutron_lib.exceptions import", "= rule_object.QosDscpMarkingRule( self.ctxt, **self.rule_data['dscp_marking_rule']) self.min_bw_rule = rule_object.QosMinimumBandwidthRule( self.ctxt, **self.rule_data['minimum_bandwidth_rule']) self.pps_rule", "self.context, \"port\": {\"id\": port.id}} with mock.patch.object(self.qos_plugin, 'validate_policy_for_port') \\ as mock_validate_policy:", "**self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", []) self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.delete_policy_bandwidth_limit_rule,", "= None if port_qos: qos_policy = port_qos_obj elif network_qos: qos_policy", "import rule as rule_object from neutron.services.qos import qos_plugin from neutron.tests.unit.db", "network_ports = [ mock.MagicMock(qos_policy_id=None), mock.MagicMock(qos_policy_id=uuidutils.generate_uuid()), mock.MagicMock(qos_policy_id=None) ] ports = [", "qos_network_policy.id if qos_network_policy else None) network = self._make_network(qos_policy_id=qos_network_policy_id) port =", "original_min_kpps=2000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1, None, orig_port,", "self._make_qos_policy() qos2 = self._make_qos_policy() bw_limit_rule1 = rule_object.QosDscpMarkingRule(dscp_mark=16) bw_limit_rule2 = rule_object.QosDscpMarkingRule(dscp_mark=18)", "test_add_policy(self, mock_qos_policy, mock_create_rbac_policy): mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_policy, 'QosPolicy') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver')", "return_value=_policy): self.qos_plugin.delete_policy_minimum_packet_rate_rule( self.ctxt, self.min_pps_rule.id, self.policy.id) self._validate_driver_params('update_policy', self.ctxt) def test_delete_policy_min_pps_rule_bad_policy(self): _policy", "self.policy.id) self._validate_driver_params('update_policy', self.ctxt) def test_delete_policy_min_pps_rule_bad_policy(self): _policy = self._get_policy() setattr(_policy, \"rules\",", "}, port['resource_request']['request_groups'] ) self.assertIn( { 'id': 'fake_uuid1', 'required': ['CUSTOM_VNIC_TYPE_NORMAL'], 'resources':", "qos1 = self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation(qos1, original_min_kbps=1000, original_min_kpps=2000) with", "port['resource_request']['request_groups'][0]['required'] ) self.assertEqual( {orc.NET_BW_EGR_KILOBIT_PER_SEC: 10}, port['resource_request']['request_groups'][0]['resources'], ) self.assertEqual( ['fake_uuid'], port['resource_request']['same_subtree'],", "self.ctxt, qos_policy_id=self.policy.id, _pager=mock.ANY, filter='filter_id') def test_get_policy_dscp_marking_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises(", "mock.Mock() mock_manager.attach_mock(qos_policy_mock, 'QosPolicy') mock_manager.attach_mock(port_mock, 'Port') mock_manager.attach_mock(rule_cls_mock, 'RuleCls') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') for", "qos_consts.RULE_TYPE_BANDWIDTH_LIMIT, rule_type_details['type']) self.assertEqual( drivers_details, rule_type_details['drivers']) def test_get_rule_type_as_user(self): self.assertRaises( lib_exc.NotAuthorized, self.qos_plugin.get_rule_type,", "get_port.assert_called_once_with(self.ctxt, id=port_id) get_policy.assert_called_once_with(admin_ctxt, id=policy_id) validate_policy_for_port.assert_called_once_with( self.ctxt, policy_mock, port_mock) def test_validate_update_port_callback_policy_changed(self):", "qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_minimum_bandwidth_rules, self.ctxt, self.policy.id) def test_create_policy_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises(", "10}, port['resource_request']['request_groups'][0]['resources'], ) self.assertEqual( ['fake_uuid'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_bulk_min_pps_rule(self): ports", "self._make_qos_policy() net_qos_id = net_qos_obj.id if network_qos else None network =", "policy_object from neutron.objects.qos import rule as rule_object from neutron.services.qos import", "def test_get_policy_minimum_bandwidth_rules_for_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumBandwidthRule.' 'get_objects') as", "{'min_kbps': 10} } def _update_rule(self, rule_type, rule_id, **kwargs): data =", "'driver') mock_manager.reset_mock() fields = obj_utils.get_updatable_fields( policy_object.QosPolicy, self.policy_data['policy']) self.qos_plugin.update_policy( self.ctxt, self.policy.id,", "test_get_rule_type_as_user(self): self.assertRaises( lib_exc.NotAuthorized, self.qos_plugin.get_rule_type, self.ctxt, qos_consts.RULE_TYPE_BANDWIDTH_LIMIT) def test_get_rule_types(self): filters =", "desired_qos, qos_network_policy=qos_network_policy) orig_port = kwargs['original_port'] qos = original_qos or qos_network_policy", "{'policy': fields}) self._validate_driver_params('update_policy', self.ctxt) policy_update_mock_call = mock.call.update() update_precommit_mock_call = mock.call.driver.call(", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.create_policy_packet_rate_limit_rule, self.ctxt, self.policy.id, self.rule_data) def test_update_policy_pps_rule_for_nonexistent_policy(self):", "return_value=[segment_mock]), \\ mock.patch( 'neutron.objects.qos.rule.QosMinimumBandwidthRule.' 'get_objects', return_value=min_bw_rules), \\ mock.patch( 'neutron.objects.qos.rule.QosMinimumPacketRateRule.' 'get_objects',", "from keystoneauth1 import exceptions as ks_exc import netaddr from neutron_lib.api.definitions", "self.rule_data) def test_update_policy_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.update_policy_packet_rate_limit_rule, self.ctxt,", "qos_network = self._make_qos_policy() desired_qos = self._make_qos_policy() kwargs = self._prepare_for_port_placement_allocation_change( qos1=None,", "self.ctxt, self.policy.id) def test_create_policy_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.create_policy_bandwidth_limit_rule,", "getattr(self.qos_plugin, \"%s_policy_rule\" % action) method(*arguments) # some actions get rule", "port.id}} with mock.patch.object(self.qos_plugin, 'validate_policy_for_port') \\ as mock_validate_policy: self.qos_plugin._validate_create_port_callback( \"PORT\", \"precommit_create\",", "test__extend_port_resource_request_bulk_min_bw_and_pps_rule(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION self.min_pps_rule.direction = lib_constants.EGRESS_DIRECTION request_groups_uuids = ['fake_uuid0',", "{TestQosPluginDB.MIN_PPS_REQUEST_GROUP_UUID: TestQosPluginDB.MIN_PPS_RP}) if desired_qos: desired_qos.rules = [] if desired_min_kbps: desired_qos.rules", "update_policy_rule_mock.assert_has_calls(calls, any_order=True) @mock.patch.object(qos_plugin.QoSPlugin, \"get_policy_rule\") def test_show_rule(self, get_policy_rule_mock): calls = []", "port['resource_request']['request_groups'][0]['id'] ) self.assertEqual( ['CUSTOM_PHYSNET_PUBLIC', 'CUSTOM_VNIC_TYPE_NORMAL'], port['resource_request']['request_groups'][0]['required'] ) self.assertEqual( {orc.NET_BW_EGR_KILOBIT_PER_SEC: 10},", "test__extend_port_resource_request_no_qos_policy(self): port = self._create_and_extend_port([], physical_network='public', has_qos_policy=False) self.assertIsNone(port.get('resource_request')) def test__extend_port_resource_request_min_bw_inherited_policy( self):", "qos_policy_id=None, device_owner='uu:id') # Port with overwritten QoS policy self._make_port(network_id=network.id, qos_policy_id=port_qos.id,", "get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id) def test_get_policy_minimum_bandwidth_rules_for_policy_with_filters(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with", "= 'e16161f4-1626-11ec-a5a2-1fc9396e27cc' def setUp(self): super(TestQosPluginDB, self).setUp() self.setup_coreplugin(load_plugins=False) cfg.CONF.set_override(\"core_plugin\", DB_PLUGIN_KLASS) cfg.CONF.set_override(\"service_plugins\",", "device_owner='') with mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy), \\ mock.patch( 'neutron.objects.network.Network.get_object', return_value=net), \\", "self._get_policy() setattr(_policy, \"rules\", [self.min_pps_rule]) new_rule_data = { 'minimum_packet_rate_rule': { 'id':", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises( qos_exc.QoSRulesConflict, self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt, _policy.id,", "setattr(_policy, \"rules\", [self.rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.qos_plugin.create_policy_minimum_bandwidth_rule( self.ctxt,", "self.rule_objects.items(): rule_id = uuidutils.generate_uuid() rule_data_name = '%s_rule' % rule_type data", "self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", [self.pps_rule]) self.qos_plugin.update_policy_packet_rate_limit_rule( self.ctxt,", "= 1 with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.assertRaises( qos_exc.QoSRuleParameterConflict, self.qos_plugin.update_policy_bandwidth_limit_rule, self.ctxt, self.rule.id,", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.create_policy_minimum_bandwidth_rule, self.ctxt, self.policy.id, self.rule_data)", "qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() bw_limit_rule1 = rule_object.QosDscpMarkingRule(dscp_mark=16) bw_limit_rule2", "= ports_object.Port( self.ctxt, id=uuidutils.generate_uuid(), network_id=uuidutils.generate_uuid(), device_owner='') with mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=policy),", "@mock.patch( 'neutron.objects.rbac_db.RbacNeutronDbObjectMixin' '.create_rbac_policy') @mock.patch('neutron.objects.qos.policy.QosPolicy') def test_add_policy(self, mock_qos_policy, mock_create_rbac_policy): mock_manager =", "self._assert_pci_info(port) def test_change_placement_allocation_decrease_min_pps(self): original_qos = self._make_qos_policy() desired_qos = self._make_qos_policy() orig_port,", "as mock_qos_get_obj: self.assertRaises( qos_exc.QoSRulesConflict, self.qos_plugin.create_policy_bandwidth_limit_rule, self.ctxt, _policy.id, new_rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id)", "Port with overwritten QoS policy self._make_port(network_id=network.id, qos_policy_id=port_qos.id, device_owner='compute:uu:id') ml2plugin_mock =", "mock_manager.mock_calls.index(rule_delete_mock_call) < mock_manager.mock_calls.index(update_precommit_mock_call) < mock_manager.mock_calls.index(update_mock_call)) def test_delete_policy_rule_bad_policy(self): _policy = policy_object.QosPolicy(", "= 'any' for rule_data in rules_data: rules = [ rule_object.QosMinimumPacketRateRule(", "\"network_id\": network_id, \"vnic_type\": \"normal\", } }, { \"resource_request\": { \"port_id\":", "return_value=_policy) as mock_qos_get_obj: self.assertRaises( qos_exc.QoSRulesConflict, self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt, _policy.id, new_rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt,", "orc.NET_BW_IGR_KILOBIT_PER_SEC: 20}, }, port['resource_request']['request_groups'] ) self.assertIn( { 'id': 'fake_uuid1', 'required':", "mock_manager.reset_mock() self.qos_plugin.create_policy(self.ctxt, self.policy_data) policy_mock_call = mock.call.QosPolicy().create() create_precommit_mock_call = mock.call.driver.call( 'create_policy_precommit',", "self.rule_data['minimum_bandwidth_rule']['min_kbps'] = 1000 with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.assertRaises( qos_exc.QoSRuleParameterConflict, self.qos_plugin.update_policy_minimum_bandwidth_rule, self.ctxt,", "'filter_id'} self.qos_plugin.get_policy_minimum_packet_rate_rules( self.ctxt, self.policy.id, filters=filters) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id, filter='filter_id')", "[] for rule_type, rule_object_class in self.rule_objects.items(): rule_id = uuidutils.generate_uuid() rule_data_name", "PORT_ID = 'f02f160e-1612-11ec-b2b8-bf60ab98186c' QOS_MIN_BW_RULE_ID = '8bf8eb46-160e-11ec-8024-9f96be32099d' # uuid -v5 f02f160e-1612-11ec-b2b8-bf60ab98186c", "qos2 = self._make_qos_policy() bw_limit_rule = rule_object.QosDscpMarkingRule(dscp_mark=16) qos2.rules = [bw_limit_rule] orig_port,", "def test_update_policy_rule_check_rule_bwlimit_less_than_minbw(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "self._get_policy() self.rule_data['bandwidth_limit_rule']['max_kbps'] = 1 setattr(_policy, \"rules\", [self.min_bw_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy)", "1000 with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.assertRaises( qos_exc.QoSRuleParameterConflict, self.qos_plugin.update_policy_minimum_bandwidth_rule, self.ctxt, self.min_bw_rule.id, self.policy.id,", "\"rules\", [self.dscp_rule]) self.qos_plugin.delete_policy_dscp_marking_rule( self.ctxt, self.dscp_rule.id, self.policy.id) self._validate_driver_params('update_policy', self.ctxt) def test_get_policy_dscp_marking_rules(self):", "self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def test_delete_policy_dscp_marking_rule(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy'])", "def test_change_placement_allocation_old_rule_not_min_bw(self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() bw_limit_rule =", "= self.policy.id elif has_net_qos_policy: self.port_data['port']['qos_network_policy_id'] = self.policy.id self.port = ports_object.Port(", "def test_update_policy_packet_rate_limit_rule(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy):", "License. import copy from unittest import mock from keystoneauth1 import", "[self._make_qos_minbw_rule( qos.id, min_kbps=original_min_kbps, rule_id=TestQosPluginDB.QOS_MIN_BW_RULE_ID)] allocation.update( {TestQosPluginDB.MIN_BW_REQUEST_GROUP_UUID: TestQosPluginDB.MIN_BW_RP}) if original_min_kpps: qos.rules", "orig_port, port = self._prepare_port_for_placement_allocation( qos1, qos2, original_min_kpps=1000, desired_min_kpps=1000) for rule", "mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={ self.MIN_PPS_RP: {", "self.rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_rule_check_rule_minbw_gr_than_bwlimit(self): _policy = self._get_policy() self.rule_data['minimum_bandwidth_rule']['min_kbps'] =", "self.qos_plugin.create_policy_dscp_marking_rule( self.ctxt, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def test_update_policy_dscp_marking_rule(self): _policy =", "# uuid -v5 f02f160e-1612-11ec-b2b8-bf60ab98186c # 6ac5db7e-1626-11ec-8c7f-0b70dbb8a8eb MIN_PPS_REQUEST_GROUP_UUID = '995008f4-f120-547a-b051-428b89076067' MIN_PPS_RP", "['CUSTOM_VNIC_TYPE_NORMAL'], port['resource_request']['request_groups'][0]['required'] ) self.assertEqual( {orc.NET_PACKET_RATE_KILOPACKET_PER_SEC: 10}, port['resource_request']['request_groups'][0]['resources'], ) self.assertEqual( ['fake_uuid'],", "[port_mock_without_own_policy]) def test_validate_update_network_callback_policy_changed(self): self._test_validate_update_network_callback( policy_id=uuidutils.generate_uuid()) def test_validate_update_network_callback_policy_not_changed(self): policy_id = uuidutils.generate_uuid()", "filters=filters) get_objects_mock.assert_called_once_with( self.ctxt, qos_policy_id=self.policy.id, _pager=mock.ANY, filter='filter_id') def test_get_policy_dscp_marking_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "return [] class QoSRuleAliasMinimumPacketRateTestExtensionManager(object): def get_resources(self): return qos_pps_minimum_rule_alias.Qos_pps_minimum_rule_alias.\\ get_resources() def", "has_net_qos_policy=True) self.assertEqual( 1, len(port['resource_request']['request_groups']) ) self.assertEqual( 'fake_uuid', port['resource_request']['request_groups'][0]['id'] ) self.assertEqual(", "states=(original_network, network))) mock_alloc_change.assert_not_called() ml2plugin_mock._make_port_dict.assert_not_called() def test_check_network_for_placement_allocation_change_no_ports_to_update( self): original_qos = self._make_qos_policy()", "self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def test_delete_policy_dscp_marking_rule(self): _policy = policy_object.QosPolicy( self.ctxt,", "orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_no_original_allocation(self): qos1 = self._make_qos_policy() rule1_obj =", "qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, self.policy.id) def test_get_policy_bandwidth_limit_rules_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None):", "self.context, \"network\": network} with mock.patch.object(self.qos_plugin, 'validate_policy_for_network') \\ as mock_validate_policy: self.qos_plugin._validate_create_network_callback(", "mock_manager.mock_calls.index(update_precommit_mock_call) < mock_manager.mock_calls.index(update_mock_call)) def test_create_policy_rule_check_rule_min_less_than_max(self): _policy = self._get_policy() setattr(_policy, \"rules\",", "self.qos_policy_id, {rule_data_name: data})) update_policy_rule_mock.assert_has_calls(calls, any_order=True) @mock.patch.object(qos_plugin.QoSPlugin, \"get_policy_rule\") def test_show_rule(self, get_policy_rule_mock):", "with mock.patch( 'neutron.objects.qos.rule.QosRule.get_object', return_value=rule ), mock.patch.object(self.qos_plugin, 'get_policy_rule', return_value=rule.to_dict()): self._delete_rule(rule_type, rule_id)", "qos2.id if qos2 else None qos_network_policy_id = ( qos_network_policy.id if", "self.ctxt, **self.rule_data['minimum_bandwidth_rule']) self.pps_rule = rule_object.QosPacketRateLimitRule( self.ctxt, **self.rule_data['packet_rate_limit_rule']) self.min_pps_rule = rule_object.QosMinimumPacketRateRule(", "} with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises( qos_exc.QoSRulesConflict, self.qos_plugin.create_policy_packet_rate_limit_rule, self.ctxt,", "as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={", "self.qos_plugin.update_policy_bandwidth_limit_rule( self.ctxt, self.rule.id, self.policy.id, self.rule_data) self.mock_qos_load_attr.assert_called_once_with('rules') self._validate_driver_params('update_policy', self.ctxt) rules =", "return network def _test_validate_create_network_callback(self, network_qos=False): net_qos_obj = self._make_qos_policy() net_qos_id =", "qos2, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={ self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': 500},", "qos_policy_id=port_qos_id) kwargs = {\"context\": self.context, \"port\": {\"id\": port.id}} with mock.patch.object(self.qos_plugin,", "port.id, \"qos_policy_id\": qos2_id}} def test_check_port_for_placement_allocation_change_no_qos_change(self): qos1_obj = self._make_qos_policy() kwargs =", "self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt, self.policy.id, new_rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) for rule_data in rules:", "original_min_kpps=500, desired_min_kpps=1000) for rule in qos2.rules: rule.direction = 'egress' with", "self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION self.min_bw_rule.qos_policy_id = self.policy.id port = self._create_and_extend_port([self.min_bw_rule],", "= mock.Mock() with mock.patch( 'neutron.objects.ports.Port.get_object', return_value=port_mock ) as get_port, mock.patch(", "port = ports_object.Port( self.ctxt, id=uuidutils.generate_uuid(), network_id=uuidutils.generate_uuid(), device_owner='compute:fake-zone') with mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object',", "self.qos_plugin.delete_policy_packet_rate_limit_rule, self.ctxt, self.pps_rule.id, self.policy.id) def test_get_pps_rule_type(self): admin_ctxt = context.get_admin_context() drivers_details", "'8086:107ed', 'physical_network': 'sriov_phy' } binding_prof.update({'allocation': allocation}) orig_port.update( {'binding:profile': binding_prof, 'device_id':", "def test_update_policy_rule_check_rule_min_pps_direction_conflict(self): _policy = self._get_policy() rules_data = [ { 'minimum_packet_rate_rule':", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", [self.rule]) self.qos_plugin.delete_policy_bandwidth_limit_rule( self.ctxt, self.rule.id, _policy.id)", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "= 'any' setattr(_policy, \"rules\", [self.min_pps_rule]) rules = [ { 'minimum_packet_rate_rule':", "kwargs['original_port'] port = kwargs['port'] with mock.patch.object( self.qos_plugin, '_change_placement_allocation') as mock_alloc_change:", "if policy_id is None or policy_id == original_policy_id: get_port.assert_not_called() get_policy.assert_not_called()", "}, \"original_port\": { \"id\": port_id, qos_consts.QOS_POLICY_ID: original_policy_id } } port_mock", "'QosBandwidthLimitRule.' 'get_objects') as get_objects_mock: self.qos_plugin.get_policy_bandwidth_limit_rules( self.ctxt, self.policy.id) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY,", "orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': 1000}}) self._assert_pci_info(port) def test_change_placement_allocation_increase_min_pps(self):", "self.rule_data[rule_data_name] rule = rule_object_class(self.ctxt, id=rule_id, qos_policy_id=self.qos_policy_id, **data) with mock.patch('neutron.objects.qos.rule.QosRule.get_object', return_value=rule):", "rule_id = uuidutils.generate_uuid() with mock.patch('neutron.objects.qos.rule.QosRule.get_object', return_value=None): resource = '%s/alias-%s-rules' %", "+= [self._make_qos_minpps_rule( desired_qos.id, min_kpps=desired_min_kpps)] binding_prof = {} if is_sriov: binding_prof", "self.policy.id, self.rule_data) self.mock_qos_load_attr.assert_called_once_with('rules') self._validate_driver_params('update_policy', self.ctxt) self.rule_data['minimum_bandwidth_rule']['min_kbps'] = 1000 with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "def setUp(self): # Remove MissingAuthPlugin exception from logs self.patch_notifier =", "mock_alloc_change: self.qos_plugin._check_network_for_placement_allocation_change( 'network', 'after_update', ml2plugin_mock, payload=events.DBEventPayload( self.context, states=(original_network, network))) mock_alloc_change.assert_not_called()", "qos_rule.create() return qos_rule def _make_qos_minpps_rule(self, policy_id, direction='ingress', min_kpps=1000, rule_id=None): rule_id", "qos_policy_id=policy_id) policy_mock = mock.MagicMock(id=policy_id) admin_ctxt = mock.Mock() with mock.patch( 'neutron.objects.ports.Port.get_object',", "[] class TestQoSRuleAlias(test_db_base_plugin_v2.NeutronDbPluginV2TestCase): def setUp(self): # Remove MissingAuthPlugin exception from", "mock.patch('neutron.objects.db.api.create_object').start() mock.patch('neutron.objects.db.api.update_object').start() mock.patch('neutron.objects.db.api.delete_object').start() mock.patch('neutron.objects.db.api.get_object').start() _mock_qos_load_attr = mock.patch( 'neutron.objects.qos.policy.QosPolicy.obj_load_attr') self.mock_qos_load_attr =", "you may # not use this file except in compliance", "'min_kpps': 10, 'direction': 'any'}, } self.policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy'])", "directory.get_plugin(plugins_constants.QOS) self.qos_plugin.driver_manager = mock.Mock() self.rpc_push = mock.patch('neutron.api.rpc.handlers.resources_rpc' '.ResourcesPushRpcApi.push').start() self.context =", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosPacketRateLimitRule.' 'get_objects') as get_objects_mock: filters", "rule_object.QosMinimumPacketRateRule( self.ctxt, **rules_data[1]['minimum_packet_rate_rule']), ] setattr(_policy, 'rules', rules) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy)", "get_request_extensions(self): return [] class TestQoSRuleAlias(test_db_base_plugin_v2.NeutronDbPluginV2TestCase): def setUp(self): # Remove MissingAuthPlugin", "self.policy, network_id=network) except qos_exc.QosRuleNotSupportedByNetwork: self.fail(\"QosRuleNotSupportedByNetwork \" \"exception unexpectedly raised\") def", "'network', 'after_update', ml2plugin_mock, payload=events.DBEventPayload( self.context, states=(original_network, network))) self.assertEqual(ml2plugin_mock._make_port_dict.call_count, 2) mock_alloc_change_calls", "self.pps_rule.id, self.policy.id) def test_get_pps_rule_type(self): admin_ctxt = context.get_admin_context() drivers_details = [{", "is None or policy_id == original_policy_id: get_policy.assert_not_called() validate_policy_for_network.assert_not_called() get_ports.assert_not_called() validate_policy_for_ports.assert_not_called()", "'NET_PACKET_RATE_EGR_KILOPACKET_PER_SEC': 1000}, self.MIN_BW_RP: { 'NET_BW_IGR_KILOBIT_PER_SEC': -1000, 'NET_BW_EGR_KILOBIT_PER_SEC': 2000}}) def test_change_placement_allocation_change_dir_min_pps_ingress_to_any(", "self.MIN_BW_RP: { 'NET_BW_IGR_KILOBIT_PER_SEC': -1000, 'NET_BW_EGR_KILOBIT_PER_SEC': 2000}}) def test_change_placement_allocation_change_dir_min_pps_ingress_to_any( self): qos1", "TestQoSRuleAlias(test_db_base_plugin_v2.NeutronDbPluginV2TestCase): def setUp(self): # Remove MissingAuthPlugin exception from logs self.patch_notifier", "self._prepare_for_port_placement_allocation_change( qos1=qos1_obj, qos2=qos2_obj) context = kwargs['context'] original_port = kwargs['original_port'] port", "= self._prepare_port_for_placement_allocation( qos1, qos2, original_min_kbps=1000, desired_min_kbps=2000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as", "self.qos_plugin._change_placement_allocation( qos1, None, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={ self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC':", "[rule1_obj] qos2 = self._make_qos_policy() rule2_obj = self._make_qos_minbw_rule(qos2.id, min_kbps=1000) qos2.rules =", "self.assertRaises( neutron_qos_exc.QosPlacementAllocationUpdateConflict, self.qos_plugin._change_placement_allocation, qos1, qos2, orig_port, port) def test_change_placement_allocation_update_generation_conflict(self): qos1", "= mock.call.driver.call( 'update_policy', self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(rule_create_mock_call) < mock_manager.mock_calls.index(update_precommit_mock_call) <", "'description': 'Test policy description', 'shared': True, 'is_default': False}} policy_details =", "uuidutils.generate_uuid(), 'min_kpps': 20, 'direction': lib_constants.INGRESS_DIRECTION} min_bw_rule_ingress = rule_object.QosMinimumBandwidthRule( self.ctxt, **min_bw_rule_ingress_data)", "qos_policy_id=self.qos_policy_id, **data) with mock.patch('neutron.objects.qos.rule.QosRule.get_object', return_value=rule): self._show_rule(rule_type, rule_id) calls.append(mock.call(mock.ANY, rule_object_class, rule_id,", "alloc_diff={self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': -1000}}) self._assert_pci_info(port) def test_change_placement_allocation_no_original_qos(self): qos1 = None", "else: get_policy.assert_called_once_with(admin_ctxt, id=policy_id) get_ports.assert_called_once_with(self.ctxt, network_id=network_id) validate_policy_for_ports.assert_called_once_with( self.ctxt, policy_mock, [port_mock_without_own_policy]) def", "import qos_plugin from neutron.tests.unit.db import test_db_base_plugin_v2 from neutron.tests.unit.services.qos import base", "context.get_admin_context() drivers_details = [{ 'name': 'fake-driver', 'supported_parameters': [{ 'parameter_name': 'min_kpps',", "= self._prepare_port_for_placement_allocation(qos1, original_min_kbps=1000, original_min_kpps=2000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(", ") self.assertIn( { 'id': 'fake_uuid0', 'required': ['CUSTOM_PHYSNET_PUBLIC', 'CUSTOM_VNIC_TYPE_NORMAL'], 'resources': {", "'pci_vendor_info': '8086:107ed', 'physical_network': 'sriov_phy' } binding_prof.update({'allocation': allocation}) orig_port.update( {'binding:profile': binding_prof,", "service_plugins = {'qos_plugin_name': SERVICE_PLUGIN_KLASS} ext_mgr = QoSRuleAliasTestExtensionManager() super(TestQoSRuleAlias, self).setUp(plugin=plugin, ext_mgr=ext_mgr,", "= self._get_policy() self.rule_data['minimum_bandwidth_rule']['min_kbps'] = 1000000 setattr(_policy, \"rules\", [self.rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "test_get_policy_bandwidth_limit_rules_for_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosBandwidthLimitRule.' 'get_objects') as get_objects_mock:", "orig_port, port = self._prepare_port_for_placement_allocation( qos1, qos2, desired_min_kbps=2000) qos1.rules = [bw_limit_rule]", "# WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "self.policy.id, self.rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_rule_check_rule_minbw_gr_than_bwlimit(self): _policy = self._get_policy() self.rule_data['minimum_bandwidth_rule']['min_kbps']", "self.rule_data) except NotImplementedError: self.fail() def test_create_policy_rule_check_rule_min_pps_direction_conflict(self): _policy = self._get_policy() self.rule_data['minimum_packet_rate_rule']['direction']", "= self.qos_plugin.get_rule_types(self.ctxt, filters=filters) self.assertEqual(sorted(qos_consts.VALID_RULE_TYPES), sorted(type_['type'] for type_ in types)) @mock.patch('neutron.objects.ports.Port')", "network.id, qos_policy_id=qos1_id, port_id=TestQosPluginDB.PORT_ID) return {\"context\": self.context, \"original_port\": { \"id\": port.id,", "= self._get_policy() setattr(_policy, \"rules\", []) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.assertRaises( qos_exc.QosRuleNotFound,", "qos.id}, mock.ANY)] mock_alloc_change.assert_has_calls(mock_alloc_change_calls, any_order=True) port1.update() port2.update() self.assertDictEqual( port1.bindings[0].profile, {'allocation': 'fake_allocation'})", "qos_plugin.QoSPlugin, \"supported_rule_type_details\", return_value=drivers_details ): rule_type_details = self.qos_plugin.get_rule_type( admin_ctxt, qos_consts.RULE_TYPE_MINIMUM_PACKET_RATE) self.assertEqual(", "def _make_port(self, network_id, qos_policy_id=None, port_id=None, qos_network_policy_id=None, device_owner=None): port_id = port_id", "id=uuidutils.generate_uuid(), network_id=uuidutils.generate_uuid(), device_owner='') with mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=policy), \\ mock.patch( 'neutron.objects.network.Network.get_object',", "mock.ANY), ] mock_alloc_change.assert_has_calls(mock_alloc_change_calls, any_order=True) port1.update() self.assertDictEqual(port1.bindings[0].profile, {}) def test_check_network_for_placement_allocation_change(self): original_qos", "= self._make_qos_policy() desired_qos = self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation( original_qos,", "} port_mock_with_own_policy = mock.MagicMock( id=uuidutils.generate_uuid(), qos_policy_id=uuidutils.generate_uuid()) port_mock_without_own_policy = mock.MagicMock( id=uuidutils.generate_uuid(),", "'id': uuidutils.generate_uuid(), 'min_kpps': 20, 'direction': lib_constants.INGRESS_DIRECTION} min_bw_rule_ingress = rule_object.QosMinimumBandwidthRule( self.ctxt,", "20, }, }, port['resource_request']['request_groups'] ) self.assertEqual( ['fake_uuid0', 'fake_uuid1'], port['resource_request']['same_subtree'], )", "10}, port['resource_request']['request_groups'][0]['resources'], ) self.assertEqual( ['fake_uuid'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_min_pps_rule(self): port", "policy = self._get_policy() policy.rules = [self.min_bw_rule] segment = network_object.NetworkSegment( physical_network='fake", "with mock.patch('neutron.objects.qos.rule.' 'QosPacketRateLimitRule.' 'get_objects') as get_objects_mock: self.qos_plugin.get_policy_packet_rate_limit_rules( self.ctxt, self.policy.id) get_objects_mock.assert_called_once_with(", "mock.patch.object( self.ctxt, \"elevated\", return_value=admin_ctxt ): self.qos_plugin._validate_update_port_callback( \"PORT\", \"precommit_update\", \"test_plugin\", payload=events.DBEventPayload(", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_packet_rate_limit_rule, self.ctxt, self.pps_rule.id, self.policy.id) def test_get_policy_packet_rate_limit_rules_for_nonexistent_policy(self):", "'Test policy description', 'shared': True, 'is_default': False} with mock.patch('neutron.objects.qos.policy.QosPolicy') as", "test__extend_port_resource_request_min_bw_rule(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION port = self._create_and_extend_port([self.min_bw_rule]) self.assertEqual( 1, len(port['resource_request']['request_groups'])", "in mock_manager.mock_calls: action_index = mock_manager.mock_calls.index(rule_mock_call) else: action_index = mock_manager.mock_calls.index( get_rule_mock_call)", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumPacketRateRule.' 'get_objects') as get_objects_mock: filters", "qos_policy_id=None, device_owner='compute:uu:id') port1_binding = ports_object.PortBinding( self.context, port_id=port1.id, host='fake_host1', vnic_type='fake_vnic_type', vif_type='fake_vif_type',", "test_change_placement_allocation_new_rule_not_min_bw(self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() bw_limit_rule = rule_object.QosDscpMarkingRule(dscp_mark=16)", "policy_mock, port_mock) def test_validate_update_port_callback_policy_changed(self): self._test_validate_update_port_callback( policy_id=uuidutils.generate_uuid()) def test_validate_update_port_callback_policy_not_changed(self): policy_id =", "self.fail(\"QosRuleNotSupported exception unexpectedly raised\") def test_validate_policy_for_network(self): network = uuidutils.generate_uuid() with", "port = self._prepare_port_for_placement_allocation( None, desired_qos, qos_network_policy=qos_network, original_min_kbps=1000, desired_min_kbps=2000) with mock.patch.object(self.qos_plugin._placement_client,", "mock.MagicMock(qos_policy_id=uuidutils.generate_uuid()), mock.MagicMock(qos_policy_id=None) ] ports = [ mock.MagicMock(qos_policy_id=self.policy.id), ] expected_network_ports =", "self.qos_plugin._change_placement_allocation(qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={ self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC':", "self.ctxt, self.policy, port) except qos_exc.QosRuleNotSupported: self.fail(\"QosRuleNotSupported exception unexpectedly raised\") def", "device_owner=device_owner, project_id=self.project_id, admin_state_up=True, status='DOWN', device_id='2', qos_policy_id=qos_policy_id, qos_network_policy_id=qos_network_policy_id, mac_address=mac, id=port_id) port.create()", "self.assertEqual( drivers_details, rule_type_details['drivers']) def test_get_min_pps_rule_type_as_user(self): self.assertRaises( lib_exc.NotAuthorized, self.qos_plugin.get_rule_type, self.ctxt, qos_consts.RULE_TYPE_MINIMUM_PACKET_RATE)", "self._prepare_port_for_placement_allocation( original_qos, desired_qos, original_min_kbps=2000, desired_min_kbps=1000, is_sriov=True) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as", "'supported_parameters': [{ 'parameter_name': 'max_kpps', 'parameter_type': lib_constants.VALUES_TYPE_RANGE, 'parameter_range': {'start': 0, 'end':", "ports_object.Port( self.ctxt, id=uuidutils.generate_uuid(), network_id=uuidutils.generate_uuid(), device_owner='compute:fake-zone') with mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy), \\", "uuidutils.generate_uuid() rule_data_name = '%s_rule' % rule_type data = self.rule_data[rule_data_name] rule", "10}, port['resource_request']['request_groups'][0]['resources'], ) self.assertEqual( ['fake_uuid'], port['resource_request']['same_subtree'], ) def test_get_ports_with_policy(self): network_ports", "'create_policy', self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(policy_mock_call) < mock_manager.mock_calls.index(create_precommit_mock_call) < mock_manager.mock_calls.index(create_mock_call)) def", "return_value=_policy) as mock_qos_get_obj: self.qos_plugin.create_policy_minimum_bandwidth_rule( self.ctxt, _policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) self.mock_qos_load_attr.assert_called_once_with('rules')", "self._get_policy() setattr(_policy, \"rules\", []) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.update_policy_minimum_packet_rate_rule,", "for the specific language governing permissions and limitations # under", "test_get_policy_dscp_marking_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_dscp_marking_rule, self.ctxt, self.dscp_rule.id, self.policy.id)", "qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_minimum_bandwidth_rule, self.ctxt, self.rule.id, self.policy.id) def test_get_policy_minimum_bandwidth_rules_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None):", "'QosBandwidthLimitRule.' 'get_objects') as get_objects_mock: filters = {'filter': 'filter_id'} self.qos_plugin.get_policy_bandwidth_limit_rules( self.ctxt,", "port) else: mock_validate_policy.assert_not_called() def test_validate_create_port_callback_policy_on_port(self): self._test_validate_create_port_callback(port_qos=True) def test_validate_create_port_callback_policy_on_port_and_network(self): self._test_validate_create_port_callback(port_qos=True, network_qos=True)", "self.policy.id) def test_get_policy_bandwidth_limit_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_bandwidth_limit_rule, self.ctxt,", "self.qos_plugin.get_policy_dscp_marking_rule, self.ctxt, self.dscp_rule.id, self.policy.id) def test_get_policy_dscp_marking_rules_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises(", "from neutron.services.qos import qos_plugin from neutron.tests.unit.db import test_db_base_plugin_v2 from neutron.tests.unit.services.qos", "'is_default': False}} policy_details = {'id': policy_id, 'project_id': project_id, 'name': 'test-policy',", "self.qos_plugin.validate_policy_for_network( self.ctxt, self.policy, network_id=network) except qos_exc.QosRuleNotSupportedByNetwork: self.fail(\"QosRuleNotSupportedByNetwork \" \"exception unexpectedly", "desired_min_kbps: desired_qos.rules += [self._make_qos_minbw_rule( desired_qos.id, min_kbps=desired_min_kbps)] if desired_min_kpps: desired_qos.rules +=", "= self.new_show_request(resource, rule_id, self.fmt) res = request.get_response(self.ext_api) self.assertEqual(webob.exc.HTTPNotFound.code, res.status_int) class", "self.qos_policy_id = uuidutils.generate_uuid() self.rule_data = { 'minimum_packet_rate_rule': {'min_kpps': 10, 'direction':", "port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_bulk_min_bw_and_pps_rule(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION self.min_pps_rule.direction = lib_constants.EGRESS_DIRECTION", "test_update_policy_min_pps_rule_bad_policy(self): _policy = self._get_policy() setattr(_policy, \"rules\", []) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy):", "= self._create_and_extend_port([], []) self.assertIsNone(port.get('resource_request')) def test__extend_port_resource_request_min_bw_non_provider_net(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION port", "= netaddr.EUI(next(net_utils.random_mac_generator(base_mac))) device_owner = device_owner if device_owner else '3' port", "[ mock.call( original_qos, qos, {'id': port1.id, 'device_owner': 'compute:uu:id', 'qos_policy_id': None,", "min_bw_rule_ingress_data = { 'id': uuidutils.generate_uuid(), 'min_kbps': 20, 'direction': lib_constants.INGRESS_DIRECTION} min_pps_rule_ingress_data", "qos_network_policy_id=None, device_owner=None): port_id = port_id if port_id else uuidutils.generate_uuid() base_mac", "as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_no_original_allocation(self): qos1", "payload=events.DBEventPayload( context, states=(original_port, port))) mock_alloc_change.assert_not_called() def test_check_port_for_placement_allocation_change(self): qos1_obj = self._make_qos_policy()", "[{ 'name': 'fake-driver', 'supported_parameters': [{ 'parameter_name': 'min_kpps', 'parameter_type': lib_constants.VALUES_TYPE_RANGE, 'parameter_range':", "self.rpc_push = mock.patch('neutron.api.rpc.handlers.resources_rpc' '.ResourcesPushRpcApi.push').start() self.ctxt = context.Context('fake_user', 'fake_tenant') self.admin_ctxt =", "'direction': 'any'}, } self.policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) self.rule =", "self.qos_plugin.update_policy( self.ctxt, self.policy.id, {'policy': fields}) self._validate_driver_params('update_policy', self.ctxt) policy_update_mock_call = mock.call.update()", "test_create_policy_min_pps_rule(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.min_pps_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy):", "def test_delete_policy_min_pps_rule(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.min_pps_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "mock.patch.object( self.qos_plugin.driver_manager, \"validate_rule_for_network\", return_value=True ): self.policy.rules = [self.rule] try: self.qos_plugin.validate_policy_for_network(", "self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id) def test_get_policy_bandwidth_limit_rules_for_policy_with_filters(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.'", "policy_delete_mock_call = mock.call.delete() delete_precommit_mock_call = mock.call.driver.call( 'delete_policy_precommit', self.ctxt, mock.ANY) delete_mock_call", "min_bw_rule_ingress = rule_object.QosMinimumBandwidthRule( self.ctxt, **min_bw_rule_ingress_data) min_pps_rule_ingress = rule_object.QosMinimumPacketRateRule( self.ctxt, **min_pps_rule_ingress_data)", "[self.rule] self.assertRaises( qos_exc.QosRuleNotSupported, self.qos_plugin.validate_policy_for_port, self.ctxt, self.policy, port) def test_validate_policy_for_port_all_rules_valid(self): port", "port2.update() with mock.patch.object( self.qos_plugin, '_change_placement_allocation') as mock_alloc_change: def fake_change_placement_allocation(orig_policy, policy,", "return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt, self.policy.id, self.rule_data) def test_update_policy_min_pps_rule(self): _policy", "= [] if desired_min_kbps: desired_qos.rules += [self._make_qos_minbw_rule( desired_qos.id, min_kbps=desired_min_kbps)] if", "ports = self._create_and_extend_ports([], [self.min_pps_rule]) for port in ports: self.assertEqual( 1,", "\"id\": network_id, qos_consts.QOS_POLICY_ID: original_policy_id } } port_mock_with_own_policy = mock.MagicMock( id=uuidutils.generate_uuid(),", "= self._get_policy() setattr(_policy, \"rules\", [self.min_pps_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.update_policy_minimum_packet_rate_rule( self.ctxt,", "= 'ml2' service_plugins = {'qos_plugin_name': SERVICE_PLUGIN_KLASS} ext_mgr = QoSRuleAliasTestExtensionManager() super(TestQoSRuleAlias,", "= port_id if port_id else uuidutils.generate_uuid() base_mac = ['aa', 'bb',", "else None port_qos_id = port_qos_obj.id if port_qos else None network", "test_change_placement_allocation_decrease_min_pps(self): original_qos = self._make_qos_policy() desired_qos = self._make_qos_policy() orig_port, port =", "[port_mock_with_own_policy, port_mock_without_own_policy] policy_mock = mock.MagicMock(id=policy_id) admin_ctxt = mock.Mock() with mock.patch(", "'neutron.objects.qos.policy.QosPolicy.get_object', return_value=policy_mock ) as get_policy, mock.patch.object( self.qos_plugin, \"validate_policy_for_port\" ) as", "test_update_policy_rule_check_rule_minbw_gr_than_bwlimit(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.min_bw_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy):", "def test_create_min_pps_rule_on_bound_port(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.min_pps_rule]) segment =", "\"qos_network_policy_id\": qos_network_policy_id}, \"port\": {\"id\": port.id, \"qos_policy_id\": qos2_id}} def test_check_port_for_placement_allocation_change_no_qos_change(self): qos1_obj", "'ml2' service_plugins = {'qos_plugin_name': SERVICE_PLUGIN_KLASS} ext_mgr = QoSRuleAliasTestExtensionManager() super(TestQoSRuleAlias, self).setUp(plugin=plugin,", "port = self._prepare_port_for_placement_allocation( qos1, qos2, original_min_kpps=1000, desired_min_kpps=1000) for rule in", "def test_delete_policy_packet_rate_limit_rule(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy):", "test_create_policy_rule_check_rule_min_pps_direction_conflict(self): _policy = self._get_policy() self.rule_data['minimum_packet_rate_rule']['direction'] = 'any' setattr(_policy, \"rules\", [self.min_pps_rule])", "payload=events.DBEventPayload( self.context, resource_id=kwargs['port']['id'],)) qos_policy = None if port_qos: qos_policy =", "qos2, original_min_kbps=1000, desired_min_kbps=2000, is_sriov=True) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(", "test_create_policy_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.create_policy_packet_rate_limit_rule, self.ctxt, self.policy.id, self.rule_data)", "self.dscp_rule.id, self.policy.id) def test_get_policy_dscp_marking_rules_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_dscp_marking_rules,", "qos2=None) kwargs['port'].pop('qos_policy_id') context = kwargs['context'] original_port = kwargs['original_port'] port =", "id=policy_id) validate_policy_for_port.assert_called_once_with( self.ctxt, policy_mock, port_mock) def test_validate_update_port_callback_policy_changed(self): self._test_validate_update_port_callback( policy_id=uuidutils.generate_uuid()) def", "lib_constants.EGRESS_DIRECTION self.min_pps_rule.direction = lib_constants.EGRESS_DIRECTION request_groups_uuids = ['fake_uuid0', 'fake_uuid1'] min_bw_rule_ingress_data =", "self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_minimum_bandwidth_rule, self.ctxt, self.rule.id, self.policy.id) def test_get_policy_minimum_bandwidth_rules_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.delete_policy_packet_rate_limit_rule, self.ctxt, self.pps_rule.id, _policy.id) def test_get_policy_packet_rate_limit_rule(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "self.assertRaises( NotImplementedError, self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt, _policy.id, self.rule_data) def test_create_min_pps_rule_on_unbound_port(self): _policy =", "{ 'bandwidth_limit_rule': { 'max_kbps': 5000, 'direction': self.rule.direction } } with", "self.assertIn('pci_slot', port['binding:profile']) self.assertIn('pci_vendor_info', port['binding:profile']) self.assertIn('physical_network', port['binding:profile']) def test_change_placement_allocation_increase(self): qos1 =", "mock.call.create() update_precommit_mock_call = mock.call.driver.call( 'update_policy_precommit', self.ctxt, mock.ANY) update_mock_call = mock.call.driver.call(", "qos2, desired_min_kbps=1000, original_min_kpps=500, desired_min_kpps=1000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(qos1,", "'port': {'id': uuidutils.generate_uuid(), 'network_id': network_id} } if has_qos_policy: self.port_data['port']['qos_policy_id'] =", "uuidutils.generate_uuid()} with mock.patch.object( self.qos_plugin.driver_manager, \"validate_rule_for_port\", return_value=False ): self.policy.rules = [self.rule]", "side_effect=request_groups_uuids): return qos_plugin.QoSPlugin._extend_port_resource_request_bulk( ports_res, None) def test__extend_port_resource_request_min_bw_rule(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION", "bw_limit_rule = rule_object.QosDscpMarkingRule(dscp_mark=16) qos2.rules = [bw_limit_rule] orig_port, port = self._prepare_port_for_placement_allocation(qos1,", "network))) self.assertEqual(ml2plugin_mock._make_port_dict.call_count, 2) mock_alloc_change_calls = [ mock.call( original_qos, qos, {'id':", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.update_policy_packet_rate_limit_rule, self.ctxt, self.pps_rule.id, self.policy.id, self.rule_data)", "'direction': 'egress' } }, ] self.rule_data['minimum_packet_rate_rule']['direction'] = 'any' for rule_data", "'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_new_rule_not_min_bw(self):", "states=(original_network, network))) mock_alloc_change.assert_not_called() ml2plugin_mock._make_port_dict.assert_not_called() def test_check_network_for_placement_allocation_change_remove_qos(self): original_qos = self._make_qos_policy() original_network", "'neutron.objects.qos.qos_policy_validator' '.check_min_pps_rule_conflict', return_value=None): self.qos_plugin.create_policy_bandwidth_limit_rule( self.ctxt, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) rule_create_mock_call", "self.ctxt, self.min_bw_rule.id, self.policy.id, self.rule_data) self.mock_qos_load_attr.assert_called_once_with('rules') self._validate_driver_params('update_policy', self.ctxt) self.rule_data['bandwidth_limit_rule']['max_kbps'] = 1", "request = self.new_update_request(resource, data, rule_id, self.fmt) res = request.get_response(self.ext_api) if", "None, {'id': port1.id, 'device_owner': 'compute:uu:id', 'qos_policy_id': None, 'qos_network_policy_id': None}, mock.ANY),", "self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.update_policy_packet_rate_limit_rule, self.ctxt, self.pps_rule.id, self.policy.id, self.rule_data) def test_delete_policy_packet_rate_limit_rule(self): _policy", "request.get_response(self.ext_api) if res.status_int >= webob.exc.HTTPClientError.code: raise webob.exc.HTTPClientError(code=res.status_int) @mock.patch.object(qos_plugin.QoSPlugin, \"update_policy_rule\") def", "except qos_exc.QosRuleNotSupportedByNetwork: self.fail(\"QosRuleNotSupportedByNetwork \" \"exception unexpectedly raised\") def test_create_min_bw_rule_on_bound_port(self): policy", "'fake_uuid1'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_non_min_bw_or_min_pps_rule(self): port = self._create_and_extend_port([], []) self.assertIsNone(port.get('resource_request'))", "as qos_exc from neutron_lib.objects import utils as obj_utils from neutron_lib.plugins", "_pager=mock.ANY, qos_policy_id=self.policy.id, filter='filter_id') def test_get_policy_min_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound,", "self.min_pps_rule.id, self.policy.id) def test_get_policy_min_pps_rules_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_minimum_packet_rate_rules,", "self._make_qos_policy() qos = self._make_qos_policy() original_network = self._make_network(original_qos.id) network = self._make_network(qos.id)", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.update_policy_packet_rate_limit_rule, self.ctxt, self.pps_rule.id, self.policy.id, self.rule_data) def", "network_id, \"vnic_type\": \"normal\", } }, { \"resource_request\": { \"port_id\": uuidutils.generate_uuid(),", "self.policy.id, filters=filters) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id, filter='filter_id') def test_get_policy_min_pps_rule_for_nonexistent_policy(self): with", "port = self._create_and_extend_port([], [self.min_pps_rule]) self.assertEqual( 1, len(port['resource_request']['request_groups']) ) self.assertEqual( 'fake_uuid',", "self.qos_plugin.update_policy_bandwidth_limit_rule( self.ctxt, self.rule.id, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) rule_update_mock_call = mock.call.update()", "self.rule.id, self.policy.id, self.rule_data) @mock.patch.object(rule_object.QosBandwidthLimitRule, 'delete') def test_delete_policy_rule(self, mock_qos_rule_delete): mock_manager =", "as mock_validate_policy: self.qos_plugin._validate_create_port_callback( \"PORT\", \"precommit_create\", \"test_plugin\", payload=events.DBEventPayload( self.context, resource_id=kwargs['port']['id'],)) qos_policy", "'%s/alias-%s-rules' % (qos.ALIAS, rule_type.replace('_', '-')) request = self.new_delete_request(resource, rule_id, self.fmt)", "test_validate_policy_for_port_all_rules_valid(self): port = {'id': uuidutils.generate_uuid()} with mock.patch.object( self.qos_plugin.driver_manager, \"validate_rule_for_port\", return_value=True", "neutron_lib import exceptions as lib_exc from neutron_lib.exceptions import placement as", "@mock.patch( 'neutron.objects.rbac_db.RbacNeutronDbObjectMixin' '.create_rbac_policy') @mock.patch.object(policy_object.QosPolicy, 'update') def test_update_policy(self, mock_qos_policy_update, mock_create_rbac_policy, mock_qos_policy_get):", "'.check_bandwidth_rule_conflict', return_value=None), \\ mock.patch( 'neutron.objects.qos.qos_policy_validator' '.check_min_pps_rule_conflict', return_value=None): self.qos_plugin.create_policy_bandwidth_limit_rule( self.ctxt, self.policy.id,", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_dscp_marking_rule, self.ctxt, self.dscp_rule.id, self.policy.id) def test_get_policy_dscp_marking_rules_for_nonexistent_policy(self):", "rule_object.QosMinimumBandwidthRule( self.ctxt, **min_bw_rule_ingress_data) min_pps_rule_ingress = rule_object.QosMinimumPacketRateRule( self.ctxt, **min_pps_rule_ingress_data) port =", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.qos_plugin.create_policy_bandwidth_limit_rule( self.ctxt, _policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt)", "has_qos_policy=False) self.assertIsNone(port.get('resource_request')) def test__extend_port_resource_request_min_bw_inherited_policy( self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION self.min_bw_rule.qos_policy_id =", "action_index, mock_manager.mock_calls.index(driver_mock_call)) def test_create_policy_packet_rate_limit_rule(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with", "'name': 'test-policy', 'description': 'Test policy description', 'shared': True, 'is_default': False}}", "policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) setattr(_policy, \"rules\", [self.rule]) with mock.patch('neutron.objects.qos.rule.get_rules', return_value=[self.rule]), mock.patch(", "orig_port = {'id': 'u:u', 'device_id': 'i:d', 'binding:profile': {}} port =", "[self.min_pps_rule, min_pps_rule_ingress], request_groups_uuids=request_groups_uuids) self.assertEqual( 2, len(port['resource_request']['request_groups']) ) self.assertIn( { 'id':", "\"get_object\") @mock.patch( 'neutron.objects.rbac_db.RbacNeutronDbObjectMixin' '.create_rbac_policy') @mock.patch.object(policy_object.QosPolicy, 'update') def test_update_policy(self, mock_qos_policy_update, mock_create_rbac_policy,", "network def _test_validate_create_network_callback(self, network_qos=False): net_qos_obj = self._make_qos_policy() net_qos_id = net_qos_obj.id", "use real models as per mocks above. We also need", "[rule2_obj] orig_port = {'id': 'u:u', 'device_id': 'i:d', 'binding:profile': {}} port", "class QoSRuleAliasTestExtensionManager(object): def get_resources(self): return qos_rules_alias.Qos_rules_alias.get_resources() def get_actions(self): return []", "mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1, None, orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_old_rule_not_min_bw(self): qos1", "( pl_exc.PlacementAllocationGenerationConflict( consumer=self.MIN_BW_RP)) self.assertRaises( pl_exc.PlacementAllocationGenerationConflict, self.qos_plugin._change_placement_allocation, qos1, qos2, orig_port, port)", "qos_policy_id=None, port_id=None, qos_network_policy_id=None, device_owner=None): port_id = port_id if port_id else", "= self.qos_plugin.driver_manager.call.call_args[0] self.assertTrue(self.qos_plugin.driver_manager.call.called) self.assertEqual(call_args[0], method_name) self.assertEqual(call_args[1], ctxt) self.assertIsInstance(call_args[2], policy_object.QosPolicy) def", "rule_type_details['drivers']) def test_get_rule_type_as_user(self): self.assertRaises( lib_exc.NotAuthorized, self.qos_plugin.get_rule_type, self.ctxt, qos_consts.RULE_TYPE_BANDWIDTH_LIMIT) def test_get_rule_types(self):", "with mock.patch( 'neutron.objects.qos.rule.QosRule.get_object', return_value=rule ), mock.patch.object(self.qos_plugin, 'get_policy_rule', return_value=rule.to_dict()): self._update_rule(rule_type, rule_id,", "def test_validate_update_port_callback_policy_not_changed(self): policy_id = uuidutils.generate_uuid() self._test_validate_update_port_callback( policy_id=policy_id, original_policy_id=policy_id) def test_validate_update_port_callback_policy_removed(self):", "= { 'minimum_packet_rate_rule': {'min_kpps': 10, 'direction': 'any'} } class TestQosPluginDB(base.BaseQosTestCase):", "ml2plugin_mock, payload=events.DBEventPayload( self.context, states=(original_network, network))) self.assertEqual(ml2plugin_mock._make_port_dict.call_count, 1) mock_alloc_change_calls = [", "'driver') mock_manager.reset_mock() with mock.patch('neutron.objects.qos.qos_policy_validator' '.check_bandwidth_rule_conflict', return_value=None), \\ mock.patch( 'neutron.objects.qos.qos_policy_validator' '.check_min_pps_rule_conflict',", ") as get_policy, mock.patch.object( self.qos_plugin, \"validate_policy_for_network\" ) as validate_policy_for_network, mock.patch.object(", "SERVICE_PLUGIN_KLASS} ext_mgr = QoSRuleAliasTestExtensionManager() super(TestQoSRuleAlias, self).setUp(plugin=plugin, ext_mgr=ext_mgr, service_plugins=service_plugins) self.qos_plugin =", "self.assertTrue( mock_manager.mock_calls.index(policy_update_mock_call) < mock_manager.mock_calls.index(update_precommit_mock_call) < mock_manager.mock_calls.index(update_mock_call)) @mock.patch('neutron.objects.db.api.get_object', return_value=None) @mock.patch.object(policy_object.QosPolicy, 'delete')", "mock.patch.object(policy_object.QosPolicy, 'set_default').start() cfg.CONF.set_override(\"core_plugin\", DB_PLUGIN_KLASS) cfg.CONF.set_override(\"service_plugins\", [\"qos\"]) manager.init() self.qos_plugin = directory.get_plugin(plugins_constants.QOS)", "desired_qos.id, min_kbps=desired_min_kbps)] if desired_min_kpps: desired_qos.rules += [self._make_qos_minpps_rule( desired_qos.id, min_kpps=desired_min_kpps)] binding_prof", "super(TestQoSRuleAlias, self).setUp(plugin=plugin, ext_mgr=ext_mgr, service_plugins=service_plugins) self.qos_plugin = directory.get_plugin(plugins_constants.QOS) self.ctxt = context.Context('fake_user',", "self.ctxt, **self.rule_data['minimum_packet_rate_rule']) def _validate_driver_params(self, method_name, ctxt): call_args = self.qos_plugin.driver_manager.call.call_args[0] self.assertTrue(self.qos_plugin.driver_manager.call.called)", "'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': -500, 'NET_PACKET_RATE_EGR_KILOPACKET_PER_SEC': 1000}, self.MIN_BW_RP: { 'NET_BW_IGR_KILOBIT_PER_SEC': -1000, 'NET_BW_EGR_KILOBIT_PER_SEC': 2000}})", "mock_manager.attach_mock(mock_qos_policy, 'QosPolicy') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() self.qos_plugin.create_policy(self.ctxt, self.policy_data) policy_mock_call = mock.call.QosPolicy().create()", "== original_policy_id: get_port.assert_not_called() get_policy.assert_not_called() validate_policy_for_port.assert_not_called() else: get_port.assert_called_once_with(self.ctxt, id=port_id) get_policy.assert_called_once_with(admin_ctxt, id=policy_id)", "self._test_validate_update_network_callback( policy_id=uuidutils.generate_uuid()) def test_validate_update_network_callback_policy_not_changed(self): policy_id = uuidutils.generate_uuid() self._test_validate_update_network_callback( policy_id=policy_id, original_policy_id=policy_id)", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosDscpMarkingRule.' 'get_objects') as get_objects_mock: filters", "self.pps_rule.id, self.policy.id) self._validate_driver_params('update_policy', self.ctxt) def test_delete_policy_pps_rule_bad_policy(self): _policy = policy_object.QosPolicy( self.ctxt,", "= [ rule_object.QosMinimumPacketRateRule( self.ctxt, **rules_data[0]['minimum_packet_rate_rule']), rule_object.QosMinimumPacketRateRule( self.ctxt, **rules_data[1]['minimum_packet_rate_rule']), ] setattr(_policy,", "def fake_make_port_dict(port): return { 'id': port.id, 'device_owner': port.device_owner, 'qos_policy_id': port.qos_policy_id,", "self.qos_plugin.delete_policy_minimum_packet_rate_rule, self.ctxt, self.min_pps_rule.id, _policy.id) def test_delete_policy_min_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises(", "self.ctxt, self.pps_rule.id, _policy.id) def test_get_policy_packet_rate_limit_rule(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.'", "port))) mock_alloc_change.assert_called_once_with( qos_network, desired_qos, kwargs['original_port'], port) def test_check_network_for_placement_allocation_change_no_qos_change(self): qos1 =", "\"rules\", [self.dscp_rule]) self.qos_plugin.update_policy_dscp_marking_rule( self.ctxt, self.dscp_rule.id, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def", "def test_delete_policy_min_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.delete_policy_minimum_packet_rate_rule, self.ctxt, self.min_pps_rule.id,", "'before_update', 'test_plugin', payload=events.DBEventPayload( context, states=(original_port, port))) mock_alloc_change.assert_called_once_with( qos1_obj, qos2_obj, kwargs['original_port'],", "def test_delete_policy(self, mock_qos_policy_delete, mock_api_get_policy): mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_policy_delete, 'delete') mock_manager.attach_mock(self.qos_plugin.driver_manager,", "'8bf8eb46-160e-11ec-8024-9f96be32099d' # uuid -v5 f02f160e-1612-11ec-b2b8-bf60ab98186c # 8bf8eb46-160e-11ec-8024-9f96be32099d MIN_BW_REQUEST_GROUP_UUID = 'c8bc1b27-59a1-5135-aa33-aeecad6093f4'", "from neutron_lib import context from neutron_lib import exceptions as lib_exc", "[ port for port in network_ports if port.qos_policy_id is None]", "self.port) def _create_and_extend_ports(self, min_bw_rules, min_pps_rules=None, physical_network='public', request_groups_uuids=None): network_id = uuidutils.generate_uuid()", "kwargs = { \"port\": { \"id\": port_id, qos_consts.QOS_POLICY_ID: policy_id },", "= self._make_qos_policy() original_network = self._make_network(original_qos.id) network = self._make_network(qos.id) ml2plugin_mock =", "import net as net_utils import os_resource_classes as orc from oslo_config", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_bandwidth_limit_rules, self.ctxt, self.policy.id) def test_create_policy_dscp_marking_rule(self):", "= self._get_policy() setattr(_policy, \"rules\", [self.min_bw_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj:", "self.ctxt, self.policy.id, self.rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_rule_check_rule_minbw_gr_than_bwlimit(self): _policy = self._get_policy()", "'min_kbps': 10}, 'packet_rate_limit_rule': { 'id': uuidutils.generate_uuid(), 'max_kpps': 20, 'max_burst_kpps': 130},", "TestQoSRuleAliasMinimumPacketRate(TestQoSRuleAlias): def setUp(self): # Remove MissingAuthPlugin exception from logs self.patch_notifier", "= self._make_network(qos_policy_id=qos_network_policy_id) port = self._make_port( network.id, qos_policy_id=qos1_id, port_id=TestQosPluginDB.PORT_ID) return {\"context\":", "side_effect=request_groups_uuids): return qos_plugin.QoSPlugin._extend_port_resource_request( port_res, self.port) def _create_and_extend_ports(self, min_bw_rules, min_pps_rules=None, physical_network='public',", "self._make_qos_policy() kwargs = self._prepare_for_port_placement_allocation_change( qos1=None, qos2=desired_qos, qos_network_policy=qos_network) context = kwargs['context']", "self.qos_plugin._change_placement_allocation( qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={ self.MIN_PPS_RP: {", "mock.call.delete() update_precommit_mock_call = mock.call.driver.call( 'update_policy_precommit', self.ctxt, mock.ANY) update_mock_call = mock.call.driver.call(", "'direction': 'egress' } }, ] for new_rule_data in rules: with", "self.policy_data['policy']) self.qos_plugin.update_policy( self.ctxt, self.policy.id, {'policy': fields}) self._validate_driver_params('update_policy', self.ctxt) policy_update_mock_call =", "res.status_int >= webob.exc.HTTPClientError.code: raise webob.exc.HTTPClientError(code=res.status_int) @mock.patch.object(qos_plugin.QoSPlugin, \"update_policy_rule\") def test_update_rule(self, update_policy_rule_mock):", "return_value=policy), \\ mock.patch( 'neutron.objects.network.Network.get_object', return_value=net), \\ mock.patch.object( self.qos_plugin, '_get_ports_with_policy', return_value=[port]):", "10}, port['resource_request']['request_groups'][0]['resources'], ) self.assertEqual( ['fake_uuid'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_bulk_min_bw_rule(self): self.min_bw_rule.direction", "qos_policy_id=policy_id, direction=direction, min_kbps=min_kbps, id=rule_id) qos_rule.create() return qos_rule def _make_qos_minpps_rule(self, policy_id,", "mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy), \\ mock.patch( 'neutron.objects.network.Network.get_object', return_value=net), \\ mock.patch.object( self.qos_plugin,", "neutron.objects import network as network_object from neutron.objects import ports as", "res.status_int >= webob.exc.HTTPClientError.code: raise webob.exc.HTTPClientError(code=res.status_int) return self.deserialize(self.fmt, res) def _delete_rule(self,", "'995008f4-f120-547a-b051-428b89076067' MIN_PPS_RP = 'e16161f4-1626-11ec-a5a2-1fc9396e27cc' def setUp(self): super(TestQosPluginDB, self).setUp() self.setup_coreplugin(load_plugins=False) cfg.CONF.set_override(\"core_plugin\",", "plugin = 'ml2' service_plugins = {'qos_plugin_name': SERVICE_PLUGIN_KLASS} ext_mgr = QoSRuleAliasTestExtensionManager()", "mock_qos_policy_get.return_value = _policy mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_rule_create, 'create') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver')", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_minimum_bandwidth_rule, self.ctxt, self.rule.id, self.policy.id) def", "import qos as qos_exc from neutron_lib.objects import utils as obj_utils", "def test_get_rule_type(self): admin_ctxt = context.get_admin_context() drivers_details = [{ 'name': 'fake-driver',", "uuidutils.generate_uuid(), 'name': 'test-policy', 'description': 'Test policy description', 'shared': True, 'is_default':", "\\ mock.patch( 'neutron.objects.network.Network.get_object', return_value=net), \\ mock.patch.object( self.qos_plugin, '_get_ports_with_policy', return_value=[port]): try:", "self._validate_driver_params('update_policy', self.ctxt) self.rule_data['minimum_bandwidth_rule']['min_kbps'] = 1000 with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.assertRaises( qos_exc.QoSRuleParameterConflict,", "= { 'bandwidth_limit': rule_object.QosBandwidthLimitRule, 'dscp_marking': rule_object.QosDscpMarkingRule, 'minimum_bandwidth': rule_object.QosMinimumBandwidthRule } self.qos_policy_id", "2000}}) def test_change_placement_allocation_change_dir_min_pps_ingress_to_any( self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy()", "original_qos, desired_qos=None, qos_network_policy=None, original_min_kbps=None, desired_min_kbps=None, original_min_kpps=None, desired_min_kpps=None, is_sriov=False): kwargs =", "qos1_obj = self._make_qos_policy() kwargs = self._prepare_for_port_placement_allocation_change( qos1=qos1_obj, qos2=None) context =", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt, self.policy.id, self.rule_data)", "mock.patch( 'uuid.uuid5', return_value='fake_uuid', side_effect=request_groups_uuids): return qos_plugin.QoSPlugin._extend_port_resource_request_bulk( ports_res, None) def test__extend_port_resource_request_min_bw_rule(self):", "id=_policy.id) def test_create_policy_rule_check_rule_bwlimit_less_than_minbw(self): _policy = self._get_policy() self.rule_data['bandwidth_limit_rule']['max_kbps'] = 1 setattr(_policy,", "{orc.NET_BW_EGR_KILOBIT_PER_SEC: 10}, port['resource_request']['request_groups'][0]['resources'], ) self.assertEqual( ['fake_uuid'], port['resource_request']['same_subtree'], ) def test_get_ports_with_policy(self):", "= network_object.NetworkSegment( physical_network='fake physnet') net = network_object.Network( self.ctxt, segments=[segment]) port", "def test_update_policy_rule(self, mock_qos_rule_update): mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_rule_update, 'update') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver')", "10, 'direction': 'egress' } }, ] for new_rule_data in rules:", "self._make_network(qos_policy_id=qos_network_policy_id) port = self._make_port( network.id, qos_policy_id=qos1_id, port_id=TestQosPluginDB.PORT_ID) return {\"context\": self.context,", "{ \"context\": self.ctxt, \"network\": { \"id\": network_id, qos_consts.QOS_POLICY_ID: policy_id },", "lib_exc from neutron_lib.exceptions import placement as pl_exc from neutron_lib.exceptions import", "You may obtain # a copy of the License at", "mock_qos_get_obj: self.assertRaises( qos_exc.QoSRulesConflict, self.qos_plugin.create_policy_bandwidth_limit_rule, self.ctxt, _policy.id, new_rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) @mock.patch.object(rule_object.QosBandwidthLimitRule,", "return_value=_policy): setattr(_policy, \"rules\", [self.rule]) self.qos_plugin.delete_policy_bandwidth_limit_rule( self.ctxt, self.rule.id, _policy.id) self._validate_driver_params('update_policy', self.ctxt)", "id=self.rule.id) def test_get_policy_bandwidth_limit_rules_for_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosBandwidthLimitRule.' 'get_objects')", "rule1_obj = self._make_qos_minbw_rule(qos1.id, min_kbps=500) qos1.rules = [rule1_obj] qos2 = self._make_qos_policy()", "mock.patch('neutron.objects.qos.rule.' 'QosMinimumBandwidthRule.' 'get_objects') as get_objects_mock: self.qos_plugin.get_policy_minimum_bandwidth_rules( self.ctxt, self.policy.id) get_objects_mock.assert_called_once_with( self.ctxt,", "context.get_admin_context() drivers_details = [{ 'name': 'fake-driver', 'supported_parameters': [{ 'parameter_name': 'max_kpps',", "setattr(_policy, \"rules\", []) self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.update_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, self.policy.id, self.rule_data)", "qos_network_policy=None): qos1_id = qos1.id if qos1 else None qos2_id =", "def test_show_rule(self, get_policy_rule_mock): calls = [] for rule_type, rule_object_class in", "return_value=_policy) as mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt, self.policy.id, new_rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id)", "kwargs = self._prepare_for_port_placement_allocation_change( qos1=qos1_obj, qos2=None) context = kwargs['context'] original_port =", "original_qos or qos_network_policy qos.rules = [] allocation = {} if", "'9416c220-160a-11ec-ba3d-474633eb825c', } port = {} with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc:", "mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.assertRaises(NotImplementedError, self.qos_plugin._change_placement_allocation, qos1, qos2, orig_port, port)", "test_get_policy_packet_rate_limit_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_packet_rate_limit_rule, self.ctxt, self.pps_rule.id, self.policy.id)", "), mock.patch.object(self.qos_plugin, 'get_policy_rule', return_value=rule.to_dict()): self._delete_rule(rule_type, rule_id) calls.append(mock.call(mock.ANY, rule_object_class, rule_id, self.qos_policy_id))", "self.policy.id) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id) def test_get_policy_dscp_marking_rules_for_policy_with_filters(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy):", "return_value=_policy): self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.delete_policy_minimum_packet_rate_rule, self.ctxt, self.min_pps_rule.id, _policy.id) def test_delete_policy_min_pps_rule_for_nonexistent_policy(self): with", "qos.rules = [] allocation = {} if original_min_kbps: qos.rules +=", "id=_policy.id) def test_update_policy_min_pps_rule_bad_policy(self): _policy = self._get_policy() setattr(_policy, \"rules\", []) with", "policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", []) self.assertRaises(", "rule_type.replace('_', '-')) request = self.new_update_request(resource, data, rule_id, self.fmt) res =", "self.assertDictEqual(port1.bindings[0].profile, {}) def test_check_network_for_placement_allocation_change(self): original_qos = self._make_qos_policy() qos = self._make_qos_policy()", "mock_alloc_change.assert_called_once_with( qos1_obj, None, kwargs['original_port'], port) def test_check_port_for_placement_allocation_change_no_qos_update(self): qos1_obj = self._make_qos_policy()", "test_create_policy_rule_check_rule_bwlimit_less_than_minbw(self): _policy = self._get_policy() self.rule_data['bandwidth_limit_rule']['max_kbps'] = 1 setattr(_policy, \"rules\", [self.min_bw_rule])", "self._make_port(network.id, qos_policy_id=port_qos_id) kwargs = {\"context\": self.context, \"port\": {\"id\": port.id}} with", "= {} with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(qos1, qos2, orig_port,", "self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_minimum_bandwidth_rules, self.ctxt, self.policy.id) def test_create_policy_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None):", "mock.ANY) self.assertTrue( mock_manager.mock_calls.index(rule_delete_mock_call) < mock_manager.mock_calls.index(update_precommit_mock_call) < mock_manager.mock_calls.index(update_mock_call)) def test_delete_policy_rule_bad_policy(self): _policy", "as ports_object from neutron.objects.qos import policy as policy_object from neutron.objects.qos", "with mock.patch('neutron.objects.qos.rule.' 'QosPacketRateLimitRule.' 'get_object') as get_object_mock: self.qos_plugin.get_policy_packet_rate_limit_rule( self.ctxt, self.pps_rule.id, self.policy.id)", "network_id = uuidutils.generate_uuid() kwargs = { \"context\": self.ctxt, \"network\": {", "desired_qos, original_min_kpps=2000, desired_min_kpps=1000, is_sriov=True) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(", "\"PORT\", \"precommit_update\", \"test_plugin\", payload=events.DBEventPayload( self.ctxt, desired_state=kwargs['port'], states=(kwargs['original_port'],))) if policy_id is", "{ 'minimum_packet_rate_rule': { 'id': uuidutils.generate_uuid(), 'min_kpps': 1234, 'direction': self.min_pps_rule.direction, },", "\"precommit_create\", \"test_plugin\", payload=events.DBEventPayload( self.context, resource_id=kwargs['network']['id'],)) qos_policy = None if network_qos:", "rule2_obj = self._make_qos_minbw_rule(qos2.id, min_kbps=1000) qos2.rules = [rule2_obj] orig_port = {'id':", "orig_port = kwargs['original_port'] qos = original_qos or qos_network_policy qos.rules =", "mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_new_rule_not_min_bw(self): qos1 =", "'.ResourcesPushRpcApi.push').start() self.ctxt = context.Context('fake_user', 'fake_tenant') self.admin_ctxt = context.get_admin_context() self.policy_data =", "self._make_qos_policy() port_qos = self._make_qos_policy() original_network = self._make_network(original_qos.id) network = self._make_network(qos.id)", "self._prepare_port_for_placement_allocation( qos1, qos2, original_min_kbps=1000, desired_min_kbps=2000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc:", "port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_new_policy_empty(self): qos1 = self._make_qos_policy() orig_port, port =", "self.min_bw_rule.id, self.policy.id, self.rule_data) def test_update_policy_rule_check_rule_minbw_gr_than_bwlimit(self): _policy = self._get_policy() setattr(_policy, \"rules\",", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt, self.policy.id, new_rule_data)", "import webob.exc from neutron.exceptions import qos as neutron_qos_exc from neutron.extensions", "setUp(self): super(TestQosPluginDB, self).setUp() self.setup_coreplugin(load_plugins=False) cfg.CONF.set_override(\"core_plugin\", DB_PLUGIN_KLASS) cfg.CONF.set_override(\"service_plugins\", [\"qos\"]) manager.init() self.qos_plugin", "self.policy, port) except qos_exc.QosRuleNotSupported: self.fail(\"QosRuleNotSupported exception unexpectedly raised\") def test_validate_policy_for_network(self):", "'bandwidth_limit_rule': {'id': uuidutils.generate_uuid(), 'max_kbps': 100, 'max_burst_kbps': 150}, 'dscp_marking_rule': {'id': uuidutils.generate_uuid(),", "admin_ctxt, qos_consts.RULE_TYPE_MINIMUM_PACKET_RATE) self.assertEqual( qos_consts.RULE_TYPE_MINIMUM_PACKET_RATE, rule_type_details['type']) self.assertEqual( drivers_details, rule_type_details['drivers']) def test_get_min_pps_rule_type_as_user(self):", "port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_update_conflict(self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy()", "orc.NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC: 20, }, }, port['resource_request']['request_groups'] ) self.assertEqual( ['fake_uuid0', 'fake_uuid1'], port['resource_request']['same_subtree'],", "= [rule2_obj] orig_port = {'id': 'u:u', 'device_id': 'i:d', 'binding:profile': {}}", "{ 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': -2000}}) def test_change_placement_allocation_no_min_bw(self): qos1 = self._make_qos_policy() qos2 =", "description', 'shared': True, 'is_default': False}} policy_details = {'id': policy_id, 'project_id':", "context, states=(original_port, port))) mock_alloc_change.assert_called_once_with( qos1_obj, qos2_obj, kwargs['original_port'], port) def test_check_port_for_placement_allocation_change_no_new_policy(self):", "def test_create_policy_rule_check_rule_min_pps_direction_conflict(self): _policy = self._get_policy() self.rule_data['minimum_packet_rate_rule']['direction'] = 'any' setattr(_policy, \"rules\",", "network_id=network.id, qos_policy_id=None, device_owner='compute:uu:id') port2_binding = ports_object.PortBinding( self.context, port_id=port2.id, host='fake_host2', vnic_type='fake_vnic_type',", "rule_cls_mock, self.rule.id, self.policy.id, {'fake_rule': {}}], 'delete': [self.ctxt, rule_cls_mock, self.rule.id, self.policy.id]}", "'filter_id'} self.qos_plugin.get_policy_packet_rate_limit_rules( self.ctxt, self.policy.id, filters=filters) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id, filter='filter_id')", "qos_consts.RULE_TYPE_MINIMUM_PACKET_RATE, rule_type_details['type']) self.assertEqual( drivers_details, rule_type_details['drivers']) def test_get_min_pps_rule_type_as_user(self): self.assertRaises( lib_exc.NotAuthorized, self.qos_plugin.get_rule_type,", "as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_update_conflict(self):", "resource = '%s/alias-%s-rules' % (qos.ALIAS, rule_type.replace('_', '-')) request = self.new_delete_request(resource,", "self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(rule_update_mock_call) < mock_manager.mock_calls.index(update_precommit_mock_call) < mock_manager.mock_calls.index(update_mock_call)) def test_update_policy_rule_check_rule_min_less_than_max(self):", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosPacketRateLimitRule.' 'get_objects') as get_objects_mock: filters =", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", [self.dscp_rule]) self.qos_plugin.delete_policy_dscp_marking_rule( self.ctxt, self.dscp_rule.id, self.policy.id) self._validate_driver_params('update_policy',", "with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1, qos2, orig_port, port)", "'update') def test_update_policy_rule(self, mock_qos_rule_update): mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_rule_update, 'update') mock_manager.attach_mock(self.qos_plugin.driver_manager,", "rule_type_details = self.qos_plugin.get_rule_type( admin_ctxt, qos_consts.RULE_TYPE_MINIMUM_PACKET_RATE) self.assertEqual( qos_consts.RULE_TYPE_MINIMUM_PACKET_RATE, rule_type_details['type']) self.assertEqual( drivers_details,", "mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_not_called()", "filter='filter_id') def test_get_policy_packet_rate_limit_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_packet_rate_limit_rule, self.ctxt,", "def test_delete_policy_min_pps_rule_bad_policy(self): _policy = self._get_policy() setattr(_policy, \"rules\", []) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "'min_kpps': 10, 'direction': 'egress' } }, ] for new_rule_data in", "drivers_details = [{ 'name': 'fake-driver', 'supported_parameters': [{ 'parameter_name': 'max_kpps', 'parameter_type':", "{ 'id': uuidutils.generate_uuid(), 'min_kpps': 10, 'direction': 'ingress' } }, {", "software # distributed under the License is distributed on an", "(the \"License\"); you may # not use this file except", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumPacketRateRule.' 'get_object') as get_object_mock: self.qos_plugin.get_policy_minimum_packet_rate_rule( self.ctxt,", "qos_exc.QosPolicyNotFound, self.qos_plugin.create_policy_packet_rate_limit_rule, self.ctxt, self.policy.id, self.rule_data) def test_update_policy_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None):", "= '995008f4-f120-547a-b051-428b89076067' MIN_PPS_RP = 'e16161f4-1626-11ec-a5a2-1fc9396e27cc' def setUp(self): super(TestQosPluginDB, self).setUp() self.setup_coreplugin(load_plugins=False)", "kwargs = self._prepare_for_port_placement_allocation_change( qos1=None, qos2=desired_qos, qos_network_policy=qos_network) context = kwargs['context'] original_port", "desired_qos = self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation( original_qos, desired_qos, original_min_kbps=2000,", "qos2 = self._make_qos_policy() bw_limit_rule = rule_object.QosDscpMarkingRule(dscp_mark=16) orig_port, port = self._prepare_port_for_placement_allocation(", "filters = {'filter': 'filter_id'} self.qos_plugin.get_policy_packet_rate_limit_rules( self.ctxt, self.policy.id, filters=filters) get_objects_mock.assert_called_once_with( self.ctxt,", "= ports_object.Port( self.ctxt, **self.port_data['port']) port_res = {\"binding:vnic_type\": \"normal\"} segment_mock =", "mock.patch( 'uuid.uuid5', return_value='fake_uuid', side_effect=request_groups_uuids): return qos_plugin.QoSPlugin._extend_port_resource_request( port_res, self.port) def _create_and_extend_ports(self,", "self.qos_plugin._check_port_for_placement_allocation_change( 'PORT', 'before_update', 'test_plugin', payload=events.DBEventPayload( context, states=(original_port, port))) mock_alloc_change.assert_called_once_with( qos_network,", "mock.patch.object( qos_plugin.QoSPlugin, \"supported_rule_type_details\", return_value=drivers_details ): rule_type_details = self.qos_plugin.get_rule_type( admin_ctxt, qos_consts.RULE_TYPE_BANDWIDTH_LIMIT)", "port1_binding.create() port1.bindings = [port1_binding] port1.update() with mock.patch.object( self.qos_plugin, '_change_placement_allocation') as", "TestQosPluginDB.MIN_BW_RP}) if original_min_kpps: qos.rules += [self._make_qos_minpps_rule( qos.id, min_kpps=original_min_kpps, rule_id=TestQosPluginDB.QOS_MIN_PPS_RULE_ID)] allocation.update(", "[]) self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.update_policy_packet_rate_limit_rule, self.ctxt, self.pps_rule.id, self.policy.id, self.rule_data) def test_delete_policy_packet_rate_limit_rule(self):", "'_get_ports_with_policy', return_value=[port]): try: self.qos_plugin.create_policy_minimum_bandwidth_rule( self.ctxt, policy.id, self.rule_data) except NotImplementedError: self.fail()", "rules_data = [ { 'minimum_packet_rate_rule': { 'id': uuidutils.generate_uuid(), 'min_kpps': 10,", "uuidutils.generate_uuid(), 'network_id': network_id} } if has_qos_policy: self.port_data['port']['qos_policy_id'] = self.policy.id elif", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", [self.pps_rule]) self.qos_plugin.update_policy_packet_rate_limit_rule( self.ctxt, self.pps_rule.id, self.policy.id,", "self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.update_policy_minimum_packet_rate_rule, self.ctxt, self.min_pps_rule.id, self.policy.id, self.rule_data) def test_update_policy_min_pps_rule_for_nonexistent_policy(self): with", "policy_id, direction='ingress', min_kbps=1000, rule_id=None): rule_id = rule_id if rule_id else", "as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_new_policy_empty(self): qos1", "qos_rule = rule_object.QosMinimumBandwidthRule( self.context, project_id=self.project_id, qos_policy_id=policy_id, direction=direction, min_kbps=min_kbps, id=rule_id) qos_rule.create()", "filters = {'type': 'type_id'} with mock.patch.object(qos_plugin.QoSPlugin, 'supported_rule_types', return_value=qos_consts.VALID_RULE_TYPES): types =", ") self.assertEqual( {orc.NET_BW_EGR_KILOBIT_PER_SEC: 10}, port['resource_request']['request_groups'][0]['resources'], ) self.assertEqual( ['fake_uuid'], port['resource_request']['same_subtree'], )", "mock.call.driver.call('update_policy', self.ctxt, mock.ANY) if rule_mock_call in mock_manager.mock_calls: action_index = mock_manager.mock_calls.index(rule_mock_call)", "lib_constants.EGRESS_DIRECTION request_groups_uuids = ['fake_uuid0', 'fake_uuid1'] min_bw_rule_ingress_data = { 'id': uuidutils.generate_uuid(),", "res) def _show_rule(self, rule_type, rule_id): resource = '%s/alias-%s-rules' % (qos.ALIAS,", "import constants as plugins_constants from neutron_lib.plugins import directory from neutron_lib.services.qos", "filters = {'filter': 'filter_id'} self.qos_plugin.get_policy_minimum_packet_rate_rules( self.ctxt, self.policy.id, filters=filters) get_objects_mock.assert_called_once_with( self.ctxt,", "= self._make_qos_policy() qos2_obj = self._make_qos_policy() kwargs = self._prepare_for_port_placement_allocation_change( qos1=qos1_obj, qos2=qos2_obj)", "10, 'direction': 'any'} } class TestQosPluginDB(base.BaseQosTestCase): PORT_ID = 'f02f160e-1612-11ec-b2b8-bf60ab98186c' QOS_MIN_BW_RULE_ID", "uuidutils import webob.exc from neutron.exceptions import qos as neutron_qos_exc from", "[self.min_bw_rule] segment = network_object.NetworkSegment( physical_network='fake physnet') net = network_object.Network( self.ctxt,", "original_min_kbps: qos.rules += [self._make_qos_minbw_rule( qos.id, min_kbps=original_min_kbps, rule_id=TestQosPluginDB.QOS_MIN_BW_RULE_ID)] allocation.update( {TestQosPluginDB.MIN_BW_REQUEST_GROUP_UUID: TestQosPluginDB.MIN_BW_RP})", "mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() with mock.patch('neutron.objects.qos.qos_policy_validator' '.check_bandwidth_rule_conflict', return_value=None), \\ mock.patch( 'neutron.objects.qos.qos_policy_validator'", "= { 'port': {'id': uuidutils.generate_uuid(), 'network_id': network_id} } if has_qos_policy:", "\"rules\", [min_pps_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt,", "return_value=_policy) as mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt, self.policy.id, self.rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id)", "self.ctxt, self.rule.id, self.policy.id, self.rule_data) self.mock_qos_load_attr.assert_called_once_with('rules') self._validate_driver_params('update_policy', self.ctxt) self.rule_data['minimum_bandwidth_rule']['min_kbps'] = 1000", "'Test policy description', 'shared': True, 'is_default': False}} self.rule_data = {", "import test_db_base_plugin_v2 from neutron.tests.unit.services.qos import base DB_PLUGIN_KLASS = 'neutron.db.db_base_plugin_v2.NeutronDbPluginV2' SERVICE_PLUGIN_KLASS", "'max_kbps', 'parameter_type': lib_constants.VALUES_TYPE_RANGE, 'parameter_range': {'start': 0, 'end': 100} }] }]", "\\ mock.patch.object( self.qos_plugin, '_get_ports_with_policy', return_value=[port]): self.assertRaises( NotImplementedError, self.qos_plugin.create_policy_minimum_bandwidth_rule, self.ctxt, policy.id,", "\"rules\", [self.min_pps_rule]) segment = network_object.NetworkSegment( physical_network='fake physnet') net = network_object.Network(", "'QosPolicy') mock_manager.attach_mock(port_mock, 'Port') mock_manager.attach_mock(rule_cls_mock, 'RuleCls') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') for action, arguments", "overwritten QoS policy self._make_port(network_id=network.id, qos_policy_id=port_qos.id, device_owner='compute:uu:id') ml2plugin_mock = mock.MagicMock() with", "self.context, project_id=self.project_id, shared=False, is_default=False) qos_policy.create() return qos_policy def _make_qos_minbw_rule(self, policy_id,", "test_check_network_for_placement_allocation_change_no_qos_change(self): qos1 = self._make_qos_policy() original_network = self._make_network(qos1.id) network = original_network", "**data) with mock.patch('neutron.objects.qos.rule.QosRule.get_object', return_value=rule): self._show_rule(rule_type, rule_id) calls.append(mock.call(mock.ANY, rule_object_class, rule_id, self.qos_policy_id))", "desired_state=kwargs['port'], states=(kwargs['original_port'],))) if policy_id is None or policy_id == original_policy_id:", "mock_create_rbac_policy): mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_policy, 'QosPolicy') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() self.qos_plugin.create_policy(self.ctxt,", "'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( original_qos, desired_qos, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id',", "from neutron_lib.exceptions import placement as pl_exc from neutron_lib.exceptions import qos", "self.rule_data) self.mock_qos_load_attr.assert_called_once_with('rules') self._validate_driver_params('update_policy', self.ctxt) def test_update_policy_rule_check_rule_bwlimit_less_than_minbw(self): _policy = self._get_policy() setattr(_policy,", "self.assertRaises(AttributeError, getattr, self.qos_plugin, 'create_policy_bandwidth_limit_rules') def test_get_rule_type(self): admin_ctxt = context.get_admin_context() drivers_details", "as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_new_rule_not_min_bw(self): qos1", "mock.patch('neutron.objects.qos.rule.' 'QosDscpMarkingRule.' 'get_objects') as get_objects_mock: self.qos_plugin.get_policy_dscp_marking_rules( self.ctxt, self.policy.id) get_objects_mock.assert_called_once_with( self.ctxt,", "self.min_pps_rule.id, _policy.id) def test_delete_policy_min_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.delete_policy_minimum_packet_rate_rule,", "'-')) request = self.new_update_request(resource, data, rule_id, self.fmt) res = request.get_response(self.ext_api)", "rule_mock_call = getattr(mock.call.RuleCls(), action)() driver_mock_call = mock.call.driver.call('update_policy', self.ctxt, mock.ANY) if", "_policy.id, new_rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_min_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises(", "port2.bindings = [port2_binding] port2.update() with mock.patch.object( self.qos_plugin, '_change_placement_allocation') as mock_alloc_change:", "test_get_policy_packet_rate_limit_rules_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_packet_rate_limit_rules, self.ctxt, self.policy.id) def", "self.ctxt, self.policy.id, filters=filters) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id, filter='filter_id') def test_get_policy_packet_rate_limit_rule_for_nonexistent_policy(self):", "} }, { \"resource_request\": { \"port_id\": uuidutils.generate_uuid(), \"qos_id\": self.policy.id, \"network_id\":", "{'id': port1.id, 'device_owner': 'compute:uu:id', 'qos_policy_id': None, 'qos_network_policy_id': None}, mock.ANY), ]", "mock.patch.object( self.qos_plugin, \"validate_policy_for_network\" ) as validate_policy_for_network, mock.patch.object( self.qos_plugin, \"validate_policy_for_ports\" )", "{'qos_plugin_name': SERVICE_PLUGIN_KLASS} ext_mgr = QoSRuleAliasMinimumPacketRateTestExtensionManager() super(TestQoSRuleAlias, self).setUp(plugin=plugin, ext_mgr=ext_mgr, service_plugins=service_plugins) self.qos_plugin", "= self._get_policy() self.rule_data['bandwidth_limit_rule']['max_kbps'] = 1 setattr(_policy, \"rules\", [self.min_bw_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "as mock_alloc_change: def fake_change_placement_allocation(orig_policy, policy, orig_port, port): port['binding:profile'] = {'allocation':", "rule_type_details['drivers']) def test_get_min_pps_rule_type_as_user(self): self.assertRaises( lib_exc.NotAuthorized, self.qos_plugin.get_rule_type, self.ctxt, qos_consts.RULE_TYPE_MINIMUM_PACKET_RATE) class QoSRuleAliasTestExtensionManager(object):", "class TestQoSRuleAliasMinimumPacketRate(TestQoSRuleAlias): def setUp(self): # Remove MissingAuthPlugin exception from logs", "\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY", "{ 'id': uuidutils.generate_uuid(), 'min_kbps': 20, 'direction': lib_constants.INGRESS_DIRECTION} min_pps_rule_ingress_data = {", "return_value=_policy): self.assertRaises( qos_exc.QoSRuleParameterConflict, self.qos_plugin.update_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, self.policy.id, self.rule_data) def _get_policy(self):", "\"elevated\", return_value=admin_ctxt ): self.qos_plugin._validate_update_network_callback( \"NETWORK\", \"precommit_update\", \"test_plugin\", payload=events.DBEventPayload( self.ctxt, desired_state=kwargs['network'],", "self._get_policy() setattr(_policy, \"rules\", []) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.delete_policy_minimum_packet_rate_rule,", "port1.bindings[0].profile, {'allocation': 'fake_allocation'}) self.assertDictEqual( port2.bindings[0].profile, {'allocation': 'fake_allocation'}) def _prepare_port_for_placement_allocation(self, original_qos,", "\"rules\", [self.min_bw_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.update_policy_minimum_bandwidth_rule( self.ctxt, self.min_bw_rule.id, self.policy.id, self.rule_data)", "self.policy.id, self.rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_min_pps_rule(self): _policy = self._get_policy() setattr(_policy,", "self.qos_plugin.create_policy_bandwidth_limit_rule, self.ctxt, _policy.id, new_rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) @mock.patch.object(rule_object.QosBandwidthLimitRule, 'update') def test_update_policy_rule(self,", "port_id=port2.id, host='fake_host2', vnic_type='fake_vnic_type', vif_type='fake_vif_type', profile={}) port2_binding.create() port2.bindings = [port2_binding] port2.update()", "def test_change_placement_allocation_equal_minkbps_and_minkpps(self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() orig_port, port", "port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_bulk_min_bw_rule(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION ports = self._create_and_extend_ports([self.min_bw_rule])", "alloc_diff={ self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': 500}}) def test_change_placement_allocation_decrease(self): original_qos = self._make_qos_policy()", "as lib_exc from neutron_lib.exceptions import placement as pl_exc from neutron_lib.exceptions", "qos_policy = net_qos_obj if qos_policy: mock_validate_policy.assert_called_once_with( self.context, qos_policy, network.id) else:", "\"qos_id\": self.policy.id, \"network_id\": network_id, \"vnic_type\": \"normal\", } }, ] segment_mock", "self.ctxt, self.pps_rule.id, self.policy.id, self.rule_data) def test_delete_policy_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises(", "from unittest import mock from keystoneauth1 import exceptions as ks_exc", "self.policy.id) def test_get_policy_minimum_bandwidth_rule(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumBandwidthRule.' 'get_object')", "self.policy.id) def test_get_policy_min_pps_rules_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_minimum_packet_rate_rules, self.ctxt,", "fields}) self._validate_driver_params('update_policy', self.ctxt) policy_update_mock_call = mock.call.update() update_precommit_mock_call = mock.call.driver.call( 'update_policy_precommit',", "if network_qos else None network = self._make_network(qos_policy_id=net_qos_id) kwargs = {\"context\":", "# some actions construct rule from class reference rule_mock_call =", "as mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt, self.policy.id, new_rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) for", "kwargs = self._prepare_for_port_placement_allocation_change( qos1=qos1_obj, qos2=None) kwargs['port'].pop('qos_policy_id') context = kwargs['context'] original_port", "= {} with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1, None,", "if rule_id else uuidutils.generate_uuid() qos_rule = rule_object.QosMinimumPacketRateRule( self.context, project_id=self.project_id, qos_policy_id=policy_id,", "desired_min_kbps=None, original_min_kpps=None, desired_min_kpps=None, is_sriov=False): kwargs = self._prepare_for_port_placement_allocation_change( original_qos, desired_qos, qos_network_policy=qos_network_policy)", "_delete_rule(self, rule_type, rule_id): resource = '%s/alias-%s-rules' % (qos.ALIAS, rule_type.replace('_', '-'))", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", [self.pps_rule]) self.qos_plugin.create_policy_packet_rate_limit_rule( self.ctxt, self.policy.id, self.rule_data) self._validate_driver_params('update_policy',", "utils as obj_utils from neutron_lib.plugins import constants as plugins_constants from", "qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': 1000}})", "original_qos, desired_qos, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': -1000}}) self._assert_pci_info(port)", "orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': -1000}}) self._assert_pci_info(port) def", "def test_create_policy_pps_rule_duplicates(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.pps_rule]) new_rule_data =", "self.qos_plugin.update_policy_minimum_packet_rate_rule( self.ctxt, self.min_pps_rule.id, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def test_update_policy_rule_check_rule_min_pps_direction_conflict(self): _policy", "get_ports.assert_called_once_with(self.ctxt, network_id=network_id) validate_policy_for_ports.assert_called_once_with( self.ctxt, policy_mock, [port_mock_without_own_policy]) def test_validate_update_network_callback_policy_changed(self): self._test_validate_update_network_callback( policy_id=uuidutils.generate_uuid())", "{ 'pci_slot': '0000:42:41.0', 'pci_vendor_info': '8086:107ed', 'physical_network': 'sriov_phy' } binding_prof.update({'allocation': allocation})", "= self._make_qos_policy() qos2 = self._make_qos_policy() bw_limit_rule = rule_object.QosDscpMarkingRule(dscp_mark=16) qos2.rules =", "def test_get_pps_rule_type_as_user(self): self.assertRaises( lib_exc.NotAuthorized, self.qos_plugin.get_rule_type, self.ctxt, qos_consts.RULE_TYPE_PACKET_RATE_LIMIT) def test_create_min_pps_rule_on_bound_port(self): _policy", "'delete_policy', self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(policy_delete_mock_call) < mock_manager.mock_calls.index(delete_precommit_mock_call) < mock_manager.mock_calls.index(delete_mock_call)) @mock.patch.object(policy_object.QosPolicy,", "from neutron_lib.utils import net as net_utils import os_resource_classes as orc", "test__extend_port_resource_request_min_pps_rule(self): port = self._create_and_extend_port([], [self.min_pps_rule]) self.assertEqual( 1, len(port['resource_request']['request_groups']) ) self.assertEqual(", "port = ports_object.Port( self.context, network_id=network_id, device_owner=device_owner, project_id=self.project_id, admin_state_up=True, status='DOWN', device_id='2',", "= mock.Mock() mock_manager.attach_mock(mock_qos_rule_update, 'update') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() _policy = policy_object.QosPolicy(", "mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id',", "\"qos_policy_id\": qos1_id, \"qos_network_policy_id\": qos_network_policy_id}, \"port\": {\"id\": port.id, \"qos_policy_id\": qos2_id}} def", "kwargs['port'] with mock.patch.object( self.qos_plugin, '_change_placement_allocation') as mock_alloc_change: self.qos_plugin._check_port_for_placement_allocation_change( 'PORT', 'before_update',", "qos = self._make_qos_policy() original_network = self._make_network(original_qos.id) network = self._make_network(qos.id) ml2plugin_mock", "self._prepare_port_for_placement_allocation( None, desired_qos, qos_network_policy=qos_network, original_min_kbps=1000, desired_min_kbps=2000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as", "self.assertTrue( mock_manager.mock_calls.index(rule_create_mock_call) < mock_manager.mock_calls.index(update_precommit_mock_call) < mock_manager.mock_calls.index(update_mock_call)) def test_create_policy_rule_check_rule_min_less_than_max(self): _policy =", "with mock.patch('neutron.objects.qos.rule.' 'QosBandwidthLimitRule.' 'get_objects') as get_objects_mock: self.qos_plugin.get_policy_bandwidth_limit_rules( self.ctxt, self.policy.id) get_objects_mock.assert_called_once_with(", "{ 'id': port.id, 'device_owner': port.device_owner, 'qos_policy_id': port.qos_policy_id, 'qos_network_policy_id': port.qos_network_policy_id, }", "unexpectedly raised\") def test_validate_policy_for_network(self): network = uuidutils.generate_uuid() with mock.patch.object( self.qos_plugin.driver_manager,", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosBandwidthLimitRule.' 'get_objects') as get_objects_mock: filters", "mock.patch( 'neutron.objects.network.Network.get_object', return_value=net), \\ mock.patch.object( self.qos_plugin, '_get_ports_with_policy', return_value=[port]): try: self.qos_plugin.create_policy_minimum_packet_rate_rule(", "fake_change_placement_allocation(orig_policy, policy, orig_port, port): port['binding:profile'] = {'allocation': 'fake_allocation'} mock_alloc_change.side_effect =", "side_effect=[network_ports, ports] ), mock.patch.object( self.policy, \"get_bound_networks\" ), mock.patch.object( self.policy, \"get_bound_ports\"", "return_value=drivers_details ): rule_type_details = self.qos_plugin.get_rule_type( admin_ctxt, qos_consts.RULE_TYPE_BANDWIDTH_LIMIT) self.assertEqual( qos_consts.RULE_TYPE_BANDWIDTH_LIMIT, rule_type_details['type'])", "[port1_binding] port1.update() with mock.patch.object( self.qos_plugin, '_change_placement_allocation') as mock_alloc_change: def fake_change_placement_allocation(orig_policy,", "desired_min_kbps=2000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: mock_update_qos_alloc.side_effect = ( pl_exc.PlacementAllocationGenerationConflict(", "'before_update', 'test_plugin', payload=events.DBEventPayload( context, states=(original_port, port))) mock_alloc_change.assert_not_called() def test_check_port_for_placement_allocation_change(self): qos1_obj", "need to mock-out # methods that work with real data", "def test_check_port_for_placement_allocation_change_no_qos_update(self): qos1_obj = self._make_qos_policy() kwargs = self._prepare_for_port_placement_allocation_change( qos1=qos1_obj, qos2=None)", "= self._prepare_port_for_placement_allocation(qos1, original_min_kbps=1000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1,", "**min_bw_rule_ingress_data) min_pps_rule_ingress = rule_object.QosMinimumPacketRateRule( self.ctxt, **min_pps_rule_ingress_data) ports = self._create_and_extend_ports( [self.min_bw_rule,", "def test_show_non_existing_rule(self): for rule_type, rule_object_class in self.rule_objects.items(): rule_id = uuidutils.generate_uuid()", "original_policy_id=policy_id) def test_validate_update_network_callback_policy_removed(self): self._test_validate_update_network_callback( policy_id=None, original_policy_id=uuidutils.generate_uuid()) def test_validate_policy_for_port_rule_not_valid(self): port =", "get_object_mock.assert_called_once_with(self.ctxt, id=self.pps_rule.id) def test_get_policy_packet_rate_limit_rules_for_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosPacketRateLimitRule.'", "mock.patch('neutron.objects.qos.rule.' 'QosMinimumPacketRateRule.' 'get_objects') as get_objects_mock: self.qos_plugin.get_policy_minimum_packet_rate_rules( self.ctxt, self.policy.id) get_objects_mock.assert_called_once_with( self.ctxt,", "self.assertDictEqual( port2.bindings[0].profile, {'allocation': 'fake_allocation'}) def _prepare_port_for_placement_allocation(self, original_qos, desired_qos=None, qos_network_policy=None, original_min_kbps=None,", "= rule_object.QosBandwidthLimitRule( self.ctxt, **self.rule_data['bandwidth_limit_rule']) self.dscp_rule = rule_object.QosDscpMarkingRule( self.ctxt, **self.rule_data['dscp_marking_rule']) self.min_bw_rule", "mock_alloc_change.assert_not_called() ml2plugin_mock._make_port_dict.assert_not_called() def test_check_network_for_placement_allocation_change_remove_qos(self): original_qos = self._make_qos_policy() original_network = self._make_network(original_qos.id)", "orig_port, port = self._prepare_port_for_placement_allocation( qos1, qos2, desired_min_kbps=1000, original_min_kpps=500, desired_min_kpps=1000) with", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", [self.dscp_rule]) self.qos_plugin.create_policy_dscp_marking_rule( self.ctxt, self.policy.id, self.rule_data) self._validate_driver_params('update_policy',", "with mock.patch.object( self.qos_plugin, '_change_placement_allocation') as mock_alloc_change: self.qos_plugin._check_port_for_placement_allocation_change( 'PORT', 'before_update', 'test_plugin',", "'qos_policy_id': None, 'qos_network_policy_id': qos.id}, mock.ANY), mock.call( original_qos, qos, {'id': port2.id,", "net_qos_id = net_qos_obj.id if network_qos else None network = self._make_network(qos_policy_id=net_qos_id)", "self.ctxt, self.policy) self.assertEqual( len(expected_ports), len(policy_ports)) for port in expected_ports: self.assertIn(port,", "'PORT', 'before_update', 'test_plugin', payload=events.DBEventPayload( context, states=(original_port, port))) mock_alloc_change.assert_not_called() def test_check_port_for_placement_allocation_change(self):", "'fake_uuid1', 'required': ['CUSTOM_VNIC_TYPE_NORMAL'], 'resources': { orc.NET_PACKET_RATE_EGR_KILOPACKET_PER_SEC: 10, orc.NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC: 20, },", "'get_objects') as get_objects_mock: filters = {'filter': 'filter_id'} self.qos_plugin.get_policy_minimum_packet_rate_rules( self.ctxt, self.policy.id,", "None qos_network_policy_id = ( qos_network_policy.id if qos_network_policy else None) network", "self._create_and_extend_port([], [self.min_pps_rule]) self.assertEqual( 1, len(port['resource_request']['request_groups']) ) self.assertEqual( 'fake_uuid', port['resource_request']['request_groups'][0]['id'] )", "self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_bandwidth_limit_rules, self.ctxt, self.policy.id) def test_create_policy_dscp_marking_rule(self): _policy = policy_object.QosPolicy(", "qos2.rules: rule.direction = 'egress' with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(", "): policy_ports = self.qos_plugin._get_ports_with_policy( self.ctxt, self.policy) self.assertEqual( len(expected_ports), len(policy_ports)) for", "if desired_qos: desired_qos.rules = [] if desired_min_kbps: desired_qos.rules += [self._make_qos_minbw_rule(", "_make_qos_policy(self): qos_policy = policy_object.QosPolicy( self.context, project_id=self.project_id, shared=False, is_default=False) qos_policy.create() return", "= rule_object.QosMinimumBandwidthRule( self.ctxt, **min_bw_rule_ingress_data) min_pps_rule_ingress = rule_object.QosMinimumPacketRateRule( self.ctxt, **min_pps_rule_ingress_data) ports", "mock_manager.attach_mock(qos_policy_mock, 'QosPolicy') mock_manager.attach_mock(port_mock, 'Port') mock_manager.attach_mock(rule_cls_mock, 'RuleCls') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') for action,", "id=_policy.id) def test_create_policy_min_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt,", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.delete_policy_minimum_packet_rate_rule, self.ctxt, self.min_pps_rule.id, self.policy.id) def test_get_policy_min_pps_rule(self):", "def test_get_policy_dscp_marking_rules_for_policy_with_filters(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosDscpMarkingRule.' 'get_objects') as", "[self.dscp_rule]) self.qos_plugin.create_policy_dscp_marking_rule( self.ctxt, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def test_update_policy_dscp_marking_rule(self): _policy", "resource = '%s/alias-%s-rules' % (qos.ALIAS, rule_type.replace('_', '-')) request = self.new_show_request(resource,", "port1_binding = ports_object.PortBinding( self.context, port_id=port1.id, host='fake_host1', vnic_type='fake_vnic_type', vif_type='fake_vif_type', profile={}) port1_binding.create()", "self.ctxt, self.policy.id) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id) def test_get_policy_minimum_bandwidth_rules_for_policy_with_filters(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "test_update_rule(self, update_policy_rule_mock): calls = [] for rule_type, rule_object_class in self.rule_objects.items():", "'delete') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with", "MIN_PPS_RP = 'e16161f4-1626-11ec-a5a2-1fc9396e27cc' def setUp(self): super(TestQosPluginDB, self).setUp() self.setup_coreplugin(load_plugins=False) cfg.CONF.set_override(\"core_plugin\", DB_PLUGIN_KLASS)", "self.ctxt) def test_update_policy_rule_check_rule_bwlimit_less_than_minbw(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.rule]) with", "self.assertRaises( qos_exc.QoSRuleParameterConflict, self.qos_plugin.update_policy_minimum_bandwidth_rule, self.ctxt, self.min_bw_rule.id, self.policy.id, self.rule_data) def test_update_policy_rule_check_rule_minbw_gr_than_bwlimit(self): _policy", "qos1.rules = [bw_limit_rule1] qos2.rules = [bw_limit_rule2] orig_port = { 'binding:profile':", "_test_validate_update_port_callback(self, policy_id=None, original_policy_id=None): port_id = uuidutils.generate_uuid() kwargs = { \"port\":", "def test_get_policy_bandwidth_limit_rules_for_policy_with_filters(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosBandwidthLimitRule.' 'get_objects') as", "f02f160e-1612-11ec-b2b8-bf60ab98186c # 8bf8eb46-160e-11ec-8024-9f96be32099d MIN_BW_REQUEST_GROUP_UUID = 'c8bc1b27-59a1-5135-aa33-aeecad6093f4' MIN_BW_RP = 'd7bea120-1626-11ec-9148-c32debfcf0f6' QOS_MIN_PPS_RULE_ID", "port))) mock_alloc_change.assert_not_called() def test_check_port_for_placement_allocation_change_qos_network_policy( self): qos_network = self._make_qos_policy() desired_qos =", "fake_change_placement_allocation(orig_policy, policy, orig_port, port): port['binding:profile'] = {} mock_alloc_change.side_effect = fake_change_placement_allocation", "self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def test_update_policy_dscp_marking_rule(self): _policy = policy_object.QosPolicy( self.ctxt,", "{'start': 0, 'end': 100} }] }] with mock.patch.object( qos_plugin.QoSPlugin, \"supported_rule_type_details\",", "self.ctxt, **min_bw_rule_ingress_data) min_pps_rule_ingress = rule_object.QosMinimumPacketRateRule( self.ctxt, **min_pps_rule_ingress_data) ports = self._create_and_extend_ports(", "vif_type='fake_vif_type', profile={'allocation': 'fake_allocation'}) port1_binding.create() port1.bindings = [port1_binding] port1.update() with mock.patch.object(", "as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_BW_RP:", "len(expected_ports), len(policy_ports)) for port in expected_ports: self.assertIn(port, policy_ports) def _test_validate_update_port_callback(self,", "port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_min_bw_dataplane_enforcement_with_pps( self): qos1 = self._make_qos_policy() qos2 =", "qos_exc.QosPolicyNotFound, self.qos_plugin.delete_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, self.policy.id) def test_verify_bad_method_call(self): self.assertRaises(AttributeError, getattr, self.qos_plugin,", "= self.new_update_request(resource, data, rule_id, self.fmt) res = request.get_response(self.ext_api) if res.status_int", "rule_id, self.fmt) res = request.get_response(self.ext_api) self.assertEqual(webob.exc.HTTPNotFound.code, res.status_int) class TestQoSRuleAliasMinimumPacketRate(TestQoSRuleAlias): def", "test_check_network_for_placement_allocation_change_no_ports_to_update( self): original_qos = self._make_qos_policy() qos = self._make_qos_policy() port_qos =", "from neutron.extensions import qos_rules_alias from neutron import manager from neutron.objects", "_policy.id) self._validate_driver_params('update_policy', self.ctxt) rule_delete_mock_call = mock.call.delete() update_precommit_mock_call = mock.call.driver.call( 'update_policy_precommit',", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "'get_objects') as get_objects_mock: filters = {'filter': 'filter_id'} self.qos_plugin.get_policy_dscp_marking_rules( self.ctxt, self.policy.id,", "self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_packet_rate_limit_rules, self.ctxt, self.policy.id) def test_create_policy_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None):", "with mock.patch.object( qos_plugin.QoSPlugin, \"supported_rule_type_details\", return_value=drivers_details ): rule_type_details = self.qos_plugin.get_rule_type( admin_ctxt,", "res = request.get_response(self.ext_api) if res.status_int >= webob.exc.HTTPClientError.code: raise webob.exc.HTTPClientError(code=res.status_int) @mock.patch.object(qos_plugin.QoSPlugin,", "port = kwargs['port'] with mock.patch.object( self.qos_plugin, '_change_placement_allocation') as mock_alloc_change: self.qos_plugin._check_port_for_placement_allocation_change(", "port) def test_check_network_for_placement_allocation_change_no_qos_change(self): qos1 = self._make_qos_policy() original_network = self._make_network(qos1.id) network", "mock.patch( 'neutron.objects.base.NeutronDbObject.modify_fields_from_db' ).start() mock.patch.object(policy_object.QosPolicy, 'unset_default').start() mock.patch.object(policy_object.QosPolicy, 'set_default').start() cfg.CONF.set_override(\"core_plugin\", DB_PLUGIN_KLASS) cfg.CONF.set_override(\"service_plugins\",", "'device_owner': port.device_owner, 'qos_policy_id': port.qos_policy_id, 'qos_network_policy_id': port.qos_network_policy_id, } ml2plugin_mock._make_port_dict.side_effect = fake_make_port_dict", "fake_make_port_dict port1 = self._make_port( network_id=network.id, qos_policy_id=None, device_owner='compute:uu:id') port1_binding = ports_object.PortBinding(", "test_change_placement_allocation_new_policy_empty(self): qos1 = self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation(qos1, original_min_kbps=1000, original_min_kpps=2000)", "as mock_qos_get_obj: self.qos_plugin.create_policy_minimum_bandwidth_rule( self.ctxt, _policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) self.mock_qos_load_attr.assert_called_once_with('rules') mock_qos_get_obj.assert_called_once_with(self.ctxt,", "original_min_kbps=1000, desired_min_kbps=2000, original_min_kpps=500, desired_min_kpps=1000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(", "test_validate_update_network_callback_policy_changed(self): self._test_validate_update_network_callback( policy_id=uuidutils.generate_uuid()) def test_validate_update_network_callback_policy_not_changed(self): policy_id = uuidutils.generate_uuid() self._test_validate_update_network_callback( policy_id=policy_id,", "self.ctxt, self.policy.id, filters=filters) get_objects_mock.assert_called_once_with( self.ctxt, qos_policy_id=self.policy.id, _pager=mock.ANY, filter='filter_id') def test_get_policy_dscp_marking_rule_for_nonexistent_policy(self):", "alloc_diff={ self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': -500, 'NET_PACKET_RATE_EGR_KILOPACKET_PER_SEC': 1000}, self.MIN_BW_RP: { 'NET_BW_IGR_KILOBIT_PER_SEC':", "an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF", "self.fail(\"QosRuleNotSupportedByNetwork \" \"exception unexpectedly raised\") def test_create_min_bw_rule_on_bound_port(self): policy = self._get_policy()", "mock.ANY) self.assertTrue( mock_manager.mock_calls.index(policy_mock_call) < mock_manager.mock_calls.index(create_precommit_mock_call) < mock_manager.mock_calls.index(create_mock_call)) def test_add_policy_with_extra_tenant_keyword(self, *mocks):", "self.fmt) res = request.get_response(self.ext_api) if res.status_int >= webob.exc.HTTPClientError.code: raise webob.exc.HTTPClientError(code=res.status_int)", "self.new_show_request(resource, rule_id, self.fmt) res = request.get_response(self.ext_api) if res.status_int >= webob.exc.HTTPClientError.code:", "qos_rule def _make_port(self, network_id, qos_policy_id=None, port_id=None, qos_network_policy_id=None, device_owner=None): port_id =", "mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={ self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': 500}}) def test_change_placement_allocation_decrease(self): original_qos", "= 1 setattr(_policy, \"rules\", [self.min_bw_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj:", "= rule_object.QosMinimumPacketRateRule( self.ctxt, **rule_data['minimum_packet_rate_rule']) setattr(_policy, \"rules\", [min_pps_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy)", "as mock_qos_get_obj: self.qos_plugin.create_policy_bandwidth_limit_rule( self.ctxt, _policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) self.mock_qos_load_attr.assert_called_once_with('rules') mock_qos_get_obj.assert_called_once_with(self.ctxt,", "[self.rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.qos_plugin.create_policy_minimum_bandwidth_rule( self.ctxt, _policy.id, self.rule_data)", "= self.policy.id port = self._create_and_extend_port([self.min_bw_rule], has_net_qos_policy=True) self.assertEqual( 1, len(port['resource_request']['request_groups']) )", "'bandwidth_limit': rule_object.QosBandwidthLimitRule, 'dscp_marking': rule_object.QosDscpMarkingRule, 'minimum_bandwidth': rule_object.QosMinimumBandwidthRule } self.qos_policy_id = uuidutils.generate_uuid()", "qos.rules += [self._make_qos_minpps_rule( qos.id, min_kpps=original_min_kpps, rule_id=TestQosPluginDB.QOS_MIN_PPS_RULE_ID)] allocation.update( {TestQosPluginDB.MIN_PPS_REQUEST_GROUP_UUID: TestQosPluginDB.MIN_PPS_RP}) if", "{'id': 'u:u', 'device_id': 'i:d', 'binding:profile': {}} port = {} with", "mock.patch('neutron.objects.qos.rule.' 'QosMinimumPacketRateRule.' 'get_objects') as get_objects_mock: filters = {'filter': 'filter_id'} self.qos_plugin.get_policy_minimum_packet_rate_rules(", "neutron_lib.objects import utils as obj_utils from neutron_lib.plugins import constants as", "test_create_policy_rule_check_rule_min_less_than_max(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy)", "= context.Context('fake_user', 'fake_tenant') self.admin_ctxt = context.get_admin_context() self.policy_data = { 'policy':", "mock.call.driver.call( 'update_policy', self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(rule_delete_mock_call) < mock_manager.mock_calls.index(update_precommit_mock_call) < mock_manager.mock_calls.index(update_mock_call))", "'name': 'fake-driver', 'supported_parameters': [{ 'parameter_name': 'min_kpps', 'parameter_type': lib_constants.VALUES_TYPE_RANGE, 'parameter_range': {'start':", ") def test__extend_port_resource_request_min_pps_rule(self): port = self._create_and_extend_port([], [self.min_pps_rule]) self.assertEqual( 1, len(port['resource_request']['request_groups'])", "[self.min_pps_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.delete_policy_minimum_packet_rate_rule( self.ctxt, self.min_pps_rule.id, self.policy.id) self._validate_driver_params('update_policy', self.ctxt)", "\"network_id\": network_id, \"vnic_type\": \"normal\", } }, ] segment_mock = mock.MagicMock(network_id=network_id,", "'neutron.objects.network.Network.get_object', return_value=net), \\ mock.patch.object( self.qos_plugin, '_get_ports_with_policy', return_value=[port]): self.assertRaises( NotImplementedError, self.qos_plugin.create_policy_minimum_packet_rate_rule,", "self.ctxt, self.rule.id, self.policy.id) get_object_mock.assert_called_once_with(self.ctxt, id=self.rule.id) def test_get_policy_bandwidth_limit_rules_for_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy):", "policy_object.QosPolicy( self.context, project_id=self.project_id, shared=False, is_default=False) qos_policy.create() return qos_policy def _make_qos_minbw_rule(self,", "self.context = context.get_admin_context() self.project_id = uuidutils.generate_uuid() def _make_qos_policy(self): qos_policy =", "return_value=_policy): self.qos_plugin.create_policy_minimum_packet_rate_rule( self.ctxt, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def test_create_policy_min_pps_rule_duplicates(self): _policy", "'device_id': 'i:d', 'binding:profile': {}} port = {} with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation')", "port_qos_id = port_qos_obj.id if port_qos else None network = self._make_network(qos_policy_id=net_qos_id)", "self.context, \"original_port\": { \"id\": port.id, \"device_owner\": \"compute:uu:id\", \"qos_policy_id\": qos1_id, \"qos_network_policy_id\":", "_policy = self._get_policy() setattr(_policy, \"rules\", [self.min_pps_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.update_policy_minimum_packet_rate_rule(", "self.ctxt) rule_create_mock_call = mock.call.create() update_precommit_mock_call = mock.call.driver.call( 'update_policy_precommit', self.ctxt, mock.ANY)", "port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_no_qos_policy(self): port = self._create_and_extend_port([], physical_network='public', has_qos_policy=False) self.assertIsNone(port.get('resource_request'))", "mock_qos_get_obj: self.assertRaises( qos_exc.QoSRulesConflict, self.qos_plugin.create_policy_packet_rate_limit_rule, self.ctxt, _policy.id, new_rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def", "action) method(*arguments) # some actions get rule from policy get_rule_mock_call", "rule_id else uuidutils.generate_uuid() qos_rule = rule_object.QosMinimumPacketRateRule( self.context, project_id=self.project_id, qos_policy_id=policy_id, direction=direction,", "= port_qos_obj.id if port_qos else None network = self._make_network(qos_policy_id=net_qos_id) port", "from class reference rule_mock_call = getattr(mock.call.RuleCls(), action)() driver_mock_call = mock.call.driver.call('update_policy',", "id=_policy.id) def test_create_policy_min_pps_rule(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.min_pps_rule]) with", "= self._make_qos_policy() qos = self._make_qos_policy() port_qos = self._make_qos_policy() original_network =", "import network as network_object from neutron.objects import ports as ports_object", "\"rules\", [self.min_bw_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.create_policy_bandwidth_limit_rule, self.ctxt,", "import constants as qos_consts from neutron_lib.utils import net as net_utils", "port = self._create_and_extend_port([self.min_bw_rule], physical_network=None) self.assertIsNone(port.get('resource_request')) def test__extend_port_resource_request_mix_rules_non_provider_net(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION", "= uuidutils.generate_uuid() project_id = uuidutils.generate_uuid() tenant_policy = { 'policy': {'id':", "self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION self.min_pps_rule.direction = lib_constants.EGRESS_DIRECTION request_groups_uuids = ['fake_uuid0', 'fake_uuid1']", "'create') def test_create_policy_rule(self, mock_qos_rule_create, mock_qos_policy_get): _policy = copy.copy(self.policy) setattr(_policy, \"rules\",", "= mock.call.driver.call( 'update_policy', self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(rule_update_mock_call) < mock_manager.mock_calls.index(update_precommit_mock_call) <", "= self._get_policy() setattr(_policy, \"rules\", [self.pps_rule]) new_rule_data = { 'packet_rate_limit_rule': {", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_packet_rate_limit_rule, self.ctxt, self.pps_rule.id, self.policy.id) def", "def test_delete_policy_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.delete_policy_packet_rate_limit_rule, self.ctxt, self.pps_rule.id,", "with mock.patch('neutron.objects.qos.rule.' 'QosDscpMarkingRule.' 'get_objects') as get_objects_mock: filters = {'filter': 'filter_id'}", "KIND, either express or implied. See the # License for", "rule_type, rule_id): resource = '%s/alias-%s-rules' % (qos.ALIAS, rule_type.replace('_', '-')) request", "16}, 'minimum_bandwidth_rule': {'min_kbps': 10} } def _update_rule(self, rule_type, rule_id, **kwargs):", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.assertRaises( qos_exc.QoSRuleParameterConflict, self.qos_plugin.update_policy_minimum_bandwidth_rule, self.ctxt, self.min_bw_rule.id, self.policy.id, self.rule_data)", "get_rule_mock_call) self.assertLess( action_index, mock_manager.mock_calls.index(driver_mock_call)) def test_create_policy_packet_rate_limit_rule(self): _policy = policy_object.QosPolicy( self.ctxt,", "(qos.ALIAS, rule_type.replace('_', '-')) request = self.new_delete_request(resource, rule_id, self.fmt) res =", "self.qos_plugin, '_get_ports_with_policy', return_value=[port]): try: self.qos_plugin.create_policy_minimum_bandwidth_rule( self.ctxt, policy.id, self.rule_data) except NotImplementedError:", "get_ports.assert_not_called() validate_policy_for_ports.assert_not_called() else: get_policy.assert_called_once_with(admin_ctxt, id=policy_id) get_ports.assert_called_once_with(self.ctxt, network_id=network_id) validate_policy_for_ports.assert_called_once_with( self.ctxt, policy_mock,", "'update_qos_allocation') as mock_update_qos_alloc: mock_update_qos_alloc.side_effect = ( pl_exc.PlacementAllocationGenerationConflict( consumer=self.MIN_BW_RP)) self.assertRaises( pl_exc.PlacementAllocationGenerationConflict,", "= net_qos_obj.id if network_qos else None network = self._make_network(qos_policy_id=net_qos_id) kwargs", "port = {'id': uuidutils.generate_uuid()} with mock.patch.object( self.qos_plugin.driver_manager, \"validate_rule_for_port\", return_value=False ):", "16}, 'minimum_bandwidth_rule': { 'id': uuidutils.generate_uuid(), 'min_kbps': 10}, 'packet_rate_limit_rule': { 'id':", "mock.patch('neutron.objects.qos.rule.' 'QosMinimumBandwidthRule.' 'get_object') as get_object_mock: self.qos_plugin.get_policy_minimum_bandwidth_rule( self.ctxt, self.rule.id, self.policy.id) get_object_mock.assert_called_once_with(self.ctxt,", "self._make_qos_policy() kwargs = self._prepare_for_port_placement_allocation_change( qos1=qos1_obj, qos2=None) context = kwargs['context'] original_port", "mock.Mock() self.rpc_push = mock.patch('neutron.api.rpc.handlers.resources_rpc' '.ResourcesPushRpcApi.push').start() self.ctxt = context.Context('fake_user', 'fake_tenant') self.admin_ctxt", "\"vnic_type\": \"normal\", } }, ] segment_mock = mock.MagicMock(network_id=network_id, physical_network=physical_network) min_pps_rules", "mock.patch('neutron.objects.qos.rule.' 'QosBandwidthLimitRule.' 'get_objects') as get_objects_mock: filters = {'filter': 'filter_id'} self.qos_plugin.get_policy_bandwidth_limit_rules(", "} }, { 'minimum_packet_rate_rule': { 'id': uuidutils.generate_uuid(), 'min_kpps': 10, 'direction':", "\"normal\", } }, { \"resource_request\": { \"port_id\": uuidutils.generate_uuid(), \"qos_id\": self.policy.id,", "port['binding:profile'] = {'allocation': 'fake_allocation'} mock_alloc_change.side_effect = fake_change_placement_allocation self.qos_plugin._check_network_for_placement_allocation_change( 'network', 'after_update',", "return_value=net), \\ mock.patch.object( self.qos_plugin, '_get_ports_with_policy', return_value=[port]): try: self.qos_plugin.create_policy_minimum_bandwidth_rule( self.ctxt, policy.id,", "self.policy, port) def test_validate_policy_for_port_all_rules_valid(self): port = {'id': uuidutils.generate_uuid()} with mock.patch.object(", "self.qos_plugin, '_change_placement_allocation') as mock_alloc_change: self.qos_plugin._check_port_for_placement_allocation_change( 'PORT', 'before_update', 'test_plugin', payload=events.DBEventPayload( context,", "net_qos_obj if qos_policy: mock_validate_policy.assert_called_once_with( self.context, qos_policy, port) else: mock_validate_policy.assert_not_called() def", "self.rule.id, self.policy.id, self.rule_data) def test_delete_policy_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound,", "= request.get_response(self.ext_api) self.assertEqual(webob.exc.HTTPNotFound.code, res.status_int) class TestQoSRuleAliasMinimumPacketRate(TestQoSRuleAlias): def setUp(self): # Remove", "orig_port, port = self._prepare_port_for_placement_allocation( None, desired_qos, qos_network_policy=qos_network, original_min_kbps=1000, desired_min_kbps=2000) with", "self.assertTrue( mock_manager.mock_calls.index(rule_delete_mock_call) < mock_manager.mock_calls.index(update_precommit_mock_call) < mock_manager.mock_calls.index(update_mock_call)) def test_delete_policy_rule_bad_policy(self): _policy =", "= self._prepare_for_port_placement_allocation_change( qos1=qos1_obj, qos2=None) kwargs['port'].pop('qos_policy_id') context = kwargs['context'] original_port =", "self.qos_plugin.create_policy_bandwidth_limit_rule( self.ctxt, _policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) self.mock_qos_load_attr.assert_called_once_with('rules') mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def", "update_precommit_mock_call = mock.call.driver.call( 'update_policy_precommit', self.ctxt, mock.ANY) update_mock_call = mock.call.driver.call( 'update_policy',", "self.qos_plugin._check_network_for_placement_allocation_change( 'network', 'after_update', ml2plugin_mock, payload=events.DBEventPayload( self.context, states=(original_network, network))) self.assertEqual(ml2plugin_mock._make_port_dict.call_count, 2)", "def test_create_policy_min_pps_rule_duplicates(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.min_pps_rule]) new_rule_data =", "{ 'id': 'fake_uuid1', 'required': ['CUSTOM_VNIC_TYPE_NORMAL'], 'resources': { orc.NET_PACKET_RATE_EGR_KILOPACKET_PER_SEC: 10, orc.NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC:", "\"id\": port.id, \"device_owner\": \"compute:uu:id\", \"qos_policy_id\": qos1_id, \"qos_network_policy_id\": qos_network_policy_id}, \"port\": {\"id\":", "self.ctxt, **rule_data['minimum_packet_rate_rule']) setattr(_policy, \"rules\", [min_pps_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj:", "'id': uuidutils.generate_uuid(), 'min_kbps': 10}, 'packet_rate_limit_rule': { 'id': uuidutils.generate_uuid(), 'max_kpps': 20,", "self.qos_plugin.get_rule_type( admin_ctxt, qos_consts.RULE_TYPE_MINIMUM_PACKET_RATE) self.assertEqual( qos_consts.RULE_TYPE_MINIMUM_PACKET_RATE, rule_type_details['type']) self.assertEqual( drivers_details, rule_type_details['drivers']) def", "'parameter_name': 'max_kbps', 'parameter_type': lib_constants.VALUES_TYPE_RANGE, 'parameter_range': {'start': 0, 'end': 100} }]", "'binding:profile': {'allocation': { self.MIN_BW_REQUEST_GROUP_UUID: self.MIN_BW_RP}}, 'device_id': 'uu:id', 'id': '9416c220-160a-11ec-ba3d-474633eb825c', }", "rule_id, **data) calls.append(mock.call(mock.ANY, rule_object_class, rule_id, self.qos_policy_id, {rule_data_name: data})) update_policy_rule_mock.assert_has_calls(calls, any_order=True)", "< mock_manager.mock_calls.index(update_precommit_mock_call) < mock_manager.mock_calls.index(update_mock_call)) def test_update_policy_rule_check_rule_min_less_than_max(self): _policy = self._get_policy() setattr(_policy,", "return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumBandwidthRule.' 'get_objects') as get_objects_mock: filters = {'filter':", "action, arguments in rule_actions.items(): mock_manager.reset_mock() method = getattr(self.qos_plugin, \"%s_policy_rule\" %", "mock_alloc_change.side_effect = fake_change_placement_allocation self.qos_plugin._check_network_for_placement_allocation_change( 'network', 'after_update', ml2plugin_mock, payload=events.DBEventPayload( self.context, states=(original_network,", "{'id': port1.id, 'device_owner': 'compute:uu:id', 'qos_policy_id': None, 'qos_network_policy_id': qos.id}, mock.ANY), mock.call(", "self.min_pps_rule.direction, }, } with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises( qos_exc.QoSRulesConflict,", "port_res, self.port) def _create_and_extend_ports(self, min_bw_rules, min_pps_rules=None, physical_network='public', request_groups_uuids=None): network_id =", "**self.policy_data['policy']) setattr(_policy, \"rules\", [self.rule]) with mock.patch('neutron.objects.qos.rule.get_rules', return_value=[self.rule]), mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy):", "with mock.patch('neutron.objects.qos.rule.QosRule.get_object', return_value=None): resource = '%s/alias-%s-rules' % (qos.ALIAS, rule_type.replace('_', '-'))", "'neutron.objects.qos.policy.QosPolicy.get_object', return_value=policy_mock ) as get_policy, mock.patch.object( self.qos_plugin, \"validate_policy_for_network\" ) as", "= self._make_qos_policy() net_qos_id = net_qos_obj.id if network_qos else None network", "else None qos2_id = qos2.id if qos2 else None qos_network_policy_id", "{orc.NET_PACKET_RATE_KILOPACKET_PER_SEC: 10}, port['resource_request']['request_groups'][0]['resources'], ) self.assertEqual( ['fake_uuid'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_min_bw_and_pps_rule(self):", "mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_update_policy_min_pps_rule_bad_policy(self): _policy = self._get_policy() setattr(_policy, \"rules\", [])", "# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "mock_validate_policy: self.qos_plugin._validate_create_port_callback( \"PORT\", \"precommit_create\", \"test_plugin\", payload=events.DBEventPayload( self.context, resource_id=kwargs['port']['id'],)) qos_policy =", "[bw_limit_rule2] orig_port = { 'binding:profile': {'allocation': { self.MIN_BW_REQUEST_GROUP_UUID: self.MIN_BW_RP}}, 'device_id':", "mock_qos_get_obj: self.qos_plugin.create_policy_minimum_bandwidth_rule( self.ctxt, _policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) self.mock_qos_load_attr.assert_called_once_with('rules') mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id)", "port = self._create_and_extend_port([], []) self.assertIsNone(port.get('resource_request')) def test__extend_port_resource_request_min_bw_non_provider_net(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION", "self.ctxt) def test_delete_policy_pps_rule_bad_policy(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "kwargs = { \"context\": self.ctxt, \"network\": { \"id\": network_id, qos_consts.QOS_POLICY_ID:", "mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_rule_check_rule_bwlimit_less_than_minbw(self): _policy = self._get_policy() self.rule_data['bandwidth_limit_rule']['max_kbps'] = 1", "test_delete_policy_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.delete_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, self.policy.id)", "port) def test_check_port_for_placement_allocation_change_no_qos_update(self): qos1_obj = self._make_qos_policy() kwargs = self._prepare_for_port_placement_allocation_change( qos1=qos1_obj,", "**kwargs): data = {'alias_%s_rule' % rule_type: kwargs} resource = '%s/alias-%s-rules'", "rule_type, rule_object_class in self.rule_objects.items(): rule_id = uuidutils.generate_uuid() with mock.patch('neutron.objects.qos.rule.QosRule.get_object', return_value=None):", "_policy.id, new_rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_update_policy_packet_rate_limit_rule(self): _policy = policy_object.QosPolicy( self.ctxt,", "= [{ 'name': 'fake-driver', 'supported_parameters': [{ 'parameter_name': 'min_kpps', 'parameter_type': lib_constants.VALUES_TYPE_RANGE,", "def _update_rule(self, rule_type, rule_id, **kwargs): data = {'alias_%s_rule' % rule_type:", "**self.rule_data['minimum_bandwidth_rule']) self.pps_rule = rule_object.QosPacketRateLimitRule( self.ctxt, **self.rule_data['packet_rate_limit_rule']) self.min_pps_rule = rule_object.QosMinimumPacketRateRule( self.ctxt,", "= {'alias_%s_rule' % rule_type: kwargs} resource = '%s/alias-%s-rules' % (qos.ALIAS,", "'neutron.objects.qos.rule.QosMinimumPacketRateRule.' 'get_objects', return_value=min_pps_rules), \\ mock.patch( 'uuid.uuid5', return_value='fake_uuid', side_effect=request_groups_uuids): return qos_plugin.QoSPlugin._extend_port_resource_request(", "mock.patch.object( self.qos_plugin.driver_manager, \"validate_rule_for_port\", return_value=False ): self.policy.rules = [self.rule] self.assertRaises( qos_exc.QosRuleNotSupported,", "self._make_port( network_id=network.id, qos_policy_id=None, device_owner='compute:uu:id') port2_binding = ports_object.PortBinding( self.context, port_id=port2.id, host='fake_host2',", "setattr(_policy, \"rules\", [self.pps_rule]) self.qos_plugin.create_policy_packet_rate_limit_rule( self.ctxt, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def", "mock.ANY) if rule_mock_call in mock_manager.mock_calls: action_index = mock_manager.mock_calls.index(rule_mock_call) else: action_index", "as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1, None, orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_old_rule_not_min_bw(self):", "'direction': 'ingress' } }, { 'minimum_packet_rate_rule': { 'id': uuidutils.generate_uuid(), 'min_kpps':", "self._test_validate_create_network_callback(network_qos=True) def test_validate_create_network_callback_no_qos(self): self._test_validate_create_network_callback(network_qos=False) def _test_validate_create_port_callback(self, port_qos=False, network_qos=False): net_qos_obj =", "from neutron_lib.plugins import constants as plugins_constants from neutron_lib.plugins import directory", "self._validate_driver_params('update_policy', self.ctxt) def test_create_policy_min_pps_rule_duplicates(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.min_pps_rule])", "expected_network_ports = [ port for port in network_ports if port.qos_policy_id", "method_name, ctxt): call_args = self.qos_plugin.driver_manager.call.call_args[0] self.assertTrue(self.qos_plugin.driver_manager.call.called) self.assertEqual(call_args[0], method_name) self.assertEqual(call_args[1], ctxt)", "original_min_kbps=1000, desired_min_kbps=2000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: mock_update_qos_alloc.side_effect = (", "setattr(_policy, \"rules\", [self.min_pps_rule]) segment = network_object.NetworkSegment( physical_network='fake physnet') net =", "with mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy), \\ mock.patch( 'neutron.objects.network.Network.get_object', return_value=net), \\ mock.patch.object(", "port['resource_request']['request_groups'][0]['required'] ) self.assertEqual( {orc.NET_PACKET_RATE_KILOPACKET_PER_SEC: 10}, port['resource_request']['request_groups'][0]['resources'], ) self.assertEqual( ['fake_uuid'], port['resource_request']['same_subtree'],", "['CUSTOM_PHYSNET_PUBLIC', 'CUSTOM_VNIC_TYPE_NORMAL'], port['resource_request']['request_groups'][0]['required'] ) self.assertEqual( {orc.NET_BW_EGR_KILOBIT_PER_SEC: 10}, port['resource_request']['request_groups'][0]['resources'], ) self.assertEqual(", "return_value=net), \\ mock.patch.object( self.qos_plugin, '_get_ports_with_policy', return_value=[port]): self.assertRaises( NotImplementedError, self.qos_plugin.create_policy_minimum_bandwidth_rule, self.ctxt,", "mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') for action, arguments in rule_actions.items(): mock_manager.reset_mock() method =", "'-')) request = self.new_delete_request(resource, rule_id, self.fmt) res = request.get_response(self.ext_api) if", "= context.Context('fake_user', 'fake_tenant') self.rule_objects = { 'minimum_packet_rate': rule_object.QosMinimumPacketRateRule } self.qos_policy_id", "= device_owner if device_owner else '3' port = ports_object.Port( self.context,", "implied. See the # License for the specific language governing", "from neutron import manager from neutron.objects import network as network_object", "test_get_policy_bandwidth_limit_rule(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosBandwidthLimitRule.' 'get_object') as get_object_mock:", "port = self._create_and_extend_port( [self.min_bw_rule, min_bw_rule_ingress], [self.min_pps_rule, min_pps_rule_ingress], request_groups_uuids=request_groups_uuids) self.assertEqual( 2,", "self.ctxt, policy_mock, [port_mock_without_own_policy]) def test_validate_update_network_callback_policy_changed(self): self._test_validate_update_network_callback( policy_id=uuidutils.generate_uuid()) def test_validate_update_network_callback_policy_not_changed(self): policy_id", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", []) self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.delete_policy_packet_rate_limit_rule, self.ctxt,", "def test_validate_create_port_callback_policy_on_network(self): self._test_validate_create_port_callback(network_qos=True) def test_validate_create_port_callback_no_policy(self): self._test_validate_create_port_callback() def _prepare_for_port_placement_allocation_change(self, qos1, qos2,", "'parameter_name': 'max_kpps', 'parameter_type': lib_constants.VALUES_TYPE_RANGE, 'parameter_range': {'start': 0, 'end': 100} }]", "= mock.MagicMock( id=uuidutils.generate_uuid(), qos_policy_id=None) ports = [port_mock_with_own_policy, port_mock_without_own_policy] policy_mock =", "Remove MissingAuthPlugin exception from logs self.patch_notifier = mock.patch( 'neutron.notifiers.batch_notifier.BatchNotifier._notify') self.patch_notifier.start()", "= [] allocation = {} if original_min_kbps: qos.rules += [self._make_qos_minbw_rule(", "self.ctxt, **rules_data[1]['minimum_packet_rate_rule']), ] setattr(_policy, 'rules', rules) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as", "mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_policy_delete, 'delete') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() self.qos_plugin.delete_policy(self.ctxt, self.policy.id)", "[self.ctxt, rule_cls_mock, self.policy.id, {'fake_rule': {}}], 'update': [self.ctxt, rule_cls_mock, self.rule.id, self.policy.id,", "= '8bf8eb46-160e-11ec-8024-9f96be32099d' # uuid -v5 f02f160e-1612-11ec-b2b8-bf60ab98186c # 8bf8eb46-160e-11ec-8024-9f96be32099d MIN_BW_REQUEST_GROUP_UUID =", "= ports_object.Port( self.context, network_id=network_id, device_owner=device_owner, project_id=self.project_id, admin_state_up=True, status='DOWN', device_id='2', qos_policy_id=qos_policy_id,", "return_value=qos_consts.VALID_RULE_TYPES): types = self.qos_plugin.get_rule_types(self.ctxt, filters=filters) self.assertEqual(sorted(qos_consts.VALID_RULE_TYPES), sorted(type_['type'] for type_ in", "self.qos_plugin.update_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, self.policy.id, self.rule_data) def _get_policy(self): return policy_object.QosPolicy( self.ctxt,", "qos_consts.RULE_TYPE_MINIMUM_PACKET_RATE) class QoSRuleAliasTestExtensionManager(object): def get_resources(self): return qos_rules_alias.Qos_rules_alias.get_resources() def get_actions(self): return", "mock_manager.mock_calls.index(update_precommit_mock_call) < mock_manager.mock_calls.index(update_mock_call)) @mock.patch('neutron.objects.db.api.get_object', return_value=None) @mock.patch.object(policy_object.QosPolicy, 'delete') def test_delete_policy(self, mock_qos_policy_delete,", "self.qos_plugin, '_change_placement_allocation') as mock_alloc_change: def fake_change_placement_allocation(orig_policy, policy, orig_port, port): port['binding:profile']", "mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={ self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': 500}, self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': 1000}})", "original_policy_id=uuidutils.generate_uuid()) def test_validate_policy_for_port_rule_not_valid(self): port = {'id': uuidutils.generate_uuid()} with mock.patch.object( self.qos_plugin.driver_manager,", "mock_alloc_change: def fake_change_placement_allocation(orig_policy, policy, orig_port, port): port['binding:profile'] = {'allocation': 'fake_allocation'}", "self.ctxt, self.pps_rule.id, self.policy.id) self._validate_driver_params('update_policy', self.ctxt) def test_delete_policy_pps_rule_bad_policy(self): _policy = policy_object.QosPolicy(", "def test_check_network_for_placement_allocation_change_no_qos_change(self): qos1 = self._make_qos_policy() original_network = self._make_network(qos1.id) network =", "self.qos_plugin.delete_policy_minimum_packet_rate_rule, self.ctxt, self.min_pps_rule.id, self.policy.id) def test_get_policy_min_pps_rule(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with", "qos2, orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_min_bw_dataplane_enforcement(self): qos1 = self._make_qos_policy() qos2", "self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def test_create_policy_min_pps_rule_duplicates(self): _policy = self._get_policy() setattr(_policy, \"rules\",", "def test_create_policy_min_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt, self.policy.id,", "orig_port, port): port['binding:profile'] = {} mock_alloc_change.side_effect = fake_change_placement_allocation self.qos_plugin._check_network_for_placement_allocation_change( 'network',", "self.policy, \"get_bound_ports\" ): policy_ports = self.qos_plugin._get_ports_with_policy( self.ctxt, self.policy) self.assertEqual( len(expected_ports),", "rule_object.QosMinimumPacketRateRule( self.ctxt, **min_pps_rule_ingress_data) port = self._create_and_extend_port( [self.min_bw_rule, min_bw_rule_ingress], [self.min_pps_rule, min_pps_rule_ingress],", "self._make_qos_policy() original_network = self._make_network(original_qos.id) network = self._make_network() ml2plugin_mock = mock.MagicMock()", "policy_id=uuidutils.generate_uuid()) def test_validate_update_port_callback_policy_not_changed(self): policy_id = uuidutils.generate_uuid() self._test_validate_update_port_callback( policy_id=policy_id, original_policy_id=policy_id) def", "neutron.exceptions import qos as neutron_qos_exc from neutron.extensions import qos_pps_minimum_rule_alias from", "admin_ctxt = mock.Mock() with mock.patch( 'neutron.objects.ports.Port.get_objects', return_value=ports ) as get_ports,", "self.qos_plugin.driver_manager, \"validate_rule_for_port\", return_value=False ): self.policy.rules = [self.rule] self.assertRaises( qos_exc.QosRuleNotSupported, self.qos_plugin.validate_policy_for_port,", "{\"id\": port.id, \"qos_policy_id\": qos2_id}} def test_check_port_for_placement_allocation_change_no_qos_change(self): qos1_obj = self._make_qos_policy() kwargs", "self.qos_plugin.get_policy_minimum_bandwidth_rules( self.ctxt, self.policy.id) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id) def test_get_policy_minimum_bandwidth_rules_for_policy_with_filters(self): with", "self.context, resource_id=kwargs['network']['id'],)) qos_policy = None if network_qos: qos_policy = net_qos_obj", "else uuidutils.generate_uuid() base_mac = ['aa', 'bb', 'cc', 'dd', 'ee', 'ff']", "{'NET_BW_IGR_KILOBIT_PER_SEC': -1000}}) def test_change_placement_allocation_equal_minkbps_and_minkpps(self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy()", "original_port = kwargs['original_port'] port = kwargs['port'] with mock.patch.object( self.qos_plugin, '_change_placement_allocation')", "\"elevated\", return_value=admin_ctxt ): self.qos_plugin._validate_update_port_callback( \"PORT\", \"precommit_update\", \"test_plugin\", payload=events.DBEventPayload( self.ctxt, desired_state=kwargs['port'],", "self._get_policy() setattr(_policy, \"rules\", [self.min_bw_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.qos_plugin.create_policy_bandwidth_limit_rule(", "= self.policy mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_policy_update, 'update') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock()", "return_value=_policy) as mock_qos_get_obj: self.assertRaises( qos_exc.QoSRulesConflict, self.qos_plugin.create_policy_packet_rate_limit_rule, self.ctxt, _policy.id, new_rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt,", "class TestQosPluginDB(base.BaseQosTestCase): PORT_ID = 'f02f160e-1612-11ec-b2b8-bf60ab98186c' QOS_MIN_BW_RULE_ID = '8bf8eb46-160e-11ec-8024-9f96be32099d' # uuid", "test_update_policy_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.update_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, self.policy.id,", "self.context, resource_id=kwargs['port']['id'],)) qos_policy = None if port_qos: qos_policy = port_qos_obj", "ml2plugin_mock._make_port_dict.assert_not_called() def test_check_network_for_placement_allocation_change_remove_qos(self): original_qos = self._make_qos_policy() original_network = self._make_network(original_qos.id) network", "= self._make_qos_policy() qos = self._make_qos_policy() original_network = self._make_network(original_qos.id) network =", "} }, ] for new_rule_data in rules: with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy)", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosBandwidthLimitRule.' 'get_object') as get_object_mock: self.qos_plugin.get_policy_bandwidth_limit_rule(", "policy_id, 'project_id': project_id, 'name': 'test-policy', 'description': 'Test policy description', 'shared':", "get_object_mock: self.qos_plugin.get_policy_bandwidth_limit_rule( self.ctxt, self.rule.id, self.policy.id) get_object_mock.assert_called_once_with(self.ctxt, id=self.rule.id) def test_get_policy_bandwidth_limit_rules_for_policy(self): with", "-500, 'NET_PACKET_RATE_EGR_KILOPACKET_PER_SEC': 1000}, self.MIN_BW_RP: { 'NET_BW_IGR_KILOBIT_PER_SEC': -1000, 'NET_BW_EGR_KILOBIT_PER_SEC': 2000}}) def", "physnet') net = network_object.Network( self.ctxt, segments=[segment]) port = ports_object.Port( self.ctxt,", "= {'id': 'u:u', 'device_id': 'i:d', 'binding:profile': {}} port = {}", "= fake_change_placement_allocation self.qos_plugin._check_network_for_placement_allocation_change( 'network', 'after_update', ml2plugin_mock, payload=events.DBEventPayload( self.context, states=(original_network, network)))", "None if network_qos: qos_policy = net_qos_obj if qos_policy: mock_validate_policy.assert_called_once_with( self.context,", "qos_exc.QosRuleNotSupported, self.qos_plugin.validate_policy_for_port, self.ctxt, self.policy, port) def test_validate_policy_for_port_all_rules_valid(self): port = {'id':", "self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def test_create_policy_min_pps_rule_duplicates(self): _policy = self._get_policy() setattr(_policy,", "{'dscp_mark': 16}, 'minimum_bandwidth_rule': {'min_kbps': 10} } def _update_rule(self, rule_type, rule_id,", "self.rule.id, self.policy.id, self.rule_data) def _get_policy(self): return policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) def", "[self.min_pps_rule, min_pps_rule_ingress], request_groups_uuids=request_groups_uuids) for port in ports: self.assertEqual( 2, len(port['resource_request']['request_groups'])", "= self._prepare_port_for_placement_allocation( qos1, qos2, original_min_kbps=1000, desired_min_kbps=2000, is_sriov=True) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation')", "uuidutils.generate_uuid(), \"qos_id\": self.policy.id, \"network_id\": network_id, \"vnic_type\": \"normal\", } }, {", "net_qos_obj = self._make_qos_policy() net_qos_id = net_qos_obj.id if network_qos else None", "def test__extend_port_resource_request_min_pps_rule(self): port = self._create_and_extend_port([], [self.min_pps_rule]) self.assertEqual( 1, len(port['resource_request']['request_groups']) )", "'_change_placement_allocation') as mock_alloc_change: def fake_change_placement_allocation(orig_policy, policy, orig_port, port): port['binding:profile'] =", "\"port\": {\"id\": port.id, \"qos_policy_id\": qos2_id}} def test_check_port_for_placement_allocation_change_no_qos_change(self): qos1_obj = self._make_qos_policy()", "self._assert_pci_info(port) def test_change_placement_allocation_increase_min_pps(self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() orig_port,", "def test_update_policy_rule_check_rule_min_less_than_max(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", ") def test__extend_port_resource_request_bulk_min_pps_rule(self): ports = self._create_and_extend_ports([], [self.min_pps_rule]) for port in", "< mock_manager.mock_calls.index(update_precommit_mock_call) < mock_manager.mock_calls.index(update_mock_call)) def test_create_policy_rule_check_rule_min_less_than_max(self): _policy = self._get_policy() setattr(_policy,", "\"rules\", [self.min_pps_rule]) new_rule_data = { 'minimum_packet_rate_rule': { 'id': uuidutils.generate_uuid(), 'min_kpps':", "= self._prepare_port_for_placement_allocation( qos1, qos2, original_min_kbps=1000, desired_min_kbps=2000, original_min_kpps=500, desired_min_kpps=1000) with mock.patch.object(self.qos_plugin._placement_client,", "orc from oslo_config import cfg from oslo_utils import uuidutils import", "'uu:id'} ) return orig_port, kwargs['port'] def _assert_pci_info(self, port): self.assertIn('pci_slot', port['binding:profile'])", "test_create_min_bw_rule_on_bound_port(self): policy = self._get_policy() policy.rules = [self.min_bw_rule] segment = network_object.NetworkSegment(", "rule_type_details['type']) self.assertEqual( drivers_details, rule_type_details['drivers']) def test_get_rule_type_as_user(self): self.assertRaises( lib_exc.NotAuthorized, self.qos_plugin.get_rule_type, self.ctxt,", "def test_get_policy_packet_rate_limit_rules_for_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosPacketRateLimitRule.' 'get_objects') as", "qos_policy_id=None) ports = [port_mock_with_own_policy, port_mock_without_own_policy] policy_mock = mock.MagicMock(id=policy_id) admin_ctxt =", "self._make_network(qos1.id) network = original_network ml2plugin_mock = mock.MagicMock() with mock.patch.object( self.qos_plugin,", "{ \"resource_request\": { \"port_id\": uuidutils.generate_uuid(), \"qos_id\": self.policy.id, \"network_id\": network_id, \"vnic_type\":", "res.status_int) class TestQoSRuleAliasMinimumPacketRate(TestQoSRuleAlias): def setUp(self): # Remove MissingAuthPlugin exception from", "self.qos_plugin.driver_manager.call.call_args[0] self.assertTrue(self.qos_plugin.driver_manager.call.called) self.assertEqual(call_args[0], method_name) self.assertEqual(call_args[1], ctxt) self.assertIsInstance(call_args[2], policy_object.QosPolicy) def _create_and_extend_port(self,", "= self._make_qos_policy() port_qos = self._make_qos_policy() original_network = self._make_network(original_qos.id) network =", "return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.create_policy_packet_rate_limit_rule, self.ctxt, self.policy.id, self.rule_data) def test_update_policy_pps_rule_for_nonexistent_policy(self): with", "self.ctxt, **rules_data[0]['minimum_packet_rate_rule']), rule_object.QosMinimumPacketRateRule( self.ctxt, **rules_data[1]['minimum_packet_rate_rule']), ] setattr(_policy, 'rules', rules) with", "\"validate_policy_for_ports\" ) as validate_policy_for_ports, mock.patch.object( self.ctxt, \"elevated\", return_value=admin_ctxt ): self.qos_plugin._validate_update_network_callback(", "return_value=_policy): self.qos_plugin.update_policy_minimum_packet_rate_rule( self.ctxt, self.min_pps_rule.id, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def test_update_policy_rule_check_rule_min_pps_direction_conflict(self):", "context.get_admin_context() drivers_details = [{ 'name': 'fake-driver', 'supported_parameters': [{ 'parameter_name': 'max_kbps',", "self._validate_driver_params('update_policy', self.ctxt) rule_update_mock_call = mock.call.update() update_precommit_mock_call = mock.call.driver.call( 'update_policy_precommit', self.ctxt,", "\"port\": {\"id\": port.id}} with mock.patch.object(self.qos_plugin, 'validate_policy_for_port') \\ as mock_validate_policy: self.qos_plugin._validate_create_port_callback(", "'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_not_called() def", "= lib_constants.EGRESS_DIRECTION ports = self._create_and_extend_ports([self.min_bw_rule]) for port in ports: self.assertEqual(", "self.ctxt, id=uuidutils.generate_uuid(), network_id=uuidutils.generate_uuid(), device_owner='') with mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=policy), \\ mock.patch(", "mock.patch( 'neutron.notifiers.batch_notifier.BatchNotifier._notify') self.patch_notifier.start() plugin = 'ml2' service_plugins = {'qos_plugin_name': SERVICE_PLUGIN_KLASS}", "project_id=self.project_id, qos_policy_id=policy_id, direction=direction, min_kbps=min_kbps, id=rule_id) qos_rule.create() return qos_rule def _make_qos_minpps_rule(self,", "_policy.id) def test_delete_policy_min_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.delete_policy_minimum_packet_rate_rule, self.ctxt,", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.delete_policy_minimum_packet_rate_rule, self.ctxt, self.min_pps_rule.id, _policy.id) def test_delete_policy_min_pps_rule_for_nonexistent_policy(self):", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", [self.dscp_rule]) self.qos_plugin.update_policy_dscp_marking_rule( self.ctxt, self.dscp_rule.id, self.policy.id,", "'test_plugin', payload=events.DBEventPayload( context, states=(original_port, port))) mock_alloc_change.assert_not_called() def test_check_port_for_placement_allocation_change_qos_network_policy( self): qos_network", "_make_network(self, qos_policy_id=None): network = network_object.Network(self.context, qos_policy_id=qos_policy_id) network.create() return network def", "test_get_ports_with_policy(self): network_ports = [ mock.MagicMock(qos_policy_id=None), mock.MagicMock(qos_policy_id=uuidutils.generate_uuid()), mock.MagicMock(qos_policy_id=None) ] ports =", "qos_exc.QosPolicyNotFound, self.qos_plugin.update_policy_packet_rate_limit_rule, self.ctxt, self.pps_rule.id, self.policy.id, self.rule_data) def test_delete_policy_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "= [ mock.call( original_qos, qos, {'id': port1.id, 'device_owner': 'compute:uu:id', 'qos_policy_id':", "= self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation( qos1, qos2, original_min_kbps=1000, desired_min_kbps=1000,", "= mock.call.update() update_precommit_mock_call = mock.call.driver.call( 'update_policy_precommit', self.ctxt, mock.ANY) update_mock_call =", "{orc.NET_BW_EGR_KILOBIT_PER_SEC: 10}, port['resource_request']['request_groups'][0]['resources'], ) self.assertEqual( ['fake_uuid'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_min_pps_rule(self):", "test_get_policy_minimum_bandwidth_rule(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumBandwidthRule.' 'get_object') as get_object_mock:", "None, 'qos_network_policy_id': None}, mock.ANY), ] mock_alloc_change.assert_has_calls(mock_alloc_change_calls, any_order=True) port1.update() self.assertDictEqual(port1.bindings[0].profile, {})", "rule_actions = {'create': [self.ctxt, rule_cls_mock, self.policy.id, {'fake_rule': {}}], 'update': [self.ctxt,", "def test_get_policy_min_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_minimum_packet_rate_rule, self.ctxt, self.min_pps_rule.id,", "obtain # a copy of the License at # #", "webob.exc.HTTPClientError(code=res.status_int) return self.deserialize(self.fmt, res) def _delete_rule(self, rule_type, rule_id): resource =", "port_mock = mock.MagicMock(id=port_id, qos_policy_id=policy_id) policy_mock = mock.MagicMock(id=policy_id) admin_ctxt = mock.Mock()", "def test_get_policy_minimum_bandwidth_rule(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumBandwidthRule.' 'get_object') as", "with mock.patch('neutron.objects.qos.rule.' 'QosMinimumBandwidthRule.' 'get_objects') as get_objects_mock: filters = {'filter': 'filter_id'}", "port['resource_request']['request_groups'] ) self.assertEqual( ['fake_uuid0', 'fake_uuid1'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_no_qos_policy(self): port", "with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: mock_update_qos_alloc.side_effect = ks_exc.Conflict( response={'errors': [{'code':", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosBandwidthLimitRule.' 'get_objects') as get_objects_mock: filters =", "= self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation( None, desired_qos, qos_network_policy=qos_network, original_min_kbps=1000,", "self.ctxt, _policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) self.mock_qos_load_attr.assert_called_once_with('rules') mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_rule_check_rule_max_more_than_min(self):", "directory.get_plugin(plugins_constants.QOS) self.qos_plugin.driver_manager = mock.Mock() self.rpc_push = mock.patch('neutron.api.rpc.handlers.resources_rpc' '.ResourcesPushRpcApi.push').start() self.ctxt =", "self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt, _policy.id, new_rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_min_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "{}) def test_check_network_for_placement_allocation_change(self): original_qos = self._make_qos_policy() qos = self._make_qos_policy() original_network", "} port = {} with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(", "as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_PPS_RP:", "self.qos_plugin = directory.get_plugin(plugins_constants.QOS) self.qos_plugin.driver_manager = mock.Mock() self.rpc_push = mock.patch('neutron.api.rpc.handlers.resources_rpc' '.ResourcesPushRpcApi.push').start()", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.update_policy_minimum_packet_rate_rule, self.ctxt, self.min_pps_rule.id, self.policy.id, self.rule_data) def", "self.ctxt, self.rule.id, _policy.id) def test_get_policy_bandwidth_limit_rule(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.'", "[self.rule, self.min_bw_rule] setattr(_policy, \"rules\", rules) self.mock_qos_load_attr.reset_mock() with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.update_policy_minimum_bandwidth_rule(", "self._make_qos_policy() kwargs = self._prepare_for_port_placement_allocation_change( qos1=qos1_obj, qos2=qos1_obj) context = kwargs['context'] original_port", "def test_change_placement_allocation_update_generation_conflict(self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() orig_port, port", "= self._prepare_for_port_placement_allocation_change( qos1=qos1_obj, qos2=None) context = kwargs['context'] original_port = kwargs['original_port']", "'test-policy', 'description': 'Test policy description', 'shared': True, 'is_default': False} with", "with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos_network, desired_qos, orig_port, port)", "neutron_qos_exc from neutron.extensions import qos_pps_minimum_rule_alias from neutron.extensions import qos_rules_alias from", "from neutron.objects import ports as ports_object from neutron.objects.qos import policy", "'id': uuidutils.generate_uuid(), 'min_kpps': 10, 'direction': 'any'}, } self.policy = policy_object.QosPolicy(", "'QosMinimumPacketRateRule.' 'get_objects') as get_objects_mock: filters = {'filter': 'filter_id'} self.qos_plugin.get_policy_minimum_packet_rate_rules( self.ctxt,", "= mock.Mock() rule_cls_mock.rule_type = 'fake' rule_actions = {'create': [self.ctxt, rule_cls_mock,", "rule_id, self.fmt) res = request.get_response(self.ext_api) if res.status_int >= webob.exc.HTTPClientError.code: raise", "self.assertRaises( lib_exc.NotAuthorized, self.qos_plugin.get_rule_type, self.ctxt, qos_consts.RULE_TYPE_MINIMUM_PACKET_RATE) class QoSRuleAliasTestExtensionManager(object): def get_resources(self): return", "pl_exc from neutron_lib.exceptions import qos as qos_exc from neutron_lib.objects import", "= copy.copy(self.policy) setattr(_policy, \"rules\", []) mock_qos_policy_get.return_value = _policy mock_manager =", "= '%s/alias-%s-rules' % (qos.ALIAS, rule_type.replace('_', '-')) request = self.new_update_request(resource, data,", "def _make_qos_policy(self): qos_policy = policy_object.QosPolicy( self.context, project_id=self.project_id, shared=False, is_default=False) qos_policy.create()", "= self._create_and_extend_ports([], [self.min_pps_rule]) for port in ports: self.assertEqual( 1, len(port['resource_request']['request_groups'])", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosDscpMarkingRule.' 'get_objects') as get_objects_mock: filters =", "= {'qos_plugin_name': SERVICE_PLUGIN_KLASS} ext_mgr = QoSRuleAliasTestExtensionManager() super(TestQoSRuleAlias, self).setUp(plugin=plugin, ext_mgr=ext_mgr, service_plugins=service_plugins)", "raised\") def test_validate_policy_for_network(self): network = uuidutils.generate_uuid() with mock.patch.object( self.qos_plugin.driver_manager, \"validate_rule_for_network\",", "'test_plugin', payload=events.DBEventPayload( context, states=(original_port, port))) mock_alloc_change.assert_not_called() def test_check_port_for_placement_allocation_change(self): qos1_obj =", "setattr(_policy, \"rules\", [self.dscp_rule]) self.qos_plugin.create_policy_dscp_marking_rule( self.ctxt, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def", "'fake-driver', 'supported_parameters': [{ 'parameter_name': 'max_kpps', 'parameter_type': lib_constants.VALUES_TYPE_RANGE, 'parameter_range': {'start': 0,", "qos_network_policy_id=qos_network_policy_id, mac_address=mac, id=port_id) port.create() return port def _make_network(self, qos_policy_id=None): network", "self.ctxt = context.Context('fake_user', 'fake_tenant') self.admin_ctxt = context.get_admin_context() self.policy_data = {", "as mock_validate_policy: self.qos_plugin._validate_create_network_callback( \"NETWORK\", \"precommit_create\", \"test_plugin\", payload=events.DBEventPayload( self.context, resource_id=kwargs['network']['id'],)) qos_policy", "port = {} with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1,", "self.qos_plugin.create_policy(self.ctxt, self.policy_data) policy_mock_call = mock.call.QosPolicy().create() create_precommit_mock_call = mock.call.driver.call( 'create_policy_precommit', self.ctxt,", "context, states=(original_port, port))) mock_alloc_change.assert_not_called() def test_check_port_for_placement_allocation_change(self): qos1_obj = self._make_qos_policy() qos2_obj", "neutron.tests.unit.db import test_db_base_plugin_v2 from neutron.tests.unit.services.qos import base DB_PLUGIN_KLASS = 'neutron.db.db_base_plugin_v2.NeutronDbPluginV2'", "mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( original_qos, desired_qos, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_PPS_RP: {", "test_get_policy_packet_rate_limit_rules_for_policy_with_filters(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosPacketRateLimitRule.' 'get_objects') as get_objects_mock:", "port['resource_request']['request_groups'] ) self.assertIn( { 'id': 'fake_uuid1', 'required': ['CUSTOM_VNIC_TYPE_NORMAL'], 'resources': {", "project_id, 'name': 'test-policy', 'description': 'Test policy description', 'shared': True, 'is_default':", "self.qos_plugin.delete_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, self.policy.id) def test_verify_bad_method_call(self): self.assertRaises(AttributeError, getattr, self.qos_plugin, 'create_policy_bandwidth_limit_rules')", "return_value=[port]): try: self.qos_plugin.create_policy_minimum_packet_rate_rule( self.ctxt, _policy.id, self.rule_data) except NotImplementedError: self.fail() def", "with mock.patch.object(self.qos_plugin, 'validate_policy_for_network') \\ as mock_validate_policy: self.qos_plugin._validate_create_network_callback( \"NETWORK\", \"precommit_create\", \"test_plugin\",", "setattr(_policy, \"rules\", [self.min_pps_rule]) rules = [ { 'minimum_packet_rate_rule': { 'id':", "return_value=min_pps_rules), \\ mock.patch( 'uuid.uuid5', return_value='fake_uuid', side_effect=request_groups_uuids): return qos_plugin.QoSPlugin._extend_port_resource_request_bulk( ports_res, None)", "self.qos_plugin.get_rule_types(self.ctxt, filters=filters) self.assertEqual(sorted(qos_consts.VALID_RULE_TYPES), sorted(type_['type'] for type_ in types)) @mock.patch('neutron.objects.ports.Port') @mock.patch('neutron.objects.qos.policy.QosPolicy')", "mock.ANY) self.assertTrue( mock_manager.mock_calls.index(policy_update_mock_call) < mock_manager.mock_calls.index(update_precommit_mock_call) < mock_manager.mock_calls.index(update_mock_call)) @mock.patch('neutron.objects.db.api.get_object', return_value=None) @mock.patch.object(policy_object.QosPolicy,", "= mock.call.delete() delete_precommit_mock_call = mock.call.driver.call( 'delete_policy_precommit', self.ctxt, mock.ANY) delete_mock_call =", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosPacketRateLimitRule.' 'get_object') as get_object_mock: self.qos_plugin.get_policy_packet_rate_limit_rule(", "{ self.MIN_BW_REQUEST_GROUP_UUID: self.MIN_BW_RP}}, 'device_id': 'uu:id', 'id': '9416c220-160a-11ec-ba3d-474633eb825c', } port =", "port_mock) def test_validate_update_port_callback_policy_changed(self): self._test_validate_update_port_callback( policy_id=uuidutils.generate_uuid()) def test_validate_update_port_callback_policy_not_changed(self): policy_id = uuidutils.generate_uuid()", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosPacketRateLimitRule.' 'get_objects') as get_objects_mock: self.qos_plugin.get_policy_packet_rate_limit_rules(", "uuidutils.generate_uuid() qos_rule = rule_object.QosMinimumPacketRateRule( self.context, project_id=self.project_id, qos_policy_id=policy_id, direction=direction, min_kpps=min_kpps, id=rule_id)", "= uuidutils.generate_uuid() self.rule_data = { 'minimum_packet_rate_rule': {'min_kpps': 10, 'direction': 'any'}", "self.qos_plugin.get_policy_minimum_packet_rate_rules( self.ctxt, self.policy.id, filters=filters) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id, filter='filter_id') def", "130}, 'minimum_packet_rate_rule': { 'id': uuidutils.generate_uuid(), 'min_kpps': 10, 'direction': 'any'}, }", "self.assertIsNone(port.get('resource_request')) def test__extend_port_resource_request_min_bw_non_provider_net(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION port = self._create_and_extend_port([self.min_bw_rule], physical_network=None)", "get_policy.assert_called_once_with(admin_ctxt, id=policy_id) get_ports.assert_called_once_with(self.ctxt, network_id=network_id) validate_policy_for_ports.assert_called_once_with( self.ctxt, policy_mock, [port_mock_without_own_policy]) def test_validate_update_network_callback_policy_changed(self):", "mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_update_policy_packet_rate_limit_rule(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with", "cfg from oslo_utils import uuidutils import webob.exc from neutron.exceptions import", "any_order=True) @mock.patch.object(qos_plugin.QoSPlugin, \"get_policy_rule\") def test_show_rule(self, get_policy_rule_mock): calls = [] for", "new_rule_data = { 'bandwidth_limit_rule': { 'max_kbps': 5000, 'direction': self.rule.direction }", "= { 'binding:profile': {'allocation': { self.MIN_BW_REQUEST_GROUP_UUID: self.MIN_BW_RP}}, 'device_id': 'uu:id', 'id':", "'filter_id'} self.qos_plugin.get_policy_bandwidth_limit_rules( self.ctxt, self.policy.id, filters=filters) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id, filter='filter_id')", "uuidutils.generate_uuid(), 'dscp_mark': 16}, 'minimum_bandwidth_rule': { 'id': uuidutils.generate_uuid(), 'min_kbps': 10}, 'packet_rate_limit_rule':", "self.ctxt, self.policy, port) def test_validate_policy_for_port_all_rules_valid(self): port = {'id': uuidutils.generate_uuid()} with", "self.qos_plugin.get_policy_bandwidth_limit_rules, self.ctxt, self.policy.id) def test_create_policy_dscp_marking_rule(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy'])", "lib_constants.EGRESS_DIRECTION self.min_bw_rule.qos_policy_id = self.policy.id port = self._create_and_extend_port([self.min_bw_rule], has_net_qos_policy=True) self.assertEqual( 1,", "'update_qos_allocation') as mock_update_qos_alloc: self.assertRaises(NotImplementedError, self.qos_plugin._change_placement_allocation, qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_not_called()", "self.qos_plugin.validate_policy_for_port, self.ctxt, self.policy, port) def test_validate_policy_for_port_all_rules_valid(self): port = {'id': uuidutils.generate_uuid()}", "QoS policy self._make_port(network_id=network.id, qos_policy_id=port_qos.id, device_owner='compute:uu:id') ml2plugin_mock = mock.MagicMock() with mock.patch.object(", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "\"rules\", [self.pps_rule]) self.qos_plugin.delete_policy_packet_rate_limit_rule( self.ctxt, self.pps_rule.id, self.policy.id) self._validate_driver_params('update_policy', self.ctxt) def test_delete_policy_pps_rule_bad_policy(self):", "self._make_qos_minbw_rule(qos1.id, min_kbps=500) qos1.rules = [rule1_obj] qos2 = self._make_qos_policy() rule2_obj =", "mock.patch('neutron.objects.qos.rule.' 'QosPacketRateLimitRule.' 'get_objects') as get_objects_mock: filters = {'filter': 'filter_id'} self.qos_plugin.get_policy_packet_rate_limit_rules(", "rule = rule_object_class(self.ctxt, id=rule_id, qos_policy_id=self.qos_policy_id, **data) with mock.patch( 'neutron.objects.qos.rule.QosRule.get_object', return_value=rule", "mock_alloc_change.assert_not_called() def test_check_port_for_placement_allocation_change(self): qos1_obj = self._make_qos_policy() qos2_obj = self._make_qos_policy() kwargs", "= mock.call.driver.call( 'create_policy_precommit', self.ctxt, mock.ANY) create_mock_call = mock.call.driver.call( 'create_policy', self.ctxt,", "= self._get_policy() setattr(_policy, \"rules\", [self.rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.update_policy_bandwidth_limit_rule( self.ctxt,", "'set_default').start() cfg.CONF.set_override(\"core_plugin\", DB_PLUGIN_KLASS) cfg.CONF.set_override(\"service_plugins\", [\"qos\"]) manager.init() self.qos_plugin = directory.get_plugin(plugins_constants.QOS) self.qos_plugin.driver_manager", "self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt, _policy.id, self.rule_data) def test_create_min_pps_rule_on_unbound_port(self): _policy = self._get_policy() setattr(_policy,", "test_get_rule_types(self): filters = {'type': 'type_id'} with mock.patch.object(qos_plugin.QoSPlugin, 'supported_rule_types', return_value=qos_consts.VALID_RULE_TYPES): types", "return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosPacketRateLimitRule.' 'get_objects') as get_objects_mock: self.qos_plugin.get_policy_packet_rate_limit_rules( self.ctxt, self.policy.id)", "get_policy_rule_mock): calls = [] for rule_type, rule_object_class in self.rule_objects.items(): rule_id", "ml2plugin_mock, payload=events.DBEventPayload( self.context, states=(original_network, network))) mock_alloc_change.assert_not_called() ml2plugin_mock._make_port_dict.assert_not_called() def test_check_network_for_placement_allocation_change_no_ports_to_update( self):", "copy.copy(self.policy) setattr(_policy, \"rules\", []) mock_qos_policy_get.return_value = _policy mock_manager = mock.Mock()", "self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': -1000}, self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': -2000}}) def test_change_placement_allocation_no_min_bw(self): qos1", "def test__extend_port_resource_request_min_bw_non_provider_net(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION port = self._create_and_extend_port([self.min_bw_rule], physical_network=None) self.assertIsNone(port.get('resource_request'))", "if res.status_int >= webob.exc.HTTPClientError.code: raise webob.exc.HTTPClientError(code=res.status_int) return self.deserialize(self.fmt, res) def", "in ports: self.assertEqual( 1, len(port['resource_request']['request_groups']) ) self.assertEqual( 'fake_uuid', port['resource_request']['request_groups'][0]['id'] )", "self.qos_plugin._change_placement_allocation(qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_min_bw_dataplane_enforcement_with_pps( self): qos1 =", "}, ] for new_rule_data in rules: with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as", "self.policy.id]} mock_manager = mock.Mock() mock_manager.attach_mock(qos_policy_mock, 'QosPolicy') mock_manager.attach_mock(port_mock, 'Port') mock_manager.attach_mock(rule_cls_mock, 'RuleCls')", "self.ctxt, self.pps_rule.id, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def test_update_policy_pps_rule_bad_policy(self): _policy =", "id=rule_id) qos_rule.create() return qos_rule def _make_port(self, network_id, qos_policy_id=None, port_id=None, qos_network_policy_id=None,", "= rule_object.QosPacketRateLimitRule( self.ctxt, **self.rule_data['packet_rate_limit_rule']) self.min_pps_rule = rule_object.QosMinimumPacketRateRule( self.ctxt, **self.rule_data['minimum_packet_rate_rule']) def", "return_value=rule): self._show_rule(rule_type, rule_id) calls.append(mock.call(mock.ANY, rule_object_class, rule_id, self.qos_policy_id)) get_policy_rule_mock.assert_has_calls(calls, any_order=True) @mock.patch.object(qos_plugin.QoSPlugin,", "qos_network_policy qos.rules = [] allocation = {} if original_min_kbps: qos.rules", "\\ as mock_validate_policy: self.qos_plugin._validate_create_network_callback( \"NETWORK\", \"precommit_create\", \"test_plugin\", payload=events.DBEventPayload( self.context, resource_id=kwargs['network']['id'],))", "as get_objects_mock: self.qos_plugin.get_policy_bandwidth_limit_rules( self.ctxt, self.policy.id) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id) def", "pl_exc.PlacementAllocationGenerationConflict, self.qos_plugin._change_placement_allocation, qos1, qos2, orig_port, port) def test_change_placement_allocation_qos_network_policy(self): qos_network =", "test_validate_update_port_callback_policy_changed(self): self._test_validate_update_port_callback( policy_id=uuidutils.generate_uuid()) def test_validate_update_port_callback_policy_not_changed(self): policy_id = uuidutils.generate_uuid() self._test_validate_update_port_callback( policy_id=policy_id,", "def _get_policy(self): return policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) def test_update_policy_rule_bad_policy(self): _policy =", "def test_update_policy_rule_bad_policy(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy):", "context.Context('fake_user', 'fake_tenant') self.admin_ctxt = context.get_admin_context() self.policy_data = { 'policy': {'id':", "self.policy.id, {'fake_rule': {}}], 'update': [self.ctxt, rule_cls_mock, self.rule.id, self.policy.id, {'fake_rule': {}}],", "original_min_kbps=None, desired_min_kbps=None, original_min_kpps=None, desired_min_kpps=None, is_sriov=False): kwargs = self._prepare_for_port_placement_allocation_change( original_qos, desired_qos,", "port) except qos_exc.QosRuleNotSupported: self.fail(\"QosRuleNotSupported exception unexpectedly raised\") def test_validate_policy_for_network(self): network", "= mock.MagicMock(id=policy_id) admin_ctxt = mock.Mock() with mock.patch( 'neutron.objects.ports.Port.get_object', return_value=port_mock )", "lib_constants.EGRESS_DIRECTION port = self._create_and_extend_port([self.min_bw_rule]) self.assertEqual( 1, len(port['resource_request']['request_groups']) ) self.assertEqual( 'fake_uuid',", "_policy = self._get_policy() self.rule_data['minimum_bandwidth_rule']['min_kbps'] = 1000000 setattr(_policy, \"rules\", [self.rule]) with", "self.qos_plugin.get_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, self.policy.id) def test_get_policy_bandwidth_limit_rules_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises(", "self.qos_plugin.create_policy_packet_rate_limit_rule( self.ctxt, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) def test_create_policy_pps_rule_duplicates(self): _policy =", "port = {} with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(qos1, qos2,", "= [bw_limit_rule] with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(qos1, qos2, orig_port,", "test_create_policy_min_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt, self.policy.id, self.rule_data)", "= self.qos_plugin.get_rule_type( admin_ctxt, qos_consts.RULE_TYPE_BANDWIDTH_LIMIT) self.assertEqual( qos_consts.RULE_TYPE_BANDWIDTH_LIMIT, rule_type_details['type']) self.assertEqual( drivers_details, rule_type_details['drivers'])", "'get_objects', return_value=min_pps_rules), \\ mock.patch( 'uuid.uuid5', return_value='fake_uuid', side_effect=request_groups_uuids): return qos_plugin.QoSPlugin._extend_port_resource_request_bulk( ports_res,", "20}, }, port['resource_request']['request_groups'] ) self.assertIn( { 'id': 'fake_uuid1', 'required': ['CUSTOM_VNIC_TYPE_NORMAL'],", "in qos2.rules: rule.direction = 'any' with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc:", "} self.qos_policy_id = uuidutils.generate_uuid() self.rule_data = { 'bandwidth_limit_rule': {'max_kbps': 100,", "'driver') mock_manager.reset_mock() _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy):", "self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.delete_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, _policy.id) def test_get_policy_bandwidth_limit_rule(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "obj_utils from neutron_lib.plugins import constants as plugins_constants from neutron_lib.plugins import", "test__extend_port_resource_request_min_bw_and_pps_rule(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION self.min_pps_rule.direction = lib_constants.EGRESS_DIRECTION request_groups_uuids = ['fake_uuid0',", "self.ctxt, self.pps_rule.id, self.policy.id) get_object_mock.assert_called_once_with(self.ctxt, id=self.pps_rule.id) def test_get_policy_packet_rate_limit_rules_for_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy):", "'CUSTOM_VNIC_TYPE_NORMAL'], port['resource_request']['request_groups'][0]['required'] ) self.assertEqual( {orc.NET_BW_EGR_KILOBIT_PER_SEC: 10}, port['resource_request']['request_groups'][0]['resources'], ) self.assertEqual( ['fake_uuid'],", "consumer_uuid='uu:id', alloc_diff={ self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': 500}, self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': 1000}}) def", "port = self._make_port(network.id, qos_policy_id=port_qos_id) kwargs = {\"context\": self.context, \"port\": {\"id\":", "mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_no_original_allocation(self): qos1 =", "= uuidutils.generate_uuid() self._test_validate_update_port_callback( policy_id=policy_id, original_policy_id=policy_id) def test_validate_update_port_callback_policy_removed(self): self._test_validate_update_port_callback( policy_id=None, original_policy_id=uuidutils.generate_uuid())", "{ 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': 500}, self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': 1000}}) def test_change_placement_allocation_change_direction_min_pps_and_min_bw( self): qos1", "orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={ self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': 500}}) def", "self.rule_objects = { 'minimum_packet_rate': rule_object.QosMinimumPacketRateRule } self.qos_policy_id = uuidutils.generate_uuid() self.rule_data", "return_value=_policy): setattr(_policy, \"rules\", [self.pps_rule]) self.qos_plugin.create_policy_packet_rate_limit_rule( self.ctxt, self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt)", "test_show_non_existing_rule(self): for rule_type, rule_object_class in self.rule_objects.items(): rule_id = uuidutils.generate_uuid() with", "= self._create_and_extend_ports([self.min_bw_rule]) for port in ports: self.assertEqual( 1, len(port['resource_request']['request_groups']) )", "setattr(_policy, \"rules\", []) self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.delete_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, _policy.id) def", "return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosBandwidthLimitRule.' 'get_objects') as get_objects_mock: self.qos_plugin.get_policy_bandwidth_limit_rules( self.ctxt, self.policy.id)", "ml2plugin_mock._make_port_dict.side_effect = fake_make_port_dict port1 = self._make_port( network_id=network.id, qos_policy_id=None, device_owner='compute:uu:id') port1_binding", "getattr( mock.call.QosPolicy.get_policy_obj().get_rule_by_id(), action)() # some actions construct rule from class", "for rule in qos2.rules: rule.direction = 'egress' with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation')", "self.ctxt, self.policy.id) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id) def test_get_policy_packet_rate_limit_rules_for_policy_with_filters(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "8bf8eb46-160e-11ec-8024-9f96be32099d MIN_BW_REQUEST_GROUP_UUID = 'c8bc1b27-59a1-5135-aa33-aeecad6093f4' MIN_BW_RP = 'd7bea120-1626-11ec-9148-c32debfcf0f6' QOS_MIN_PPS_RULE_ID = '6ac5db7e-1626-11ec-8c7f-0b70dbb8a8eb'", "rules) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.update_policy_minimum_packet_rate_rule, self.ctxt, rule_data['minimum_packet_rate_rule']['id'],", "self._show_rule(rule_type, rule_id) calls.append(mock.call(mock.ANY, rule_object_class, rule_id, self.qos_policy_id)) get_policy_rule_mock.assert_has_calls(calls, any_order=True) @mock.patch.object(qos_plugin.QoSPlugin, \"delete_policy_rule\")", "mock_manager.attach_mock(mock_qos_rule_update, 'update') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy'])", "'neutron.objects.ports.Port.get_objects', side_effect=[network_ports, ports] ), mock.patch.object( self.policy, \"get_bound_networks\" ), mock.patch.object( self.policy,", "self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(policy_mock_call) < mock_manager.mock_calls.index(create_precommit_mock_call) < mock_manager.mock_calls.index(create_mock_call)) def test_add_policy_with_extra_tenant_keyword(self,", "self.assertIn( { 'id': 'fake_uuid1', 'required': ['CUSTOM_VNIC_TYPE_NORMAL'], 'resources': { orc.NET_PACKET_RATE_EGR_KILOPACKET_PER_SEC: 10,", "return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosPacketRateLimitRule.' 'get_objects') as get_objects_mock: filters = {'filter':", "filter='filter_id') def test_get_policy_dscp_marking_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_dscp_marking_rule, self.ctxt,", "return { 'id': port.id, 'device_owner': port.device_owner, 'qos_policy_id': port.qos_policy_id, 'qos_network_policy_id': port.qos_network_policy_id,", "port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_new_rule_not_min_bw(self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy()", "port def _make_network(self, qos_policy_id=None): network = network_object.Network(self.context, qos_policy_id=qos_policy_id) network.create() return", "'%s_rule' % rule_type data = self.rule_data[rule_data_name] rule = rule_object_class(self.ctxt, id=rule_id,", "self.new_show_request(resource, rule_id, self.fmt) res = request.get_response(self.ext_api) self.assertEqual(webob.exc.HTTPNotFound.code, res.status_int) class TestQoSRuleAliasMinimumPacketRate(TestQoSRuleAlias):", "'.ResourcesPushRpcApi.push').start() self.context = context.get_admin_context() self.project_id = uuidutils.generate_uuid() def _make_qos_policy(self): qos_policy", "2.0 (the \"License\"); you may # not use this file", "rule_object.QosMinimumBandwidthRule } self.qos_policy_id = uuidutils.generate_uuid() self.rule_data = { 'bandwidth_limit_rule': {'max_kbps':", "rule_type, rule_id, **kwargs): data = {'alias_%s_rule' % rule_type: kwargs} resource", "= mock.call.driver.call('update_policy', self.ctxt, mock.ANY) if rule_mock_call in mock_manager.mock_calls: action_index =", "_pager=mock.ANY, qos_policy_id=self.policy.id, filter='filter_id') def test_get_policy_packet_rate_limit_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound,", "port_qos=False, network_qos=False): net_qos_obj = self._make_qos_policy() port_qos_obj = self._make_qos_policy() net_qos_id =", "self.min_bw_rule = rule_object.QosMinimumBandwidthRule( self.ctxt, **self.rule_data['minimum_bandwidth_rule']) self.pps_rule = rule_object.QosPacketRateLimitRule( self.ctxt, **self.rule_data['packet_rate_limit_rule'])", "{'filter': 'filter_id'} self.qos_plugin.get_policy_minimum_bandwidth_rules( self.ctxt, self.policy.id, filters=filters) get_objects_mock.assert_called_once_with( self.ctxt, _pager=mock.ANY, qos_policy_id=self.policy.id,", "mock_manager.mock_calls.index(driver_mock_call)) def test_create_policy_packet_rate_limit_rule(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "def test_update_policy_dscp_marking_rule(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy):", "original_min_kbps=2000, desired_min_kbps=1000, is_sriov=True) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( original_qos,", "[]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.update_policy_minimum_packet_rate_rule, self.ctxt, self.min_pps_rule.id, self.policy.id,", "\"rules\", []) self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.update_policy_packet_rate_limit_rule, self.ctxt, self.pps_rule.id, self.policy.id, self.rule_data) def", "qos1, qos2, original_min_kbps=1000, desired_min_kbps=2000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: mock_update_qos_alloc.side_effect", "def test_create_min_bw_rule_on_unbound_port(self): policy = self._get_policy() policy.rules = [self.min_bw_rule] segment =", "'minimum_packet_rate_rule': { 'id': uuidutils.generate_uuid(), 'min_kpps': 10, 'direction': 'any'}, } self.policy", "test_get_policy_min_pps_rules_for_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumPacketRateRule.' 'get_objects') as get_objects_mock:", "def test__extend_port_resource_request_bulk_min_bw_and_pps_rule(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION self.min_pps_rule.direction = lib_constants.EGRESS_DIRECTION request_groups_uuids =", "def get_request_extensions(self): return [] class TestQoSRuleAlias(test_db_base_plugin_v2.NeutronDbPluginV2TestCase): def setUp(self): # Remove", "original_policy_id: get_policy.assert_not_called() validate_policy_for_network.assert_not_called() get_ports.assert_not_called() validate_policy_for_ports.assert_not_called() else: get_policy.assert_called_once_with(admin_ctxt, id=policy_id) get_ports.assert_called_once_with(self.ctxt, network_id=network_id)", "'compute:uu:id', 'qos_policy_id': None, 'qos_network_policy_id': qos.id}, mock.ANY)] mock_alloc_change.assert_has_calls(mock_alloc_change_calls, any_order=True) port1.update() port2.update()", "method(*arguments) # some actions get rule from policy get_rule_mock_call =", "return self.deserialize(self.fmt, res) def _delete_rule(self, rule_type, rule_id): resource = '%s/alias-%s-rules'", "self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation( None, desired_qos, qos_network_policy=qos_network, original_min_kbps=1000, desired_min_kbps=2000)", "test_get_rule_type(self): admin_ctxt = context.get_admin_context() drivers_details = [{ 'name': 'fake-driver', 'supported_parameters':", "= self._get_policy() setattr(_policy, \"rules\", [self.rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj:", "return_value=drivers_details ): rule_type_details = self.qos_plugin.get_rule_type( admin_ctxt, qos_consts.RULE_TYPE_MINIMUM_PACKET_RATE) self.assertEqual( qos_consts.RULE_TYPE_MINIMUM_PACKET_RATE, rule_type_details['type'])", "from neutron.extensions import qos_pps_minimum_rule_alias from neutron.extensions import qos_rules_alias from neutron", "self.policy.id, self.rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_rule_duplicates(self): _policy = self._get_policy() setattr(_policy,", "by applicable law or agreed to in writing, software #", "self.qos_plugin.get_policy_minimum_bandwidth_rule( self.ctxt, self.rule.id, self.policy.id) get_object_mock.assert_called_once_with(self.ctxt, id=self.rule.id) def test_get_policy_minimum_bandwidth_rules_for_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.create_policy_packet_rate_limit_rule, self.ctxt, self.policy.id, self.rule_data) def", "= self._make_qos_policy() kwargs = self._prepare_for_port_placement_allocation_change( qos1=qos1_obj, qos2=None) context = kwargs['context']", "'id': uuidutils.generate_uuid(), 'min_kpps': 10, 'direction': 'ingress' } }, { 'minimum_packet_rate_rule':", "states=(original_network, network))) self.assertEqual(ml2plugin_mock._make_port_dict.call_count, 1) mock_alloc_change_calls = [ mock.call( original_qos, None,", "port2.update() self.assertDictEqual( port1.bindings[0].profile, {'allocation': 'fake_allocation'}) self.assertDictEqual( port2.bindings[0].profile, {'allocation': 'fake_allocation'}) def", "self.assertIn('pci_vendor_info', port['binding:profile']) self.assertIn('physical_network', port['binding:profile']) def test_change_placement_allocation_increase(self): qos1 = self._make_qos_policy() qos2", "= self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation( original_qos, desired_qos, original_min_kpps=2000, desired_min_kpps=1000,", "mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_new_rule_not_min_bw(self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() bw_limit_rule", "\"port\": { \"id\": port_id, qos_consts.QOS_POLICY_ID: policy_id }, \"original_port\": { \"id\":", "qos2, original_min_kbps=1000, desired_min_kbps=2000, original_min_kpps=500, desired_min_kpps=1000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc:", "import exceptions as ks_exc import netaddr from neutron_lib.api.definitions import qos", "desired_qos=None, qos_network_policy=None, original_min_kbps=None, desired_min_kbps=None, original_min_kpps=None, desired_min_kpps=None, is_sriov=False): kwargs = self._prepare_for_port_placement_allocation_change(", "mock_qos_policy_get): mock_qos_policy_get.return_value = self.policy mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_policy_update, 'update') mock_manager.attach_mock(self.qos_plugin.driver_manager,", "policy as policy_object from neutron.objects.qos import rule as rule_object from", "return_value='fake_uuid', side_effect=request_groups_uuids): return qos_plugin.QoSPlugin._extend_port_resource_request_bulk( ports_res, None) def test__extend_port_resource_request_min_bw_rule(self): self.min_bw_rule.direction =", "network = self._make_network(qos_policy_id=net_qos_id) kwargs = {\"context\": self.context, \"network\": network} with", "kwargs['context'] original_port = kwargs['original_port'] port = kwargs['port'] with mock.patch.object( self.qos_plugin,", "network.create() return network def _test_validate_create_network_callback(self, network_qos=False): net_qos_obj = self._make_qos_policy() net_qos_id", "None}, mock.ANY), ] mock_alloc_change.assert_has_calls(mock_alloc_change_calls, any_order=True) port1.update() self.assertDictEqual(port1.bindings[0].profile, {}) def test_check_network_for_placement_allocation_change(self):", "self.qos_plugin.update_policy_minimum_packet_rate_rule, self.ctxt, rule_data['minimum_packet_rate_rule']['id'], self.policy.id, self.rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_update_policy_min_pps_rule_bad_policy(self): _policy", "self.ctxt) self.mock_qos_load_attr.assert_called_once_with('rules') mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_rule_check_rule_bwlimit_less_than_minbw(self): _policy = self._get_policy() self.rule_data['bandwidth_limit_rule']['max_kbps']", "return policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) def test_update_policy_rule_bad_policy(self): _policy = policy_object.QosPolicy( self.ctxt,", "mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() self.qos_plugin.create_policy(self.ctxt, self.policy_data) policy_mock_call = mock.call.QosPolicy().create() create_precommit_mock_call =", "get_port.assert_not_called() get_policy.assert_not_called() validate_policy_for_port.assert_not_called() else: get_port.assert_called_once_with(self.ctxt, id=port_id) get_policy.assert_called_once_with(admin_ctxt, id=policy_id) validate_policy_for_port.assert_called_once_with( self.ctxt,", "network = self._make_network(qos_policy_id=qos_network_policy_id) port = self._make_port( network.id, qos_policy_id=qos1_id, port_id=TestQosPluginDB.PORT_ID) return", "models as per mocks above. We also need to mock-out", "port['resource_request']['request_groups'][0]['resources'], ) self.assertEqual( ['fake_uuid'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_bulk_min_pps_rule(self): ports =", "self.rule_data) def test_update_policy_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.update_policy_bandwidth_limit_rule, self.ctxt,", "{'id': port2.id, 'device_owner': 'compute:uu:id', 'qos_policy_id': None, 'qos_network_policy_id': qos.id}, mock.ANY)] mock_alloc_change.assert_has_calls(mock_alloc_change_calls,", "_policy = self._get_policy() setattr(_policy, \"rules\", [self.pps_rule]) new_rule_data = { 'packet_rate_limit_rule':", "mock_manager.mock_calls.index(policy_update_mock_call) < mock_manager.mock_calls.index(update_precommit_mock_call) < mock_manager.mock_calls.index(update_mock_call)) @mock.patch('neutron.objects.db.api.get_object', return_value=None) @mock.patch.object(policy_object.QosPolicy, 'delete') def", "mock.ANY) update_mock_call = mock.call.driver.call( 'update_policy', self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(policy_update_mock_call) <", "self.min_pps_rule.id, self.policy.id) get_object_mock.assert_called_once_with( self.ctxt, id=self.min_pps_rule.id) def test_get_policy_min_pps_rules_for_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy):", "get_actions(self): return [] def get_request_extensions(self): return [] class TestQoSRuleAlias(test_db_base_plugin_v2.NeutronDbPluginV2TestCase): def", "'update_policy', self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(policy_update_mock_call) < mock_manager.mock_calls.index(update_precommit_mock_call) < mock_manager.mock_calls.index(update_mock_call)) @mock.patch('neutron.objects.db.api.get_object',", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.delete_policy_packet_rate_limit_rule, self.ctxt, self.pps_rule.id, self.policy.id) def test_get_pps_rule_type(self):", "orc.NET_BW_EGR_KILOBIT_PER_SEC: 10, orc.NET_BW_IGR_KILOBIT_PER_SEC: 20}, }, port['resource_request']['request_groups'] ) self.assertIn( { 'id':", "rule_type_details = self.qos_plugin.get_rule_type( admin_ctxt, qos_consts.RULE_TYPE_PACKET_RATE_LIMIT) self.assertEqual( qos_consts.RULE_TYPE_PACKET_RATE_LIMIT, rule_type_details['type']) self.assertEqual( drivers_details,", "{ 'id': uuidutils.generate_uuid(), 'min_kpps': 10, 'direction': 'any'}, } self.policy =", "def test_delete_policy_rule_bad_policy(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy):", "id=uuidutils.generate_uuid(), network_id=uuidutils.generate_uuid(), device_owner='compute:fake-zone') with mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy), \\ mock.patch( 'neutron.objects.network.Network.get_object',", "QoSRuleAliasTestExtensionManager() super(TestQoSRuleAlias, self).setUp(plugin=plugin, ext_mgr=ext_mgr, service_plugins=service_plugins) self.qos_plugin = directory.get_plugin(plugins_constants.QOS) self.ctxt =", "rule_object.QosMinimumBandwidthRule( self.context, project_id=self.project_id, qos_policy_id=policy_id, direction=direction, min_kbps=min_kbps, id=rule_id) qos_rule.create() return qos_rule", "return orig_port, kwargs['port'] def _assert_pci_info(self, port): self.assertIn('pci_slot', port['binding:profile']) self.assertIn('pci_vendor_info', port['binding:profile'])", "= network_object.Network( self.ctxt, segments=[segment]) port = ports_object.Port( self.ctxt, id=uuidutils.generate_uuid(), network_id=uuidutils.generate_uuid(),", "= rule_object.QosMinimumBandwidthRule( self.context, project_id=self.project_id, qos_policy_id=policy_id, direction=direction, min_kbps=min_kbps, id=rule_id) qos_rule.create() return", "port = self._prepare_port_for_placement_allocation(qos1, original_min_kbps=1000, original_min_kpps=2000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc:", "= self._make_qos_policy() rule1_obj = self._make_qos_minbw_rule(qos1.id, min_kbps=500) qos1.rules = [rule1_obj] qos2", "mock.patch( 'neutron.objects.qos.rule.QosMinimumPacketRateRule.' 'get_objects', return_value=min_pps_rules), \\ mock.patch( 'uuid.uuid5', return_value='fake_uuid', side_effect=request_groups_uuids): return", "self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION port = self._create_and_extend_port([self.min_bw_rule], [self.min_pps_rule], physical_network=None) self.assertEqual( 1,", "return_value=policy_mock ) as get_policy, mock.patch.object( self.qos_plugin, \"validate_policy_for_network\" ) as validate_policy_for_network,", "def test_update_policy_min_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.update_policy_minimum_packet_rate_rule, self.ctxt, self.min_pps_rule.id,", "mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=policy_mock ) as get_policy, mock.patch.object( self.qos_plugin, \"validate_policy_for_network\" )", "self.policy.id, self.rule_data) def test_update_policy_min_pps_rule(self): _policy = self._get_policy() setattr(_policy, \"rules\", [self.min_pps_rule])", "delete_mock_call = mock.call.driver.call( 'delete_policy', self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(policy_delete_mock_call) < mock_manager.mock_calls.index(delete_precommit_mock_call)", "class QoSRuleAliasMinimumPacketRateTestExtensionManager(object): def get_resources(self): return qos_pps_minimum_rule_alias.Qos_pps_minimum_rule_alias.\\ get_resources() def get_actions(self): return", "physical_network='public', has_qos_policy=True, has_net_qos_policy=False, request_groups_uuids=None): network_id = uuidutils.generate_uuid() self.port_data = {", "{ 'max_kpps': 400, 'direction': self.pps_rule.direction } } with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy)", "self._make_qos_policy() qos2 = self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation( qos1, qos2,", "test_change_placement_allocation_increase_min_pps(self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() orig_port, port =", "qos1 = None qos2 = self._make_qos_policy() rule2_obj = self._make_qos_minbw_rule(qos2.id, min_kbps=1000)", "self.assertEqual( ['fake_uuid'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_min_pps_rule(self): port = self._create_and_extend_port([], [self.min_pps_rule])", "self.rule_data) def _get_policy(self): return policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) def test_update_policy_rule_bad_policy(self): _policy", "1) mock_alloc_change_calls = [ mock.call( original_qos, None, {'id': port1.id, 'device_owner':", "self.policy.id, self.rule_data) def test_delete_policy_packet_rate_limit_rule(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with", "if network_qos: qos_policy = net_qos_obj if qos_policy: mock_validate_policy.assert_called_once_with( self.context, qos_policy,", "QoSRuleAliasTestExtensionManager(object): def get_resources(self): return qos_rules_alias.Qos_rules_alias.get_resources() def get_actions(self): return [] def", "context = kwargs['context'] original_port = kwargs['original_port'] port = kwargs['port'] with", "self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation( original_qos, desired_qos, original_min_kbps=2000, desired_min_kbps=1000, is_sriov=True)", "qos1, qos2, orig_port, port) def test_change_placement_allocation_qos_network_policy(self): qos_network = self._make_qos_policy() desired_qos", "QoSRuleAliasMinimumPacketRateTestExtensionManager(object): def get_resources(self): return qos_pps_minimum_rule_alias.Qos_pps_minimum_rule_alias.\\ get_resources() def get_actions(self): return []", "): self.qos_plugin._validate_update_network_callback( \"NETWORK\", \"precommit_update\", \"test_plugin\", payload=events.DBEventPayload( self.ctxt, desired_state=kwargs['network'], states=(kwargs['original_network'],))) if", "mock.ANY) update_mock_call = mock.call.driver.call( 'update_policy', self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(rule_update_mock_call) <", "mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt, self.policy.id, new_rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) for rule_data", "self.ctxt) rules = [self.rule, self.min_bw_rule] setattr(_policy, \"rules\", rules) self.mock_qos_load_attr.reset_mock() with", "NotImplementedError: self.fail() def test_create_policy_rule_check_rule_min_pps_direction_conflict(self): _policy = self._get_policy() self.rule_data['minimum_packet_rate_rule']['direction'] = 'any'", "self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_bandwidth_limit_rule, self.ctxt, self.rule.id, self.policy.id) def test_get_policy_bandwidth_limit_rules_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "real data types mock.patch( 'neutron.objects.base.NeutronDbObject.modify_fields_from_db' ).start() mock.patch.object(policy_object.QosPolicy, 'unset_default').start() mock.patch.object(policy_object.QosPolicy, 'set_default').start()", "policy description', 'shared': True, 'is_default': False}} self.rule_data = { 'bandwidth_limit_rule':", "test_change_placement_allocation_change_direction_min_pps_and_min_bw( self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() orig_port, port", "qos_rule = rule_object.QosMinimumPacketRateRule( self.context, project_id=self.project_id, qos_policy_id=policy_id, direction=direction, min_kpps=min_kpps, id=rule_id) qos_rule.create()", "self.ctxt, \"network\": { \"id\": network_id, qos_consts.QOS_POLICY_ID: policy_id }, \"original_network\": {", "def test_check_network_for_placement_allocation_change(self): original_qos = self._make_qos_policy() qos = self._make_qos_policy() original_network =", "= {} mock_alloc_change.side_effect = fake_change_placement_allocation self.qos_plugin._check_network_for_placement_allocation_change( 'network', 'after_update', ml2plugin_mock, payload=events.DBEventPayload(", "ports_object.PortBinding( self.context, port_id=port1.id, host='fake_host1', vnic_type='fake_vnic_type', vif_type='fake_vif_type', profile={}) port1_binding.create() port1.bindings =", "with mock.patch('neutron.objects.qos.rule.' 'QosMinimumBandwidthRule.' 'get_objects') as get_objects_mock: self.qos_plugin.get_policy_minimum_bandwidth_rules( self.ctxt, self.policy.id) get_objects_mock.assert_called_once_with(", "= self._make_qos_policy() original_network = self._make_network(original_qos.id) network = self._make_network(qos.id) # Port", "import exceptions as lib_exc from neutron_lib.exceptions import placement as pl_exc", "get_object_mock: self.qos_plugin.get_policy_packet_rate_limit_rule( self.ctxt, self.pps_rule.id, self.policy.id) get_object_mock.assert_called_once_with(self.ctxt, id=self.pps_rule.id) def test_get_policy_packet_rate_limit_rules_for_policy(self): with", "desired_min_kbps=1000, original_min_kpps=1000, desired_min_kpps=1000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1,", "desired_state=kwargs['network'], states=(kwargs['original_network'],))) if policy_id is None or policy_id == original_policy_id:", "self.policy.id, self.rule_data) def test_update_policy_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.update_policy_bandwidth_limit_rule,", "[self.ctxt, rule_cls_mock, self.rule.id, self.policy.id]} mock_manager = mock.Mock() mock_manager.attach_mock(qos_policy_mock, 'QosPolicy') mock_manager.attach_mock(port_mock,", "qos2, desired_min_kbps=2000) qos1.rules = [bw_limit_rule] with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc:", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy, self.ctxt, self.policy.id) def test_get_policy_bandwidth_limit_rule_for_nonexistent_policy(self): with", "'get_object') as get_object_mock: self.qos_plugin.get_policy_minimum_bandwidth_rule( self.ctxt, self.rule.id, self.policy.id) get_object_mock.assert_called_once_with(self.ctxt, id=self.rule.id) def", "applicable law or agreed to in writing, software # distributed", "port_id=port1.id, host='fake_host1', vnic_type='fake_vnic_type', vif_type='fake_vif_type', profile={}) port1_binding.create() port1.bindings = [port1_binding] port1.update()", "port))) mock_alloc_change.assert_called_once_with( qos1_obj, None, kwargs['original_port'], port) def test_check_port_for_placement_allocation_change_no_qos_update(self): qos1_obj =", "port = self._prepare_port_for_placement_allocation( qos1, qos2, original_min_kbps=1000, desired_min_kbps=2000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation')", "mock_alloc_change.assert_called_once_with( qos1_obj, qos2_obj, kwargs['original_port'], port) def test_check_port_for_placement_allocation_change_no_new_policy(self): qos1_obj = self._make_qos_policy()", "self._make_network() ml2plugin_mock = mock.MagicMock() def fake_make_port_dict(port): return { 'id': port.id,", "{'qos_plugin_name': SERVICE_PLUGIN_KLASS} ext_mgr = QoSRuleAliasTestExtensionManager() super(TestQoSRuleAlias, self).setUp(plugin=plugin, ext_mgr=ext_mgr, service_plugins=service_plugins) self.qos_plugin", "self.qos_plugin._change_placement_allocation( qos1, qos2, orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_update_conflict(self): qos1 =", "[self.min_bw_rule, min_bw_rule_ingress], [self.min_pps_rule, min_pps_rule_ingress], request_groups_uuids=request_groups_uuids) for port in ports: self.assertEqual(", "test_get_policy_packet_rate_limit_rules_for_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosPacketRateLimitRule.' 'get_objects') as get_objects_mock:", "qos_policy_id=qos_policy_id) network.create() return network def _test_validate_create_network_callback(self, network_qos=False): net_qos_obj = self._make_qos_policy()", "validate_policy_for_port.assert_not_called() else: get_port.assert_called_once_with(self.ctxt, id=port_id) get_policy.assert_called_once_with(admin_ctxt, id=policy_id) validate_policy_for_port.assert_called_once_with( self.ctxt, policy_mock, port_mock)", "kwargs = {\"context\": self.context, \"port\": {\"id\": port.id}} with mock.patch.object(self.qos_plugin, 'validate_policy_for_port')", "else '3' port = ports_object.Port( self.context, network_id=network_id, device_owner=device_owner, project_id=self.project_id, admin_state_up=True,", "'min_kpps': 1234, 'direction': self.min_pps_rule.direction, }, } with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as", "{ 'id': uuidutils.generate_uuid(), 'min_kpps': 20, 'direction': lib_constants.INGRESS_DIRECTION} min_bw_rule_ingress = rule_object.QosMinimumBandwidthRule(", "test_get_policy_min_pps_rules_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_minimum_packet_rate_rules, self.ctxt, self.policy.id) def", "= self._make_port( network_id=network.id, qos_policy_id=None, device_owner='compute:uu:id') port2_binding = ports_object.PortBinding( self.context, port_id=port2.id,", "filters = {'filter': 'filter_id'} self.qos_plugin.get_policy_minimum_bandwidth_rules( self.ctxt, self.policy.id, filters=filters) get_objects_mock.assert_called_once_with( self.ctxt,", "['fake_uuid0', 'fake_uuid1'] min_bw_rule_ingress_data = { 'id': uuidutils.generate_uuid(), 'min_kbps': 20, 'direction':", "for port in network_ports if port.qos_policy_id is None] expected_ports =", "def test_validate_policy_for_port_rule_not_valid(self): port = {'id': uuidutils.generate_uuid()} with mock.patch.object( self.qos_plugin.driver_manager, \"validate_rule_for_port\",", "WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express", "mock.patch('neutron.objects.qos.rule.' 'QosDscpMarkingRule.' 'get_objects') as get_objects_mock: filters = {'filter': 'filter_id'} self.qos_plugin.get_policy_dscp_marking_rules(", "methods that work with real data types mock.patch( 'neutron.objects.base.NeutronDbObject.modify_fields_from_db' ).start()", "= {'id': policy_id, 'project_id': project_id, 'name': 'test-policy', 'description': 'Test policy", "test__extend_port_resource_request_min_bw_inherited_policy( self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION self.min_bw_rule.qos_policy_id = self.policy.id port =", "'filter_id'} self.qos_plugin.get_policy_dscp_marking_rules( self.ctxt, self.policy.id, filters=filters) get_objects_mock.assert_called_once_with( self.ctxt, qos_policy_id=self.policy.id, _pager=mock.ANY, filter='filter_id')", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", []) self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.update_policy_bandwidth_limit_rule, self.ctxt, self.rule.id,", "directory.get_plugin(plugins_constants.QOS) self.ctxt = context.Context('fake_user', 'fake_tenant') self.rule_objects = { 'bandwidth_limit': rule_object.QosBandwidthLimitRule,", "mock.patch.object( self.qos_plugin, '_get_ports_with_policy', return_value=[port]): self.assertRaises( NotImplementedError, self.qos_plugin.create_policy_minimum_bandwidth_rule, self.ctxt, policy.id, self.rule_data)", "= directory.get_plugin(plugins_constants.QOS) self.qos_plugin.driver_manager = mock.Mock() self.rpc_push = mock.patch('neutron.api.rpc.handlers.resources_rpc' '.ResourcesPushRpcApi.push').start() self.ctxt", "with mock.patch('neutron.objects.qos.qos_policy_validator' '.check_bandwidth_rule_conflict', return_value=None), \\ mock.patch( 'neutron.objects.qos.qos_policy_validator' '.check_min_pps_rule_conflict', return_value=None): self.qos_plugin.create_policy_bandwidth_limit_rule(", "self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.create_policy_packet_rate_limit_rule, self.ctxt, self.policy.id, self.rule_data) def test_update_policy_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "self.rule_data = { 'bandwidth_limit_rule': {'max_kbps': 100, 'max_burst_kbps': 150}, 'dscp_marking_rule': {'dscp_mark':", "'delete') def test_delete_policy_rule(self, mock_qos_rule_delete): mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_rule_delete, 'delete') mock_manager.attach_mock(self.qos_plugin.driver_manager,", "'physical_network': 'sriov_phy' } binding_prof.update({'allocation': allocation}) orig_port.update( {'binding:profile': binding_prof, 'device_id': 'uu:id'}", "{orc.NET_PACKET_RATE_KILOPACKET_PER_SEC: 10}, port['resource_request']['request_groups'][0]['resources'], ) self.assertEqual( ['fake_uuid'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_bulk_min_bw_and_pps_rule(self):", "test_get_policy_dscp_marking_rules_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_dscp_marking_rules, self.ctxt, self.policy.id) def", "self.new_delete_request(resource, rule_id, self.fmt) res = request.get_response(self.ext_api) if res.status_int >= webob.exc.HTTPClientError.code:", "rule in qos2.rules: rule.direction = 'any' with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as", "qos2, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={ self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': -500,", "for port in expected_ports: self.assertIn(port, policy_ports) def _test_validate_update_port_callback(self, policy_id=None, original_policy_id=None):", "payload=events.DBEventPayload( self.ctxt, desired_state=kwargs['network'], states=(kwargs['original_network'],))) if policy_id is None or policy_id", "self.ctxt, self.rule.id, self.policy.id) def test_get_policy_bandwidth_limit_rules_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound,", "self.ctxt) def test_delete_policy_min_pps_rule_bad_policy(self): _policy = self._get_policy() setattr(_policy, \"rules\", []) with", "return qos_pps_minimum_rule_alias.Qos_pps_minimum_rule_alias.\\ get_resources() def get_actions(self): return [] def get_request_extensions(self): return", "= rule_object_class(self.ctxt, id=rule_id, qos_policy_id=self.qos_policy_id, **data) with mock.patch('neutron.objects.qos.rule.QosRule.get_object', return_value=rule): self._show_rule(rule_type, rule_id)", "self.qos_plugin.get_policy_dscp_marking_rules, self.ctxt, self.policy.id) def test_get_policy_minimum_bandwidth_rule(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.'", "'fake_allocation'}) port1_binding.create() port1.bindings = [port1_binding] port1.update() with mock.patch.object( self.qos_plugin, '_change_placement_allocation')", "min_pps_rule_ingress], request_groups_uuids=request_groups_uuids) self.assertEqual( 2, len(port['resource_request']['request_groups']) ) self.assertIn( { 'id': 'fake_uuid0',", "= {'id': uuidutils.generate_uuid()} with mock.patch.object( self.qos_plugin.driver_manager, \"validate_rule_for_port\", return_value=False ): self.policy.rules", "self._prepare_port_for_placement_allocation( qos1, qos2, desired_min_kbps=2000) qos1.rules = [bw_limit_rule] with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation')", "self.ctxt, mock.ANY) delete_mock_call = mock.call.driver.call( 'delete_policy', self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(policy_delete_mock_call)", "mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.rule_data['bandwidth_limit_rule']['max_kbps'] = 1 self.qos_plugin.update_policy_bandwidth_limit_rule( self.ctxt, self.rule.id, self.policy.id,", "return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_bandwidth_limit_rules, self.ctxt, self.policy.id) def test_create_policy_dscp_marking_rule(self): _policy =", "'neutron.services.qos.qos_plugin.QoSPlugin' class TestQosPlugin(base.BaseQosTestCase): def setUp(self): super(TestQosPlugin, self).setUp() self.setup_coreplugin(load_plugins=False) mock.patch('neutron.objects.db.api.create_object').start() mock.patch('neutron.objects.db.api.update_object').start()", "neutron.objects import ports as ports_object from neutron.objects.qos import policy as", "tenant_policy) QosMocked.assert_called_once_with(self.ctxt, **policy_details) @mock.patch.object(policy_object.QosPolicy, \"get_object\") @mock.patch( 'neutron.objects.rbac_db.RbacNeutronDbObjectMixin' '.create_rbac_policy') @mock.patch.object(policy_object.QosPolicy, 'update')", "{}}], 'delete': [self.ctxt, rule_cls_mock, self.rule.id, self.policy.id]} mock_manager = mock.Mock() mock_manager.attach_mock(qos_policy_mock,", "= [{ 'name': 'fake-driver', 'supported_parameters': [{ 'parameter_name': 'max_kpps', 'parameter_type': lib_constants.VALUES_TYPE_RANGE,", "self.qos_plugin.get_rule_type( admin_ctxt, qos_consts.RULE_TYPE_PACKET_RATE_LIMIT) self.assertEqual( qos_consts.RULE_TYPE_PACKET_RATE_LIMIT, rule_type_details['type']) self.assertEqual( drivers_details, rule_type_details['drivers']) def", "uuid -v5 f02f160e-1612-11ec-b2b8-bf60ab98186c # 6ac5db7e-1626-11ec-8c7f-0b70dbb8a8eb MIN_PPS_REQUEST_GROUP_UUID = '995008f4-f120-547a-b051-428b89076067' MIN_PPS_RP =", "'cc', 'dd', 'ee', 'ff'] mac = netaddr.EUI(next(net_utils.random_mac_generator(base_mac))) device_owner = device_owner", "self.ctxt, self.min_pps_rule.id, _policy.id) def test_delete_policy_min_pps_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound,", "port): port['binding:profile'] = {'allocation': 'fake_allocation'} mock_alloc_change.side_effect = fake_change_placement_allocation self.qos_plugin._check_network_for_placement_allocation_change( 'network',", "mock.patch('neutron.objects.db.api.get_object').start() _mock_qos_load_attr = mock.patch( 'neutron.objects.qos.policy.QosPolicy.obj_load_attr') self.mock_qos_load_attr = _mock_qos_load_attr.start() # We", "per mocks above. We also need to mock-out # methods", "setattr(_policy, \"rules\", [self.min_bw_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict, self.qos_plugin.create_policy_bandwidth_limit_rule,", "self.ctxt, id=self.min_pps_rule.id) def test_get_policy_min_pps_rules_for_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumPacketRateRule.'", "orig_port, port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_new_policy_empty(self): qos1 = self._make_qos_policy() orig_port, port", "port) mock_update_qos_alloc.assert_not_called() def test_change_placement_allocation_old_rule_not_min_bw(self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy()", "as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1, None, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={", ") self.assertEqual( ['fake_uuid'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_bulk_min_bw_rule(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION", "update_mock_call = mock.call.driver.call( 'update_policy', self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(rule_delete_mock_call) < mock_manager.mock_calls.index(update_precommit_mock_call)", "self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", [self.dscp_rule]) self.qos_plugin.create_policy_dscp_marking_rule( self.ctxt,", "150}, 'dscp_marking_rule': {'dscp_mark': 16}, 'minimum_bandwidth_rule': {'min_kbps': 10} } def _update_rule(self,", "self.MIN_BW_RP}}, 'device_id': 'uu:id', 'id': '9416c220-160a-11ec-ba3d-474633eb825c', } port = {} with", "{ 'id': uuidutils.generate_uuid(), 'min_kpps': 10, 'direction': 'egress' } }, ]", "1, len(port['resource_request']['request_groups']) ) self.assertEqual( 'fake_uuid', port['resource_request']['request_groups'][0]['id'] ) self.assertEqual( ['CUSTOM_PHYSNET_PUBLIC', 'CUSTOM_VNIC_TYPE_NORMAL'],", "rule_id, **kwargs): data = {'alias_%s_rule' % rule_type: kwargs} resource =", "{orc.NET_BW_EGR_KILOBIT_PER_SEC: 10}, port['resource_request']['request_groups'][0]['resources'], ) self.assertEqual( ['fake_uuid'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_bulk_min_pps_rule(self):", "['CUSTOM_PHYSNET_PUBLIC', 'CUSTOM_VNIC_TYPE_NORMAL'], 'resources': { orc.NET_BW_EGR_KILOBIT_PER_SEC: 10, orc.NET_BW_IGR_KILOBIT_PER_SEC: 20}, }, port['resource_request']['request_groups']", "id=policy_id) get_ports.assert_called_once_with(self.ctxt, network_id=network_id) validate_policy_for_ports.assert_called_once_with( self.ctxt, policy_mock, [port_mock_without_own_policy]) def test_validate_update_network_callback_policy_changed(self): self._test_validate_update_network_callback(", "\"exception unexpectedly raised\") def test_create_min_bw_rule_on_bound_port(self): policy = self._get_policy() policy.rules =", "\\ mock.patch( 'uuid.uuid5', return_value='fake_uuid', side_effect=request_groups_uuids): return qos_plugin.QoSPlugin._extend_port_resource_request_bulk( ports_res, None) def", "resource_id=kwargs['network']['id'],)) qos_policy = None if network_qos: qos_policy = net_qos_obj if", "directory from neutron_lib.services.qos import constants as qos_consts from neutron_lib.utils import", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.create_policy_bandwidth_limit_rule, self.ctxt, self.policy.id, self.rule_data) def test_update_policy_rule_for_nonexistent_policy(self):", "as lib_constants from neutron_lib import context from neutron_lib import exceptions", "rule_update_mock_call = mock.call.update() update_precommit_mock_call = mock.call.driver.call( 'update_policy_precommit', self.ctxt, mock.ANY) update_mock_call", "self._test_validate_create_network_callback(network_qos=False) def _test_validate_create_port_callback(self, port_qos=False, network_qos=False): net_qos_obj = self._make_qos_policy() port_qos_obj =", "@mock.patch.object(policy_object.QosPolicy, 'delete') def test_delete_policy(self, mock_qos_policy_delete, mock_api_get_policy): mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_policy_delete,", "{ 'minimum_packet_rate_rule': {'min_kpps': 10, 'direction': 'any'} } class TestQosPluginDB(base.BaseQosTestCase): PORT_ID", "# License for the specific language governing permissions and limitations", "setattr(_policy, \"rules\", [self.dscp_rule]) self.qos_plugin.delete_policy_dscp_marking_rule( self.ctxt, self.dscp_rule.id, self.policy.id) self._validate_driver_params('update_policy', self.ctxt) def", "[] allocation = {} if original_min_kbps: qos.rules += [self._make_qos_minbw_rule( qos.id,", "alloc_diff={ self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': 500}, self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': 1000}}) def test_change_placement_allocation_change_direction_min_pps_and_min_bw(", "qos_consts.QOS_POLICY_ID: original_policy_id } } port_mock_with_own_policy = mock.MagicMock( id=uuidutils.generate_uuid(), qos_policy_id=uuidutils.generate_uuid()) port_mock_without_own_policy", "qos_exc.QosPolicyNotFound, self.qos_plugin.update_policy_minimum_packet_rate_rule, self.ctxt, self.min_pps_rule.id, self.policy.id, self.rule_data) def test_delete_policy_min_pps_rule(self): _policy =", "'minimum_bandwidth': rule_object.QosMinimumBandwidthRule } self.qos_policy_id = uuidutils.generate_uuid() self.rule_data = { 'bandwidth_limit_rule':", "project_id=self.project_id, shared=False, is_default=False) qos_policy.create() return qos_policy def _make_qos_minbw_rule(self, policy_id, direction='ingress',", "{} with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(qos1, qos2, orig_port, port)", "class reference rule_mock_call = getattr(mock.call.RuleCls(), action)() driver_mock_call = mock.call.driver.call('update_policy', self.ctxt,", "self.ctxt = context.Context('fake_user', 'fake_tenant') self.rule_objects = { 'bandwidth_limit': rule_object.QosBandwidthLimitRule, 'dscp_marking':", "port) def test_check_port_for_placement_allocation_change_no_new_policy(self): qos1_obj = self._make_qos_policy() kwargs = self._prepare_for_port_placement_allocation_change( qos1=qos1_obj,", "'fake_tenant') self.rule_objects = { 'minimum_packet_rate': rule_object.QosMinimumPacketRateRule } self.qos_policy_id = uuidutils.generate_uuid()", "test_get_policy_bandwidth_limit_rules_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_bandwidth_limit_rules, self.ctxt, self.policy.id) def", "uuidutils.generate_uuid()} with mock.patch.object( self.qos_plugin.driver_manager, \"validate_rule_for_port\", return_value=True ): self.policy.rules = [self.rule]", "test_delete_policy_pps_rule_bad_policy(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy,", "policy get_rule_mock_call = getattr( mock.call.QosPolicy.get_policy_obj().get_rule_by_id(), action)() # some actions construct", "port_id=port1.id, host='fake_host1', vnic_type='fake_vnic_type', vif_type='fake_vif_type', profile={'allocation': 'fake_allocation'}) port1_binding.create() port1.bindings = [port1_binding]", "mock_alloc_change: self.qos_plugin._check_port_for_placement_allocation_change( 'PORT', 'before_update', 'test_plugin', payload=events.DBEventPayload( context, states=(original_port, port))) mock_alloc_change.assert_called_once_with(", "rule_id) calls.append(mock.call(mock.ANY, rule_object_class, rule_id, self.qos_policy_id)) delete_policy_rule_mock.assert_has_calls(calls, any_order=True) def test_show_non_existing_rule(self): for", "self.ctxt, self.policy.id) def test_get_policy_bandwidth_limit_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_bandwidth_limit_rule,", "[self.rule]) new_rule_data = { 'bandwidth_limit_rule': { 'max_kbps': 5000, 'direction': self.rule.direction", "desired_min_kpps=1000) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation(qos1, qos2, orig_port, port)", "def test_get_policy_dscp_marking_rules_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_dscp_marking_rules, self.ctxt, self.policy.id)", "qos_plugin from neutron.tests.unit.db import test_db_base_plugin_v2 from neutron.tests.unit.services.qos import base DB_PLUGIN_KLASS", ") def test__extend_port_resource_request_bulk_min_bw_rule(self): self.min_bw_rule.direction = lib_constants.EGRESS_DIRECTION ports = self._create_and_extend_ports([self.min_bw_rule]) for", "qos_plugin.QoSPlugin, \"supported_rule_type_details\", return_value=drivers_details ): rule_type_details = self.qos_plugin.get_rule_type( admin_ctxt, qos_consts.RULE_TYPE_BANDWIDTH_LIMIT) self.assertEqual(", "network_object from neutron.objects import ports as ports_object from neutron.objects.qos import", "['fake_uuid0', 'fake_uuid1'], port['resource_request']['same_subtree'], ) def test__extend_port_resource_request_non_min_bw_or_min_pps_rule(self): port = self._create_and_extend_port([], [])", "self.policy.id) def test_get_policy_min_pps_rule(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=self.policy): with mock.patch('neutron.objects.qos.rule.' 'QosMinimumPacketRateRule.' 'get_object')", "mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',", "orig_port, port = self._prepare_port_for_placement_allocation( qos1, qos2, original_min_kbps=1000, desired_min_kbps=2000) with mock.patch.object(self.qos_plugin._placement_client,", "# 6ac5db7e-1626-11ec-8c7f-0b70dbb8a8eb MIN_PPS_REQUEST_GROUP_UUID = '995008f4-f120-547a-b051-428b89076067' MIN_PPS_RP = 'e16161f4-1626-11ec-a5a2-1fc9396e27cc' def setUp(self):", "segments=[segment]) port = ports_object.Port( self.ctxt, id=uuidutils.generate_uuid(), network_id=uuidutils.generate_uuid(), device_owner='compute:fake-zone') with mock.patch(", "mock_manager.mock_calls.index(update_precommit_mock_call) < mock_manager.mock_calls.index(update_mock_call)) def test_update_policy_rule_check_rule_min_less_than_max(self): _policy = self._get_policy() setattr(_policy, \"rules\",", "has_net_qos_policy=False, request_groups_uuids=None): network_id = uuidutils.generate_uuid() self.port_data = { 'port': {'id':", "10, 'direction': 'egress' } }, ] self.rule_data['minimum_packet_rate_rule']['direction'] = 'any' for", "= self._get_policy() setattr(_policy, \"rules\", [self.min_pps_rule]) segment = network_object.NetworkSegment( physical_network='fake physnet')", "test_change_placement_allocation_update_generation_conflict(self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() orig_port, port =", "self.policy.id, self.rule_data) self._validate_driver_params('update_policy', self.ctxt) rule_create_mock_call = mock.call.create() update_precommit_mock_call = mock.call.driver.call(", "test_create_policy_dscp_marking_rule(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy,", "action_index = mock_manager.mock_calls.index(rule_mock_call) else: action_index = mock_manager.mock_calls.index( get_rule_mock_call) self.assertLess( action_index,", "network_id=network_id, device_owner=device_owner, project_id=self.project_id, admin_state_up=True, status='DOWN', device_id='2', qos_policy_id=qos_policy_id, qos_network_policy_id=qos_network_policy_id, mac_address=mac, id=port_id)", "# under the License. import copy from unittest import mock", "'id': uuidutils.generate_uuid(), 'min_kpps': 10, 'direction': 'egress' } }, ] for", "mock.patch('neutron.api.rpc.handlers.resources_rpc' '.ResourcesPushRpcApi.push').start() self.ctxt = context.Context('fake_user', 'fake_tenant') self.admin_ctxt = context.get_admin_context() self.policy_data", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.update_policy_minimum_packet_rate_rule, self.ctxt, self.min_pps_rule.id, self.policy.id, self.rule_data)", "return_value=[self.rule]), mock.patch( 'neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.rule_data['bandwidth_limit_rule']['max_kbps'] = 1 self.qos_plugin.update_policy_bandwidth_limit_rule( self.ctxt, self.rule.id,", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.assertRaises( qos_exc.QosRuleNotFound, self.qos_plugin.update_policy_minimum_packet_rate_rule, self.ctxt, self.min_pps_rule.id, self.policy.id, self.rule_data) def", "self._validate_driver_params('update_policy', self.ctxt) def test_delete_policy_dscp_marking_rule(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with", "self._validate_driver_params('update_policy', self.ctxt) def test_delete_policy_pps_rule_bad_policy(self): _policy = policy_object.QosPolicy( self.ctxt, **self.policy_data['policy']) with", "as get_objects_mock: filters = {'filter': 'filter_id'} self.qos_plugin.get_policy_dscp_marking_rules( self.ctxt, self.policy.id, filters=filters)", "test_check_port_for_placement_allocation_change_no_qos_update(self): qos1_obj = self._make_qos_policy() kwargs = self._prepare_for_port_placement_allocation_change( qos1=qos1_obj, qos2=None) kwargs['port'].pop('qos_policy_id')", "else None) network = self._make_network(qos_policy_id=qos_network_policy_id) port = self._make_port( network.id, qos_policy_id=qos1_id,", "neutron_lib.callbacks import events from neutron_lib import constants as lib_constants from", "= mock.patch('neutron.api.rpc.handlers.resources_rpc' '.ResourcesPushRpcApi.push').start() self.ctxt = context.Context('fake_user', 'fake_tenant') self.admin_ctxt = context.get_admin_context()", "mock.call.driver.call( 'delete_policy_precommit', self.ctxt, mock.ANY) delete_mock_call = mock.call.driver.call( 'delete_policy', self.ctxt, mock.ANY)", "else uuidutils.generate_uuid() qos_rule = rule_object.QosMinimumBandwidthRule( self.context, project_id=self.project_id, qos_policy_id=policy_id, direction=direction, min_kbps=min_kbps,", "self.rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_rule_duplicates(self): _policy = self._get_policy() setattr(_policy, \"rules\",", "qos_policy_id=uuidutils.generate_uuid()) port_mock_without_own_policy = mock.MagicMock( id=uuidutils.generate_uuid(), qos_policy_id=None) ports = [port_mock_with_own_policy, port_mock_without_own_policy]", "self.rule.id, self.policy.id) def test_get_policy_minimum_bandwidth_rules_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_minimum_bandwidth_rules,", "'neutron.objects.qos.policy.QosPolicy.get_object', return_value=policy), \\ mock.patch( 'neutron.objects.network.Network.get_object', return_value=net), \\ mock.patch.object( self.qos_plugin, '_get_ports_with_policy',", "return [] def get_request_extensions(self): return [] class QoSRuleAliasMinimumPacketRateTestExtensionManager(object): def get_resources(self):", "self._make_network(qos.id) ml2plugin_mock = mock.MagicMock() def fake_make_port_dict(port): return { 'id': port.id,", "lib_constants.INGRESS_DIRECTION} min_pps_rule_ingress_data = { 'id': uuidutils.generate_uuid(), 'min_kpps': 20, 'direction': lib_constants.INGRESS_DIRECTION}", "in qos2.rules: rule.direction = 'egress' with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc:", "= { 'id': uuidutils.generate_uuid(), 'min_kpps': 20, 'direction': lib_constants.INGRESS_DIRECTION} min_bw_rule_ingress =", "as policy_object from neutron.objects.qos import rule as rule_object from neutron.services.qos", "self.min_bw_rule.id, self.policy.id, self.rule_data) self.mock_qos_load_attr.assert_called_once_with('rules') self._validate_driver_params('update_policy', self.ctxt) def test_update_policy_rule_check_rule_bwlimit_less_than_minbw(self): _policy =", "rule_object.QosMinimumPacketRateRule( self.ctxt, **min_pps_rule_ingress_data) ports = self._create_and_extend_ports( [self.min_bw_rule, min_bw_rule_ingress], [self.min_pps_rule, min_pps_rule_ingress],", "self.MIN_PPS_RP: { 'NET_PACKET_RATE_IGR_KILOPACKET_PER_SEC': 500}}) def test_change_placement_allocation_decrease(self): original_qos = self._make_qos_policy() desired_qos", "mock.patch( 'neutron.objects.qos.rule.QosMinimumBandwidthRule.' 'get_objects', return_value=min_bw_rules), \\ mock.patch( 'neutron.objects.qos.rule.QosMinimumPacketRateRule.' 'get_objects', return_value=min_pps_rules), \\", "test_change_placement_allocation_update_conflict(self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy() orig_port, port =", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_minimum_bandwidth_rules, self.ctxt, self.policy.id) def test_create_policy_rule_for_nonexistent_policy(self):", "return_value=_policy): setattr(_policy, \"rules\", [self.dscp_rule]) self.qos_plugin.delete_policy_dscp_marking_rule( self.ctxt, self.dscp_rule.id, self.policy.id) self._validate_driver_params('update_policy', self.ctxt)", "= { \"context\": self.ctxt, \"network\": { \"id\": network_id, qos_consts.QOS_POLICY_ID: policy_id", "request_groups_uuids = ['fake_uuid0', 'fake_uuid1'] * 2 min_bw_rule_ingress_data = { 'id':", "mock.MagicMock( id=uuidutils.generate_uuid(), qos_policy_id=None) ports = [port_mock_with_own_policy, port_mock_without_own_policy] policy_mock = mock.MagicMock(id=policy_id)", "kwargs} resource = '%s/alias-%s-rules' % (qos.ALIAS, rule_type.replace('_', '-')) request =", "original_qos = self._make_qos_policy() desired_qos = self._make_qos_policy() orig_port, port = self._prepare_port_for_placement_allocation(", "states=(original_network, network))) self.assertEqual(ml2plugin_mock._make_port_dict.call_count, 2) mock_alloc_change_calls = [ mock.call( original_qos, qos,", "network = uuidutils.generate_uuid() with mock.patch.object( self.qos_plugin.driver_manager, \"validate_rule_for_network\", return_value=True ): self.policy.rules", "mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_rule_create, 'create') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver') mock_manager.reset_mock() with mock.patch('neutron.objects.qos.qos_policy_validator'", "1 setattr(_policy, \"rules\", [self.min_bw_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj: self.assertRaises(qos_exc.QoSRuleParameterConflict,", "\"compute:uu:id\", \"qos_policy_id\": qos1_id, \"qos_network_policy_id\": qos_network_policy_id}, \"port\": {\"id\": port.id, \"qos_policy_id\": qos2_id}}", "language governing permissions and limitations # under the License. import", "self.qos_plugin.update_policy_minimum_bandwidth_rule( self.ctxt, self.min_bw_rule.id, self.policy.id, self.rule_data) self.mock_qos_load_attr.assert_called_once_with('rules') self._validate_driver_params('update_policy', self.ctxt) def test_update_policy_rule_check_rule_bwlimit_less_than_minbw(self):", "get_resources() def get_actions(self): return [] def get_request_extensions(self): return [] class", "License. You may obtain # a copy of the License", "qos1=qos1_obj, qos2=None) context = kwargs['context'] original_port = kwargs['original_port'] port =", "'is_default': False} with mock.patch('neutron.objects.qos.policy.QosPolicy') as QosMocked: self.qos_plugin.create_policy(self.ctxt, tenant_policy) QosMocked.assert_called_once_with(self.ctxt, **policy_details)", "self.ctxt) def test_update_policy_rule_check_rule_min_pps_direction_conflict(self): _policy = self._get_policy() rules_data = [ {", "original_qos, desired_qos, original_min_kpps=2000, desired_min_kpps=1000, is_sriov=True) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc:", "= 'c8bc1b27-59a1-5135-aa33-aeecad6093f4' MIN_BW_RP = 'd7bea120-1626-11ec-9148-c32debfcf0f6' QOS_MIN_PPS_RULE_ID = '6ac5db7e-1626-11ec-8c7f-0b70dbb8a8eb' # uuid", "mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt, self.policy.id, self.rule_data) def test_update_policy_min_pps_rule(self):", "ANY KIND, either express or implied. See the # License", "self._make_network(original_qos.id) network = self._make_network(qos.id) # Port which is not compute", "self._prepare_port_for_placement_allocation( qos1, qos2, original_min_kbps=1000, desired_min_kbps=2000, is_sriov=True) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as", "delete_precommit_mock_call = mock.call.driver.call( 'delete_policy_precommit', self.ctxt, mock.ANY) delete_mock_call = mock.call.driver.call( 'delete_policy',", "update_mock_call = mock.call.driver.call( 'update_policy', self.ctxt, mock.ANY) self.assertTrue( mock_manager.mock_calls.index(rule_create_mock_call) < mock_manager.mock_calls.index(update_precommit_mock_call)", "validate_policy_for_ports.assert_not_called() else: get_policy.assert_called_once_with(admin_ctxt, id=policy_id) get_ports.assert_called_once_with(self.ctxt, network_id=network_id) validate_policy_for_ports.assert_called_once_with( self.ctxt, policy_mock, [port_mock_without_own_policy])", "100, 'max_burst_kbps': 150}, 'dscp_marking_rule': {'dscp_mark': 16}, 'minimum_bandwidth_rule': {'min_kbps': 10} }", "'supported_parameters': [{ 'parameter_name': 'max_kbps', 'parameter_type': lib_constants.VALUES_TYPE_RANGE, 'parameter_range': {'start': 0, 'end':", "data, rule_id, self.fmt) res = request.get_response(self.ext_api) if res.status_int >= webob.exc.HTTPClientError.code:", "data = {'alias_%s_rule' % rule_type: kwargs} resource = '%s/alias-%s-rules' %", "'_get_ports_with_policy', return_value=[port]): self.assertRaises( NotImplementedError, self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt, _policy.id, self.rule_data) def test_create_min_pps_rule_on_unbound_port(self):", "elif has_net_qos_policy: self.port_data['port']['qos_network_policy_id'] = self.policy.id self.port = ports_object.Port( self.ctxt, **self.port_data['port'])", "import directory from neutron_lib.services.qos import constants as qos_consts from neutron_lib.utils", "test_delete_policy(self, mock_qos_policy_delete, mock_api_get_policy): mock_manager = mock.Mock() mock_manager.attach_mock(mock_qos_policy_delete, 'delete') mock_manager.attach_mock(self.qos_plugin.driver_manager, 'driver')", "self.assertEqual( ['fake_uuid'], port['resource_request']['same_subtree'], ) def test_get_ports_with_policy(self): network_ports = [ mock.MagicMock(qos_policy_id=None),", "'project_id': project_id, 'tenant_id': project_id, 'name': 'test-policy', 'description': 'Test policy description',", "plugin = 'ml2' service_plugins = {'qos_plugin_name': SERVICE_PLUGIN_KLASS} ext_mgr = QoSRuleAliasMinimumPacketRateTestExtensionManager()", "def test_get_policy_bandwidth_limit_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_bandwidth_limit_rule, self.ctxt, self.rule.id,", "with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): setattr(_policy, \"rules\", [self.dscp_rule]) self.qos_plugin.create_policy_dscp_marking_rule( self.ctxt, self.policy.id, self.rule_data)", "orig_port, kwargs['port'] def _assert_pci_info(self, port): self.assertIn('pci_slot', port['binding:profile']) self.assertIn('pci_vendor_info', port['binding:profile']) self.assertIn('physical_network',", "import qos_rules_alias from neutron import manager from neutron.objects import network", "test_get_policy_minimum_bandwidth_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound, self.qos_plugin.get_policy_minimum_bandwidth_rule, self.ctxt, self.rule.id, self.policy.id)", "**data) with mock.patch( 'neutron.objects.qos.rule.QosRule.get_object', return_value=rule ), mock.patch.object(self.qos_plugin, 'get_policy_rule', return_value=rule.to_dict()): self._update_rule(rule_type,", "qos_rule.create() return qos_rule def _make_port(self, network_id, qos_policy_id=None, port_id=None, qos_network_policy_id=None, device_owner=None):", "self.qos_plugin._change_placement_allocation( original_qos, desired_qos, orig_port, port) mock_update_qos_alloc.assert_called_once_with( consumer_uuid='uu:id', alloc_diff={self.MIN_BW_RP: {'NET_BW_IGR_KILOBIT_PER_SEC': -1000}})", "{ 'bandwidth_limit': rule_object.QosBandwidthLimitRule, 'dscp_marking': rule_object.QosDscpMarkingRule, 'minimum_bandwidth': rule_object.QosMinimumBandwidthRule } self.qos_policy_id =", "as per mocks above. We also need to mock-out #", "1234, 'direction': self.min_pps_rule.direction, }, } with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy) as mock_qos_get_obj:", "qos1, qos2, original_min_kpps=1000, desired_min_kpps=2000, is_sriov=True) with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc:", "QOS_MIN_BW_RULE_ID = '8bf8eb46-160e-11ec-8024-9f96be32099d' # uuid -v5 f02f160e-1612-11ec-b2b8-bf60ab98186c # 8bf8eb46-160e-11ec-8024-9f96be32099d MIN_BW_REQUEST_GROUP_UUID", "rule.direction = 'egress' with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.qos_plugin._change_placement_allocation( qos1,", "= lib_constants.EGRESS_DIRECTION self.min_pps_rule.direction = lib_constants.EGRESS_DIRECTION request_groups_uuids = ['fake_uuid0', 'fake_uuid1'] *", "'6ac5db7e-1626-11ec-8c7f-0b70dbb8a8eb' # uuid -v5 f02f160e-1612-11ec-b2b8-bf60ab98186c # 6ac5db7e-1626-11ec-8c7f-0b70dbb8a8eb MIN_PPS_REQUEST_GROUP_UUID = '995008f4-f120-547a-b051-428b89076067'", "with mock.patch.object(self.qos_plugin._placement_client, 'update_qos_allocation') as mock_update_qos_alloc: self.assertRaises(NotImplementedError, self.qos_plugin._change_placement_allocation, qos1, qos2, orig_port,", "self.assertTrue( mock_manager.mock_calls.index(policy_delete_mock_call) < mock_manager.mock_calls.index(delete_precommit_mock_call) < mock_manager.mock_calls.index(delete_mock_call)) @mock.patch.object(policy_object.QosPolicy, \"get_object\") @mock.patch.object(rule_object.QosBandwidthLimitRule, 'create')", "[self.min_bw_rule]) with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=_policy): self.qos_plugin.update_policy_minimum_bandwidth_rule( self.ctxt, self.min_bw_rule.id, self.policy.id, self.rule_data) self.mock_qos_load_attr.assert_called_once_with('rules')", "qos_exc.QoSRulesConflict, self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt, _policy.id, new_rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_min_pps_rule_for_nonexistent_policy(self): with", "qos_network_policy=qos_network_policy) orig_port = kwargs['original_port'] qos = original_qos or qos_network_policy qos.rules", "mock_manager.mock_calls.index(policy_delete_mock_call) < mock_manager.mock_calls.index(delete_precommit_mock_call) < mock_manager.mock_calls.index(delete_mock_call)) @mock.patch.object(policy_object.QosPolicy, \"get_object\") @mock.patch.object(rule_object.QosBandwidthLimitRule, 'create') def", "qos_policy_id=self.policy.id, _pager=mock.ANY, filter='filter_id') def test_get_policy_dscp_marking_rule_for_nonexistent_policy(self): with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object', return_value=None): self.assertRaises( qos_exc.QosPolicyNotFound,", "= self._prepare_port_for_placement_allocation( qos1, qos2, original_min_kpps=1000, desired_min_kpps=1000) for rule in qos2.rules:", "uuidutils.generate_uuid(), 'min_kpps': 10, 'direction': 'egress' } }, ] self.rule_data['minimum_packet_rate_rule']['direction'] =", "{ 'id': uuidutils.generate_uuid(), 'max_kpps': 20, 'max_burst_kpps': 130}, 'minimum_packet_rate_rule': { 'id':", "profile={}) port1_binding.create() port1.bindings = [port1_binding] port1.update() port2 = self._make_port( network_id=network.id,", "20, 'direction': lib_constants.INGRESS_DIRECTION} min_pps_rule_ingress_data = { 'id': uuidutils.generate_uuid(), 'min_kpps': 20,", "'QosBandwidthLimitRule.' 'get_object') as get_object_mock: self.qos_plugin.get_policy_bandwidth_limit_rule( self.ctxt, self.rule.id, self.policy.id) get_object_mock.assert_called_once_with(self.ctxt, id=self.rule.id)", "self.assertRaises( qos_exc.QoSRulesConflict, self.qos_plugin.create_policy_minimum_packet_rate_rule, self.ctxt, _policy.id, new_rule_data) mock_qos_get_obj.assert_called_once_with(self.ctxt, id=_policy.id) def test_create_policy_min_pps_rule_for_nonexistent_policy(self):", "1000}}) self._assert_pci_info(port) def test_change_placement_allocation_increase_min_pps_and_min_bw(self): qos1 = self._make_qos_policy() qos2 = self._make_qos_policy()", "self._make_qos_policy() bw_limit_rule = rule_object.QosDscpMarkingRule(dscp_mark=16) orig_port, port = self._prepare_port_for_placement_allocation( qos1, qos2,", "@mock.patch('neutron.objects.qos.policy.QosPolicy') def test_rule_notification_and_driver_ordering(self, qos_policy_mock, port_mock): rule_cls_mock = mock.Mock() rule_cls_mock.rule_type =", "or implied. See the # License for the specific language" ]
[ "None: await ctx.send(newword) else: await ctx.send(\"I cannot covfefeify that word\")", "almost any word into covfefe\"\"\" newword = await self.covfefe(msg) if", "await self.covfefe(msg) if newword is not None: await ctx.send(newword) else:", "c + ((\"bcdfgkpstvz\" + c)[\"pgtvkgbzdfs\".find(c)] + v) * 2 except", "class Covfefe(commands.Cog): \"\"\" Convert almost any word into covfefe \"\"\"", "x)[0] return b + c + ((\"bcdfgkpstvz\" + c)[\"pgtvkgbzdfs\".find(c)] +", "any word into covfefe\"\"\" newword = await self.covfefe(msg) if newword", "def red_delete_data_for_user(self, **kwargs): \"\"\" Nothing to delete \"\"\" return @commands.command()", "to delete \"\"\" return @commands.command() async def covefy(self, ctx, msg):", "covfefe(self, x, k=\"aeiouy])\"): \"\"\" https://codegolf.stackexchange.com/a/123697 \"\"\" try: b, c, v", "@commands.command() async def covefy(self, ctx, msg): \"\"\"Convert almost any word", "almost any word into covfefe \"\"\" def __init__(self, bot): self.bot", "k=\"aeiouy])\"): \"\"\" https://codegolf.stackexchange.com/a/123697 \"\"\" try: b, c, v = re.findall(f\"(.*?[{k}([^{k}.*?([{k}\",", "async def covefy(self, ctx, msg): \"\"\"Convert almost any word into", "bot async def covfefe(self, x, k=\"aeiouy])\"): \"\"\" https://codegolf.stackexchange.com/a/123697 \"\"\" try:", "def __init__(self, bot): self.bot = bot async def covfefe(self, x,", "* 2 except IndexError: return None async def red_delete_data_for_user(self, **kwargs):", "+ c + ((\"bcdfgkpstvz\" + c)[\"pgtvkgbzdfs\".find(c)] + v) * 2", "= bot async def covfefe(self, x, k=\"aeiouy])\"): \"\"\" https://codegolf.stackexchange.com/a/123697 \"\"\"", "\"\"\" Convert almost any word into covfefe \"\"\" def __init__(self,", "= re.findall(f\"(.*?[{k}([^{k}.*?([{k}\", x)[0] return b + c + ((\"bcdfgkpstvz\" +", "newword = await self.covfefe(msg) if newword is not None: await", "b + c + ((\"bcdfgkpstvz\" + c)[\"pgtvkgbzdfs\".find(c)] + v) *", "return b + c + ((\"bcdfgkpstvz\" + c)[\"pgtvkgbzdfs\".find(c)] + v)", "\"\"\" def __init__(self, bot): self.bot = bot async def covfefe(self,", "into covfefe\"\"\" newword = await self.covfefe(msg) if newword is not", "((\"bcdfgkpstvz\" + c)[\"pgtvkgbzdfs\".find(c)] + v) * 2 except IndexError: return", "self.bot = bot async def covfefe(self, x, k=\"aeiouy])\"): \"\"\" https://codegolf.stackexchange.com/a/123697", "Covfefe(commands.Cog): \"\"\" Convert almost any word into covfefe \"\"\" def", "commands class Covfefe(commands.Cog): \"\"\" Convert almost any word into covfefe", "def covfefe(self, x, k=\"aeiouy])\"): \"\"\" https://codegolf.stackexchange.com/a/123697 \"\"\" try: b, c,", "re import discord from redbot.core import commands class Covfefe(commands.Cog): \"\"\"", "delete \"\"\" return @commands.command() async def covefy(self, ctx, msg): \"\"\"Convert", "\"\"\" try: b, c, v = re.findall(f\"(.*?[{k}([^{k}.*?([{k}\", x)[0] return b", "= await self.covfefe(msg) if newword is not None: await ctx.send(newword)", "word into covfefe\"\"\" newword = await self.covfefe(msg) if newword is", "async def red_delete_data_for_user(self, **kwargs): \"\"\" Nothing to delete \"\"\" return", "async def covfefe(self, x, k=\"aeiouy])\"): \"\"\" https://codegolf.stackexchange.com/a/123697 \"\"\" try: b,", "import commands class Covfefe(commands.Cog): \"\"\" Convert almost any word into", "if newword is not None: await ctx.send(newword) else: await ctx.send(\"I", "bot): self.bot = bot async def covfefe(self, x, k=\"aeiouy])\"): \"\"\"", "**kwargs): \"\"\" Nothing to delete \"\"\" return @commands.command() async def", "return None async def red_delete_data_for_user(self, **kwargs): \"\"\" Nothing to delete", "not None: await ctx.send(newword) else: await ctx.send(\"I cannot covfefeify that", "return @commands.command() async def covefy(self, ctx, msg): \"\"\"Convert almost any", "discord from redbot.core import commands class Covfefe(commands.Cog): \"\"\" Convert almost", "__init__(self, bot): self.bot = bot async def covfefe(self, x, k=\"aeiouy])\"):", "word into covfefe \"\"\" def __init__(self, bot): self.bot = bot", "into covfefe \"\"\" def __init__(self, bot): self.bot = bot async", "ctx, msg): \"\"\"Convert almost any word into covfefe\"\"\" newword =", "redbot.core import commands class Covfefe(commands.Cog): \"\"\" Convert almost any word", "\"\"\" return @commands.command() async def covefy(self, ctx, msg): \"\"\"Convert almost", "\"\"\" https://codegolf.stackexchange.com/a/123697 \"\"\" try: b, c, v = re.findall(f\"(.*?[{k}([^{k}.*?([{k}\", x)[0]", "covfefe \"\"\" def __init__(self, bot): self.bot = bot async def", "import re import discord from redbot.core import commands class Covfefe(commands.Cog):", "+ c)[\"pgtvkgbzdfs\".find(c)] + v) * 2 except IndexError: return None", "\"\"\" Nothing to delete \"\"\" return @commands.command() async def covefy(self,", "+ ((\"bcdfgkpstvz\" + c)[\"pgtvkgbzdfs\".find(c)] + v) * 2 except IndexError:", "c, v = re.findall(f\"(.*?[{k}([^{k}.*?([{k}\", x)[0] return b + c +", "https://codegolf.stackexchange.com/a/123697 \"\"\" try: b, c, v = re.findall(f\"(.*?[{k}([^{k}.*?([{k}\", x)[0] return", "x, k=\"aeiouy])\"): \"\"\" https://codegolf.stackexchange.com/a/123697 \"\"\" try: b, c, v =", "try: b, c, v = re.findall(f\"(.*?[{k}([^{k}.*?([{k}\", x)[0] return b +", "v = re.findall(f\"(.*?[{k}([^{k}.*?([{k}\", x)[0] return b + c + ((\"bcdfgkpstvz\"", "Convert almost any word into covfefe \"\"\" def __init__(self, bot):", "c)[\"pgtvkgbzdfs\".find(c)] + v) * 2 except IndexError: return None async", "def covefy(self, ctx, msg): \"\"\"Convert almost any word into covfefe\"\"\"", "+ v) * 2 except IndexError: return None async def", "2 except IndexError: return None async def red_delete_data_for_user(self, **kwargs): \"\"\"", "None async def red_delete_data_for_user(self, **kwargs): \"\"\" Nothing to delete \"\"\"", "covefy(self, ctx, msg): \"\"\"Convert almost any word into covfefe\"\"\" newword", "from redbot.core import commands class Covfefe(commands.Cog): \"\"\" Convert almost any", "v) * 2 except IndexError: return None async def red_delete_data_for_user(self,", "covfefe\"\"\" newword = await self.covfefe(msg) if newword is not None:", "red_delete_data_for_user(self, **kwargs): \"\"\" Nothing to delete \"\"\" return @commands.command() async", "is not None: await ctx.send(newword) else: await ctx.send(\"I cannot covfefeify", "Nothing to delete \"\"\" return @commands.command() async def covefy(self, ctx,", "b, c, v = re.findall(f\"(.*?[{k}([^{k}.*?([{k}\", x)[0] return b + c", "any word into covfefe \"\"\" def __init__(self, bot): self.bot =", "\"\"\"Convert almost any word into covfefe\"\"\" newword = await self.covfefe(msg)", "IndexError: return None async def red_delete_data_for_user(self, **kwargs): \"\"\" Nothing to", "self.covfefe(msg) if newword is not None: await ctx.send(newword) else: await", "except IndexError: return None async def red_delete_data_for_user(self, **kwargs): \"\"\" Nothing", "newword is not None: await ctx.send(newword) else: await ctx.send(\"I cannot", "msg): \"\"\"Convert almost any word into covfefe\"\"\" newword = await", "re.findall(f\"(.*?[{k}([^{k}.*?([{k}\", x)[0] return b + c + ((\"bcdfgkpstvz\" + c)[\"pgtvkgbzdfs\".find(c)]", "import discord from redbot.core import commands class Covfefe(commands.Cog): \"\"\" Convert" ]
[ "= local_serializers.GeneralLogSerializer lookup_field = \"id\" class LoginLogViewSet(AdvancedModelViewSet, AdvancedListAPIView): queryset =", "permissions and limitations under the License. \"\"\" from bkuser_core.common.viewset import", "LogIn.objects.all() serializer_class = local_serializers.LoginLogSerializer lookup_field = \"id\" class ResetPasswordLogViewSet(AdvancedModelViewSet, AdvancedListAPIView):", "Unless required by applicable law or agreed to in writing,", "by applicable law or agreed to in writing, software distributed", ". import serializers as local_serializers from .models import GeneralLog, LogIn,", "Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All", "http://opensource.org/licenses/MIT Unless required by applicable law or agreed to in", "= \"id\" class LoginLogViewSet(AdvancedModelViewSet, AdvancedListAPIView): queryset = LogIn.objects.all() serializer_class =", "\"id\" class LoginLogViewSet(AdvancedModelViewSet, AdvancedListAPIView): queryset = LogIn.objects.all() serializer_class = local_serializers.LoginLogSerializer", "software distributed under the License is distributed on an \"AS", "distributed under the License is distributed on an \"AS IS\"", "License. \"\"\" from bkuser_core.common.viewset import AdvancedListAPIView, AdvancedModelViewSet from . import", "CONDITIONS OF ANY KIND, either express or implied. See the", "of the License at http://opensource.org/licenses/MIT Unless required by applicable law", "writing, software distributed under the License is distributed on an", "2017-2021 THL A29 Limited, a Tencent company. All rights reserved.", ".models import GeneralLog, LogIn, ResetPassword class GeneralLogViewSet(AdvancedModelViewSet, AdvancedListAPIView): queryset =", "= GeneralLog.objects.all() serializer_class = local_serializers.GeneralLogSerializer lookup_field = \"id\" class LoginLogViewSet(AdvancedModelViewSet,", "not use this file except in compliance with the License.", "express or implied. See the License for the specific language", "queryset = GeneralLog.objects.all() serializer_class = local_serializers.GeneralLogSerializer lookup_field = \"id\" class", "queryset = LogIn.objects.all() serializer_class = local_serializers.LoginLogSerializer lookup_field = \"id\" class", "IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "in compliance with the License. You may obtain a copy", "a copy of the License at http://opensource.org/licenses/MIT Unless required by", "the License. \"\"\" from bkuser_core.common.viewset import AdvancedListAPIView, AdvancedModelViewSet from .", "you may not use this file except in compliance with", "serializers as local_serializers from .models import GeneralLog, LogIn, ResetPassword class", "making 蓝鲸智云-用户管理(Bk-User) available. Copyright (C) 2017-2021 THL A29 Limited, a", "is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR", "the License. You may obtain a copy of the License", "agreed to in writing, software distributed under the License is", "\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "\"\"\" TencentBlueKing is pleased to support the open source community", "AdvancedListAPIView): queryset = LogIn.objects.all() serializer_class = local_serializers.LoginLogSerializer lookup_field = \"id\"", "distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS", "under the License. \"\"\" from bkuser_core.common.viewset import AdvancedListAPIView, AdvancedModelViewSet from", "Tencent company. All rights reserved. Licensed under the MIT License", "pleased to support the open source community by making 蓝鲸智云-用户管理(Bk-User)", "use this file except in compliance with the License. You", "A29 Limited, a Tencent company. All rights reserved. Licensed under", "AdvancedListAPIView, AdvancedModelViewSet from . import serializers as local_serializers from .models", "ANY KIND, either express or implied. See the License for", "class ResetPasswordLogViewSet(AdvancedModelViewSet, AdvancedListAPIView): queryset = ResetPassword.objects.all() serializer_class = local_serializers.ResetPasswordLogSerializer lookup_field", "community by making 蓝鲸智云-用户管理(Bk-User) available. Copyright (C) 2017-2021 THL A29", "by making 蓝鲸智云-用户管理(Bk-User) available. Copyright (C) 2017-2021 THL A29 Limited,", "and limitations under the License. \"\"\" from bkuser_core.common.viewset import AdvancedListAPIView,", "TencentBlueKing is pleased to support the open source community by", "= \"id\" class ResetPasswordLogViewSet(AdvancedModelViewSet, AdvancedListAPIView): queryset = ResetPassword.objects.all() serializer_class =", "either express or implied. See the License for the specific", "utf-8 -*- \"\"\" TencentBlueKing is pleased to support the open", "BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "available. Copyright (C) 2017-2021 THL A29 Limited, a Tencent company.", "under the License is distributed on an \"AS IS\" BASIS,", "\"License\"); you may not use this file except in compliance", "import AdvancedListAPIView, AdvancedModelViewSet from . import serializers as local_serializers from", "import GeneralLog, LogIn, ResetPassword class GeneralLogViewSet(AdvancedModelViewSet, AdvancedListAPIView): queryset = GeneralLog.objects.all()", "License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES", "the open source community by making 蓝鲸智云-用户管理(Bk-User) available. Copyright (C)", "support the open source community by making 蓝鲸智云-用户管理(Bk-User) available. Copyright", "GeneralLog.objects.all() serializer_class = local_serializers.GeneralLogSerializer lookup_field = \"id\" class LoginLogViewSet(AdvancedModelViewSet, AdvancedListAPIView):", "ResetPasswordLogViewSet(AdvancedModelViewSet, AdvancedListAPIView): queryset = ResetPassword.objects.all() serializer_class = local_serializers.ResetPasswordLogSerializer lookup_field =", "with the License. You may obtain a copy of the", "= LogIn.objects.all() serializer_class = local_serializers.LoginLogSerializer lookup_field = \"id\" class ResetPasswordLogViewSet(AdvancedModelViewSet,", "copy of the License at http://opensource.org/licenses/MIT Unless required by applicable", "License for the specific language governing permissions and limitations under", "limitations under the License. \"\"\" from bkuser_core.common.viewset import AdvancedListAPIView, AdvancedModelViewSet", "from . import serializers as local_serializers from .models import GeneralLog,", "License at http://opensource.org/licenses/MIT Unless required by applicable law or agreed", "= local_serializers.LoginLogSerializer lookup_field = \"id\" class ResetPasswordLogViewSet(AdvancedModelViewSet, AdvancedListAPIView): queryset =", "local_serializers.LoginLogSerializer lookup_field = \"id\" class ResetPasswordLogViewSet(AdvancedModelViewSet, AdvancedListAPIView): queryset = ResetPassword.objects.all()", "the MIT License (the \"License\"); you may not use this", "serializer_class = local_serializers.LoginLogSerializer lookup_field = \"id\" class ResetPasswordLogViewSet(AdvancedModelViewSet, AdvancedListAPIView): queryset", "Licensed under the MIT License (the \"License\"); you may not", "lookup_field = \"id\" class ResetPasswordLogViewSet(AdvancedModelViewSet, AdvancedListAPIView): queryset = ResetPassword.objects.all() serializer_class", "this file except in compliance with the License. You may", "bkuser_core.common.viewset import AdvancedListAPIView, AdvancedModelViewSet from . import serializers as local_serializers", "as local_serializers from .models import GeneralLog, LogIn, ResetPassword class GeneralLogViewSet(AdvancedModelViewSet,", "governing permissions and limitations under the License. \"\"\" from bkuser_core.common.viewset", "open source community by making 蓝鲸智云-用户管理(Bk-User) available. Copyright (C) 2017-2021", "specific language governing permissions and limitations under the License. \"\"\"", "class LoginLogViewSet(AdvancedModelViewSet, AdvancedListAPIView): queryset = LogIn.objects.all() serializer_class = local_serializers.LoginLogSerializer lookup_field", "(the \"License\"); you may not use this file except in", "(C) 2017-2021 THL A29 Limited, a Tencent company. All rights", "LogIn, ResetPassword class GeneralLogViewSet(AdvancedModelViewSet, AdvancedListAPIView): queryset = GeneralLog.objects.all() serializer_class =", "language governing permissions and limitations under the License. \"\"\" from", "<reponame>trueware/bk-user # -*- coding: utf-8 -*- \"\"\" TencentBlueKing is pleased", "applicable law or agreed to in writing, software distributed under", "local_serializers from .models import GeneralLog, LogIn, ResetPassword class GeneralLogViewSet(AdvancedModelViewSet, AdvancedListAPIView):", "the License is distributed on an \"AS IS\" BASIS, WITHOUT", "is pleased to support the open source community by making", "the specific language governing permissions and limitations under the License.", "-*- \"\"\" TencentBlueKing is pleased to support the open source", "obtain a copy of the License at http://opensource.org/licenses/MIT Unless required", "serializer_class = local_serializers.GeneralLogSerializer lookup_field = \"id\" class LoginLogViewSet(AdvancedModelViewSet, AdvancedListAPIView): queryset", "local_serializers.GeneralLogSerializer lookup_field = \"id\" class LoginLogViewSet(AdvancedModelViewSet, AdvancedListAPIView): queryset = LogIn.objects.all()", "a Tencent company. All rights reserved. Licensed under the MIT", "file except in compliance with the License. You may obtain", "except in compliance with the License. You may obtain a", "or implied. See the License for the specific language governing", "KIND, either express or implied. See the License for the", "to in writing, software distributed under the License is distributed", "Limited, a Tencent company. All rights reserved. Licensed under the", "蓝鲸智云-用户管理(Bk-User) available. Copyright (C) 2017-2021 THL A29 Limited, a Tencent", "AdvancedListAPIView): queryset = GeneralLog.objects.all() serializer_class = local_serializers.GeneralLogSerializer lookup_field = \"id\"", "lookup_field = \"id\" class LoginLogViewSet(AdvancedModelViewSet, AdvancedListAPIView): queryset = LogIn.objects.all() serializer_class", "or agreed to in writing, software distributed under the License", "may obtain a copy of the License at http://opensource.org/licenses/MIT Unless", "law or agreed to in writing, software distributed under the", "OR CONDITIONS OF ANY KIND, either express or implied. See", "rights reserved. Licensed under the MIT License (the \"License\"); you", "compliance with the License. You may obtain a copy of", "reserved. Licensed under the MIT License (the \"License\"); you may", "OF ANY KIND, either express or implied. See the License", "on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF", "under the MIT License (the \"License\"); you may not use", "from .models import GeneralLog, LogIn, ResetPassword class GeneralLogViewSet(AdvancedModelViewSet, AdvancedListAPIView): queryset", "at http://opensource.org/licenses/MIT Unless required by applicable law or agreed to", "License (the \"License\"); you may not use this file except", "GeneralLogViewSet(AdvancedModelViewSet, AdvancedListAPIView): queryset = GeneralLog.objects.all() serializer_class = local_serializers.GeneralLogSerializer lookup_field =", "to support the open source community by making 蓝鲸智云-用户管理(Bk-User) available.", "coding: utf-8 -*- \"\"\" TencentBlueKing is pleased to support the", "import serializers as local_serializers from .models import GeneralLog, LogIn, ResetPassword", "All rights reserved. Licensed under the MIT License (the \"License\");", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "for the specific language governing permissions and limitations under the", "See the License for the specific language governing permissions and", "the License at http://opensource.org/licenses/MIT Unless required by applicable law or", "# -*- coding: utf-8 -*- \"\"\" TencentBlueKing is pleased to", "from bkuser_core.common.viewset import AdvancedListAPIView, AdvancedModelViewSet from . import serializers as", "-*- coding: utf-8 -*- \"\"\" TencentBlueKing is pleased to support", "AdvancedListAPIView): queryset = ResetPassword.objects.all() serializer_class = local_serializers.ResetPasswordLogSerializer lookup_field = \"id\"", "License. You may obtain a copy of the License at", "AdvancedModelViewSet from . import serializers as local_serializers from .models import", "\"id\" class ResetPasswordLogViewSet(AdvancedModelViewSet, AdvancedListAPIView): queryset = ResetPassword.objects.all() serializer_class = local_serializers.ResetPasswordLogSerializer", "class GeneralLogViewSet(AdvancedModelViewSet, AdvancedListAPIView): queryset = GeneralLog.objects.all() serializer_class = local_serializers.GeneralLogSerializer lookup_field", "THL A29 Limited, a Tencent company. All rights reserved. Licensed", "MIT License (the \"License\"); you may not use this file", "the License for the specific language governing permissions and limitations", "may not use this file except in compliance with the", "in writing, software distributed under the License is distributed on", "LoginLogViewSet(AdvancedModelViewSet, AdvancedListAPIView): queryset = LogIn.objects.all() serializer_class = local_serializers.LoginLogSerializer lookup_field =", "required by applicable law or agreed to in writing, software", "implied. See the License for the specific language governing permissions", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "GeneralLog, LogIn, ResetPassword class GeneralLogViewSet(AdvancedModelViewSet, AdvancedListAPIView): queryset = GeneralLog.objects.all() serializer_class", "an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY", "You may obtain a copy of the License at http://opensource.org/licenses/MIT", "\"\"\" from bkuser_core.common.viewset import AdvancedListAPIView, AdvancedModelViewSet from . import serializers", "company. All rights reserved. Licensed under the MIT License (the", "source community by making 蓝鲸智云-用户管理(Bk-User) available. Copyright (C) 2017-2021 THL", "ResetPassword class GeneralLogViewSet(AdvancedModelViewSet, AdvancedListAPIView): queryset = GeneralLog.objects.all() serializer_class = local_serializers.GeneralLogSerializer" ]
[ "cfg.TEST.SPLIT_VQA scene_graph_file = cfg.SCENE_GRAPH_FILE % \\ cfg.TEST.SPLIT_VQA.replace('_balanced', '').replace('_all', '') data_reader", "% snapshot_file) snapshot_saver = tf.train.Saver(var_names) snapshot_saver.restore(sess, snapshot_file) print('Done') # Write", "cfg.TEST.ITER, cfg.TEST.SPLIT_VQA, accuracy, answer_correct, num_questions), file=f) if cfg.TEST.OUTPUT_VQA_EVAL_PRED: with open(pred_file,", "accuracy will be zero (no labels provided)**\\n') vqa_scores_value = sess.run(model.vqa_scores,", "batch: batch['answer_label_batch'] = -np.ones( len(batch['qid_list']), np.int32) if num_questions == 0:", "f: json.dump(output_predictions, f, indent=2) print('prediction file written to %s' %", "dummy labels.\\n\\n' '**The final accuracy will be zero (no labels", "= -np.ones( len(batch['qid_list']), np.int32) if num_questions == 0: print('imdb has", "None]) seq_length_batch = tf.placeholder(tf.int32, [None]) image_feat_batch = tf.placeholder( tf.float32, [None,", "model input_seq_batch = tf.placeholder(tf.int32, [None, None]) seq_length_batch = tf.placeholder(tf.int32, [None])", "final accuracy on %s = %f (%d / %d)' %", "= sess.run(model.vqa_scores, feed_dict={ input_seq_batch: batch['input_seq_batch'], seq_length_batch: batch['seq_length_batch'], image_feat_batch: batch['image_feat_batch'], image_valid_batch:", "% (cfg.EXP_NAME, cfg.TEST.ITER) print('loading model snapshot from %s' % snapshot_file)", "num_vocab=num_vocab, num_choices=num_choices, is_training=False) # Load snapshot if cfg.TEST.USE_EMA: ema =", "% \\ cfg.TEST.SPLIT_VQA.replace('_balanced', '').replace('_all', '') data_reader = DataReader( imdb_file, shuffle=False,", "vqa_labels) num_questions += len(vqa_labels) accuracy = answer_correct / num_questions if", "image_feat_batch: batch['image_feat_batch'], image_valid_batch: batch['image_valid_batch']}) # compute accuracy vqa_labels = batch['answer_label_batch']", "%s, iter = %d, accumulated accuracy on %s = %f", "open(pred_file, 'w') as f: json.dump(output_predictions, f, indent=2) print('prediction file written", "import tensorflow as tf from models_gqa.model import Model from models_gqa.config", "be zero (no labels provided)**\\n') vqa_scores_value = sess.run(model.vqa_scores, feed_dict={ input_seq_batch:", "# decay doesn't matter var_names = { (ema.average_name(v) if v", "= data_reader.batch_loader.answer_dict.word_list pred_file = os.path.join( result_dir, 'gqa_eval_preds_%s_%s_%08d.json' % ( cfg.TEST.SPLIT_VQA,", "in tf.global_variables()} snapshot_file = cfg.TEST.SNAPSHOT_FILE % (cfg.EXP_NAME, cfg.TEST.ITER) print('loading model", "answer_word_list = data_reader.batch_loader.answer_dict.word_list pred_file = os.path.join( result_dir, 'gqa_eval_preds_%s_%s_%08d.json' % (", "image_valid_batch, num_vocab=num_vocab, num_choices=num_choices, is_training=False) # Load snapshot if cfg.TEST.USE_EMA: ema", "as f: print('\\nexp: %s, iter = %d, final accuracy on", "is_training=False) # Load snapshot if cfg.TEST.USE_EMA: ema = tf.train.ExponentialMovingAverage(decay=0.9) #", "num_questions)) print('exp: %s, iter = %d, final accuracy on %s", "% 20 == 0: print('exp: %s, iter = %d, accumulated", "Using dummy labels.\\n\\n' '**The final accuracy will be zero (no", "open(os.path.join( result_dir, 'vqa_results_%s.txt' % cfg.TEST.SPLIT_VQA), 'w') as f: print('\\nexp: %s,", "= tf.Session(config=tf.ConfigProto( gpu_options=tf.GPUOptions(allow_growth=cfg.GPU_MEM_GROWTH))) # Data files imdb_file = cfg.IMDB_FILE %", "len(batch['qid_list']), np.int32) if num_questions == 0: print('imdb has no answer", "data_reader.batch_loader.answer_dict.word_list pred_file = os.path.join( result_dir, 'gqa_eval_preds_%s_%s_%08d.json' % ( cfg.TEST.SPLIT_VQA, cfg.EXP_NAME,", "%s' % snapshot_file) snapshot_saver = tf.train.Saver(var_names) snapshot_saver.restore(sess, snapshot_file) print('Done') #", "tf from models_gqa.model import Model from models_gqa.config import build_cfg_from_argparse from", "batch in enumerate(data_reader.batches()): if 'answer_label_batch' not in batch: batch['answer_label_batch'] =", "answer_correct += np.sum(vqa_predictions == vqa_labels) num_questions += len(vqa_labels) accuracy =", "np.sum(vqa_predictions == vqa_labels) num_questions += len(vqa_labels) accuracy = answer_correct /", "# Data files imdb_file = cfg.IMDB_FILE % cfg.TEST.SPLIT_VQA scene_graph_file =", "0, 0 if cfg.TEST.OUTPUT_VQA_EVAL_PRED: output_predictions = [] answer_word_list = data_reader.batch_loader.answer_dict.word_list", "if v in model.params else v.op.name): v for v in", "input_seq_batch, seq_length_batch, image_feat_batch, image_valid_batch, num_vocab=num_vocab, num_choices=num_choices, is_training=False) # Load snapshot", "with open(os.path.join( result_dir, 'vqa_results_%s.txt' % cfg.TEST.SPLIT_VQA), 'w') as f: print('\\nexp:", "= 0, 0 if cfg.TEST.OUTPUT_VQA_EVAL_PRED: output_predictions = [] answer_word_list =", "num_choices = data_reader.batch_loader.answer_dict.num_vocab # Inputs and model input_seq_batch = tf.placeholder(tf.int32,", "%s = %f (%d / %d)' % (cfg.EXP_NAME, cfg.TEST.ITER, cfg.TEST.SPLIT_VQA,", "cfg.TEST.RESULT_DIR % (cfg.EXP_NAME, cfg.TEST.ITER) os.makedirs(result_dir, exist_ok=True) # Run test answer_correct,", "tf.train.Saver(var_names) snapshot_saver.restore(sess, snapshot_file) print('Done') # Write results result_dir = cfg.TEST.RESULT_DIR", "as f: json.dump(output_predictions, f, indent=2) print('prediction file written to %s'", "[None]) image_feat_batch = tf.placeholder( tf.float32, [None, cfg.H_FEAT, cfg.W_FEAT, cfg.D_FEAT]) image_valid_batch", "and model input_seq_batch = tf.placeholder(tf.int32, [None, None]) seq_length_batch = tf.placeholder(tf.int32,", "cfg.TEST.ITER, cfg.TEST.SPLIT_VQA, accuracy, answer_correct, num_questions)) if cfg.TEST.OUTPUT_VQA_EVAL_PRED: output_predictions.extend([ {\"questionId\": qId,", "gpu_options=tf.GPUOptions(allow_growth=cfg.GPU_MEM_GROWTH))) # Data files imdb_file = cfg.IMDB_FILE % cfg.TEST.SPLIT_VQA scene_graph_file", "n_batch % 20 == 0: print('exp: %s, iter = %d,", "= Model( input_seq_batch, seq_length_batch, image_feat_batch, image_valid_batch, num_vocab=num_vocab, num_choices=num_choices, is_training=False) #", "+= np.sum(vqa_predictions == vqa_labels) num_questions += len(vqa_labels) accuracy = answer_correct", "'gqa_eval_preds_%s_%s_%08d.json' % ( cfg.TEST.SPLIT_VQA, cfg.EXP_NAME, cfg.TEST.ITER)) for n_batch, batch in", "image_valid_batch = tf.placeholder( tf.float32, [None, cfg.H_FEAT, cfg.W_FEAT]) model = Model(", "len(vqa_labels) accuracy = answer_correct / num_questions if n_batch % 20", "seq_length_batch = tf.placeholder(tf.int32, [None]) image_feat_batch = tf.placeholder( tf.float32, [None, cfg.H_FEAT,", "feature_type=cfg.FEAT_TYPE, spatial_feature_dir=cfg.SPATIAL_FEATURE_DIR, objects_feature_dir=cfg.OBJECTS_FEATURE_DIR, objects_max_num=cfg.W_FEAT, scene_graph_file=scene_graph_file, vocab_name_file=cfg.VOCAB_NAME_FILE, vocab_attr_file=cfg.VOCAB_ATTR_FILE, spatial_pos_enc_dim=cfg.SPATIAL_POS_ENC_DIM, bbox_tile_num=cfg.BBOX_TILE_NUM) num_vocab", "= tf.placeholder( tf.float32, [None, cfg.H_FEAT, cfg.W_FEAT, cfg.D_FEAT]) image_valid_batch = tf.placeholder(", "seq_length_batch: batch['seq_length_batch'], image_feat_batch: batch['image_feat_batch'], image_valid_batch: batch['image_valid_batch']}) # compute accuracy vqa_labels", "cfg.H_FEAT, cfg.W_FEAT, cfg.D_FEAT]) image_valid_batch = tf.placeholder( tf.float32, [None, cfg.H_FEAT, cfg.W_FEAT])", "result_dir = cfg.TEST.RESULT_DIR % (cfg.EXP_NAME, cfg.TEST.ITER) os.makedirs(result_dir, exist_ok=True) # Run", "if cfg.TEST.OUTPUT_VQA_EVAL_PRED: output_predictions = [] answer_word_list = data_reader.batch_loader.answer_dict.word_list pred_file =", "in tf.global_variables()} else: var_names = {v.op.name: v for v in", "snapshot_file = cfg.TEST.SNAPSHOT_FILE % (cfg.EXP_NAME, cfg.TEST.ITER) print('loading model snapshot from", "results result_dir = cfg.TEST.RESULT_DIR % (cfg.EXP_NAME, cfg.TEST.ITER) os.makedirs(result_dir, exist_ok=True) #", "print('loading model snapshot from %s' % snapshot_file) snapshot_saver = tf.train.Saver(var_names)", "-np.ones( len(batch['qid_list']), np.int32) if num_questions == 0: print('imdb has no", "has no answer labels. Using dummy labels.\\n\\n' '**The final accuracy", "'') data_reader = DataReader( imdb_file, shuffle=False, one_pass=True, batch_size=cfg.TEST.BATCH_SIZE, T_encoder=cfg.T_ENCODER, vocab_question_file=cfg.VOCAB_QUESTION_FILE,", "%d)' % (cfg.EXP_NAME, cfg.TEST.ITER, cfg.TEST.SPLIT_VQA, accuracy, answer_correct, num_questions)) print('exp: %s,", "if cfg.TEST.OUTPUT_VQA_EVAL_PRED: with open(pred_file, 'w') as f: json.dump(output_predictions, f, indent=2)", "answer_word_list[p]} for qId, p in zip(batch['qid_list'], vqa_predictions)]) with open(os.path.join( result_dir,", "vqa_labels = batch['answer_label_batch'] vqa_predictions = np.argmax(vqa_scores_value, axis=1) answer_correct += np.sum(vqa_predictions", "accumulated accuracy on %s = %f (%d / %d)' %", "on %s = %f (%d / %d)' % (cfg.EXP_NAME, cfg.TEST.ITER,", "num_questions if n_batch % 20 == 0: print('exp: %s, iter", "{ (ema.average_name(v) if v in model.params else v.op.name): v for", "= tf.placeholder(tf.int32, [None, None]) seq_length_batch = tf.placeholder(tf.int32, [None]) image_feat_batch =", "(cfg.EXP_NAME, cfg.TEST.ITER, cfg.TEST.SPLIT_VQA, accuracy, answer_correct, num_questions), file=f) if cfg.TEST.OUTPUT_VQA_EVAL_PRED: with", "zip(batch['qid_list'], vqa_predictions)]) with open(os.path.join( result_dir, 'vqa_results_%s.txt' % cfg.TEST.SPLIT_VQA), 'w') as", "cfg.TEST.SPLIT_VQA, cfg.EXP_NAME, cfg.TEST.ITER)) for n_batch, batch in enumerate(data_reader.batches()): if 'answer_label_batch'", "= cfg.TEST.SNAPSHOT_FILE % (cfg.EXP_NAME, cfg.TEST.ITER) print('loading model snapshot from %s'", "'w') as f: print('\\nexp: %s, iter = %d, final accuracy", "= cfg.TEST.RESULT_DIR % (cfg.EXP_NAME, cfg.TEST.ITER) os.makedirs(result_dir, exist_ok=True) # Run test", "data_reader.batch_loader.answer_dict.num_vocab # Inputs and model input_seq_batch = tf.placeholder(tf.int32, [None, None])", "model.params else v.op.name): v for v in tf.global_variables()} else: var_names", "print('exp: %s, iter = %d, accumulated accuracy on %s =", "answer labels. Using dummy labels.\\n\\n' '**The final accuracy will be", "'vqa_results_%s.txt' % cfg.TEST.SPLIT_VQA), 'w') as f: print('\\nexp: %s, iter =", "= %d, final accuracy on %s = %f (%d /", "cfg.TEST.ITER) os.makedirs(result_dir, exist_ok=True) # Run test answer_correct, num_questions = 0,", "num_questions), file=f) if cfg.TEST.OUTPUT_VQA_EVAL_PRED: with open(pred_file, 'w') as f: json.dump(output_predictions,", "imdb_file = cfg.IMDB_FILE % cfg.TEST.SPLIT_VQA scene_graph_file = cfg.SCENE_GRAPH_FILE % \\", "'').replace('_all', '') data_reader = DataReader( imdb_file, shuffle=False, one_pass=True, batch_size=cfg.TEST.BATCH_SIZE, T_encoder=cfg.T_ENCODER,", "= %f (%d / %d)' % (cfg.EXP_NAME, cfg.TEST.ITER, cfg.TEST.SPLIT_VQA, accuracy,", "accuracy on %s = %f (%d / %d)' % (cfg.EXP_NAME,", "build_cfg_from_argparse from util.gqa_train.data_reader import DataReader import json # Load config", "exist_ok=True) # Run test answer_correct, num_questions = 0, 0 if", "cfg.TEST.ITER) print('loading model snapshot from %s' % snapshot_file) snapshot_saver =", "= os.path.join( result_dir, 'gqa_eval_preds_%s_%s_%08d.json' % ( cfg.TEST.SPLIT_VQA, cfg.EXP_NAME, cfg.TEST.ITER)) for", "vocab_name_file=cfg.VOCAB_NAME_FILE, vocab_attr_file=cfg.VOCAB_ATTR_FILE, spatial_pos_enc_dim=cfg.SPATIAL_POS_ENC_DIM, bbox_tile_num=cfg.BBOX_TILE_NUM) num_vocab = data_reader.batch_loader.vocab_dict.num_vocab num_choices = data_reader.batch_loader.answer_dict.num_vocab", "snapshot from %s' % snapshot_file) snapshot_saver = tf.train.Saver(var_names) snapshot_saver.restore(sess, snapshot_file)", "import Model from models_gqa.config import build_cfg_from_argparse from util.gqa_train.data_reader import DataReader", "cfg.TEST.OUTPUT_VQA_EVAL_PRED: output_predictions.extend([ {\"questionId\": qId, \"prediction\": answer_word_list[p]} for qId, p in", "snapshot if cfg.TEST.USE_EMA: ema = tf.train.ExponentialMovingAverage(decay=0.9) # decay doesn't matter", "0 if cfg.TEST.OUTPUT_VQA_EVAL_PRED: output_predictions = [] answer_word_list = data_reader.batch_loader.answer_dict.word_list pred_file", "% (cfg.EXP_NAME, cfg.TEST.ITER, cfg.TEST.SPLIT_VQA, accuracy, answer_correct, num_questions)) print('exp: %s, iter", "from models_gqa.model import Model from models_gqa.config import build_cfg_from_argparse from util.gqa_train.data_reader", "{v.op.name: v for v in tf.global_variables()} snapshot_file = cfg.TEST.SNAPSHOT_FILE %", "util.gqa_train.data_reader import DataReader import json # Load config cfg =", "cfg.D_FEAT]) image_valid_batch = tf.placeholder( tf.float32, [None, cfg.H_FEAT, cfg.W_FEAT]) model =", "model = Model( input_seq_batch, seq_length_batch, image_feat_batch, image_valid_batch, num_vocab=num_vocab, num_choices=num_choices, is_training=False)", "in batch: batch['answer_label_batch'] = -np.ones( len(batch['qid_list']), np.int32) if num_questions ==", "if num_questions == 0: print('imdb has no answer labels. Using", "objects_feature_dir=cfg.OBJECTS_FEATURE_DIR, objects_max_num=cfg.W_FEAT, scene_graph_file=scene_graph_file, vocab_name_file=cfg.VOCAB_NAME_FILE, vocab_attr_file=cfg.VOCAB_ATTR_FILE, spatial_pos_enc_dim=cfg.SPATIAL_POS_ENC_DIM, bbox_tile_num=cfg.BBOX_TILE_NUM) num_vocab = data_reader.batch_loader.vocab_dict.num_vocab", "os.environ[\"CUDA_VISIBLE_DEVICES\"] = str(cfg.GPU_ID) sess = tf.Session(config=tf.ConfigProto( gpu_options=tf.GPUOptions(allow_growth=cfg.GPU_MEM_GROWTH))) # Data files", "v in model.params else v.op.name): v for v in tf.global_variables()}", "= tf.train.ExponentialMovingAverage(decay=0.9) # decay doesn't matter var_names = { (ema.average_name(v)", "= tf.train.Saver(var_names) snapshot_saver.restore(sess, snapshot_file) print('Done') # Write results result_dir =", "vocab_answer_file=cfg.VOCAB_ANSWER_FILE, feature_type=cfg.FEAT_TYPE, spatial_feature_dir=cfg.SPATIAL_FEATURE_DIR, objects_feature_dir=cfg.OBJECTS_FEATURE_DIR, objects_max_num=cfg.W_FEAT, scene_graph_file=scene_graph_file, vocab_name_file=cfg.VOCAB_NAME_FILE, vocab_attr_file=cfg.VOCAB_ATTR_FILE, spatial_pos_enc_dim=cfg.SPATIAL_POS_ENC_DIM, bbox_tile_num=cfg.BBOX_TILE_NUM)", "snapshot_saver.restore(sess, snapshot_file) print('Done') # Write results result_dir = cfg.TEST.RESULT_DIR %", "Model( input_seq_batch, seq_length_batch, image_feat_batch, image_valid_batch, num_vocab=num_vocab, num_choices=num_choices, is_training=False) # Load", "os import numpy as np import tensorflow as tf from", "Load snapshot if cfg.TEST.USE_EMA: ema = tf.train.ExponentialMovingAverage(decay=0.9) # decay doesn't", "( cfg.TEST.SPLIT_VQA, cfg.EXP_NAME, cfg.TEST.ITER)) for n_batch, batch in enumerate(data_reader.batches()): if", "input_seq_batch: batch['input_seq_batch'], seq_length_batch: batch['seq_length_batch'], image_feat_batch: batch['image_feat_batch'], image_valid_batch: batch['image_valid_batch']}) # compute", "bbox_tile_num=cfg.BBOX_TILE_NUM) num_vocab = data_reader.batch_loader.vocab_dict.num_vocab num_choices = data_reader.batch_loader.answer_dict.num_vocab # Inputs and", "= DataReader( imdb_file, shuffle=False, one_pass=True, batch_size=cfg.TEST.BATCH_SIZE, T_encoder=cfg.T_ENCODER, vocab_question_file=cfg.VOCAB_QUESTION_FILE, vocab_answer_file=cfg.VOCAB_ANSWER_FILE, feature_type=cfg.FEAT_TYPE,", "answer_correct, num_questions = 0, 0 if cfg.TEST.OUTPUT_VQA_EVAL_PRED: output_predictions = []", "cfg.IMDB_FILE % cfg.TEST.SPLIT_VQA scene_graph_file = cfg.SCENE_GRAPH_FILE % \\ cfg.TEST.SPLIT_VQA.replace('_balanced', '').replace('_all',", "num_choices=num_choices, is_training=False) # Load snapshot if cfg.TEST.USE_EMA: ema = tf.train.ExponentialMovingAverage(decay=0.9)", "'**The final accuracy will be zero (no labels provided)**\\n') vqa_scores_value", "%d)' % (cfg.EXP_NAME, cfg.TEST.ITER, cfg.TEST.SPLIT_VQA, accuracy, answer_correct, num_questions)) if cfg.TEST.OUTPUT_VQA_EVAL_PRED:", "= data_reader.batch_loader.vocab_dict.num_vocab num_choices = data_reader.batch_loader.answer_dict.num_vocab # Inputs and model input_seq_batch", "(cfg.EXP_NAME, cfg.TEST.ITER, cfg.TEST.SPLIT_VQA, accuracy, answer_correct, num_questions)) if cfg.TEST.OUTPUT_VQA_EVAL_PRED: output_predictions.extend([ {\"questionId\":", "axis=1) answer_correct += np.sum(vqa_predictions == vqa_labels) num_questions += len(vqa_labels) accuracy", "shuffle=False, one_pass=True, batch_size=cfg.TEST.BATCH_SIZE, T_encoder=cfg.T_ENCODER, vocab_question_file=cfg.VOCAB_QUESTION_FILE, vocab_answer_file=cfg.VOCAB_ANSWER_FILE, feature_type=cfg.FEAT_TYPE, spatial_feature_dir=cfg.SPATIAL_FEATURE_DIR, objects_feature_dir=cfg.OBJECTS_FEATURE_DIR, objects_max_num=cfg.W_FEAT,", "% (cfg.EXP_NAME, cfg.TEST.ITER) os.makedirs(result_dir, exist_ok=True) # Run test answer_correct, num_questions", "answer_correct, num_questions)) print('exp: %s, iter = %d, final accuracy on", "cfg.TEST.SPLIT_VQA), 'w') as f: print('\\nexp: %s, iter = %d, final", "Model from models_gqa.config import build_cfg_from_argparse from util.gqa_train.data_reader import DataReader import", "Start session os.environ[\"CUDA_VISIBLE_DEVICES\"] = str(cfg.GPU_ID) sess = tf.Session(config=tf.ConfigProto( gpu_options=tf.GPUOptions(allow_growth=cfg.GPU_MEM_GROWTH))) #", "'answer_label_batch' not in batch: batch['answer_label_batch'] = -np.ones( len(batch['qid_list']), np.int32) if", "files imdb_file = cfg.IMDB_FILE % cfg.TEST.SPLIT_VQA scene_graph_file = cfg.SCENE_GRAPH_FILE %", "0: print('exp: %s, iter = %d, accumulated accuracy on %s", "# Inputs and model input_seq_batch = tf.placeholder(tf.int32, [None, None]) seq_length_batch", "== 0: print('imdb has no answer labels. Using dummy labels.\\n\\n'", "sess = tf.Session(config=tf.ConfigProto( gpu_options=tf.GPUOptions(allow_growth=cfg.GPU_MEM_GROWTH))) # Data files imdb_file = cfg.IMDB_FILE", "batch['image_valid_batch']}) # compute accuracy vqa_labels = batch['answer_label_batch'] vqa_predictions = np.argmax(vqa_scores_value,", "accuracy, answer_correct, num_questions), file=f) if cfg.TEST.OUTPUT_VQA_EVAL_PRED: with open(pred_file, 'w') as", "decay doesn't matter var_names = { (ema.average_name(v) if v in", "= tf.placeholder( tf.float32, [None, cfg.H_FEAT, cfg.W_FEAT]) model = Model( input_seq_batch,", "(ema.average_name(v) if v in model.params else v.op.name): v for v", "= tf.placeholder(tf.int32, [None]) image_feat_batch = tf.placeholder( tf.float32, [None, cfg.H_FEAT, cfg.W_FEAT,", "tf.float32, [None, cfg.H_FEAT, cfg.W_FEAT, cfg.D_FEAT]) image_valid_batch = tf.placeholder( tf.float32, [None,", "cfg.EXP_NAME, cfg.TEST.ITER)) for n_batch, batch in enumerate(data_reader.batches()): if 'answer_label_batch' not", "data_reader = DataReader( imdb_file, shuffle=False, one_pass=True, batch_size=cfg.TEST.BATCH_SIZE, T_encoder=cfg.T_ENCODER, vocab_question_file=cfg.VOCAB_QUESTION_FILE, vocab_answer_file=cfg.VOCAB_ANSWER_FILE,", "%s, iter = %d, final accuracy on %s = %f", "str(cfg.GPU_ID) sess = tf.Session(config=tf.ConfigProto( gpu_options=tf.GPUOptions(allow_growth=cfg.GPU_MEM_GROWTH))) # Data files imdb_file =", "# compute accuracy vqa_labels = batch['answer_label_batch'] vqa_predictions = np.argmax(vqa_scores_value, axis=1)", "== 0: print('exp: %s, iter = %d, accumulated accuracy on", "Write results result_dir = cfg.TEST.RESULT_DIR % (cfg.EXP_NAME, cfg.TEST.ITER) os.makedirs(result_dir, exist_ok=True)", "else v.op.name): v for v in tf.global_variables()} else: var_names =", "cfg.TEST.SPLIT_VQA, accuracy, answer_correct, num_questions)) if cfg.TEST.OUTPUT_VQA_EVAL_PRED: output_predictions.extend([ {\"questionId\": qId, \"prediction\":", "scene_graph_file = cfg.SCENE_GRAPH_FILE % \\ cfg.TEST.SPLIT_VQA.replace('_balanced', '').replace('_all', '') data_reader =", "[None, cfg.H_FEAT, cfg.W_FEAT]) model = Model( input_seq_batch, seq_length_batch, image_feat_batch, image_valid_batch,", "tensorflow as tf from models_gqa.model import Model from models_gqa.config import", "batch['answer_label_batch'] = -np.ones( len(batch['qid_list']), np.int32) if num_questions == 0: print('imdb", "tf.float32, [None, cfg.H_FEAT, cfg.W_FEAT]) model = Model( input_seq_batch, seq_length_batch, image_feat_batch,", "% cfg.TEST.SPLIT_VQA), 'w') as f: print('\\nexp: %s, iter = %d,", "doesn't matter var_names = { (ema.average_name(v) if v in model.params", "batch['answer_label_batch'] vqa_predictions = np.argmax(vqa_scores_value, axis=1) answer_correct += np.sum(vqa_predictions == vqa_labels)", "% (cfg.EXP_NAME, cfg.TEST.ITER, cfg.TEST.SPLIT_VQA, accuracy, answer_correct, num_questions)) if cfg.TEST.OUTPUT_VQA_EVAL_PRED: output_predictions.extend([", "\\ cfg.TEST.SPLIT_VQA.replace('_balanced', '').replace('_all', '') data_reader = DataReader( imdb_file, shuffle=False, one_pass=True,", "vqa_predictions)]) with open(os.path.join( result_dir, 'vqa_results_%s.txt' % cfg.TEST.SPLIT_VQA), 'w') as f:", "accuracy, answer_correct, num_questions)) print('exp: %s, iter = %d, final accuracy", "cfg.TEST.SPLIT_VQA, accuracy, answer_correct, num_questions)) print('exp: %s, iter = %d, final", "as tf from models_gqa.model import Model from models_gqa.config import build_cfg_from_argparse", "(%d / %d)' % (cfg.EXP_NAME, cfg.TEST.ITER, cfg.TEST.SPLIT_VQA, accuracy, answer_correct, num_questions))", "matter var_names = { (ema.average_name(v) if v in model.params else", "var_names = { (ema.average_name(v) if v in model.params else v.op.name):", "accuracy vqa_labels = batch['answer_label_batch'] vqa_predictions = np.argmax(vqa_scores_value, axis=1) answer_correct +=", "print('imdb has no answer labels. Using dummy labels.\\n\\n' '**The final", "with open(pred_file, 'w') as f: json.dump(output_predictions, f, indent=2) print('prediction file", "== vqa_labels) num_questions += len(vqa_labels) accuracy = answer_correct / num_questions", "tf.global_variables()} snapshot_file = cfg.TEST.SNAPSHOT_FILE % (cfg.EXP_NAME, cfg.TEST.ITER) print('loading model snapshot", "imdb_file, shuffle=False, one_pass=True, batch_size=cfg.TEST.BATCH_SIZE, T_encoder=cfg.T_ENCODER, vocab_question_file=cfg.VOCAB_QUESTION_FILE, vocab_answer_file=cfg.VOCAB_ANSWER_FILE, feature_type=cfg.FEAT_TYPE, spatial_feature_dir=cfg.SPATIAL_FEATURE_DIR, objects_feature_dir=cfg.OBJECTS_FEATURE_DIR,", "if cfg.TEST.USE_EMA: ema = tf.train.ExponentialMovingAverage(decay=0.9) # decay doesn't matter var_names", "num_vocab = data_reader.batch_loader.vocab_dict.num_vocab num_choices = data_reader.batch_loader.answer_dict.num_vocab # Inputs and model", "pred_file = os.path.join( result_dir, 'gqa_eval_preds_%s_%s_%08d.json' % ( cfg.TEST.SPLIT_VQA, cfg.EXP_NAME, cfg.TEST.ITER))", "accuracy, answer_correct, num_questions)) if cfg.TEST.OUTPUT_VQA_EVAL_PRED: output_predictions.extend([ {\"questionId\": qId, \"prediction\": answer_word_list[p]}", "tf.global_variables()} else: var_names = {v.op.name: v for v in tf.global_variables()}", "batch['input_seq_batch'], seq_length_batch: batch['seq_length_batch'], image_feat_batch: batch['image_feat_batch'], image_valid_batch: batch['image_valid_batch']}) # compute accuracy", "spatial_feature_dir=cfg.SPATIAL_FEATURE_DIR, objects_feature_dir=cfg.OBJECTS_FEATURE_DIR, objects_max_num=cfg.W_FEAT, scene_graph_file=scene_graph_file, vocab_name_file=cfg.VOCAB_NAME_FILE, vocab_attr_file=cfg.VOCAB_ATTR_FILE, spatial_pos_enc_dim=cfg.SPATIAL_POS_ENC_DIM, bbox_tile_num=cfg.BBOX_TILE_NUM) num_vocab =", "'w') as f: json.dump(output_predictions, f, indent=2) print('prediction file written to", "numpy as np import tensorflow as tf from models_gqa.model import", "snapshot_saver = tf.train.Saver(var_names) snapshot_saver.restore(sess, snapshot_file) print('Done') # Write results result_dir", "cfg.TEST.OUTPUT_VQA_EVAL_PRED: output_predictions = [] answer_word_list = data_reader.batch_loader.answer_dict.word_list pred_file = os.path.join(", "%f (%d / %d)' % (cfg.EXP_NAME, cfg.TEST.ITER, cfg.TEST.SPLIT_VQA, accuracy, answer_correct,", "will be zero (no labels provided)**\\n') vqa_scores_value = sess.run(model.vqa_scores, feed_dict={", "v.op.name): v for v in tf.global_variables()} else: var_names = {v.op.name:", "Load config cfg = build_cfg_from_argparse() # Start session os.environ[\"CUDA_VISIBLE_DEVICES\"] =", "output_predictions = [] answer_word_list = data_reader.batch_loader.answer_dict.word_list pred_file = os.path.join( result_dir,", "tf.placeholder( tf.float32, [None, cfg.H_FEAT, cfg.W_FEAT]) model = Model( input_seq_batch, seq_length_batch,", "# Run test answer_correct, num_questions = 0, 0 if cfg.TEST.OUTPUT_VQA_EVAL_PRED:", "= data_reader.batch_loader.answer_dict.num_vocab # Inputs and model input_seq_batch = tf.placeholder(tf.int32, [None,", "\"prediction\": answer_word_list[p]} for qId, p in zip(batch['qid_list'], vqa_predictions)]) with open(os.path.join(", "import os import numpy as np import tensorflow as tf", "vqa_predictions = np.argmax(vqa_scores_value, axis=1) answer_correct += np.sum(vqa_predictions == vqa_labels) num_questions", "ema = tf.train.ExponentialMovingAverage(decay=0.9) # decay doesn't matter var_names = {", "/ num_questions if n_batch % 20 == 0: print('exp: %s,", "# Load config cfg = build_cfg_from_argparse() # Start session os.environ[\"CUDA_VISIBLE_DEVICES\"]", "= answer_correct / num_questions if n_batch % 20 == 0:", "if n_batch % 20 == 0: print('exp: %s, iter =", "Data files imdb_file = cfg.IMDB_FILE % cfg.TEST.SPLIT_VQA scene_graph_file = cfg.SCENE_GRAPH_FILE", "/ %d)' % (cfg.EXP_NAME, cfg.TEST.ITER, cfg.TEST.SPLIT_VQA, accuracy, answer_correct, num_questions)) print('exp:", "os.makedirs(result_dir, exist_ok=True) # Run test answer_correct, num_questions = 0, 0", "import json # Load config cfg = build_cfg_from_argparse() # Start", "# Start session os.environ[\"CUDA_VISIBLE_DEVICES\"] = str(cfg.GPU_ID) sess = tf.Session(config=tf.ConfigProto( gpu_options=tf.GPUOptions(allow_growth=cfg.GPU_MEM_GROWTH)))", "vocab_attr_file=cfg.VOCAB_ATTR_FILE, spatial_pos_enc_dim=cfg.SPATIAL_POS_ENC_DIM, bbox_tile_num=cfg.BBOX_TILE_NUM) num_vocab = data_reader.batch_loader.vocab_dict.num_vocab num_choices = data_reader.batch_loader.answer_dict.num_vocab #", "compute accuracy vqa_labels = batch['answer_label_batch'] vqa_predictions = np.argmax(vqa_scores_value, axis=1) answer_correct", "= { (ema.average_name(v) if v in model.params else v.op.name): v", "= batch['answer_label_batch'] vqa_predictions = np.argmax(vqa_scores_value, axis=1) answer_correct += np.sum(vqa_predictions ==", "in zip(batch['qid_list'], vqa_predictions)]) with open(os.path.join( result_dir, 'vqa_results_%s.txt' % cfg.TEST.SPLIT_VQA), 'w')", "# Write results result_dir = cfg.TEST.RESULT_DIR % (cfg.EXP_NAME, cfg.TEST.ITER) os.makedirs(result_dir,", "image_valid_batch: batch['image_valid_batch']}) # compute accuracy vqa_labels = batch['answer_label_batch'] vqa_predictions =", "final accuracy will be zero (no labels provided)**\\n') vqa_scores_value =", "models_gqa.config import build_cfg_from_argparse from util.gqa_train.data_reader import DataReader import json #", "in model.params else v.op.name): v for v in tf.global_variables()} else:", "os.path.join( result_dir, 'gqa_eval_preds_%s_%s_%08d.json' % ( cfg.TEST.SPLIT_VQA, cfg.EXP_NAME, cfg.TEST.ITER)) for n_batch,", "/ %d)' % (cfg.EXP_NAME, cfg.TEST.ITER, cfg.TEST.SPLIT_VQA, accuracy, answer_correct, num_questions), file=f)", "= np.argmax(vqa_scores_value, axis=1) answer_correct += np.sum(vqa_predictions == vqa_labels) num_questions +=", "# Load snapshot if cfg.TEST.USE_EMA: ema = tf.train.ExponentialMovingAverage(decay=0.9) # decay", "%d, final accuracy on %s = %f (%d / %d)'", "spatial_pos_enc_dim=cfg.SPATIAL_POS_ENC_DIM, bbox_tile_num=cfg.BBOX_TILE_NUM) num_vocab = data_reader.batch_loader.vocab_dict.num_vocab num_choices = data_reader.batch_loader.answer_dict.num_vocab # Inputs", "objects_max_num=cfg.W_FEAT, scene_graph_file=scene_graph_file, vocab_name_file=cfg.VOCAB_NAME_FILE, vocab_attr_file=cfg.VOCAB_ATTR_FILE, spatial_pos_enc_dim=cfg.SPATIAL_POS_ENC_DIM, bbox_tile_num=cfg.BBOX_TILE_NUM) num_vocab = data_reader.batch_loader.vocab_dict.num_vocab num_choices", "for v in tf.global_variables()} else: var_names = {v.op.name: v for", "iter = %d, final accuracy on %s = %f (%d", "build_cfg_from_argparse() # Start session os.environ[\"CUDA_VISIBLE_DEVICES\"] = str(cfg.GPU_ID) sess = tf.Session(config=tf.ConfigProto(", "import numpy as np import tensorflow as tf from models_gqa.model", "tf.train.ExponentialMovingAverage(decay=0.9) # decay doesn't matter var_names = { (ema.average_name(v) if", "test answer_correct, num_questions = 0, 0 if cfg.TEST.OUTPUT_VQA_EVAL_PRED: output_predictions =", "(cfg.EXP_NAME, cfg.TEST.ITER, cfg.TEST.SPLIT_VQA, accuracy, answer_correct, num_questions)) print('exp: %s, iter =", "feed_dict={ input_seq_batch: batch['input_seq_batch'], seq_length_batch: batch['seq_length_batch'], image_feat_batch: batch['image_feat_batch'], image_valid_batch: batch['image_valid_batch']}) #", "cfg.H_FEAT, cfg.W_FEAT]) model = Model( input_seq_batch, seq_length_batch, image_feat_batch, image_valid_batch, num_vocab=num_vocab,", "batch['seq_length_batch'], image_feat_batch: batch['image_feat_batch'], image_valid_batch: batch['image_valid_batch']}) # compute accuracy vqa_labels =", "= %d, accumulated accuracy on %s = %f (%d /", "/ %d)' % (cfg.EXP_NAME, cfg.TEST.ITER, cfg.TEST.SPLIT_VQA, accuracy, answer_correct, num_questions)) if", "v in tf.global_variables()} else: var_names = {v.op.name: v for v", "enumerate(data_reader.batches()): if 'answer_label_batch' not in batch: batch['answer_label_batch'] = -np.ones( len(batch['qid_list']),", "%d, accumulated accuracy on %s = %f (%d / %d)'", "from util.gqa_train.data_reader import DataReader import json # Load config cfg", "(cfg.EXP_NAME, cfg.TEST.ITER) os.makedirs(result_dir, exist_ok=True) # Run test answer_correct, num_questions =", "result_dir, 'gqa_eval_preds_%s_%s_%08d.json' % ( cfg.TEST.SPLIT_VQA, cfg.EXP_NAME, cfg.TEST.ITER)) for n_batch, batch", "zero (no labels provided)**\\n') vqa_scores_value = sess.run(model.vqa_scores, feed_dict={ input_seq_batch: batch['input_seq_batch'],", "20 == 0: print('exp: %s, iter = %d, accumulated accuracy", "provided)**\\n') vqa_scores_value = sess.run(model.vqa_scores, feed_dict={ input_seq_batch: batch['input_seq_batch'], seq_length_batch: batch['seq_length_batch'], image_feat_batch:", "model snapshot from %s' % snapshot_file) snapshot_saver = tf.train.Saver(var_names) snapshot_saver.restore(sess,", "% cfg.TEST.SPLIT_VQA scene_graph_file = cfg.SCENE_GRAPH_FILE % \\ cfg.TEST.SPLIT_VQA.replace('_balanced', '').replace('_all', '')", "for v in tf.global_variables()} snapshot_file = cfg.TEST.SNAPSHOT_FILE % (cfg.EXP_NAME, cfg.TEST.ITER)", "cfg.TEST.SPLIT_VQA.replace('_balanced', '').replace('_all', '') data_reader = DataReader( imdb_file, shuffle=False, one_pass=True, batch_size=cfg.TEST.BATCH_SIZE,", "answer_correct, num_questions), file=f) if cfg.TEST.OUTPUT_VQA_EVAL_PRED: with open(pred_file, 'w') as f:", "models_gqa.model import Model from models_gqa.config import build_cfg_from_argparse from util.gqa_train.data_reader import", "v in tf.global_variables()} snapshot_file = cfg.TEST.SNAPSHOT_FILE % (cfg.EXP_NAME, cfg.TEST.ITER) print('loading", "DataReader import json # Load config cfg = build_cfg_from_argparse() #", "(%d / %d)' % (cfg.EXP_NAME, cfg.TEST.ITER, cfg.TEST.SPLIT_VQA, accuracy, answer_correct, num_questions),", "batch_size=cfg.TEST.BATCH_SIZE, T_encoder=cfg.T_ENCODER, vocab_question_file=cfg.VOCAB_QUESTION_FILE, vocab_answer_file=cfg.VOCAB_ANSWER_FILE, feature_type=cfg.FEAT_TYPE, spatial_feature_dir=cfg.SPATIAL_FEATURE_DIR, objects_feature_dir=cfg.OBJECTS_FEATURE_DIR, objects_max_num=cfg.W_FEAT, scene_graph_file=scene_graph_file, vocab_name_file=cfg.VOCAB_NAME_FILE,", "seq_length_batch, image_feat_batch, image_valid_batch, num_vocab=num_vocab, num_choices=num_choices, is_training=False) # Load snapshot if", "qId, \"prediction\": answer_word_list[p]} for qId, p in zip(batch['qid_list'], vqa_predictions)]) with", "from %s' % snapshot_file) snapshot_saver = tf.train.Saver(var_names) snapshot_saver.restore(sess, snapshot_file) print('Done')", "labels provided)**\\n') vqa_scores_value = sess.run(model.vqa_scores, feed_dict={ input_seq_batch: batch['input_seq_batch'], seq_length_batch: batch['seq_length_batch'],", "file=f) if cfg.TEST.OUTPUT_VQA_EVAL_PRED: with open(pred_file, 'w') as f: json.dump(output_predictions, f,", "print('Done') # Write results result_dir = cfg.TEST.RESULT_DIR % (cfg.EXP_NAME, cfg.TEST.ITER)", "T_encoder=cfg.T_ENCODER, vocab_question_file=cfg.VOCAB_QUESTION_FILE, vocab_answer_file=cfg.VOCAB_ANSWER_FILE, feature_type=cfg.FEAT_TYPE, spatial_feature_dir=cfg.SPATIAL_FEATURE_DIR, objects_feature_dir=cfg.OBJECTS_FEATURE_DIR, objects_max_num=cfg.W_FEAT, scene_graph_file=scene_graph_file, vocab_name_file=cfg.VOCAB_NAME_FILE, vocab_attr_file=cfg.VOCAB_ATTR_FILE,", "cfg.W_FEAT, cfg.D_FEAT]) image_valid_batch = tf.placeholder( tf.float32, [None, cfg.H_FEAT, cfg.W_FEAT]) model", "if 'answer_label_batch' not in batch: batch['answer_label_batch'] = -np.ones( len(batch['qid_list']), np.int32)", "vocab_question_file=cfg.VOCAB_QUESTION_FILE, vocab_answer_file=cfg.VOCAB_ANSWER_FILE, feature_type=cfg.FEAT_TYPE, spatial_feature_dir=cfg.SPATIAL_FEATURE_DIR, objects_feature_dir=cfg.OBJECTS_FEATURE_DIR, objects_max_num=cfg.W_FEAT, scene_graph_file=scene_graph_file, vocab_name_file=cfg.VOCAB_NAME_FILE, vocab_attr_file=cfg.VOCAB_ATTR_FILE, spatial_pos_enc_dim=cfg.SPATIAL_POS_ENC_DIM,", "import build_cfg_from_argparse from util.gqa_train.data_reader import DataReader import json # Load", "iter = %d, accumulated accuracy on %s = %f (%d", "data_reader.batch_loader.vocab_dict.num_vocab num_choices = data_reader.batch_loader.answer_dict.num_vocab # Inputs and model input_seq_batch =", "config cfg = build_cfg_from_argparse() # Start session os.environ[\"CUDA_VISIBLE_DEVICES\"] = str(cfg.GPU_ID)", "cfg.SCENE_GRAPH_FILE % \\ cfg.TEST.SPLIT_VQA.replace('_balanced', '').replace('_all', '') data_reader = DataReader( imdb_file,", "snapshot_file) snapshot_saver = tf.train.Saver(var_names) snapshot_saver.restore(sess, snapshot_file) print('Done') # Write results", "np.int32) if num_questions == 0: print('imdb has no answer labels.", "Run test answer_correct, num_questions = 0, 0 if cfg.TEST.OUTPUT_VQA_EVAL_PRED: output_predictions", "image_feat_batch = tf.placeholder( tf.float32, [None, cfg.H_FEAT, cfg.W_FEAT, cfg.D_FEAT]) image_valid_batch =", "tf.placeholder( tf.float32, [None, cfg.H_FEAT, cfg.W_FEAT, cfg.D_FEAT]) image_valid_batch = tf.placeholder( tf.float32,", "answer_correct / num_questions if n_batch % 20 == 0: print('exp:", "n_batch, batch in enumerate(data_reader.batches()): if 'answer_label_batch' not in batch: batch['answer_label_batch']", "labels.\\n\\n' '**The final accuracy will be zero (no labels provided)**\\n')", "json.dump(output_predictions, f, indent=2) print('prediction file written to %s' % pred_file)", "vqa_scores_value = sess.run(model.vqa_scores, feed_dict={ input_seq_batch: batch['input_seq_batch'], seq_length_batch: batch['seq_length_batch'], image_feat_batch: batch['image_feat_batch'],", "num_questions += len(vqa_labels) accuracy = answer_correct / num_questions if n_batch", "session os.environ[\"CUDA_VISIBLE_DEVICES\"] = str(cfg.GPU_ID) sess = tf.Session(config=tf.ConfigProto( gpu_options=tf.GPUOptions(allow_growth=cfg.GPU_MEM_GROWTH))) # Data", "from models_gqa.config import build_cfg_from_argparse from util.gqa_train.data_reader import DataReader import json", "np.argmax(vqa_scores_value, axis=1) answer_correct += np.sum(vqa_predictions == vqa_labels) num_questions += len(vqa_labels)", "for n_batch, batch in enumerate(data_reader.batches()): if 'answer_label_batch' not in batch:", "tf.placeholder(tf.int32, [None, None]) seq_length_batch = tf.placeholder(tf.int32, [None]) image_feat_batch = tf.placeholder(", "(cfg.EXP_NAME, cfg.TEST.ITER) print('loading model snapshot from %s' % snapshot_file) snapshot_saver", "tf.Session(config=tf.ConfigProto( gpu_options=tf.GPUOptions(allow_growth=cfg.GPU_MEM_GROWTH))) # Data files imdb_file = cfg.IMDB_FILE % cfg.TEST.SPLIT_VQA", "= {v.op.name: v for v in tf.global_variables()} snapshot_file = cfg.TEST.SNAPSHOT_FILE", "% ( cfg.TEST.SPLIT_VQA, cfg.EXP_NAME, cfg.TEST.ITER)) for n_batch, batch in enumerate(data_reader.batches()):", "+= len(vqa_labels) accuracy = answer_correct / num_questions if n_batch %", "one_pass=True, batch_size=cfg.TEST.BATCH_SIZE, T_encoder=cfg.T_ENCODER, vocab_question_file=cfg.VOCAB_QUESTION_FILE, vocab_answer_file=cfg.VOCAB_ANSWER_FILE, feature_type=cfg.FEAT_TYPE, spatial_feature_dir=cfg.SPATIAL_FEATURE_DIR, objects_feature_dir=cfg.OBJECTS_FEATURE_DIR, objects_max_num=cfg.W_FEAT, scene_graph_file=scene_graph_file,", "0: print('imdb has no answer labels. Using dummy labels.\\n\\n' '**The", "= cfg.SCENE_GRAPH_FILE % \\ cfg.TEST.SPLIT_VQA.replace('_balanced', '').replace('_all', '') data_reader = DataReader(", "Inputs and model input_seq_batch = tf.placeholder(tf.int32, [None, None]) seq_length_batch =", "% (cfg.EXP_NAME, cfg.TEST.ITER, cfg.TEST.SPLIT_VQA, accuracy, answer_correct, num_questions), file=f) if cfg.TEST.OUTPUT_VQA_EVAL_PRED:", "cfg.TEST.SPLIT_VQA, accuracy, answer_correct, num_questions), file=f) if cfg.TEST.OUTPUT_VQA_EVAL_PRED: with open(pred_file, 'w')", "labels. Using dummy labels.\\n\\n' '**The final accuracy will be zero", "f: print('\\nexp: %s, iter = %d, final accuracy on %s", "answer_correct, num_questions)) if cfg.TEST.OUTPUT_VQA_EVAL_PRED: output_predictions.extend([ {\"questionId\": qId, \"prediction\": answer_word_list[p]} for", "= build_cfg_from_argparse() # Start session os.environ[\"CUDA_VISIBLE_DEVICES\"] = str(cfg.GPU_ID) sess =", "[None, None]) seq_length_batch = tf.placeholder(tf.int32, [None]) image_feat_batch = tf.placeholder( tf.float32,", "for qId, p in zip(batch['qid_list'], vqa_predictions)]) with open(os.path.join( result_dir, 'vqa_results_%s.txt'", "cfg.W_FEAT]) model = Model( input_seq_batch, seq_length_batch, image_feat_batch, image_valid_batch, num_vocab=num_vocab, num_choices=num_choices,", "snapshot_file) print('Done') # Write results result_dir = cfg.TEST.RESULT_DIR % (cfg.EXP_NAME,", "%d)' % (cfg.EXP_NAME, cfg.TEST.ITER, cfg.TEST.SPLIT_VQA, accuracy, answer_correct, num_questions), file=f) if", "var_names = {v.op.name: v for v in tf.global_variables()} snapshot_file =", "import DataReader import json # Load config cfg = build_cfg_from_argparse()", "else: var_names = {v.op.name: v for v in tf.global_variables()} snapshot_file", "print('\\nexp: %s, iter = %d, final accuracy on %s =", "cfg.TEST.ITER, cfg.TEST.SPLIT_VQA, accuracy, answer_correct, num_questions)) print('exp: %s, iter = %d,", "num_questions)) if cfg.TEST.OUTPUT_VQA_EVAL_PRED: output_predictions.extend([ {\"questionId\": qId, \"prediction\": answer_word_list[p]} for qId,", "cfg = build_cfg_from_argparse() # Start session os.environ[\"CUDA_VISIBLE_DEVICES\"] = str(cfg.GPU_ID) sess", "v for v in tf.global_variables()} snapshot_file = cfg.TEST.SNAPSHOT_FILE % (cfg.EXP_NAME,", "not in batch: batch['answer_label_batch'] = -np.ones( len(batch['qid_list']), np.int32) if num_questions", "(no labels provided)**\\n') vqa_scores_value = sess.run(model.vqa_scores, feed_dict={ input_seq_batch: batch['input_seq_batch'], seq_length_batch:", "[None, cfg.H_FEAT, cfg.W_FEAT, cfg.D_FEAT]) image_valid_batch = tf.placeholder( tf.float32, [None, cfg.H_FEAT,", "as np import tensorflow as tf from models_gqa.model import Model", "tf.placeholder(tf.int32, [None]) image_feat_batch = tf.placeholder( tf.float32, [None, cfg.H_FEAT, cfg.W_FEAT, cfg.D_FEAT])", "input_seq_batch = tf.placeholder(tf.int32, [None, None]) seq_length_batch = tf.placeholder(tf.int32, [None]) image_feat_batch", "{\"questionId\": qId, \"prediction\": answer_word_list[p]} for qId, p in zip(batch['qid_list'], vqa_predictions)])", "= [] answer_word_list = data_reader.batch_loader.answer_dict.word_list pred_file = os.path.join( result_dir, 'gqa_eval_preds_%s_%s_%08d.json'", "= cfg.IMDB_FILE % cfg.TEST.SPLIT_VQA scene_graph_file = cfg.SCENE_GRAPH_FILE % \\ cfg.TEST.SPLIT_VQA.replace('_balanced',", "scene_graph_file=scene_graph_file, vocab_name_file=cfg.VOCAB_NAME_FILE, vocab_attr_file=cfg.VOCAB_ATTR_FILE, spatial_pos_enc_dim=cfg.SPATIAL_POS_ENC_DIM, bbox_tile_num=cfg.BBOX_TILE_NUM) num_vocab = data_reader.batch_loader.vocab_dict.num_vocab num_choices =", "num_questions == 0: print('imdb has no answer labels. Using dummy", "print('exp: %s, iter = %d, final accuracy on %s =", "num_questions = 0, 0 if cfg.TEST.OUTPUT_VQA_EVAL_PRED: output_predictions = [] answer_word_list", "batch['image_feat_batch'], image_valid_batch: batch['image_valid_batch']}) # compute accuracy vqa_labels = batch['answer_label_batch'] vqa_predictions", "[] answer_word_list = data_reader.batch_loader.answer_dict.word_list pred_file = os.path.join( result_dir, 'gqa_eval_preds_%s_%s_%08d.json' %", "cfg.TEST.OUTPUT_VQA_EVAL_PRED: with open(pred_file, 'w') as f: json.dump(output_predictions, f, indent=2) print('prediction", "accuracy = answer_correct / num_questions if n_batch % 20 ==", "qId, p in zip(batch['qid_list'], vqa_predictions)]) with open(os.path.join( result_dir, 'vqa_results_%s.txt' %", "json # Load config cfg = build_cfg_from_argparse() # Start session", "= str(cfg.GPU_ID) sess = tf.Session(config=tf.ConfigProto( gpu_options=tf.GPUOptions(allow_growth=cfg.GPU_MEM_GROWTH))) # Data files imdb_file", "no answer labels. Using dummy labels.\\n\\n' '**The final accuracy will", "in enumerate(data_reader.batches()): if 'answer_label_batch' not in batch: batch['answer_label_batch'] = -np.ones(", "sess.run(model.vqa_scores, feed_dict={ input_seq_batch: batch['input_seq_batch'], seq_length_batch: batch['seq_length_batch'], image_feat_batch: batch['image_feat_batch'], image_valid_batch: batch['image_valid_batch']})", "DataReader( imdb_file, shuffle=False, one_pass=True, batch_size=cfg.TEST.BATCH_SIZE, T_encoder=cfg.T_ENCODER, vocab_question_file=cfg.VOCAB_QUESTION_FILE, vocab_answer_file=cfg.VOCAB_ANSWER_FILE, feature_type=cfg.FEAT_TYPE, spatial_feature_dir=cfg.SPATIAL_FEATURE_DIR,", "image_feat_batch, image_valid_batch, num_vocab=num_vocab, num_choices=num_choices, is_training=False) # Load snapshot if cfg.TEST.USE_EMA:", "result_dir, 'vqa_results_%s.txt' % cfg.TEST.SPLIT_VQA), 'w') as f: print('\\nexp: %s, iter", "cfg.TEST.ITER)) for n_batch, batch in enumerate(data_reader.batches()): if 'answer_label_batch' not in", "output_predictions.extend([ {\"questionId\": qId, \"prediction\": answer_word_list[p]} for qId, p in zip(batch['qid_list'],", "v for v in tf.global_variables()} else: var_names = {v.op.name: v", "cfg.TEST.USE_EMA: ema = tf.train.ExponentialMovingAverage(decay=0.9) # decay doesn't matter var_names =", "if cfg.TEST.OUTPUT_VQA_EVAL_PRED: output_predictions.extend([ {\"questionId\": qId, \"prediction\": answer_word_list[p]} for qId, p", "p in zip(batch['qid_list'], vqa_predictions)]) with open(os.path.join( result_dir, 'vqa_results_%s.txt' % cfg.TEST.SPLIT_VQA),", "np import tensorflow as tf from models_gqa.model import Model from", "cfg.TEST.SNAPSHOT_FILE % (cfg.EXP_NAME, cfg.TEST.ITER) print('loading model snapshot from %s' %" ]
[ "self.num_row_page = num_row_page def iterate(self, callback): for page_num in range(1,", "= last_row self.num_col_page = num_col_page def __iter__(self): self.cur_row = self.start_row", "last_col self.last_row = last_row self.num_col_page = num_col_page def __iter__(self): self.cur_row", "last_page_row_end self.num_col_page = num_col_page self.num_row_page = num_row_page def iterate(self, callback):", "1: last_col = self.num_col_page if self.num_pages > 1 else self.last_page_col_end", "num_row_page def iterate(self, callback): for page_num in range(1, self.num_pages +", "first_page_row_start, last_page_row_start, last_page_col_end, last_page_row_end, num_col_page=5, num_row_page=3): self.num_pages = num_pages self.first_page_col_start", "def __next__(self): position = (self.cur_row, self.cur_col) if self.cur_row > self.last_row", "self.num_col_page) return page class Page: def __init__(self, start_col, start_row, last_col,", "def iterate(self, callback): for page_num in range(1, self.num_pages + 1):", "= start_row self.last_col = last_col self.last_row = last_row self.num_col_page =", "= Page(1, self.last_page_row_start, self.last_page_col_end, self.last_page_row_end, self.num_col_page) else: page = Page(1,", "> 1 else self.last_page_col_end last_row = self.num_row_page if self.num_pages >", "else: page = Page(1, 1, self.num_col_page, self.num_row_page, self.num_col_page) return page", "start_col, start_row, last_col, last_row, num_col_page=5): self.start_col = start_col self.start_row =", "self.start_col return self def __next__(self): position = (self.cur_row, self.cur_col) if", "num_col_page self.num_row_page = num_row_page def iterate(self, callback): for page_num in", "num_pages self.first_page_col_start = first_page_col_start self.first_page_row_start = first_page_row_start self.last_page_row_start = last_page_row_start", "1 else self.last_page_col_end last_row = self.num_row_page if self.num_pages > 1", "1 self.cur_row += 1 else: self.cur_col += 1 return position", "self.last_page_row_end, self.num_col_page) else: page = Page(1, 1, self.num_col_page, self.num_row_page, self.num_col_page)", "def __init__(self, num_pages, first_page_col_start, first_page_row_start, last_page_row_start, last_page_col_end, last_page_row_end, num_col_page=5, num_row_page=3):", "for page_num in range(1, self.num_pages + 1): page = self.create_page(page_num)", "self.last_page_row_start = last_page_row_start self.last_page_col_end = last_page_col_end self.last_page_row_end = last_page_row_end self.num_col_page", "or (self.cur_col > self.last_col and self.cur_row == self.last_row): raise StopIteration", "self.last_row): raise StopIteration elif self.cur_col == self.num_col_page: self.cur_col = 1", "i) i += 1 def create_page(self, page_num): if page_num ==", "self.last_page_col_end, self.last_page_row_end, self.num_col_page) else: page = Page(1, 1, self.num_col_page, self.num_row_page,", "page = self.create_page(page_num) i = 0 for coord in page:", "i = 0 for coord in page: callback(coord, page_num, i)", "callback): for page_num in range(1, self.num_pages + 1): page =", "class Page: def __init__(self, start_col, start_row, last_col, last_row, num_col_page=5): self.start_col", "= (self.cur_row, self.cur_col) if self.cur_row > self.last_row or (self.cur_col >", "num_col_page=5, num_row_page=3): self.num_pages = num_pages self.first_page_col_start = first_page_col_start self.first_page_row_start =", "__iter__(self): self.cur_row = self.start_row self.cur_col = self.start_col return self def", "StopIteration elif self.cur_col == self.num_col_page: self.cur_col = 1 self.cur_row +=", "first_page_row_start self.last_page_row_start = last_page_row_start self.last_page_col_end = last_page_col_end self.last_page_row_end = last_page_row_end", "last_page_col_end self.last_page_row_end = last_page_row_end self.num_col_page = num_col_page self.num_row_page = num_row_page", "last_col, last_row, num_col_page=5): self.start_col = start_col self.start_row = start_row self.last_col", "num_row_page=3): self.num_pages = num_pages self.first_page_col_start = first_page_col_start self.first_page_row_start = first_page_row_start", "self.cur_col = 1 self.cur_row += 1 else: self.cur_col += 1", "page: callback(coord, page_num, i) i += 1 def create_page(self, page_num):", "Page(1, 1, self.num_col_page, self.num_row_page, self.num_col_page) return page class Page: def", "= self.start_col return self def __next__(self): position = (self.cur_row, self.cur_col)", "self.last_col and self.cur_row == self.last_row): raise StopIteration elif self.cur_col ==", "return self def __next__(self): position = (self.cur_row, self.cur_col) if self.cur_row", "page_num, i) i += 1 def create_page(self, page_num): if page_num", "self.num_row_page, self.num_col_page) return page class Page: def __init__(self, start_col, start_row,", "= num_pages self.first_page_col_start = first_page_col_start self.first_page_row_start = first_page_row_start self.last_page_row_start =", "self.num_col_page: self.cur_col = 1 self.cur_row += 1 else: self.cur_col +=", "last_row self.num_col_page = num_col_page def __iter__(self): self.cur_row = self.start_row self.cur_col", "== 1: last_col = self.num_col_page if self.num_pages > 1 else", "= last_page_row_end self.num_col_page = num_col_page self.num_row_page = num_row_page def iterate(self,", "page_num == 1: last_col = self.num_col_page if self.num_pages > 1", "page = Page(self.first_page_col_start, self.first_page_row_start, last_col, last_row, self.num_col_page) elif page_num ==", "= 0 for coord in page: callback(coord, page_num, i) i", "page = Page(1, 1, self.num_col_page, self.num_row_page, self.num_col_page) return page class", "elif self.cur_col == self.num_col_page: self.cur_col = 1 self.cur_row += 1", "if self.num_pages > 1 else self.last_page_col_end last_row = self.num_row_page if", "= Page(self.first_page_col_start, self.first_page_row_start, last_col, last_row, self.num_col_page) elif page_num == self.num_pages:", "first_page_col_start self.first_page_row_start = first_page_row_start self.last_page_row_start = last_page_row_start self.last_page_col_end = last_page_col_end", "Page(1, self.last_page_row_start, self.last_page_col_end, self.last_page_row_end, self.num_col_page) else: page = Page(1, 1,", "def create_page(self, page_num): if page_num == 1: last_col = self.num_col_page", "i += 1 def create_page(self, page_num): if page_num == 1:", "start_row self.last_col = last_col self.last_row = last_row self.num_col_page = num_col_page", "> self.last_col and self.cur_row == self.last_row): raise StopIteration elif self.cur_col", "self.num_row_page if self.num_pages > 1 else self.last_page_row_end page = Page(self.first_page_col_start,", "== self.num_col_page: self.cur_col = 1 self.cur_row += 1 else: self.cur_col", "self.last_col = last_col self.last_row = last_row self.num_col_page = num_col_page def", "__init__(self, num_pages, first_page_col_start, first_page_row_start, last_page_row_start, last_page_col_end, last_page_row_end, num_col_page=5, num_row_page=3): self.num_pages", "= num_col_page def __iter__(self): self.cur_row = self.start_row self.cur_col = self.start_col", "= self.start_row self.cur_col = self.start_col return self def __next__(self): position", "(self.cur_col > self.last_col and self.cur_row == self.last_row): raise StopIteration elif", "__init__(self, start_col, start_row, last_col, last_row, num_col_page=5): self.start_col = start_col self.start_row", "in page: callback(coord, page_num, i) i += 1 def create_page(self,", "self.num_col_page = num_col_page self.num_row_page = num_row_page def iterate(self, callback): for", "> self.last_row or (self.cur_col > self.last_col and self.cur_row == self.last_row):", "self.start_row self.cur_col = self.start_col return self def __next__(self): position =", "= num_col_page self.num_row_page = num_row_page def iterate(self, callback): for page_num", "= start_col self.start_row = start_row self.last_col = last_col self.last_row =", "callback(coord, page_num, i) i += 1 def create_page(self, page_num): if", "page_num): if page_num == 1: last_col = self.num_col_page if self.num_pages", "self.num_pages > 1 else self.last_page_col_end last_row = self.num_row_page if self.num_pages", "= last_page_col_end self.last_page_row_end = last_page_row_end self.num_col_page = num_col_page self.num_row_page =", "if page_num == 1: last_col = self.num_col_page if self.num_pages >", "def __iter__(self): self.cur_row = self.start_row self.cur_col = self.start_col return self", "== self.num_pages: page = Page(1, self.last_page_row_start, self.last_page_col_end, self.last_page_row_end, self.num_col_page) else:", "Page(self.first_page_col_start, self.first_page_row_start, last_col, last_row, self.num_col_page) elif page_num == self.num_pages: page", "self.first_page_col_start = first_page_col_start self.first_page_row_start = first_page_row_start self.last_page_row_start = last_page_row_start self.last_page_col_end", "+ 1): page = self.create_page(page_num) i = 0 for coord", "= num_row_page def iterate(self, callback): for page_num in range(1, self.num_pages", "self.first_page_row_start, last_col, last_row, self.num_col_page) elif page_num == self.num_pages: page =", "last_col = self.num_col_page if self.num_pages > 1 else self.last_page_col_end last_row", "self.num_col_page if self.num_pages > 1 else self.last_page_col_end last_row = self.num_row_page", "= self.num_row_page if self.num_pages > 1 else self.last_page_row_end page =", "self.num_col_page) else: page = Page(1, 1, self.num_col_page, self.num_row_page, self.num_col_page) return", "0 for coord in page: callback(coord, page_num, i) i +=", "self def __next__(self): position = (self.cur_row, self.cur_col) if self.cur_row >", "page_num in range(1, self.num_pages + 1): page = self.create_page(page_num) i", "1, self.num_col_page, self.num_row_page, self.num_col_page) return page class Page: def __init__(self,", "in range(1, self.num_pages + 1): page = self.create_page(page_num) i =", "(self.cur_row, self.cur_col) if self.cur_row > self.last_row or (self.cur_col > self.last_col", "elif page_num == self.num_pages: page = Page(1, self.last_page_row_start, self.last_page_col_end, self.last_page_row_end,", "create_page(self, page_num): if page_num == 1: last_col = self.num_col_page if", "1 else self.last_page_row_end page = Page(self.first_page_col_start, self.first_page_row_start, last_col, last_row, self.num_col_page)", "return page class Page: def __init__(self, start_col, start_row, last_col, last_row,", "self.last_row = last_row self.num_col_page = num_col_page def __iter__(self): self.cur_row =", "page = Page(1, self.last_page_row_start, self.last_page_col_end, self.last_page_row_end, self.num_col_page) else: page =", "self.num_pages > 1 else self.last_page_row_end page = Page(self.first_page_col_start, self.first_page_row_start, last_col,", "range(1, self.num_pages + 1): page = self.create_page(page_num) i = 0", "def __init__(self, start_col, start_row, last_col, last_row, num_col_page=5): self.start_col = start_col", "for coord in page: callback(coord, page_num, i) i += 1", "self.num_pages + 1): page = self.create_page(page_num) i = 0 for", "self.num_col_page, self.num_row_page, self.num_col_page) return page class Page: def __init__(self, start_col,", "self.last_page_col_end last_row = self.num_row_page if self.num_pages > 1 else self.last_page_row_end", "num_pages, first_page_col_start, first_page_row_start, last_page_row_start, last_page_col_end, last_page_row_end, num_col_page=5, num_row_page=3): self.num_pages =", "+= 1 def create_page(self, page_num): if page_num == 1: last_col", "self.cur_row > self.last_row or (self.cur_col > self.last_col and self.cur_row ==", "first_page_col_start, first_page_row_start, last_page_row_start, last_page_col_end, last_page_row_end, num_col_page=5, num_row_page=3): self.num_pages = num_pages", "raise StopIteration elif self.cur_col == self.num_col_page: self.cur_col = 1 self.cur_row", "= first_page_col_start self.first_page_row_start = first_page_row_start self.last_page_row_start = last_page_row_start self.last_page_col_end =", "self.last_page_row_end page = Page(self.first_page_col_start, self.first_page_row_start, last_col, last_row, self.num_col_page) elif page_num", "position = (self.cur_row, self.cur_col) if self.cur_row > self.last_row or (self.cur_col", "self.last_page_row_end = last_page_row_end self.num_col_page = num_col_page self.num_row_page = num_row_page def", "ArmorVisitor: def __init__(self, num_pages, first_page_col_start, first_page_row_start, last_page_row_start, last_page_col_end, last_page_row_end, num_col_page=5,", "last_row, num_col_page=5): self.start_col = start_col self.start_row = start_row self.last_col =", "else self.last_page_col_end last_row = self.num_row_page if self.num_pages > 1 else", "Page: def __init__(self, start_col, start_row, last_col, last_row, num_col_page=5): self.start_col =", "self.start_row = start_row self.last_col = last_col self.last_row = last_row self.num_col_page", "1): page = self.create_page(page_num) i = 0 for coord in", "= last_col self.last_row = last_row self.num_col_page = num_col_page def __iter__(self):", "self.num_pages = num_pages self.first_page_col_start = first_page_col_start self.first_page_row_start = first_page_row_start self.last_page_row_start", "self.last_row or (self.cur_col > self.last_col and self.cur_row == self.last_row): raise", "last_page_col_end, last_page_row_end, num_col_page=5, num_row_page=3): self.num_pages = num_pages self.first_page_col_start = first_page_col_start", "self.num_col_page = num_col_page def __iter__(self): self.cur_row = self.start_row self.cur_col =", "= self.create_page(page_num) i = 0 for coord in page: callback(coord,", "= last_page_row_start self.last_page_col_end = last_page_col_end self.last_page_row_end = last_page_row_end self.num_col_page =", "page_num == self.num_pages: page = Page(1, self.last_page_row_start, self.last_page_col_end, self.last_page_row_end, self.num_col_page)", "= Page(1, 1, self.num_col_page, self.num_row_page, self.num_col_page) return page class Page:", "num_col_page def __iter__(self): self.cur_row = self.start_row self.cur_col = self.start_col return", "last_page_row_start self.last_page_col_end = last_page_col_end self.last_page_row_end = last_page_row_end self.num_col_page = num_col_page", "self.last_page_row_start, self.last_page_col_end, self.last_page_row_end, self.num_col_page) else: page = Page(1, 1, self.num_col_page,", "= 1 self.cur_row += 1 else: self.cur_col += 1 return", "if self.num_pages > 1 else self.last_page_row_end page = Page(self.first_page_col_start, self.first_page_row_start,", "self.cur_row == self.last_row): raise StopIteration elif self.cur_col == self.num_col_page: self.cur_col", "self.start_col = start_col self.start_row = start_row self.last_col = last_col self.last_row", "<filename>extract_gear/armor_visitor.py class ArmorVisitor: def __init__(self, num_pages, first_page_col_start, first_page_row_start, last_page_row_start, last_page_col_end,", "num_col_page=5): self.start_col = start_col self.start_row = start_row self.last_col = last_col", "self.create_page(page_num) i = 0 for coord in page: callback(coord, page_num,", "self.num_pages: page = Page(1, self.last_page_row_start, self.last_page_col_end, self.last_page_row_end, self.num_col_page) else: page", "if self.cur_row > self.last_row or (self.cur_col > self.last_col and self.cur_row", "last_page_row_end, num_col_page=5, num_row_page=3): self.num_pages = num_pages self.first_page_col_start = first_page_col_start self.first_page_row_start", "start_col self.start_row = start_row self.last_col = last_col self.last_row = last_row", "last_col, last_row, self.num_col_page) elif page_num == self.num_pages: page = Page(1,", "self.num_col_page) elif page_num == self.num_pages: page = Page(1, self.last_page_row_start, self.last_page_col_end,", "class ArmorVisitor: def __init__(self, num_pages, first_page_col_start, first_page_row_start, last_page_row_start, last_page_col_end, last_page_row_end,", "1 def create_page(self, page_num): if page_num == 1: last_col =", "last_row, self.num_col_page) elif page_num == self.num_pages: page = Page(1, self.last_page_row_start,", "self.last_page_col_end = last_page_col_end self.last_page_row_end = last_page_row_end self.num_col_page = num_col_page self.num_row_page", "last_row = self.num_row_page if self.num_pages > 1 else self.last_page_row_end page", "self.cur_col) if self.cur_row > self.last_row or (self.cur_col > self.last_col and", "self.cur_row = self.start_row self.cur_col = self.start_col return self def __next__(self):", "self.first_page_row_start = first_page_row_start self.last_page_row_start = last_page_row_start self.last_page_col_end = last_page_col_end self.last_page_row_end", "iterate(self, callback): for page_num in range(1, self.num_pages + 1): page", "and self.cur_row == self.last_row): raise StopIteration elif self.cur_col == self.num_col_page:", "last_page_row_start, last_page_col_end, last_page_row_end, num_col_page=5, num_row_page=3): self.num_pages = num_pages self.first_page_col_start =", "else self.last_page_row_end page = Page(self.first_page_col_start, self.first_page_row_start, last_col, last_row, self.num_col_page) elif", "page class Page: def __init__(self, start_col, start_row, last_col, last_row, num_col_page=5):", "> 1 else self.last_page_row_end page = Page(self.first_page_col_start, self.first_page_row_start, last_col, last_row,", "self.cur_col = self.start_col return self def __next__(self): position = (self.cur_row,", "self.cur_col == self.num_col_page: self.cur_col = 1 self.cur_row += 1 else:", "= self.num_col_page if self.num_pages > 1 else self.last_page_col_end last_row =", "== self.last_row): raise StopIteration elif self.cur_col == self.num_col_page: self.cur_col =", "__next__(self): position = (self.cur_row, self.cur_col) if self.cur_row > self.last_row or", "coord in page: callback(coord, page_num, i) i += 1 def", "= first_page_row_start self.last_page_row_start = last_page_row_start self.last_page_col_end = last_page_col_end self.last_page_row_end =", "start_row, last_col, last_row, num_col_page=5): self.start_col = start_col self.start_row = start_row" ]
[ "\"https://www.domain.com/path?param1=param1#anchor\", ) == \"https://www.domain.com/path?param1=param1&a=123#anchor\" ) def test_add_to_query_string2(): assert ( url_utils.add_to_query_string(", "def test_add_to_query_string2(): assert ( url_utils.add_to_query_string( {\"param1\": 123}, \"https://www.domain.com/path?param1=param1#anchor\", ) ==", "<filename>gamla/url_utils_test.py from gamla import url_utils def test_add_to_query_string1(): assert ( url_utils.add_to_query_string(", "assert ( url_utils.add_to_query_string( {\"param1\": 123}, \"https://www.domain.com/path?param1=param1#anchor\", ) == \"https://www.domain.com/path?param1=123#anchor\" )", "( url_utils.add_to_query_string( {\"a\": 123}, \"https://www.domain.com/path?param1=param1#anchor\", ) == \"https://www.domain.com/path?param1=param1&a=123#anchor\" ) def", "import url_utils def test_add_to_query_string1(): assert ( url_utils.add_to_query_string( {\"a\": 123}, \"https://www.domain.com/path?param1=param1#anchor\",", "{\"a\": 123}, \"https://www.domain.com/path?param1=param1#anchor\", ) == \"https://www.domain.com/path?param1=param1&a=123#anchor\" ) def test_add_to_query_string2(): assert", "from gamla import url_utils def test_add_to_query_string1(): assert ( url_utils.add_to_query_string( {\"a\":", "gamla import url_utils def test_add_to_query_string1(): assert ( url_utils.add_to_query_string( {\"a\": 123},", "test_add_to_query_string1(): assert ( url_utils.add_to_query_string( {\"a\": 123}, \"https://www.domain.com/path?param1=param1#anchor\", ) == \"https://www.domain.com/path?param1=param1&a=123#anchor\"", "== \"https://www.domain.com/path?param1=param1&a=123#anchor\" ) def test_add_to_query_string2(): assert ( url_utils.add_to_query_string( {\"param1\": 123},", ") def test_add_to_query_string2(): assert ( url_utils.add_to_query_string( {\"param1\": 123}, \"https://www.domain.com/path?param1=param1#anchor\", )", "url_utils.add_to_query_string( {\"a\": 123}, \"https://www.domain.com/path?param1=param1#anchor\", ) == \"https://www.domain.com/path?param1=param1&a=123#anchor\" ) def test_add_to_query_string2():", "def test_add_to_query_string1(): assert ( url_utils.add_to_query_string( {\"a\": 123}, \"https://www.domain.com/path?param1=param1#anchor\", ) ==", "\"https://www.domain.com/path?param1=param1&a=123#anchor\" ) def test_add_to_query_string2(): assert ( url_utils.add_to_query_string( {\"param1\": 123}, \"https://www.domain.com/path?param1=param1#anchor\",", "123}, \"https://www.domain.com/path?param1=param1#anchor\", ) == \"https://www.domain.com/path?param1=param1&a=123#anchor\" ) def test_add_to_query_string2(): assert (", "url_utils def test_add_to_query_string1(): assert ( url_utils.add_to_query_string( {\"a\": 123}, \"https://www.domain.com/path?param1=param1#anchor\", )", ") == \"https://www.domain.com/path?param1=param1&a=123#anchor\" ) def test_add_to_query_string2(): assert ( url_utils.add_to_query_string( {\"param1\":", "test_add_to_query_string2(): assert ( url_utils.add_to_query_string( {\"param1\": 123}, \"https://www.domain.com/path?param1=param1#anchor\", ) == \"https://www.domain.com/path?param1=123#anchor\"", "assert ( url_utils.add_to_query_string( {\"a\": 123}, \"https://www.domain.com/path?param1=param1#anchor\", ) == \"https://www.domain.com/path?param1=param1&a=123#anchor\" )" ]
[ "# Feie # --- EDIT ------------------ # Make a grid", "object sec = roppy.linear_section(i0, i1, j0, j1, grd) # Read", "------------------ # Make a grid object f = Dataset(romsfile) grd", "points x0, y0 = grd.ll2xy(lon0, lat0) x1, y1 = grd.ll2xy(lon1,", "from netCDF4 import Dataset # Import development version of roppy", "to the section temp_sec = sec.sample3D(temp) # Compute mean temperature", "= sec.sample3D(temp) # Compute mean temperature along section # using", "print \"mean tempeature = \", np.sum(sec.Area * temp_sec) / np.sum(sec.Area)", "4.72, 60.75 # Feie # --- EDIT ------------------ # Make", "section temp_sec = sec.sample3D(temp) # Compute mean temperature along section", "roppy import sys sys.path = ['..'] + sys.path import roppy", "Find nearest rho-points i0, j0, i1, j1 = [int(round(v)) for", "version of roppy import sys sys.path = ['..'] + sys.path", "end points x0, y0 = grd.ll2xy(lon0, lat0) x1, y1 =", "np from netCDF4 import Dataset # Import development version of", "j0, j1, grd) # Read in a 3D temperature field", "Import development version of roppy import sys sys.path = ['..']", "lat0 = -0.67, 60.75 # Shetland lon1, lat1 = 4.72,", "a grid object f = Dataset(romsfile) grd = roppy.SGrid(f) #", "/ np.sum(sec.Area) # TODO: Make a mean method in the", "lon1, lat1 = 4.72, 60.75 # Feie # --- EDIT", "j0, i1, j1 = [int(round(v)) for v in x0, y0,", "# Get grid coordinates of end points x0, y0 =", "temperature field temp = f.variables['temp'][0,:,:,:] # Interpolate to the section", "roppy.SGrid(f) # Get grid coordinates of end points x0, y0", "development version of roppy import sys sys.path = ['..'] +", "sys.path = ['..'] + sys.path import roppy # --- EDIT", "Compute mean temperature along section # using trapezoidal integration print", "j1, grd) # Read in a 3D temperature field temp", "i1, j0, j1, grd) # Read in a 3D temperature", "import sys sys.path = ['..'] + sys.path import roppy #", "Interpolate to the section temp_sec = sec.sample3D(temp) # Compute mean", "temp_sec) / np.sum(sec.Area) # TODO: Make a mean method in", "in the Section class # Usage: sec.mean(temp_sec) # or even", "of end points x0, y0 = grd.ll2xy(lon0, lat0) x1, y1", "x0, y0 = grd.ll2xy(lon0, lat0) x1, y1 = grd.ll2xy(lon1, lat1)", "y0, x1, y1] # Make a Section object sec =", "roppy.linear_section(i0, i1, j0, j1, grd) # Read in a 3D", "class # Usage: sec.mean(temp_sec) # or even directly from 3D:", "--- EDIT ------------------ # Make a grid object f =", "grd) # Read in a 3D temperature field temp =", "using trapezoidal integration print \"mean tempeature = \", np.sum(sec.Area *", "i0, j0, i1, j1 = [int(round(v)) for v in x0,", "trapezoidal integration print \"mean tempeature = \", np.sum(sec.Area * temp_sec)", "mean temperature along section # using trapezoidal integration print \"mean", "# Make a grid object f = Dataset(romsfile) grd =", "romsfile = 'data/ocean_avg_example.nc' # Section definition lon0, lat0 = -0.67,", "= [int(round(v)) for v in x0, y0, x1, y1] #", "import Dataset # Import development version of roppy import sys", "in x0, y0, x1, y1] # Make a Section object", "a 3D temperature field temp = f.variables['temp'][0,:,:,:] # Interpolate to", "# Import development version of roppy import sys sys.path =", "Section object sec = roppy.linear_section(i0, i1, j0, j1, grd) #", "method in the Section class # Usage: sec.mean(temp_sec) # or", "Dataset # Import development version of roppy import sys sys.path", "EDIT ----------------- # ROMS file romsfile = 'data/ocean_avg_example.nc' # Section", "v in x0, y0, x1, y1] # Make a Section", "= grd.ll2xy(lon0, lat0) x1, y1 = grd.ll2xy(lon1, lat1) # Find", "= \", np.sum(sec.Area * temp_sec) / np.sum(sec.Area) # TODO: Make", "f.variables['temp'][0,:,:,:] # Interpolate to the section temp_sec = sec.sample3D(temp) #", "lat1 = 4.72, 60.75 # Feie # --- EDIT ------------------", "roppy # --- EDIT ----------------- # ROMS file romsfile =", "# Find nearest rho-points i0, j0, i1, j1 = [int(round(v))", "tempeature = \", np.sum(sec.Area * temp_sec) / np.sum(sec.Area) # TODO:", "the section temp_sec = sec.sample3D(temp) # Compute mean temperature along", "= ['..'] + sys.path import roppy # --- EDIT -----------------", "Feie # --- EDIT ------------------ # Make a grid object", "y1] # Make a Section object sec = roppy.linear_section(i0, i1,", "a Section object sec = roppy.linear_section(i0, i1, j0, j1, grd)", "'data/ocean_avg_example.nc' # Section definition lon0, lat0 = -0.67, 60.75 #", "a mean method in the Section class # Usage: sec.mean(temp_sec)", "along section # using trapezoidal integration print \"mean tempeature =", "sec = roppy.linear_section(i0, i1, j0, j1, grd) # Read in", "= 'data/ocean_avg_example.nc' # Section definition lon0, lat0 = -0.67, 60.75", "numpy as np from netCDF4 import Dataset # Import development", "lat1) # Find nearest rho-points i0, j0, i1, j1 =", "# Compute mean temperature along section # using trapezoidal integration", "--- EDIT ----------------- # ROMS file romsfile = 'data/ocean_avg_example.nc' #", "= 4.72, 60.75 # Feie # --- EDIT ------------------ #", "integration print \"mean tempeature = \", np.sum(sec.Area * temp_sec) /", "----------------- # ROMS file romsfile = 'data/ocean_avg_example.nc' # Section definition", "x1, y1 = grd.ll2xy(lon1, lat1) # Find nearest rho-points i0,", "* temp_sec) / np.sum(sec.Area) # TODO: Make a mean method", "rho-points i0, j0, i1, j1 = [int(round(v)) for v in", "sys.path import roppy # --- EDIT ----------------- # ROMS file", "# Shetland lon1, lat1 = 4.72, 60.75 # Feie #", "as np from netCDF4 import Dataset # Import development version", "field temp = f.variables['temp'][0,:,:,:] # Interpolate to the section temp_sec", "= Dataset(romsfile) grd = roppy.SGrid(f) # Get grid coordinates of", "grid coordinates of end points x0, y0 = grd.ll2xy(lon0, lat0)", "sec.sample3D(temp) # Compute mean temperature along section # using trapezoidal", "TODO: Make a mean method in the Section class #", "the Section class # Usage: sec.mean(temp_sec) # or even directly", "60.75 # Feie # --- EDIT ------------------ # Make a", "# Interpolate to the section temp_sec = sec.sample3D(temp) # Compute", "Get grid coordinates of end points x0, y0 = grd.ll2xy(lon0,", "Shetland lon1, lat1 = 4.72, 60.75 # Feie # ---", "temp_sec = sec.sample3D(temp) # Compute mean temperature along section #", "grid object f = Dataset(romsfile) grd = roppy.SGrid(f) # Get", "definition lon0, lat0 = -0.67, 60.75 # Shetland lon1, lat1", "60.75 # Shetland lon1, lat1 = 4.72, 60.75 # Feie", "temp = f.variables['temp'][0,:,:,:] # Interpolate to the section temp_sec =", "mean method in the Section class # Usage: sec.mean(temp_sec) #", "# Section definition lon0, lat0 = -0.67, 60.75 # Shetland", "object f = Dataset(romsfile) grd = roppy.SGrid(f) # Get grid", "# Read in a 3D temperature field temp = f.variables['temp'][0,:,:,:]", "import numpy as np from netCDF4 import Dataset # Import", "grd.ll2xy(lon1, lat1) # Find nearest rho-points i0, j0, i1, j1", "in a 3D temperature field temp = f.variables['temp'][0,:,:,:] # Interpolate", "lon0, lat0 = -0.67, 60.75 # Shetland lon1, lat1 =", "f = Dataset(romsfile) grd = roppy.SGrid(f) # Get grid coordinates", "file romsfile = 'data/ocean_avg_example.nc' # Section definition lon0, lat0 =", "of roppy import sys sys.path = ['..'] + sys.path import", "= grd.ll2xy(lon1, lat1) # Find nearest rho-points i0, j0, i1,", "grd.ll2xy(lon0, lat0) x1, y1 = grd.ll2xy(lon1, lat1) # Find nearest", "import roppy # --- EDIT ----------------- # ROMS file romsfile", "y1 = grd.ll2xy(lon1, lat1) # Find nearest rho-points i0, j0,", "x1, y1] # Make a Section object sec = roppy.linear_section(i0,", "# using trapezoidal integration print \"mean tempeature = \", np.sum(sec.Area", "= -0.67, 60.75 # Shetland lon1, lat1 = 4.72, 60.75", "\", np.sum(sec.Area * temp_sec) / np.sum(sec.Area) # TODO: Make a", "for v in x0, y0, x1, y1] # Make a", "= roppy.SGrid(f) # Get grid coordinates of end points x0,", "# --- EDIT ----------------- # ROMS file romsfile = 'data/ocean_avg_example.nc'", "# Usage: sec.mean(temp_sec) # or even directly from 3D: sec.mean(temp)", "Make a Section object sec = roppy.linear_section(i0, i1, j0, j1,", "[int(round(v)) for v in x0, y0, x1, y1] # Make", "section # using trapezoidal integration print \"mean tempeature = \",", "Make a mean method in the Section class # Usage:", "= roppy.linear_section(i0, i1, j0, j1, grd) # Read in a", "\"mean tempeature = \", np.sum(sec.Area * temp_sec) / np.sum(sec.Area) #", "-0.67, 60.75 # Shetland lon1, lat1 = 4.72, 60.75 #", "coordinates of end points x0, y0 = grd.ll2xy(lon0, lat0) x1,", "# TODO: Make a mean method in the Section class", "x0, y0, x1, y1] # Make a Section object sec", "= f.variables['temp'][0,:,:,:] # Interpolate to the section temp_sec = sec.sample3D(temp)", "['..'] + sys.path import roppy # --- EDIT ----------------- #", "netCDF4 import Dataset # Import development version of roppy import", "y0 = grd.ll2xy(lon0, lat0) x1, y1 = grd.ll2xy(lon1, lat1) #", "3D temperature field temp = f.variables['temp'][0,:,:,:] # Interpolate to the", "temperature along section # using trapezoidal integration print \"mean tempeature", "Dataset(romsfile) grd = roppy.SGrid(f) # Get grid coordinates of end", "lat0) x1, y1 = grd.ll2xy(lon1, lat1) # Find nearest rho-points", "# Make a Section object sec = roppy.linear_section(i0, i1, j0,", "nearest rho-points i0, j0, i1, j1 = [int(round(v)) for v", "np.sum(sec.Area) # TODO: Make a mean method in the Section", "ROMS file romsfile = 'data/ocean_avg_example.nc' # Section definition lon0, lat0", "i1, j1 = [int(round(v)) for v in x0, y0, x1,", "j1 = [int(round(v)) for v in x0, y0, x1, y1]", "np.sum(sec.Area * temp_sec) / np.sum(sec.Area) # TODO: Make a mean", "# ROMS file romsfile = 'data/ocean_avg_example.nc' # Section definition lon0,", "grd = roppy.SGrid(f) # Get grid coordinates of end points", "Make a grid object f = Dataset(romsfile) grd = roppy.SGrid(f)", "EDIT ------------------ # Make a grid object f = Dataset(romsfile)", "Read in a 3D temperature field temp = f.variables['temp'][0,:,:,:] #", "sys sys.path = ['..'] + sys.path import roppy # ---", "+ sys.path import roppy # --- EDIT ----------------- # ROMS", "Section definition lon0, lat0 = -0.67, 60.75 # Shetland lon1,", "Section class # Usage: sec.mean(temp_sec) # or even directly from", "# --- EDIT ------------------ # Make a grid object f" ]
[ "know your data file format: TypeError: TestFileReadability argument %Id: %V", "you get this error, ParaView doesn't know your data file", "import paraview.simple as pvs p = argparse.ArgumentParser() p.add_argument(\"fn\", help=\"data file", "data file format: TypeError: TestFileReadability argument %Id: %V \"\"\" from", "example of 3D scalar field If you get this error,", "field If you get this error, ParaView doesn't know your", "format: TypeError: TestFileReadability argument %Id: %V \"\"\" from pathlib import", "\"\"\" from pathlib import Path import argparse import paraview.simple as", "p.add_argument(\"fn\", help=\"data file to load with paraview OpenDataFile()\") P =", "argparse import paraview.simple as pvs p = argparse.ArgumentParser() p.add_argument(\"fn\", help=\"data", "of 3D scalar field If you get this error, ParaView", "doesn't know your data file format: TypeError: TestFileReadability argument %Id:", "= p.parse_args() fn = Path(P.fn).expanduser() if not fn.is_file(): raise FileNotFoundError(fn)", "as pvs p = argparse.ArgumentParser() p.add_argument(\"fn\", help=\"data file to load", "file format: TypeError: TestFileReadability argument %Id: %V \"\"\" from pathlib", "load with paraview OpenDataFile()\") P = p.parse_args() fn = Path(P.fn).expanduser()", "argparse.ArgumentParser() p.add_argument(\"fn\", help=\"data file to load with paraview OpenDataFile()\") P", "from pathlib import Path import argparse import paraview.simple as pvs", "%V \"\"\" from pathlib import Path import argparse import paraview.simple", "help=\"data file to load with paraview OpenDataFile()\") P = p.parse_args()", "TestFileReadability argument %Id: %V \"\"\" from pathlib import Path import", "argument %Id: %V \"\"\" from pathlib import Path import argparse", "%Id: %V \"\"\" from pathlib import Path import argparse import", "scalar field If you get this error, ParaView doesn't know", "3D scalar field If you get this error, ParaView doesn't", "this error, ParaView doesn't know your data file format: TypeError:", "pvs p = argparse.ArgumentParser() p.add_argument(\"fn\", help=\"data file to load with", "to load with paraview OpenDataFile()\") P = p.parse_args() fn =", "#!/usr/bin/env python3 \"\"\" example of 3D scalar field If you", "error, ParaView doesn't know your data file format: TypeError: TestFileReadability", "get this error, ParaView doesn't know your data file format:", "p = argparse.ArgumentParser() p.add_argument(\"fn\", help=\"data file to load with paraview", "file to load with paraview OpenDataFile()\") P = p.parse_args() fn", "import Path import argparse import paraview.simple as pvs p =", "= argparse.ArgumentParser() p.add_argument(\"fn\", help=\"data file to load with paraview OpenDataFile()\")", "P = p.parse_args() fn = Path(P.fn).expanduser() if not fn.is_file(): raise", "paraview OpenDataFile()\") P = p.parse_args() fn = Path(P.fn).expanduser() if not", "If you get this error, ParaView doesn't know your data", "Path import argparse import paraview.simple as pvs p = argparse.ArgumentParser()", "TypeError: TestFileReadability argument %Id: %V \"\"\" from pathlib import Path", "with paraview OpenDataFile()\") P = p.parse_args() fn = Path(P.fn).expanduser() if", "python3 \"\"\" example of 3D scalar field If you get", "p.parse_args() fn = Path(P.fn).expanduser() if not fn.is_file(): raise FileNotFoundError(fn) pvs.OpenDataFile(str(fn))", "OpenDataFile()\") P = p.parse_args() fn = Path(P.fn).expanduser() if not fn.is_file():", "your data file format: TypeError: TestFileReadability argument %Id: %V \"\"\"", "pathlib import Path import argparse import paraview.simple as pvs p", "import argparse import paraview.simple as pvs p = argparse.ArgumentParser() p.add_argument(\"fn\",", "\"\"\" example of 3D scalar field If you get this", "ParaView doesn't know your data file format: TypeError: TestFileReadability argument", "paraview.simple as pvs p = argparse.ArgumentParser() p.add_argument(\"fn\", help=\"data file to" ]
[ "for creating and modifying language objects \"\"\" class Meta: model", "from django import forms from ...models import Language class LanguageForm(forms.ModelForm):", "and modifying language objects \"\"\" class Meta: model = Language", "...models import Language class LanguageForm(forms.ModelForm): \"\"\" Form for creating and", "django import forms from ...models import Language class LanguageForm(forms.ModelForm): \"\"\"", "modifying language objects \"\"\" class Meta: model = Language fields", "Language class LanguageForm(forms.ModelForm): \"\"\" Form for creating and modifying language", "import Language class LanguageForm(forms.ModelForm): \"\"\" Form for creating and modifying", "LanguageForm(forms.ModelForm): \"\"\" Form for creating and modifying language objects \"\"\"", "\"\"\" class Meta: model = Language fields = [ \"code\",", "<filename>src/cms/forms/languages/language_form.py from django import forms from ...models import Language class", "forms from ...models import Language class LanguageForm(forms.ModelForm): \"\"\" Form for", "= Language fields = [ \"code\", \"english_name\", \"native_name\", \"text_direction\", ]", "model = Language fields = [ \"code\", \"english_name\", \"native_name\", \"text_direction\",", "\"\"\" Form for creating and modifying language objects \"\"\" class", "Form for creating and modifying language objects \"\"\" class Meta:", "language objects \"\"\" class Meta: model = Language fields =", "Meta: model = Language fields = [ \"code\", \"english_name\", \"native_name\",", "from ...models import Language class LanguageForm(forms.ModelForm): \"\"\" Form for creating", "objects \"\"\" class Meta: model = Language fields = [", "import forms from ...models import Language class LanguageForm(forms.ModelForm): \"\"\" Form", "class Meta: model = Language fields = [ \"code\", \"english_name\",", "class LanguageForm(forms.ModelForm): \"\"\" Form for creating and modifying language objects", "creating and modifying language objects \"\"\" class Meta: model =" ]
[ "in skip_fields: add = (f.name,f.name,) search_fields.append(add) search_field = ChoiceFieldNoValidation(choices=sorted(search_fields)) and_or", "skip_fields = [ 'id', 'machine_group', 'report', 'activity', 'errors', 'warnings', 'install_log',", "class ChoiceFieldNoValidation(forms.ChoiceField): def validate(self, value): pass class SaveSearchForm(forms.ModelForm): class Meta:", ".models import * from server.models import * class ChoiceFieldNoValidation(forms.ChoiceField): def", "search_group_count == 0 and self.search_group: self.fields['and_or'] = ChoiceFieldNoValidation( initial='AND', widget=forms.HiddenInput()", "from server.models import * class ChoiceFieldNoValidation(forms.ChoiceField): def validate(self, value): pass", "'id', 'machine_group', 'report', 'activity', 'errors', 'warnings', 'install_log', 'puppet_errors', 'install_log_hash' ]", "from django import forms from .models import * from server.models", "ChoiceFieldNoValidation( initial='AND', widget=forms.HiddenInput() ) class Meta: model = SearchRow fields", "SearchRowForm(forms.ModelForm): skip_fields = [ 'id', 'machine_group', 'report', 'activity', 'errors', 'warnings',", "if search_group_count == 0 and self.search_group: self.fields['and_or'] = ChoiceFieldNoValidation( initial='AND',", "value): pass class SaveSearchForm(forms.ModelForm): class Meta: model = SavedSearch fields", "'install_log_hash' ] search_fields = [] for f in Machine._meta.fields: if", "self.search_group = kwargs.pop('search_group', None) super(SearchRowForm, self).__init__(*args, **kwargs) try: search_group_count =", "try: search_group_count = self.search_group.searchrow_set.count() except: search_group_count = 0 if search_group_count", "class Meta: model = SavedSearch fields = ('name',) class SearchRowForm(forms.ModelForm):", "None) super(SearchRowForm, self).__init__(*args, **kwargs) try: search_group_count = self.search_group.searchrow_set.count() except: search_group_count", "= SavedSearch fields = ('name',) class SearchRowForm(forms.ModelForm): skip_fields = [", "'warnings', 'install_log', 'puppet_errors', 'install_log_hash' ] search_fields = [] for f", "* from server.models import * class ChoiceFieldNoValidation(forms.ChoiceField): def validate(self, value):", "search_group_count = 0 if search_group_count == 0 and self.search_group: self.fields['and_or']", "not in skip_fields: add = (f.name,f.name,) search_fields.append(add) search_field = ChoiceFieldNoValidation(choices=sorted(search_fields))", "[ 'id', 'machine_group', 'report', 'activity', 'errors', 'warnings', 'install_log', 'puppet_errors', 'install_log_hash'", "class SearchRowForm(forms.ModelForm): skip_fields = [ 'id', 'machine_group', 'report', 'activity', 'errors',", "def __init__(self, *args, **kwargs): self.search_group = kwargs.pop('search_group', None) super(SearchRowForm, self).__init__(*args,", "Meta: model = SearchRow fields = ('search_models', 'search_field', 'and_or', 'operator','search_term',)", "= 0 if search_group_count == 0 and self.search_group: self.fields['and_or'] =", "self).__init__(*args, **kwargs) try: search_group_count = self.search_group.searchrow_set.count() except: search_group_count = 0", "def validate(self, value): pass class SaveSearchForm(forms.ModelForm): class Meta: model =", "from .models import * from server.models import * class ChoiceFieldNoValidation(forms.ChoiceField):", "'puppet_errors', 'install_log_hash' ] search_fields = [] for f in Machine._meta.fields:", "'errors', 'warnings', 'install_log', 'puppet_errors', 'install_log_hash' ] search_fields = [] for", "skip_fields: add = (f.name,f.name,) search_fields.append(add) search_field = ChoiceFieldNoValidation(choices=sorted(search_fields)) and_or =", "'machine_group', 'report', 'activity', 'errors', 'warnings', 'install_log', 'puppet_errors', 'install_log_hash' ] search_fields", "in Machine._meta.fields: if f.name not in skip_fields: add = (f.name,f.name,)", "(f.name,f.name,) search_fields.append(add) search_field = ChoiceFieldNoValidation(choices=sorted(search_fields)) and_or = ChoiceFieldNoValidation(choices=AND_OR_CHOICES) def __init__(self,", "search_fields.append(add) search_field = ChoiceFieldNoValidation(choices=sorted(search_fields)) and_or = ChoiceFieldNoValidation(choices=AND_OR_CHOICES) def __init__(self, *args,", "pass class SaveSearchForm(forms.ModelForm): class Meta: model = SavedSearch fields =", "self.search_group.searchrow_set.count() except: search_group_count = 0 if search_group_count == 0 and", "add = (f.name,f.name,) search_fields.append(add) search_field = ChoiceFieldNoValidation(choices=sorted(search_fields)) and_or = ChoiceFieldNoValidation(choices=AND_OR_CHOICES)", "**kwargs): self.search_group = kwargs.pop('search_group', None) super(SearchRowForm, self).__init__(*args, **kwargs) try: search_group_count", "SaveSearchForm(forms.ModelForm): class Meta: model = SavedSearch fields = ('name',) class", "== 0 and self.search_group: self.fields['and_or'] = ChoiceFieldNoValidation( initial='AND', widget=forms.HiddenInput() )", "f.name not in skip_fields: add = (f.name,f.name,) search_fields.append(add) search_field =", "self.search_group: self.fields['and_or'] = ChoiceFieldNoValidation( initial='AND', widget=forms.HiddenInput() ) class Meta: model", "[] for f in Machine._meta.fields: if f.name not in skip_fields:", "and self.search_group: self.fields['and_or'] = ChoiceFieldNoValidation( initial='AND', widget=forms.HiddenInput() ) class Meta:", "validate(self, value): pass class SaveSearchForm(forms.ModelForm): class Meta: model = SavedSearch", "super(SearchRowForm, self).__init__(*args, **kwargs) try: search_group_count = self.search_group.searchrow_set.count() except: search_group_count =", "= ChoiceFieldNoValidation(choices=sorted(search_fields)) and_or = ChoiceFieldNoValidation(choices=AND_OR_CHOICES) def __init__(self, *args, **kwargs): self.search_group", "__init__(self, *args, **kwargs): self.search_group = kwargs.pop('search_group', None) super(SearchRowForm, self).__init__(*args, **kwargs)", "* class ChoiceFieldNoValidation(forms.ChoiceField): def validate(self, value): pass class SaveSearchForm(forms.ModelForm): class", "initial='AND', widget=forms.HiddenInput() ) class Meta: model = SearchRow fields =", "] search_fields = [] for f in Machine._meta.fields: if f.name", "0 if search_group_count == 0 and self.search_group: self.fields['and_or'] = ChoiceFieldNoValidation(", "import * class ChoiceFieldNoValidation(forms.ChoiceField): def validate(self, value): pass class SaveSearchForm(forms.ModelForm):", "forms from .models import * from server.models import * class", "if f.name not in skip_fields: add = (f.name,f.name,) search_fields.append(add) search_field", "'install_log', 'puppet_errors', 'install_log_hash' ] search_fields = [] for f in", "= [ 'id', 'machine_group', 'report', 'activity', 'errors', 'warnings', 'install_log', 'puppet_errors',", "ChoiceFieldNoValidation(forms.ChoiceField): def validate(self, value): pass class SaveSearchForm(forms.ModelForm): class Meta: model", "0 and self.search_group: self.fields['and_or'] = ChoiceFieldNoValidation( initial='AND', widget=forms.HiddenInput() ) class", "class SaveSearchForm(forms.ModelForm): class Meta: model = SavedSearch fields = ('name',)", "= ('name',) class SearchRowForm(forms.ModelForm): skip_fields = [ 'id', 'machine_group', 'report',", "= [] for f in Machine._meta.fields: if f.name not in", ") class Meta: model = SearchRow fields = ('search_models', 'search_field',", "ChoiceFieldNoValidation(choices=sorted(search_fields)) and_or = ChoiceFieldNoValidation(choices=AND_OR_CHOICES) def __init__(self, *args, **kwargs): self.search_group =", "kwargs.pop('search_group', None) super(SearchRowForm, self).__init__(*args, **kwargs) try: search_group_count = self.search_group.searchrow_set.count() except:", "import * from server.models import * class ChoiceFieldNoValidation(forms.ChoiceField): def validate(self,", "**kwargs) try: search_group_count = self.search_group.searchrow_set.count() except: search_group_count = 0 if", "except: search_group_count = 0 if search_group_count == 0 and self.search_group:", "Meta: model = SavedSearch fields = ('name',) class SearchRowForm(forms.ModelForm): skip_fields", "Machine._meta.fields: if f.name not in skip_fields: add = (f.name,f.name,) search_fields.append(add)", "search_group_count = self.search_group.searchrow_set.count() except: search_group_count = 0 if search_group_count ==", "= kwargs.pop('search_group', None) super(SearchRowForm, self).__init__(*args, **kwargs) try: search_group_count = self.search_group.searchrow_set.count()", "f in Machine._meta.fields: if f.name not in skip_fields: add =", "SavedSearch fields = ('name',) class SearchRowForm(forms.ModelForm): skip_fields = [ 'id',", "'activity', 'errors', 'warnings', 'install_log', 'puppet_errors', 'install_log_hash' ] search_fields = []", "('name',) class SearchRowForm(forms.ModelForm): skip_fields = [ 'id', 'machine_group', 'report', 'activity',", "search_field = ChoiceFieldNoValidation(choices=sorted(search_fields)) and_or = ChoiceFieldNoValidation(choices=AND_OR_CHOICES) def __init__(self, *args, **kwargs):", "*args, **kwargs): self.search_group = kwargs.pop('search_group', None) super(SearchRowForm, self).__init__(*args, **kwargs) try:", "= ChoiceFieldNoValidation( initial='AND', widget=forms.HiddenInput() ) class Meta: model = SearchRow", "server.models import * class ChoiceFieldNoValidation(forms.ChoiceField): def validate(self, value): pass class", "'report', 'activity', 'errors', 'warnings', 'install_log', 'puppet_errors', 'install_log_hash' ] search_fields =", "model = SavedSearch fields = ('name',) class SearchRowForm(forms.ModelForm): skip_fields =", "import forms from .models import * from server.models import *", "django import forms from .models import * from server.models import", "fields = ('name',) class SearchRowForm(forms.ModelForm): skip_fields = [ 'id', 'machine_group',", "self.fields['and_or'] = ChoiceFieldNoValidation( initial='AND', widget=forms.HiddenInput() ) class Meta: model =", "class Meta: model = SearchRow fields = ('search_models', 'search_field', 'and_or',", "= (f.name,f.name,) search_fields.append(add) search_field = ChoiceFieldNoValidation(choices=sorted(search_fields)) and_or = ChoiceFieldNoValidation(choices=AND_OR_CHOICES) def", "search_fields = [] for f in Machine._meta.fields: if f.name not", "and_or = ChoiceFieldNoValidation(choices=AND_OR_CHOICES) def __init__(self, *args, **kwargs): self.search_group = kwargs.pop('search_group',", "for f in Machine._meta.fields: if f.name not in skip_fields: add", "widget=forms.HiddenInput() ) class Meta: model = SearchRow fields = ('search_models',", "= self.search_group.searchrow_set.count() except: search_group_count = 0 if search_group_count == 0", "ChoiceFieldNoValidation(choices=AND_OR_CHOICES) def __init__(self, *args, **kwargs): self.search_group = kwargs.pop('search_group', None) super(SearchRowForm,", "= ChoiceFieldNoValidation(choices=AND_OR_CHOICES) def __init__(self, *args, **kwargs): self.search_group = kwargs.pop('search_group', None)" ]
[ "#for para in paras: # print(para.text) def get_body(self) -> list:", "for img in imgs: try: if \"blank_white_space\" not in img.img['src']:", "in imgs: # print(img['src']) paras = self.soup.find_all('div', {\"class\" : \"ssrcss-17j9f6r-RichTextContainer", "print(para.text) return [p.text for p in paras] #return [p.text for", "self.title = self.get_title() self.author = self.get_author() self.images = self.get_images() self.date", "pass return imgs_lst def get_date(self) -> str: date = self.soup.find_all('time')[0]", "for p in paras] #return [p.text for p in body.find_all(\"p\")]", "__init__(self, url:str): article = requests.get(url) self.soup = bs(article.content, \"html.parser\") #print(dir(self.soup))", "-> str: #return self.soup.find(class_=\"story-body__h1\").text return self.soup.h1.text def get_author(self) -> str:", "parsed = BBC(\"https://www.bbc.co.uk/news/world-europe-49345912\") #print(parsed.title) #print(parsed.link) #print(parsed.author) #print(parsed.date) #print(parsed.title) #print(parsed.body) #print(parsed.images)", "#for img in imgs: # print(img['src']) paras = self.soup.find_all('div', {\"class\"", "[p.text for p in body.find_all(\"p\")] def get_title(self) -> str: #return", "in imgs: try: if \"blank_white_space\" not in img.img['src']: imgs_lst.append(img.img['src'])#['div']['span']['span']['img']) except:", "return [p.text for p in paras] #return [p.text for p", "requests class BBC: def __init__(self, url:str): article = requests.get(url) self.soup", "imgs = self.soup.find_all('figure', {'class' : 'ssrcss-wpgbih-StyledFigure e34k3c23'}) imgs_lst = []", "url self.title = self.get_title() self.author = self.get_author() self.images = self.get_images()", "imgs_lst def get_date(self) -> str: date = self.soup.find_all('time')[0] return date['datetime']", "url:str): article = requests.get(url) self.soup = bs(article.content, \"html.parser\") #print(dir(self.soup)) #print(self.soup.h1.text)", "def get_author(self) -> str: author = self.soup.find('p', {'class' : 'ssrcss-1rv0moy-Contributor", "\"blank_white_space\" not in img.img['src']: imgs_lst.append(img.img['src'])#['div']['span']['span']['img']) except: pass return imgs_lst def", "print(para.text) def get_body(self) -> list: #body = self.soup.find(property=\"articleBody\") paras =", "img.img['src']: imgs_lst.append(img.img['src'])#['div']['span']['span']['img']) except: pass return imgs_lst def get_date(self) -> str:", "return imgs_lst def get_date(self) -> str: date = self.soup.find_all('time')[0] return", "#return self.soup.find(class_=\"story-body__h1\").text return self.soup.h1.text def get_author(self) -> str: author =", "import requests class BBC: def __init__(self, url:str): article = requests.get(url)", "paras = self.soup.find_all('div', {\"class\" : \"ssrcss-17j9f6r-RichTextContainer e5tfeyi1\"}) #for para in", "return date['datetime'] parsed = BBC(\"https://www.bbc.co.uk/news/world-europe-49345912\") #print(parsed.title) #print(parsed.link) #print(parsed.author) #print(parsed.date) #print(parsed.title)", "imgs_lst = [] for img in imgs: try: if \"blank_white_space\"", "in body.find_all(\"p\")] def get_title(self) -> str: #return self.soup.find(class_=\"story-body__h1\").text return self.soup.h1.text", "-> str: author = self.soup.find('p', {'class' : 'ssrcss-1rv0moy-Contributor e5xb54n2'}) return", "str: #return self.soup.find(class_=\"story-body__h1\").text return self.soup.h1.text def get_author(self) -> str: author", "body.find_all(\"p\")] def get_title(self) -> str: #return self.soup.find(class_=\"story-body__h1\").text return self.soup.h1.text def", "self.soup.h1.text def get_author(self) -> str: author = self.soup.find('p', {'class' :", "= bs(article.content, \"html.parser\") #print(dir(self.soup)) #print(self.soup.h1.text) self.body = self.get_body() self.link =", ": \"ssrcss-17j9f6r-RichTextContainer e5tfeyi1\"}) #for para in paras: # print(para.text) def", "# print(para.text) def get_body(self) -> list: #body = self.soup.find(property=\"articleBody\") paras", "self.soup = bs(article.content, \"html.parser\") #print(dir(self.soup)) #print(self.soup.h1.text) self.body = self.get_body() self.link", "in paras: # print(para.text) return [p.text for p in paras]", "BBC: def __init__(self, url:str): article = requests.get(url) self.soup = bs(article.content,", "list: #body = self.soup.find(property=\"articleBody\") paras = self.soup.find_all('div', {\"class\" : \"ssrcss-17j9f6r-RichTextContainer", "= self.soup.find_all('figure', {'class' : 'ssrcss-wpgbih-StyledFigure e34k3c23'}) imgs_lst = [] for", ": 'ssrcss-wpgbih-StyledFigure e34k3c23'}) imgs_lst = [] for img in imgs:", "'ssrcss-1rv0moy-Contributor e5xb54n2'}) return author.text.replace(\"BBC News\", \"\") def get_images(self) -> list:", "get_body(self) -> list: #body = self.soup.find(property=\"articleBody\") paras = self.soup.find_all('div', {\"class\"", "#print(self.soup.h1.text) self.body = self.get_body() self.link = url self.title = self.get_title()", "= self.get_author() self.images = self.get_images() self.date = self.get_date() #author =", ": \"ssrcss-17j9f6r-RichTextContainer e5tfeyi1\"}) #for para in paras: # print(para.text) return", "in paras] #return [p.text for p in body.find_all(\"p\")] def get_title(self)", "paras] #return [p.text for p in body.find_all(\"p\")] def get_title(self) ->", "e5xb54n2'}) return author.text.replace(\"BBC News\", \"\") def get_images(self) -> list: imgs", "= self.get_images() self.date = self.get_date() #author = self.soup.find #date =", "bs4 import BeautifulSoup as bs import requests class BBC: def", "author.text.replace(\"BBC News\", \"\") def get_images(self) -> list: imgs = self.soup.find_all('figure',", "self.author = self.get_author() self.images = self.get_images() self.date = self.get_date() #author", "date['datetime'] parsed = BBC(\"https://www.bbc.co.uk/news/world-europe-49345912\") #print(parsed.title) #print(parsed.link) #print(parsed.author) #print(parsed.date) #print(parsed.title) #print(parsed.body)", "bs(article.content, \"html.parser\") #print(dir(self.soup)) #print(self.soup.h1.text) self.body = self.get_body() self.link = url", "def get_body(self) -> list: #body = self.soup.find(property=\"articleBody\") paras = self.soup.find_all('div',", "imgs_lst.append(img.img['src'])#['div']['span']['span']['img']) except: pass return imgs_lst def get_date(self) -> str: date", "-> str: date = self.soup.find_all('time')[0] return date['datetime'] parsed = BBC(\"https://www.bbc.co.uk/news/world-europe-49345912\")", "self.get_title() self.author = self.get_author() self.images = self.get_images() self.date = self.get_date()", "paras: # print(para.text) return [p.text for p in paras] #return", "if \"blank_white_space\" not in img.img['src']: imgs_lst.append(img.img['src'])#['div']['span']['span']['img']) except: pass return imgs_lst", "class BBC: def __init__(self, url:str): article = requests.get(url) self.soup =", "{'class' : 'ssrcss-wpgbih-StyledFigure e34k3c23'}) imgs_lst = [] for img in", "= requests.get(url) self.soup = bs(article.content, \"html.parser\") #print(dir(self.soup)) #print(self.soup.h1.text) self.body =", "'ssrcss-wpgbih-StyledFigure e34k3c23'}) imgs_lst = [] for img in imgs: try:", "#author = self.soup.find #date = self.soup #for img in imgs:", "self.soup #for img in imgs: # print(img['src']) paras = self.soup.find_all('div',", "= [] for img in imgs: try: if \"blank_white_space\" not", "<reponame>antoreep-jana/BBC-News-Analyzer from bs4 import BeautifulSoup as bs import requests class", "get_title(self) -> str: #return self.soup.find(class_=\"story-body__h1\").text return self.soup.h1.text def get_author(self) ->", "for p in body.find_all(\"p\")] def get_title(self) -> str: #return self.soup.find(class_=\"story-body__h1\").text", "p in body.find_all(\"p\")] def get_title(self) -> str: #return self.soup.find(class_=\"story-body__h1\").text return", "def get_date(self) -> str: date = self.soup.find_all('time')[0] return date['datetime'] parsed", "#body = self.soup.find(property=\"articleBody\") paras = self.soup.find_all('div', {\"class\" : \"ssrcss-17j9f6r-RichTextContainer e5tfeyi1\"})", "imgs: # print(img['src']) paras = self.soup.find_all('div', {\"class\" : \"ssrcss-17j9f6r-RichTextContainer e5tfeyi1\"})", "get_author(self) -> str: author = self.soup.find('p', {'class' : 'ssrcss-1rv0moy-Contributor e5xb54n2'})", "\"html.parser\") #print(dir(self.soup)) #print(self.soup.h1.text) self.body = self.get_body() self.link = url self.title", "self.get_date() #author = self.soup.find #date = self.soup #for img in", "def get_title(self) -> str: #return self.soup.find(class_=\"story-body__h1\").text return self.soup.h1.text def get_author(self)", "e34k3c23'}) imgs_lst = [] for img in imgs: try: if", "News\", \"\") def get_images(self) -> list: imgs = self.soup.find_all('figure', {'class'", "img in imgs: # print(img['src']) paras = self.soup.find_all('div', {\"class\" :", "author = self.soup.find('p', {'class' : 'ssrcss-1rv0moy-Contributor e5xb54n2'}) return author.text.replace(\"BBC News\",", "bs import requests class BBC: def __init__(self, url:str): article =", "#for para in paras: # print(para.text) return [p.text for p", "imgs: try: if \"blank_white_space\" not in img.img['src']: imgs_lst.append(img.img['src'])#['div']['span']['span']['img']) except: pass", "from bs4 import BeautifulSoup as bs import requests class BBC:", "-> list: imgs = self.soup.find_all('figure', {'class' : 'ssrcss-wpgbih-StyledFigure e34k3c23'}) imgs_lst", "self.get_author() self.images = self.get_images() self.date = self.get_date() #author = self.soup.find", "= url self.title = self.get_title() self.author = self.get_author() self.images =", "BeautifulSoup as bs import requests class BBC: def __init__(self, url:str):", "self.images = self.get_images() self.date = self.get_date() #author = self.soup.find #date", "self.get_body() self.link = url self.title = self.get_title() self.author = self.get_author()", "= self.soup.find_all('time')[0] return date['datetime'] parsed = BBC(\"https://www.bbc.co.uk/news/world-europe-49345912\") #print(parsed.title) #print(parsed.link) #print(parsed.author)", "self.soup.find #date = self.soup #for img in imgs: # print(img['src'])", "self.link = url self.title = self.get_title() self.author = self.get_author() self.images", "e5tfeyi1\"}) #for para in paras: # print(para.text) def get_body(self) ->", "requests.get(url) self.soup = bs(article.content, \"html.parser\") #print(dir(self.soup)) #print(self.soup.h1.text) self.body = self.get_body()", "in img.img['src']: imgs_lst.append(img.img['src'])#['div']['span']['span']['img']) except: pass return imgs_lst def get_date(self) ->", "in paras: # print(para.text) def get_body(self) -> list: #body =", "# print(para.text) return [p.text for p in paras] #return [p.text", "#return [p.text for p in body.find_all(\"p\")] def get_title(self) -> str:", "return self.soup.h1.text def get_author(self) -> str: author = self.soup.find('p', {'class'", "\"\") def get_images(self) -> list: imgs = self.soup.find_all('figure', {'class' :", "self.soup.find_all('time')[0] return date['datetime'] parsed = BBC(\"https://www.bbc.co.uk/news/world-europe-49345912\") #print(parsed.title) #print(parsed.link) #print(parsed.author) #print(parsed.date)", ": 'ssrcss-1rv0moy-Contributor e5xb54n2'}) return author.text.replace(\"BBC News\", \"\") def get_images(self) ->", "not in img.img['src']: imgs_lst.append(img.img['src'])#['div']['span']['span']['img']) except: pass return imgs_lst def get_date(self)", "para in paras: # print(para.text) def get_body(self) -> list: #body", "self.soup.find_all('div', {\"class\" : \"ssrcss-17j9f6r-RichTextContainer e5tfeyi1\"}) #for para in paras: #", "self.body = self.get_body() self.link = url self.title = self.get_title() self.author", "self.soup.find_all('figure', {'class' : 'ssrcss-wpgbih-StyledFigure e34k3c23'}) imgs_lst = [] for img", "p in paras] #return [p.text for p in body.find_all(\"p\")] def", "import BeautifulSoup as bs import requests class BBC: def __init__(self,", "#date = self.soup #for img in imgs: # print(img['src']) paras", "print(img['src']) paras = self.soup.find_all('div', {\"class\" : \"ssrcss-17j9f6r-RichTextContainer e5tfeyi1\"}) #for para", "self.soup.find(class_=\"story-body__h1\").text return self.soup.h1.text def get_author(self) -> str: author = self.soup.find('p',", "date = self.soup.find_all('time')[0] return date['datetime'] parsed = BBC(\"https://www.bbc.co.uk/news/world-europe-49345912\") #print(parsed.title) #print(parsed.link)", "article = requests.get(url) self.soup = bs(article.content, \"html.parser\") #print(dir(self.soup)) #print(self.soup.h1.text) self.body", "= self.soup.find_all('div', {\"class\" : \"ssrcss-17j9f6r-RichTextContainer e5tfeyi1\"}) #for para in paras:", "get_date(self) -> str: date = self.soup.find_all('time')[0] return date['datetime'] parsed =", "{\"class\" : \"ssrcss-17j9f6r-RichTextContainer e5tfeyi1\"}) #for para in paras: # print(para.text)", "self.soup.find('p', {'class' : 'ssrcss-1rv0moy-Contributor e5xb54n2'}) return author.text.replace(\"BBC News\", \"\") def", "def __init__(self, url:str): article = requests.get(url) self.soup = bs(article.content, \"html.parser\")", "as bs import requests class BBC: def __init__(self, url:str): article", "img in imgs: try: if \"blank_white_space\" not in img.img['src']: imgs_lst.append(img.img['src'])#['div']['span']['span']['img'])", "paras: # print(para.text) def get_body(self) -> list: #body = self.soup.find(property=\"articleBody\")", "[p.text for p in paras] #return [p.text for p in", "= self.soup.find('p', {'class' : 'ssrcss-1rv0moy-Contributor e5xb54n2'}) return author.text.replace(\"BBC News\", \"\")", "= self.get_title() self.author = self.get_author() self.images = self.get_images() self.date =", "= self.get_date() #author = self.soup.find #date = self.soup #for img", "self.get_images() self.date = self.get_date() #author = self.soup.find #date = self.soup", "str: author = self.soup.find('p', {'class' : 'ssrcss-1rv0moy-Contributor e5xb54n2'}) return author.text.replace(\"BBC", "except: pass return imgs_lst def get_date(self) -> str: date =", "#print(dir(self.soup)) #print(self.soup.h1.text) self.body = self.get_body() self.link = url self.title =", "try: if \"blank_white_space\" not in img.img['src']: imgs_lst.append(img.img['src'])#['div']['span']['span']['img']) except: pass return", "[] for img in imgs: try: if \"blank_white_space\" not in", "return author.text.replace(\"BBC News\", \"\") def get_images(self) -> list: imgs =", "{'class' : 'ssrcss-1rv0moy-Contributor e5xb54n2'}) return author.text.replace(\"BBC News\", \"\") def get_images(self)", "def get_images(self) -> list: imgs = self.soup.find_all('figure', {'class' : 'ssrcss-wpgbih-StyledFigure", "= self.soup.find #date = self.soup #for img in imgs: #", "str: date = self.soup.find_all('time')[0] return date['datetime'] parsed = BBC(\"https://www.bbc.co.uk/news/world-europe-49345912\") #print(parsed.title)", "get_images(self) -> list: imgs = self.soup.find_all('figure', {'class' : 'ssrcss-wpgbih-StyledFigure e34k3c23'})", "self.date = self.get_date() #author = self.soup.find #date = self.soup #for", "= BBC(\"https://www.bbc.co.uk/news/world-europe-49345912\") #print(parsed.title) #print(parsed.link) #print(parsed.author) #print(parsed.date) #print(parsed.title) #print(parsed.body) #print(parsed.images) #print(parsed.body)", "= self.soup #for img in imgs: # print(img['src']) paras =", "\"ssrcss-17j9f6r-RichTextContainer e5tfeyi1\"}) #for para in paras: # print(para.text) return [p.text", "e5tfeyi1\"}) #for para in paras: # print(para.text) return [p.text for", "self.soup.find(property=\"articleBody\") paras = self.soup.find_all('div', {\"class\" : \"ssrcss-17j9f6r-RichTextContainer e5tfeyi1\"}) #for para", "para in paras: # print(para.text) return [p.text for p in", "\"ssrcss-17j9f6r-RichTextContainer e5tfeyi1\"}) #for para in paras: # print(para.text) def get_body(self)", "list: imgs = self.soup.find_all('figure', {'class' : 'ssrcss-wpgbih-StyledFigure e34k3c23'}) imgs_lst =", "# print(img['src']) paras = self.soup.find_all('div', {\"class\" : \"ssrcss-17j9f6r-RichTextContainer e5tfeyi1\"}) #for", "-> list: #body = self.soup.find(property=\"articleBody\") paras = self.soup.find_all('div', {\"class\" :", "= self.get_body() self.link = url self.title = self.get_title() self.author =", "= self.soup.find(property=\"articleBody\") paras = self.soup.find_all('div', {\"class\" : \"ssrcss-17j9f6r-RichTextContainer e5tfeyi1\"}) #for" ]
[ "gamma, delta): S, E, I, R = y dSdt =", "legend.get_frame().set_alpha(0.5) for spine in ('top', 'right', 'bottom', 'left'): ax.spines[spine].set_visible(False) plt.savefig('Plot.png')", "S, E, I, R = ret.T # In[46]: def plotsir(t,", "-beta * S * I / N # S(t) –", "E, I, R): f, ax = plt.subplots(1,1,figsize=(10,4)) ax.plot(t, S, 'b',", "1.0 / D #Reoval rate (Hur många som tillfrisknar) delta", "y0, t, args=(N, beta, gamma, delta)) S, E, I, R", "= y dSdt = -beta * S * I /", "- gamma * E dIdt = delta * E -", "dIdt = delta * E - gamma * I #", "four days gamma = 1.0 / D #Reoval rate (Hur", "gamma, delta)) S, E, I, R = ret.T # In[46]:", "ax.yaxis.set_tick_params(length=0) ax.xaxis.set_tick_params(length=0) ax.grid(b=True, which='major', c='w', lw=2, ls='-') legend = ax.legend()", "# describe the model def deriv(y, t, N, beta, gamma,", "ls='-') legend = ax.legend() legend.get_frame().set_alpha(0.5) for spine in ('top', 'right',", "E - gamma * I # I(t) – infected (de", "= ax.legend() legend.get_frame().set_alpha(0.5) for spine in ('top', 'right', 'bottom', 'left'):", "= ret.T # In[46]: def plotsir(t, S, E, I, R):", "har pågående infektion) dRdt = gamma * I return dSdt,", "# S(t) – susceptible (de som är mottagliga för infektion).", "grid, t. ret = odeint(deriv, y0, t, args=(N, beta, gamma,", "#Rt = R0 * S(t)/Ntot* (1 – b). b =", "ax.spines[spine].set_visible(False) plt.savefig('Plot.png') plt.show(); # plot the graph # In[47]: plotsir(t,", "100) # Grid of time points (in days) y0 =", "return dSdt, dEdt, dIdt, dRdt # In[44]: # describe the", "days) y0 = S0, E0, I0, R0 # Initial conditions", "ax.plot(t, R, 'g', alpha=0.7, linewidth=2, label='Recovered') ax.set_xlabel('Time (days)') ax.yaxis.set_tick_params(length=0) ax.xaxis.set_tick_params(length=0)", "hur vi beter oss). S0, E0, I0, R0 = N-1,", "ax.xaxis.set_tick_params(length=0) ax.grid(b=True, which='major', c='w', lw=2, ls='-') legend = ax.legend() legend.get_frame().set_alpha(0.5)", "delta): S, E, I, R = y dSdt = -beta", "tid (beror på virusets egenskaper samt hur vi beter oss).", "'y', alpha=0.7, linewidth=2, label='Exposed') ax.plot(t, I, 'r', alpha=0.7, linewidth=2, label='Infected')", "graph # In[47]: plotsir(t, S, E, I, R) # In[", "(de som är mottagliga för infektion). dEdt = beta *", "points (in days) y0 = S0, E0, I0, R0 #", "from scipy.integrate import odeint import numpy as np import matplotlib.pyplot", "S0, E0, I0, R0 # Initial conditions vector # Integrate", "S, E, I, R): f, ax = plt.subplots(1,1,figsize=(10,4)) ax.plot(t, S,", "dEdt = beta * S * I / N -", "= 4.0 #infections last four days gamma = 1.0 /", "def deriv(y, t, N, beta, gamma, delta): S, E, I,", "N # S(t) – susceptible (de som är mottagliga för", "och per tid (beror på virusets egenskaper samt hur vi", "= np.linspace(0, 99, 100) # Grid of time points (in", "R0 = N-1, 1, 0, 0 # initial conditions: one", "I / N # S(t) – susceptible (de som är", "R): f, ax = plt.subplots(1,1,figsize=(10,4)) ax.plot(t, S, 'b', alpha=0.7, linewidth=2,", "= beta * S * I / N - gamma", "= plt.subplots(1,1,figsize=(10,4)) ax.plot(t, S, 'b', alpha=0.7, linewidth=2, label='Susceptible') ax.plot(t, E,", "4.0 #infections last four days gamma = 1.0 / D", "# I(t) – infected (de som har pågående infektion) dRdt", "E0, I0, R0 = N-1, 1, 0, 0 # initial", "1.0 / 5.0 #incubation period of five days R_0 =", "antal som smittas per infekterad och per tid (beror på", "label='Exposed') ax.plot(t, I, 'r', alpha=0.7, linewidth=2, label='Infected') ax.plot(t, R, 'g',", "som tillfrisknar) delta = 1.0 / 5.0 #incubation period of", "N - gamma * E dIdt = delta * E", "period of five days R_0 = 2.5 #Reproduktionstalet beta =", "gamma * I return dSdt, dEdt, dIdt, dRdt # In[44]:", "* I return dSdt, dEdt, dIdt, dRdt # In[44]: #", "initial conditions: one infected, rest susceptible #Rt = R0 *", "In[45]: t = np.linspace(0, 99, 100) # Grid of time", "# Grid of time points (in days) y0 = S0,", "c='w', lw=2, ls='-') legend = ax.legend() legend.get_frame().set_alpha(0.5) for spine in", "('top', 'right', 'bottom', 'left'): ax.spines[spine].set_visible(False) plt.savefig('Plot.png') plt.show(); # plot the", "N-1, 1, 0, 0 # initial conditions: one infected, rest", "= 1.0 / 5.0 #incubation period of five days R_0", "infected (de som har pågående infektion) dRdt = gamma *", "vi beter oss). S0, E0, I0, R0 = N-1, 1,", "args=(N, beta, gamma, delta)) S, E, I, R = ret.T", "odeint import numpy as np import matplotlib.pyplot as plt #", "# plot the graph # In[47]: plotsir(t, S, E, I,", "delta)) S, E, I, R = ret.T # In[46]: def", "conditions vector # Integrate the SIR equations over the time", "'b', alpha=0.7, linewidth=2, label='Susceptible') ax.plot(t, E, 'y', alpha=0.7, linewidth=2, label='Exposed')", "= odeint(deriv, y0, t, args=(N, beta, gamma, delta)) S, E,", "f, ax = plt.subplots(1,1,figsize=(10,4)) ax.plot(t, S, 'b', alpha=0.7, linewidth=2, label='Susceptible')", "Grid of time points (in days) y0 = S0, E0,", "beta = R_0 * gamma #r_0=beta/gamma. antal som smittas per", "2283 #Totala befolkningen N=s(t)+I(t)+R(t) D = 4.0 #infections last four", "= effekt av policy och beteendeförändringar # In[45]: t =", "the SIR equations over the time grid, t. ret =", "= -beta * S * I / N # S(t)", "in ('top', 'right', 'bottom', 'left'): ax.spines[spine].set_visible(False) plt.savefig('Plot.png') plt.show(); # plot", "S, 'b', alpha=0.7, linewidth=2, label='Susceptible') ax.plot(t, E, 'y', alpha=0.7, linewidth=2,", "= delta * E - gamma * I # I(t)", "beta, gamma, delta): S, E, I, R = y dSdt", "oss). S0, E0, I0, R0 = N-1, 1, 0, 0", "I, R = ret.T # In[46]: def plotsir(t, S, E,", "ret.T # In[46]: def plotsir(t, S, E, I, R): f,", "odeint(deriv, y0, t, args=(N, beta, gamma, delta)) S, E, I,", "E, I, R = y dSdt = -beta * S", "som har pågående infektion) dRdt = gamma * I return", "last four days gamma = 1.0 / D #Reoval rate", "scipy.integrate import odeint import numpy as np import matplotlib.pyplot as", "dRdt # In[44]: # describe the parameters N = 2283", "describe the parameters N = 2283 #Totala befolkningen N=s(t)+I(t)+R(t) D", "= 2.5 #Reproduktionstalet beta = R_0 * gamma #r_0=beta/gamma. antal", "/ 5.0 #incubation period of five days R_0 = 2.5", "per tid (beror på virusets egenskaper samt hur vi beter", "ax.plot(t, E, 'y', alpha=0.7, linewidth=2, label='Exposed') ax.plot(t, I, 'r', alpha=0.7,", "plt.show(); # plot the graph # In[47]: plotsir(t, S, E,", "import odeint import numpy as np import matplotlib.pyplot as plt", "infekterad och per tid (beror på virusets egenskaper samt hur", "I(t) – infected (de som har pågående infektion) dRdt =", "tillfrisknar) delta = 1.0 / 5.0 #incubation period of five", "t, N, beta, gamma, delta): S, E, I, R =", "parameters N = 2283 #Totala befolkningen N=s(t)+I(t)+R(t) D = 4.0", "# In[45]: t = np.linspace(0, 99, 100) # Grid of", "S, E, I, R = y dSdt = -beta *", "= N-1, 1, 0, 0 # initial conditions: one infected,", "* S * I / N - gamma * E", "av policy och beteendeförändringar # In[45]: t = np.linspace(0, 99,", "plot the graph # In[47]: plotsir(t, S, E, I, R)", "samt hur vi beter oss). S0, E0, I0, R0 =", "# In[43]: # describe the model def deriv(y, t, N,", "S(t)/Ntot* (1 – b). b = effekt av policy och", "= S0, E0, I0, R0 # Initial conditions vector #", "infektion) dRdt = gamma * I return dSdt, dEdt, dIdt,", "numpy as np import matplotlib.pyplot as plt # In[43]: #", "I, R = y dSdt = -beta * S *", "legend = ax.legend() legend.get_frame().set_alpha(0.5) for spine in ('top', 'right', 'bottom',", "the graph # In[47]: plotsir(t, S, E, I, R) #", "på virusets egenskaper samt hur vi beter oss). S0, E0,", "befolkningen N=s(t)+I(t)+R(t) D = 4.0 #infections last four days gamma", "som smittas per infekterad och per tid (beror på virusets", "# Initial conditions vector # Integrate the SIR equations over", "N = 2283 #Totala befolkningen N=s(t)+I(t)+R(t) D = 4.0 #infections", "days R_0 = 2.5 #Reproduktionstalet beta = R_0 * gamma", "conditions: one infected, rest susceptible #Rt = R0 * S(t)/Ntot*", "dSdt, dEdt, dIdt, dRdt # In[44]: # describe the parameters", "plt # In[43]: # describe the model def deriv(y, t,", "D = 4.0 #infections last four days gamma = 1.0", "matplotlib.pyplot as plt # In[43]: # describe the model def", "gamma #r_0=beta/gamma. antal som smittas per infekterad och per tid", "equations over the time grid, t. ret = odeint(deriv, y0,", "egenskaper samt hur vi beter oss). S0, E0, I0, R0", "model def deriv(y, t, N, beta, gamma, delta): S, E,", "infected, rest susceptible #Rt = R0 * S(t)/Ntot* (1 –", "the model def deriv(y, t, N, beta, gamma, delta): S,", "R = y dSdt = -beta * S * I", "of time points (in days) y0 = S0, E0, I0,", "= R_0 * gamma #r_0=beta/gamma. antal som smittas per infekterad", "linewidth=2, label='Infected') ax.plot(t, R, 'g', alpha=0.7, linewidth=2, label='Recovered') ax.set_xlabel('Time (days)')", "beta, gamma, delta)) S, E, I, R = ret.T #", "'r', alpha=0.7, linewidth=2, label='Infected') ax.plot(t, R, 'g', alpha=0.7, linewidth=2, label='Recovered')", "I return dSdt, dEdt, dIdt, dRdt # In[44]: # describe", "describe the model def deriv(y, t, N, beta, gamma, delta):", "* E - gamma * I # I(t) – infected", "t = np.linspace(0, 99, 100) # Grid of time points", "och beteendeförändringar # In[45]: t = np.linspace(0, 99, 100) #", "pågående infektion) dRdt = gamma * I return dSdt, dEdt,", "beteendeförändringar # In[45]: t = np.linspace(0, 99, 100) # Grid", "ret = odeint(deriv, y0, t, args=(N, beta, gamma, delta)) S,", "ax = plt.subplots(1,1,figsize=(10,4)) ax.plot(t, S, 'b', alpha=0.7, linewidth=2, label='Susceptible') ax.plot(t,", "S(t) – susceptible (de som är mottagliga för infektion). dEdt", "som är mottagliga för infektion). dEdt = beta * S", "99, 100) # Grid of time points (in days) y0", "E, 'y', alpha=0.7, linewidth=2, label='Exposed') ax.plot(t, I, 'r', alpha=0.7, linewidth=2,", "one infected, rest susceptible #Rt = R0 * S(t)/Ntot* (1", "'bottom', 'left'): ax.spines[spine].set_visible(False) plt.savefig('Plot.png') plt.show(); # plot the graph #", "= R0 * S(t)/Ntot* (1 – b). b = effekt", "y dSdt = -beta * S * I / N", "gamma * I # I(t) – infected (de som har", "policy och beteendeförändringar # In[45]: t = np.linspace(0, 99, 100)", "5.0 #incubation period of five days R_0 = 2.5 #Reproduktionstalet", "I0, R0 # Initial conditions vector # Integrate the SIR", "* I / N # S(t) – susceptible (de som", "spine in ('top', 'right', 'bottom', 'left'): ax.spines[spine].set_visible(False) plt.savefig('Plot.png') plt.show(); #", "/ N # S(t) – susceptible (de som är mottagliga", "N, beta, gamma, delta): S, E, I, R = y", "which='major', c='w', lw=2, ls='-') legend = ax.legend() legend.get_frame().set_alpha(0.5) for spine", "för infektion). dEdt = beta * S * I /", "/ D #Reoval rate (Hur många som tillfrisknar) delta =", "gamma * E dIdt = delta * E - gamma", "(beror på virusets egenskaper samt hur vi beter oss). S0,", "R_0 * gamma #r_0=beta/gamma. antal som smittas per infekterad och", "* E dIdt = delta * E - gamma *", "ax.legend() legend.get_frame().set_alpha(0.5) for spine in ('top', 'right', 'bottom', 'left'): ax.spines[spine].set_visible(False)", "smittas per infekterad och per tid (beror på virusets egenskaper", "– susceptible (de som är mottagliga för infektion). dEdt =", "def plotsir(t, S, E, I, R): f, ax = plt.subplots(1,1,figsize=(10,4))", "linewidth=2, label='Susceptible') ax.plot(t, E, 'y', alpha=0.7, linewidth=2, label='Exposed') ax.plot(t, I,", "(days)') ax.yaxis.set_tick_params(length=0) ax.xaxis.set_tick_params(length=0) ax.grid(b=True, which='major', c='w', lw=2, ls='-') legend =", "as plt # In[43]: # describe the model def deriv(y,", "# In[47]: plotsir(t, S, E, I, R) # In[ ]:", "dIdt, dRdt # In[44]: # describe the parameters N =", "# describe the parameters N = 2283 #Totala befolkningen N=s(t)+I(t)+R(t)", "alpha=0.7, linewidth=2, label='Recovered') ax.set_xlabel('Time (days)') ax.yaxis.set_tick_params(length=0) ax.xaxis.set_tick_params(length=0) ax.grid(b=True, which='major', c='w',", "2.5 #Reproduktionstalet beta = R_0 * gamma #r_0=beta/gamma. antal som", "# In[42]: from scipy.integrate import odeint import numpy as np", "import numpy as np import matplotlib.pyplot as plt # In[43]:", "* gamma #r_0=beta/gamma. antal som smittas per infekterad och per", "infektion). dEdt = beta * S * I / N", "R0 # Initial conditions vector # Integrate the SIR equations", "y0 = S0, E0, I0, R0 # Initial conditions vector", "'right', 'bottom', 'left'): ax.spines[spine].set_visible(False) plt.savefig('Plot.png') plt.show(); # plot the graph", "time points (in days) y0 = S0, E0, I0, R0", "(in days) y0 = S0, E0, I0, R0 # Initial", "#incubation period of five days R_0 = 2.5 #Reproduktionstalet beta", "five days R_0 = 2.5 #Reproduktionstalet beta = R_0 *", "0 # initial conditions: one infected, rest susceptible #Rt =", "np.linspace(0, 99, 100) # Grid of time points (in days)", "(de som har pågående infektion) dRdt = gamma * I", "gamma = 1.0 / D #Reoval rate (Hur många som", "b). b = effekt av policy och beteendeförändringar # In[45]:", "effekt av policy och beteendeförändringar # In[45]: t = np.linspace(0,", "#infections last four days gamma = 1.0 / D #Reoval", "beta * S * I / N - gamma *", "days gamma = 1.0 / D #Reoval rate (Hur många", "# Integrate the SIR equations over the time grid, t.", "deriv(y, t, N, beta, gamma, delta): S, E, I, R", "I, 'r', alpha=0.7, linewidth=2, label='Infected') ax.plot(t, R, 'g', alpha=0.7, linewidth=2,", "b = effekt av policy och beteendeförändringar # In[45]: t", "ax.plot(t, S, 'b', alpha=0.7, linewidth=2, label='Susceptible') ax.plot(t, E, 'y', alpha=0.7,", "alpha=0.7, linewidth=2, label='Susceptible') ax.plot(t, E, 'y', alpha=0.7, linewidth=2, label='Exposed') ax.plot(t,", "as np import matplotlib.pyplot as plt # In[43]: # describe", "dRdt = gamma * I return dSdt, dEdt, dIdt, dRdt", "R0 * S(t)/Ntot* (1 – b). b = effekt av", "delta = 1.0 / 5.0 #incubation period of five days", "* S(t)/Ntot* (1 – b). b = effekt av policy", "vector # Integrate the SIR equations over the time grid,", "per infekterad och per tid (beror på virusets egenskaper samt", "Initial conditions vector # Integrate the SIR equations over the", "ax.grid(b=True, which='major', c='w', lw=2, ls='-') legend = ax.legend() legend.get_frame().set_alpha(0.5) for", "import matplotlib.pyplot as plt # In[43]: # describe the model", "S * I / N # S(t) – susceptible (de", "mottagliga för infektion). dEdt = beta * S * I", "(Hur många som tillfrisknar) delta = 1.0 / 5.0 #incubation", "of five days R_0 = 2.5 #Reproduktionstalet beta = R_0", "= 2283 #Totala befolkningen N=s(t)+I(t)+R(t) D = 4.0 #infections last", "E, I, R = ret.T # In[46]: def plotsir(t, S,", "susceptible (de som är mottagliga för infektion). dEdt = beta", "delta * E - gamma * I # I(t) –", "S0, E0, I0, R0 = N-1, 1, 0, 0 #", "alpha=0.7, linewidth=2, label='Exposed') ax.plot(t, I, 'r', alpha=0.7, linewidth=2, label='Infected') ax.plot(t,", "the parameters N = 2283 #Totala befolkningen N=s(t)+I(t)+R(t) D =", "t, args=(N, beta, gamma, delta)) S, E, I, R =", "SIR equations over the time grid, t. ret = odeint(deriv,", "dSdt = -beta * S * I / N #", "- gamma * I # I(t) – infected (de som", "många som tillfrisknar) delta = 1.0 / 5.0 #incubation period", "linewidth=2, label='Recovered') ax.set_xlabel('Time (days)') ax.yaxis.set_tick_params(length=0) ax.xaxis.set_tick_params(length=0) ax.grid(b=True, which='major', c='w', lw=2,", "E0, I0, R0 # Initial conditions vector # Integrate the", "np import matplotlib.pyplot as plt # In[43]: # describe the", "virusets egenskaper samt hur vi beter oss). S0, E0, I0,", "N=s(t)+I(t)+R(t) D = 4.0 #infections last four days gamma =", "for spine in ('top', 'right', 'bottom', 'left'): ax.spines[spine].set_visible(False) plt.savefig('Plot.png') plt.show();", "In[44]: # describe the parameters N = 2283 #Totala befolkningen", "1, 0, 0 # initial conditions: one infected, rest susceptible", "plt.savefig('Plot.png') plt.show(); # plot the graph # In[47]: plotsir(t, S,", "plt.subplots(1,1,figsize=(10,4)) ax.plot(t, S, 'b', alpha=0.7, linewidth=2, label='Susceptible') ax.plot(t, E, 'y',", "beter oss). S0, E0, I0, R0 = N-1, 1, 0,", "the time grid, t. ret = odeint(deriv, y0, t, args=(N,", "I / N - gamma * E dIdt = delta", "#r_0=beta/gamma. antal som smittas per infekterad och per tid (beror", "'left'): ax.spines[spine].set_visible(False) plt.savefig('Plot.png') plt.show(); # plot the graph # In[47]:", "I0, R0 = N-1, 1, 0, 0 # initial conditions:", "# initial conditions: one infected, rest susceptible #Rt = R0", "susceptible #Rt = R0 * S(t)/Ntot* (1 – b). b", "time grid, t. ret = odeint(deriv, y0, t, args=(N, beta,", "'g', alpha=0.7, linewidth=2, label='Recovered') ax.set_xlabel('Time (days)') ax.yaxis.set_tick_params(length=0) ax.xaxis.set_tick_params(length=0) ax.grid(b=True, which='major',", "#Reproduktionstalet beta = R_0 * gamma #r_0=beta/gamma. antal som smittas", "* I # I(t) – infected (de som har pågående", "dEdt, dIdt, dRdt # In[44]: # describe the parameters N", "# In[46]: def plotsir(t, S, E, I, R): f, ax", "R_0 = 2.5 #Reproduktionstalet beta = R_0 * gamma #r_0=beta/gamma.", "(1 – b). b = effekt av policy och beteendeförändringar", "– b). b = effekt av policy och beteendeförändringar #", "In[43]: # describe the model def deriv(y, t, N, beta,", "* S * I / N # S(t) – susceptible", "In[46]: def plotsir(t, S, E, I, R): f, ax =", "= 1.0 / D #Reoval rate (Hur många som tillfrisknar)", "– infected (de som har pågående infektion) dRdt = gamma", "linewidth=2, label='Exposed') ax.plot(t, I, 'r', alpha=0.7, linewidth=2, label='Infected') ax.plot(t, R,", "label='Recovered') ax.set_xlabel('Time (days)') ax.yaxis.set_tick_params(length=0) ax.xaxis.set_tick_params(length=0) ax.grid(b=True, which='major', c='w', lw=2, ls='-')", "#Reoval rate (Hur många som tillfrisknar) delta = 1.0 /", "/ N - gamma * E dIdt = delta *", "label='Susceptible') ax.plot(t, E, 'y', alpha=0.7, linewidth=2, label='Exposed') ax.plot(t, I, 'r',", "In[42]: from scipy.integrate import odeint import numpy as np import", "#Totala befolkningen N=s(t)+I(t)+R(t) D = 4.0 #infections last four days", "Integrate the SIR equations over the time grid, t. ret", "plotsir(t, S, E, I, R): f, ax = plt.subplots(1,1,figsize=(10,4)) ax.plot(t,", "D #Reoval rate (Hur många som tillfrisknar) delta = 1.0", "S * I / N - gamma * E dIdt", "over the time grid, t. ret = odeint(deriv, y0, t,", "R = ret.T # In[46]: def plotsir(t, S, E, I,", "t. ret = odeint(deriv, y0, t, args=(N, beta, gamma, delta))", "rate (Hur många som tillfrisknar) delta = 1.0 / 5.0", "0, 0 # initial conditions: one infected, rest susceptible #Rt", "är mottagliga för infektion). dEdt = beta * S *", "# In[44]: # describe the parameters N = 2283 #Totala", "I, R): f, ax = plt.subplots(1,1,figsize=(10,4)) ax.plot(t, S, 'b', alpha=0.7,", "ax.plot(t, I, 'r', alpha=0.7, linewidth=2, label='Infected') ax.plot(t, R, 'g', alpha=0.7,", "I # I(t) – infected (de som har pågående infektion)", "alpha=0.7, linewidth=2, label='Infected') ax.plot(t, R, 'g', alpha=0.7, linewidth=2, label='Recovered') ax.set_xlabel('Time", "* I / N - gamma * E dIdt =", "label='Infected') ax.plot(t, R, 'g', alpha=0.7, linewidth=2, label='Recovered') ax.set_xlabel('Time (days)') ax.yaxis.set_tick_params(length=0)", "R, 'g', alpha=0.7, linewidth=2, label='Recovered') ax.set_xlabel('Time (days)') ax.yaxis.set_tick_params(length=0) ax.xaxis.set_tick_params(length=0) ax.grid(b=True,", "lw=2, ls='-') legend = ax.legend() legend.get_frame().set_alpha(0.5) for spine in ('top',", "rest susceptible #Rt = R0 * S(t)/Ntot* (1 – b).", "ax.set_xlabel('Time (days)') ax.yaxis.set_tick_params(length=0) ax.xaxis.set_tick_params(length=0) ax.grid(b=True, which='major', c='w', lw=2, ls='-') legend", "= gamma * I return dSdt, dEdt, dIdt, dRdt #", "E dIdt = delta * E - gamma * I" ]
[ "tiempo >= 21 and tiempo <=45: print 'Es un tiempo", "'Eres afortunado' if pregunta == False: print 'Trabajas fuera de", "<=20: print 'Es poco tiempo' elif tiempo >= 21 and", "print 'Es un tiempo razonable' else: print 'Busca otras rutas'", "if tiempo == 0: print 'trabajas desde casa' elif tiempo", "0: print 'trabajas desde casa' elif tiempo <=20: print 'Es", "if pregunta == False: print 'Trabajas fuera de casa' tiempo", "True: print 'Eres afortunado' if pregunta == False: print 'Trabajas", "casa? ') if pregunta == True: print 'Eres afortunado' if", "'Trabajas fuera de casa' tiempo = input('Cuantos minutos haces al", "'Es poco tiempo' elif tiempo >= 21 and tiempo <=45:", "tiempo <=20: print 'Es poco tiempo' elif tiempo >= 21", "minutos haces al trabajo: ') if tiempo == 0: print", "pregunta = input('trabajas desde casa? ') if pregunta == True:", "tiempo <=45: print 'Es un tiempo razonable' else: print 'Busca", "print 'Es poco tiempo' elif tiempo >= 21 and tiempo", "haces al trabajo: ') if tiempo == 0: print 'trabajas", "print 'Eres afortunado' if pregunta == False: print 'Trabajas fuera", "tiempo == 0: print 'trabajas desde casa' elif tiempo <=20:", "print 'Trabajas fuera de casa' tiempo = input('Cuantos minutos haces", "elif tiempo <=20: print 'Es poco tiempo' elif tiempo >=", "if pregunta == True: print 'Eres afortunado' if pregunta ==", "pregunta == False: print 'Trabajas fuera de casa' tiempo =", "al trabajo: ') if tiempo == 0: print 'trabajas desde", "and tiempo <=45: print 'Es un tiempo razonable' else: print", "poco tiempo' elif tiempo >= 21 and tiempo <=45: print", "= input('Cuantos minutos haces al trabajo: ') if tiempo ==", "== False: print 'Trabajas fuera de casa' tiempo = input('Cuantos", "tiempo = input('Cuantos minutos haces al trabajo: ') if tiempo", "<=45: print 'Es un tiempo razonable' else: print 'Busca otras", "') if tiempo == 0: print 'trabajas desde casa' elif", "casa' elif tiempo <=20: print 'Es poco tiempo' elif tiempo", "elif tiempo >= 21 and tiempo <=45: print 'Es un", "input('Cuantos minutos haces al trabajo: ') if tiempo == 0:", "= input('trabajas desde casa? ') if pregunta == True: print", "desde casa? ') if pregunta == True: print 'Eres afortunado'", "'trabajas desde casa' elif tiempo <=20: print 'Es poco tiempo'", "fuera de casa' tiempo = input('Cuantos minutos haces al trabajo:", "pregunta == True: print 'Eres afortunado' if pregunta == False:", "== 0: print 'trabajas desde casa' elif tiempo <=20: print", "de casa' tiempo = input('Cuantos minutos haces al trabajo: ')", "print 'trabajas desde casa' elif tiempo <=20: print 'Es poco", "== True: print 'Eres afortunado' if pregunta == False: print", "False: print 'Trabajas fuera de casa' tiempo = input('Cuantos minutos", "casa' tiempo = input('Cuantos minutos haces al trabajo: ') if", "tiempo' elif tiempo >= 21 and tiempo <=45: print 'Es", "21 and tiempo <=45: print 'Es un tiempo razonable' else:", "desde casa' elif tiempo <=20: print 'Es poco tiempo' elif", ">= 21 and tiempo <=45: print 'Es un tiempo razonable'", "input('trabajas desde casa? ') if pregunta == True: print 'Eres", "trabajo: ') if tiempo == 0: print 'trabajas desde casa'", "afortunado' if pregunta == False: print 'Trabajas fuera de casa'", "') if pregunta == True: print 'Eres afortunado' if pregunta" ]
[ "for each request before # the view (and later middleware)", "adds appropriate cache headers to GET and HEAD methods. NOTE:", "in ('GET', 'HEAD') and not request.path.startswith(urlparse(settings.STATIC_URL).path) ): logger.debug( \"Patching cache", "request before # the view (and later middleware) are called.", "endpoints are marked as never cache. ''' def __init__(self, get_response):", "= settings.STAC_BASE_V class CacheHeadersMiddleware: '''Middleware that adds appropriate cache headers", "= settings.STAC_BASE STAC_BASE_V = settings.STAC_BASE_V class CacheHeadersMiddleware: '''Middleware that adds", "(and later middleware) are called. response = self.get_response(request) # Code", "logger.debug( \"Patching cache headers for request %s %s\", request.method, request.path,", "__init__(self, get_response): self.get_response = get_response def __call__(self, request): # Code", "are called. response = self.get_response(request) # Code to be executed", "HEAD methods. NOTE: /checker, /get-token, /metrics and /{healthcheck} endpoints are", "/api/stac/{healthcheck}, /api/stac/get-token if re.match(fr'^(/{STAC_BASE})?/\\w+$', request.path): add_never_cache_headers(response) elif ( request.method in", "'''Middleware that adds appropriate cache headers to GET and HEAD", "patch_cache_control from django.utils.cache import patch_response_headers logger = logging.getLogger(__name__) STAC_BASE =", "self.get_response(request) # Code to be executed for each request/response after", "be executed for each request before # the view (and", "marked as never cache. ''' def __init__(self, get_response): self.get_response =", "__call__(self, request): # Code to be executed for each request", "called. response = self.get_response(request) # Code to be executed for", "headers for request %s %s\", request.method, request.path, extra={\"request\": request} )", "from django.utils.cache import patch_cache_control from django.utils.cache import patch_response_headers logger =", "re.match(fr'^(/{STAC_BASE})?/\\w+$', request.path): add_never_cache_headers(response) elif ( request.method in ('GET', 'HEAD') and", "class CacheHeadersMiddleware: '''Middleware that adds appropriate cache headers to GET", "from urllib.parse import urlparse from django.conf import settings from django.utils.cache", "= get_response def __call__(self, request): # Code to be executed", "to be executed for each request before # the view", "cache headers for request %s %s\", request.method, request.path, extra={\"request\": request}", "/{healthcheck} endpoints are marked as never cache. ''' def __init__(self,", "view (and later middleware) are called. response = self.get_response(request) #", "to be executed for each request/response after # the view", "# Code to be executed for each request before #", "for each request/response after # the view is called. #", "each request/response after # the view is called. # match", "request.path, extra={\"request\": request} ) patch_response_headers(response, settings.CACHE_MIDDLEWARE_SECONDS) patch_cache_control(response, public=True) return response", "# the view (and later middleware) are called. response =", "add_never_cache_headers from django.utils.cache import patch_cache_control from django.utils.cache import patch_response_headers logger", "request/response after # the view is called. # match /xxx", "def __call__(self, request): # Code to be executed for each", "from django.utils.cache import add_never_cache_headers from django.utils.cache import patch_cache_control from django.utils.cache", "/checker, /get-token, /metrics and /{healthcheck} endpoints are marked as never", "/api/stac/xxx # f.ex. /metrics, /checker, /api/stac/{healthcheck}, /api/stac/get-token if re.match(fr'^(/{STAC_BASE})?/\\w+$', request.path):", "each request before # the view (and later middleware) are", "for request %s %s\", request.method, request.path, extra={\"request\": request} ) patch_response_headers(response,", "methods. NOTE: /checker, /get-token, /metrics and /{healthcheck} endpoints are marked", "logging import re from urllib.parse import urlparse from django.conf import", "/checker, /api/stac/{healthcheck}, /api/stac/get-token if re.match(fr'^(/{STAC_BASE})?/\\w+$', request.path): add_never_cache_headers(response) elif ( request.method", "settings.STAC_BASE_V class CacheHeadersMiddleware: '''Middleware that adds appropriate cache headers to", "# Code to be executed for each request/response after #", "# f.ex. /metrics, /checker, /api/stac/{healthcheck}, /api/stac/get-token if re.match(fr'^(/{STAC_BASE})?/\\w+$', request.path): add_never_cache_headers(response)", "request): # Code to be executed for each request before", "settings from django.utils.cache import add_never_cache_headers from django.utils.cache import patch_cache_control from", "CacheHeadersMiddleware: '''Middleware that adds appropriate cache headers to GET and", "('GET', 'HEAD') and not request.path.startswith(urlparse(settings.STATIC_URL).path) ): logger.debug( \"Patching cache headers", "urlparse from django.conf import settings from django.utils.cache import add_never_cache_headers from", "import settings from django.utils.cache import add_never_cache_headers from django.utils.cache import patch_cache_control", "cache. ''' def __init__(self, get_response): self.get_response = get_response def __call__(self,", "self.get_response = get_response def __call__(self, request): # Code to be", "= self.get_response(request) # Code to be executed for each request/response", "after # the view is called. # match /xxx or", "'HEAD') and not request.path.startswith(urlparse(settings.STATIC_URL).path) ): logger.debug( \"Patching cache headers for", "Code to be executed for each request/response after # the", "is called. # match /xxx or /api/stac/xxx # f.ex. /metrics,", "later middleware) are called. response = self.get_response(request) # Code to", "urllib.parse import urlparse from django.conf import settings from django.utils.cache import", "logger = logging.getLogger(__name__) STAC_BASE = settings.STAC_BASE STAC_BASE_V = settings.STAC_BASE_V class", "GET and HEAD methods. NOTE: /checker, /get-token, /metrics and /{healthcheck}", "get_response def __call__(self, request): # Code to be executed for", "and HEAD methods. NOTE: /checker, /get-token, /metrics and /{healthcheck} endpoints", "called. # match /xxx or /api/stac/xxx # f.ex. /metrics, /checker,", "import patch_cache_control from django.utils.cache import patch_response_headers logger = logging.getLogger(__name__) STAC_BASE", "executed for each request/response after # the view is called.", "django.utils.cache import patch_response_headers logger = logging.getLogger(__name__) STAC_BASE = settings.STAC_BASE STAC_BASE_V", "be executed for each request/response after # the view is", "): logger.debug( \"Patching cache headers for request %s %s\", request.method,", "before # the view (and later middleware) are called. response", "import add_never_cache_headers from django.utils.cache import patch_cache_control from django.utils.cache import patch_response_headers", "NOTE: /checker, /get-token, /metrics and /{healthcheck} endpoints are marked as", "request.method in ('GET', 'HEAD') and not request.path.startswith(urlparse(settings.STATIC_URL).path) ): logger.debug( \"Patching", "/api/stac/get-token if re.match(fr'^(/{STAC_BASE})?/\\w+$', request.path): add_never_cache_headers(response) elif ( request.method in ('GET',", "middleware) are called. response = self.get_response(request) # Code to be", "Code to be executed for each request before # the", "import urlparse from django.conf import settings from django.utils.cache import add_never_cache_headers", "request.path): add_never_cache_headers(response) elif ( request.method in ('GET', 'HEAD') and not", "request %s %s\", request.method, request.path, extra={\"request\": request} ) patch_response_headers(response, settings.CACHE_MIDDLEWARE_SECONDS)", "headers to GET and HEAD methods. NOTE: /checker, /get-token, /metrics", "and /{healthcheck} endpoints are marked as never cache. ''' def", "STAC_BASE_V = settings.STAC_BASE_V class CacheHeadersMiddleware: '''Middleware that adds appropriate cache", "the view is called. # match /xxx or /api/stac/xxx #", "cache headers to GET and HEAD methods. NOTE: /checker, /get-token,", "request.method, request.path, extra={\"request\": request} ) patch_response_headers(response, settings.CACHE_MIDDLEWARE_SECONDS) patch_cache_control(response, public=True) return", "and not request.path.startswith(urlparse(settings.STATIC_URL).path) ): logger.debug( \"Patching cache headers for request", "<gh_stars>1-10 import logging import re from urllib.parse import urlparse from", "/metrics, /checker, /api/stac/{healthcheck}, /api/stac/get-token if re.match(fr'^(/{STAC_BASE})?/\\w+$', request.path): add_never_cache_headers(response) elif (", "%s %s\", request.method, request.path, extra={\"request\": request} ) patch_response_headers(response, settings.CACHE_MIDDLEWARE_SECONDS) patch_cache_control(response,", "that adds appropriate cache headers to GET and HEAD methods.", "are marked as never cache. ''' def __init__(self, get_response): self.get_response", "STAC_BASE = settings.STAC_BASE STAC_BASE_V = settings.STAC_BASE_V class CacheHeadersMiddleware: '''Middleware that", "= logging.getLogger(__name__) STAC_BASE = settings.STAC_BASE STAC_BASE_V = settings.STAC_BASE_V class CacheHeadersMiddleware:", "re from urllib.parse import urlparse from django.conf import settings from", "not request.path.startswith(urlparse(settings.STATIC_URL).path) ): logger.debug( \"Patching cache headers for request %s", "/get-token, /metrics and /{healthcheck} endpoints are marked as never cache.", "view is called. # match /xxx or /api/stac/xxx # f.ex.", "or /api/stac/xxx # f.ex. /metrics, /checker, /api/stac/{healthcheck}, /api/stac/get-token if re.match(fr'^(/{STAC_BASE})?/\\w+$',", "f.ex. /metrics, /checker, /api/stac/{healthcheck}, /api/stac/get-token if re.match(fr'^(/{STAC_BASE})?/\\w+$', request.path): add_never_cache_headers(response) elif", "''' def __init__(self, get_response): self.get_response = get_response def __call__(self, request):", "import logging import re from urllib.parse import urlparse from django.conf", "from django.conf import settings from django.utils.cache import add_never_cache_headers from django.utils.cache", "response = self.get_response(request) # Code to be executed for each", "add_never_cache_headers(response) elif ( request.method in ('GET', 'HEAD') and not request.path.startswith(urlparse(settings.STATIC_URL).path)", "\"Patching cache headers for request %s %s\", request.method, request.path, extra={\"request\":", "django.utils.cache import patch_cache_control from django.utils.cache import patch_response_headers logger = logging.getLogger(__name__)", "get_response): self.get_response = get_response def __call__(self, request): # Code to", "# match /xxx or /api/stac/xxx # f.ex. /metrics, /checker, /api/stac/{healthcheck},", "( request.method in ('GET', 'HEAD') and not request.path.startswith(urlparse(settings.STATIC_URL).path) ): logger.debug(", "if re.match(fr'^(/{STAC_BASE})?/\\w+$', request.path): add_never_cache_headers(response) elif ( request.method in ('GET', 'HEAD')", "logging.getLogger(__name__) STAC_BASE = settings.STAC_BASE STAC_BASE_V = settings.STAC_BASE_V class CacheHeadersMiddleware: '''Middleware", "elif ( request.method in ('GET', 'HEAD') and not request.path.startswith(urlparse(settings.STATIC_URL).path) ):", "to GET and HEAD methods. NOTE: /checker, /get-token, /metrics and", "executed for each request before # the view (and later", "patch_response_headers logger = logging.getLogger(__name__) STAC_BASE = settings.STAC_BASE STAC_BASE_V = settings.STAC_BASE_V", "%s\", request.method, request.path, extra={\"request\": request} ) patch_response_headers(response, settings.CACHE_MIDDLEWARE_SECONDS) patch_cache_control(response, public=True)", "django.conf import settings from django.utils.cache import add_never_cache_headers from django.utils.cache import", "django.utils.cache import add_never_cache_headers from django.utils.cache import patch_cache_control from django.utils.cache import", "as never cache. ''' def __init__(self, get_response): self.get_response = get_response", "/metrics and /{healthcheck} endpoints are marked as never cache. '''", "the view (and later middleware) are called. response = self.get_response(request)", "from django.utils.cache import patch_response_headers logger = logging.getLogger(__name__) STAC_BASE = settings.STAC_BASE", "def __init__(self, get_response): self.get_response = get_response def __call__(self, request): #", "request.path.startswith(urlparse(settings.STATIC_URL).path) ): logger.debug( \"Patching cache headers for request %s %s\",", "import re from urllib.parse import urlparse from django.conf import settings", "# the view is called. # match /xxx or /api/stac/xxx", "never cache. ''' def __init__(self, get_response): self.get_response = get_response def", "appropriate cache headers to GET and HEAD methods. NOTE: /checker,", "import patch_response_headers logger = logging.getLogger(__name__) STAC_BASE = settings.STAC_BASE STAC_BASE_V =", "match /xxx or /api/stac/xxx # f.ex. /metrics, /checker, /api/stac/{healthcheck}, /api/stac/get-token", "/xxx or /api/stac/xxx # f.ex. /metrics, /checker, /api/stac/{healthcheck}, /api/stac/get-token if", "settings.STAC_BASE STAC_BASE_V = settings.STAC_BASE_V class CacheHeadersMiddleware: '''Middleware that adds appropriate" ]
[ "SingleStageDetector from ...registry import DETECTORS from ...builder import build_detector @DETECTORS.register_module", "from ...registry import DETECTORS from ...builder import build_detector @DETECTORS.register_module class", "import SingleStageDetector from ...registry import DETECTORS from ...builder import build_detector", "neck=None, bbox_head=None, train_cfg=None, test_cfg=None, pretrained=None): super(KDSingleStageDetector, self).__init__(backbone, neck=neck, bbox_head=bbox_head, train_cfg=train_cfg,", "= self.teacher_detector.neck(t_backbone_feats) if self.train_cfg.teacher.neck_at: t_feats += t_neck_feats t_outs = self.teacher_detector.bbox_head(t_neck_feats)", "gt_bboxes_ignore=None, beta=1000.): feats = () backbone_feats = self.backbone(img) if self.train_cfg.teacher.backbone_at:", "t_neck_feats t_outs = self.teacher_detector.bbox_head(t_neck_feats) else: t_outs = self.teacher_detector.bbox_head(t_backbone_feats) loss_inputs =", "if self.train_cfg.teacher.backbone_at: for i in self.train_cfg.teacher.backbone_at_idxes: feats += (backbone_feats[i],) if", "(t_feats,) + t_outs + (gt_bboxes, gt_labels, img_metas, self.train_cfg) losses =", "test_cfg=test_cfg) load_checkpoint(self.teacher_detector, teacher.checkpoint) self.teacher_detector.eval() self.beta = train_cfg.teacher.beta def forward_train(self, img,", "train_cfg=None, test_cfg=None, pretrained=None): super(KDSingleStageDetector, self).__init__(backbone, neck=neck, bbox_head=bbox_head, train_cfg=train_cfg, test_cfg=test_cfg, pretrained=pretrained)", "outs + (t_feats,) + t_outs + (gt_bboxes, gt_labels, img_metas, self.train_cfg)", "= self.teacher_detector.bbox_head(t_backbone_feats) loss_inputs = (feats,) + outs + (t_feats,) +", "mmcv.runner import load_checkpoint from ..base import BaseDetector from ..single_stage import", "from mmcv.runner import load_checkpoint from ..base import BaseDetector from ..single_stage", "neck_feats outs = self.bbox_head(neck_feats) else: outs = self.bbox_head(backbone_feats) with torch.no_grad():", "t_neck_feats = self.teacher_detector.neck(t_backbone_feats) if self.train_cfg.teacher.neck_at: t_feats += t_neck_feats t_outs =", "self.neck(backbone_feats) if self.train_cfg.teacher.neck_at: feats += neck_feats outs = self.bbox_head(neck_feats) else:", "beta=1000.): feats = () backbone_feats = self.backbone(img) if self.train_cfg.teacher.backbone_at: for", "if self.train_cfg.teacher.neck_at: feats += neck_feats outs = self.bbox_head(neck_feats) else: outs", "...registry import DETECTORS from ...builder import build_detector @DETECTORS.register_module class KDSingleStageDetector(SingleStageDetector):", "t_feats += (t_backbone_feats[i],) if self.with_neck: t_neck_feats = self.teacher_detector.neck(t_backbone_feats) if self.train_cfg.teacher.neck_at:", "(t_backbone_feats[i],) if self.with_neck: t_neck_feats = self.teacher_detector.neck(t_backbone_feats) if self.train_cfg.teacher.neck_at: t_feats +=", "self.teacher_detector.backbone(img) if self.train_cfg.teacher.backbone_at: for i in self.train_cfg.teacher.backbone_at_idxes: t_feats += (t_backbone_feats[i],)", "neck=neck, bbox_head=bbox_head, train_cfg=train_cfg, test_cfg=test_cfg, pretrained=pretrained) self.teacher_detector = build_detector(teacher.model, train_cfg=None, test_cfg=test_cfg)", "t_outs = self.teacher_detector.bbox_head(t_neck_feats) else: t_outs = self.teacher_detector.bbox_head(t_backbone_feats) loss_inputs = (feats,)", "torch from mmcv.runner import load_checkpoint from ..base import BaseDetector from", "i in self.train_cfg.teacher.backbone_at_idxes: feats += (backbone_feats[i],) if self.with_neck: neck_feats =", "+= neck_feats outs = self.bbox_head(neck_feats) else: outs = self.bbox_head(backbone_feats) with", "self.train_cfg.teacher.backbone_at: for i in self.train_cfg.teacher.backbone_at_idxes: feats += (backbone_feats[i],) if self.with_neck:", "train_cfg=None, test_cfg=test_cfg) load_checkpoint(self.teacher_detector, teacher.checkpoint) self.teacher_detector.eval() self.beta = train_cfg.teacher.beta def forward_train(self,", "= build_detector(teacher.model, train_cfg=None, test_cfg=test_cfg) load_checkpoint(self.teacher_detector, teacher.checkpoint) self.teacher_detector.eval() self.beta = train_cfg.teacher.beta", "class KDSingleStageDetector(SingleStageDetector): def __init__(self, backbone, teacher, neck=None, bbox_head=None, train_cfg=None, test_cfg=None,", "(gt_bboxes, gt_labels, img_metas, self.train_cfg) losses = self.bbox_head.loss( *loss_inputs, gt_bboxes_ignore=gt_bboxes_ignore) return", "import torch from mmcv.runner import load_checkpoint from ..base import BaseDetector", "bbox_head=None, train_cfg=None, test_cfg=None, pretrained=None): super(KDSingleStageDetector, self).__init__(backbone, neck=neck, bbox_head=bbox_head, train_cfg=train_cfg, test_cfg=test_cfg,", "self).__init__(backbone, neck=neck, bbox_head=bbox_head, train_cfg=train_cfg, test_cfg=test_cfg, pretrained=pretrained) self.teacher_detector = build_detector(teacher.model, train_cfg=None,", "(backbone_feats[i],) if self.with_neck: neck_feats = self.neck(backbone_feats) if self.train_cfg.teacher.neck_at: feats +=", "from ..base import BaseDetector from ..single_stage import SingleStageDetector from ...registry", "self.with_neck: neck_feats = self.neck(backbone_feats) if self.train_cfg.teacher.neck_at: feats += neck_feats outs", "DETECTORS from ...builder import build_detector @DETECTORS.register_module class KDSingleStageDetector(SingleStageDetector): def __init__(self,", "self.bbox_head(neck_feats) else: outs = self.bbox_head(backbone_feats) with torch.no_grad(): t_feats = ()", "import build_detector @DETECTORS.register_module class KDSingleStageDetector(SingleStageDetector): def __init__(self, backbone, teacher, neck=None,", "backbone_feats = self.backbone(img) if self.train_cfg.teacher.backbone_at: for i in self.train_cfg.teacher.backbone_at_idxes: feats", "self.teacher_detector.bbox_head(t_neck_feats) else: t_outs = self.teacher_detector.bbox_head(t_backbone_feats) loss_inputs = (feats,) + outs", "KDSingleStageDetector(SingleStageDetector): def __init__(self, backbone, teacher, neck=None, bbox_head=None, train_cfg=None, test_cfg=None, pretrained=None):", "load_checkpoint from ..base import BaseDetector from ..single_stage import SingleStageDetector from", "gt_labels, img_metas, self.train_cfg) losses = self.bbox_head.loss( *loss_inputs, gt_bboxes_ignore=gt_bboxes_ignore) return losses", "torch.no_grad(): t_feats = () t_backbone_feats = self.teacher_detector.backbone(img) if self.train_cfg.teacher.backbone_at: for", "t_feats = () t_backbone_feats = self.teacher_detector.backbone(img) if self.train_cfg.teacher.backbone_at: for i", "teacher, neck=None, bbox_head=None, train_cfg=None, test_cfg=None, pretrained=None): super(KDSingleStageDetector, self).__init__(backbone, neck=neck, bbox_head=bbox_head,", "t_outs = self.teacher_detector.bbox_head(t_backbone_feats) loss_inputs = (feats,) + outs + (t_feats,)", "from ...builder import build_detector @DETECTORS.register_module class KDSingleStageDetector(SingleStageDetector): def __init__(self, backbone,", "+ t_outs + (gt_bboxes, gt_labels, img_metas, self.train_cfg) losses = self.bbox_head.loss(", "= self.neck(backbone_feats) if self.train_cfg.teacher.neck_at: feats += neck_feats outs = self.bbox_head(neck_feats)", "t_outs + (gt_bboxes, gt_labels, img_metas, self.train_cfg) losses = self.bbox_head.loss( *loss_inputs,", "if self.with_neck: neck_feats = self.neck(backbone_feats) if self.train_cfg.teacher.neck_at: feats += neck_feats", "outs = self.bbox_head(backbone_feats) with torch.no_grad(): t_feats = () t_backbone_feats =", "test_cfg=None, pretrained=None): super(KDSingleStageDetector, self).__init__(backbone, neck=neck, bbox_head=bbox_head, train_cfg=train_cfg, test_cfg=test_cfg, pretrained=pretrained) self.teacher_detector", "pretrained=pretrained) self.teacher_detector = build_detector(teacher.model, train_cfg=None, test_cfg=test_cfg) load_checkpoint(self.teacher_detector, teacher.checkpoint) self.teacher_detector.eval() self.beta", "import load_checkpoint from ..base import BaseDetector from ..single_stage import SingleStageDetector", "outs = self.bbox_head(neck_feats) else: outs = self.bbox_head(backbone_feats) with torch.no_grad(): t_feats", "..base import BaseDetector from ..single_stage import SingleStageDetector from ...registry import", "img, img_metas, gt_bboxes, gt_labels, gt_bboxes_ignore=None, beta=1000.): feats = () backbone_feats", "in self.train_cfg.teacher.backbone_at_idxes: t_feats += (t_backbone_feats[i],) if self.with_neck: t_neck_feats = self.teacher_detector.neck(t_backbone_feats)", "import BaseDetector from ..single_stage import SingleStageDetector from ...registry import DETECTORS", "author huangchuanhong import torch from mmcv.runner import load_checkpoint from ..base", "= train_cfg.teacher.beta def forward_train(self, img, img_metas, gt_bboxes, gt_labels, gt_bboxes_ignore=None, beta=1000.):", "feats += (backbone_feats[i],) if self.with_neck: neck_feats = self.neck(backbone_feats) if self.train_cfg.teacher.neck_at:", "if self.train_cfg.teacher.backbone_at: for i in self.train_cfg.teacher.backbone_at_idxes: t_feats += (t_backbone_feats[i],) if", "self.bbox_head(backbone_feats) with torch.no_grad(): t_feats = () t_backbone_feats = self.teacher_detector.backbone(img) if", "bbox_head=bbox_head, train_cfg=train_cfg, test_cfg=test_cfg, pretrained=pretrained) self.teacher_detector = build_detector(teacher.model, train_cfg=None, test_cfg=test_cfg) load_checkpoint(self.teacher_detector,", "else: t_outs = self.teacher_detector.bbox_head(t_backbone_feats) loss_inputs = (feats,) + outs +", "+ (t_feats,) + t_outs + (gt_bboxes, gt_labels, img_metas, self.train_cfg) losses", "img_metas, gt_bboxes, gt_labels, gt_bboxes_ignore=None, beta=1000.): feats = () backbone_feats =", "__init__(self, backbone, teacher, neck=None, bbox_head=None, train_cfg=None, test_cfg=None, pretrained=None): super(KDSingleStageDetector, self).__init__(backbone,", "gt_bboxes, gt_labels, gt_bboxes_ignore=None, beta=1000.): feats = () backbone_feats = self.backbone(img)", "load_checkpoint(self.teacher_detector, teacher.checkpoint) self.teacher_detector.eval() self.beta = train_cfg.teacher.beta def forward_train(self, img, img_metas,", "huangchuanhong import torch from mmcv.runner import load_checkpoint from ..base import", "if self.with_neck: t_neck_feats = self.teacher_detector.neck(t_backbone_feats) if self.train_cfg.teacher.neck_at: t_feats += t_neck_feats", "self.teacher_detector.eval() self.beta = train_cfg.teacher.beta def forward_train(self, img, img_metas, gt_bboxes, gt_labels,", "() backbone_feats = self.backbone(img) if self.train_cfg.teacher.backbone_at: for i in self.train_cfg.teacher.backbone_at_idxes:", "forward_train(self, img, img_metas, gt_bboxes, gt_labels, gt_bboxes_ignore=None, beta=1000.): feats = ()", "(feats,) + outs + (t_feats,) + t_outs + (gt_bboxes, gt_labels,", "= self.bbox_head(neck_feats) else: outs = self.bbox_head(backbone_feats) with torch.no_grad(): t_feats =", "<filename>mmdet/models/detectors/knowledge_distilling/kd_single_stage.py # author huangchuanhong import torch from mmcv.runner import load_checkpoint", "self.train_cfg.teacher.backbone_at_idxes: feats += (backbone_feats[i],) if self.with_neck: neck_feats = self.neck(backbone_feats) if", "self.train_cfg.teacher.neck_at: t_feats += t_neck_feats t_outs = self.teacher_detector.bbox_head(t_neck_feats) else: t_outs =", "feats = () backbone_feats = self.backbone(img) if self.train_cfg.teacher.backbone_at: for i", "self.beta = train_cfg.teacher.beta def forward_train(self, img, img_metas, gt_bboxes, gt_labels, gt_bboxes_ignore=None,", "build_detector @DETECTORS.register_module class KDSingleStageDetector(SingleStageDetector): def __init__(self, backbone, teacher, neck=None, bbox_head=None,", "train_cfg=train_cfg, test_cfg=test_cfg, pretrained=pretrained) self.teacher_detector = build_detector(teacher.model, train_cfg=None, test_cfg=test_cfg) load_checkpoint(self.teacher_detector, teacher.checkpoint)", "self.backbone(img) if self.train_cfg.teacher.backbone_at: for i in self.train_cfg.teacher.backbone_at_idxes: feats += (backbone_feats[i],)", "self.train_cfg.teacher.backbone_at_idxes: t_feats += (t_backbone_feats[i],) if self.with_neck: t_neck_feats = self.teacher_detector.neck(t_backbone_feats) if", "+ outs + (t_feats,) + t_outs + (gt_bboxes, gt_labels, img_metas,", "= self.teacher_detector.bbox_head(t_neck_feats) else: t_outs = self.teacher_detector.bbox_head(t_backbone_feats) loss_inputs = (feats,) +", "...builder import build_detector @DETECTORS.register_module class KDSingleStageDetector(SingleStageDetector): def __init__(self, backbone, teacher,", "self.teacher_detector.neck(t_backbone_feats) if self.train_cfg.teacher.neck_at: t_feats += t_neck_feats t_outs = self.teacher_detector.bbox_head(t_neck_feats) else:", "= self.backbone(img) if self.train_cfg.teacher.backbone_at: for i in self.train_cfg.teacher.backbone_at_idxes: feats +=", "build_detector(teacher.model, train_cfg=None, test_cfg=test_cfg) load_checkpoint(self.teacher_detector, teacher.checkpoint) self.teacher_detector.eval() self.beta = train_cfg.teacher.beta def", "self.teacher_detector = build_detector(teacher.model, train_cfg=None, test_cfg=test_cfg) load_checkpoint(self.teacher_detector, teacher.checkpoint) self.teacher_detector.eval() self.beta =", "self.train_cfg.teacher.backbone_at: for i in self.train_cfg.teacher.backbone_at_idxes: t_feats += (t_backbone_feats[i],) if self.with_neck:", "self.train_cfg.teacher.neck_at: feats += neck_feats outs = self.bbox_head(neck_feats) else: outs =", "super(KDSingleStageDetector, self).__init__(backbone, neck=neck, bbox_head=bbox_head, train_cfg=train_cfg, test_cfg=test_cfg, pretrained=pretrained) self.teacher_detector = build_detector(teacher.model,", "with torch.no_grad(): t_feats = () t_backbone_feats = self.teacher_detector.backbone(img) if self.train_cfg.teacher.backbone_at:", "self.teacher_detector.bbox_head(t_backbone_feats) loss_inputs = (feats,) + outs + (t_feats,) + t_outs", "feats += neck_feats outs = self.bbox_head(neck_feats) else: outs = self.bbox_head(backbone_feats)", "neck_feats = self.neck(backbone_feats) if self.train_cfg.teacher.neck_at: feats += neck_feats outs =", "t_backbone_feats = self.teacher_detector.backbone(img) if self.train_cfg.teacher.backbone_at: for i in self.train_cfg.teacher.backbone_at_idxes: t_feats", "() t_backbone_feats = self.teacher_detector.backbone(img) if self.train_cfg.teacher.backbone_at: for i in self.train_cfg.teacher.backbone_at_idxes:", "+ (gt_bboxes, gt_labels, img_metas, self.train_cfg) losses = self.bbox_head.loss( *loss_inputs, gt_bboxes_ignore=gt_bboxes_ignore)", "if self.train_cfg.teacher.neck_at: t_feats += t_neck_feats t_outs = self.teacher_detector.bbox_head(t_neck_feats) else: t_outs", "t_feats += t_neck_feats t_outs = self.teacher_detector.bbox_head(t_neck_feats) else: t_outs = self.teacher_detector.bbox_head(t_backbone_feats)", "= () t_backbone_feats = self.teacher_detector.backbone(img) if self.train_cfg.teacher.backbone_at: for i in", "+= (t_backbone_feats[i],) if self.with_neck: t_neck_feats = self.teacher_detector.neck(t_backbone_feats) if self.train_cfg.teacher.neck_at: t_feats", "+= t_neck_feats t_outs = self.teacher_detector.bbox_head(t_neck_feats) else: t_outs = self.teacher_detector.bbox_head(t_backbone_feats) loss_inputs", "= (feats,) + outs + (t_feats,) + t_outs + (gt_bboxes,", "self.with_neck: t_neck_feats = self.teacher_detector.neck(t_backbone_feats) if self.train_cfg.teacher.neck_at: t_feats += t_neck_feats t_outs", "gt_labels, gt_bboxes_ignore=None, beta=1000.): feats = () backbone_feats = self.backbone(img) if", "@DETECTORS.register_module class KDSingleStageDetector(SingleStageDetector): def __init__(self, backbone, teacher, neck=None, bbox_head=None, train_cfg=None,", "= self.teacher_detector.backbone(img) if self.train_cfg.teacher.backbone_at: for i in self.train_cfg.teacher.backbone_at_idxes: t_feats +=", "train_cfg.teacher.beta def forward_train(self, img, img_metas, gt_bboxes, gt_labels, gt_bboxes_ignore=None, beta=1000.): feats", "from ..single_stage import SingleStageDetector from ...registry import DETECTORS from ...builder", "+= (backbone_feats[i],) if self.with_neck: neck_feats = self.neck(backbone_feats) if self.train_cfg.teacher.neck_at: feats", "for i in self.train_cfg.teacher.backbone_at_idxes: feats += (backbone_feats[i],) if self.with_neck: neck_feats", "# author huangchuanhong import torch from mmcv.runner import load_checkpoint from", "for i in self.train_cfg.teacher.backbone_at_idxes: t_feats += (t_backbone_feats[i],) if self.with_neck: t_neck_feats", "test_cfg=test_cfg, pretrained=pretrained) self.teacher_detector = build_detector(teacher.model, train_cfg=None, test_cfg=test_cfg) load_checkpoint(self.teacher_detector, teacher.checkpoint) self.teacher_detector.eval()", "BaseDetector from ..single_stage import SingleStageDetector from ...registry import DETECTORS from", "= () backbone_feats = self.backbone(img) if self.train_cfg.teacher.backbone_at: for i in", "i in self.train_cfg.teacher.backbone_at_idxes: t_feats += (t_backbone_feats[i],) if self.with_neck: t_neck_feats =", "loss_inputs = (feats,) + outs + (t_feats,) + t_outs +", "def __init__(self, backbone, teacher, neck=None, bbox_head=None, train_cfg=None, test_cfg=None, pretrained=None): super(KDSingleStageDetector,", "teacher.checkpoint) self.teacher_detector.eval() self.beta = train_cfg.teacher.beta def forward_train(self, img, img_metas, gt_bboxes,", "import DETECTORS from ...builder import build_detector @DETECTORS.register_module class KDSingleStageDetector(SingleStageDetector): def", "def forward_train(self, img, img_metas, gt_bboxes, gt_labels, gt_bboxes_ignore=None, beta=1000.): feats =", "else: outs = self.bbox_head(backbone_feats) with torch.no_grad(): t_feats = () t_backbone_feats", "backbone, teacher, neck=None, bbox_head=None, train_cfg=None, test_cfg=None, pretrained=None): super(KDSingleStageDetector, self).__init__(backbone, neck=neck,", "pretrained=None): super(KDSingleStageDetector, self).__init__(backbone, neck=neck, bbox_head=bbox_head, train_cfg=train_cfg, test_cfg=test_cfg, pretrained=pretrained) self.teacher_detector =", "= self.bbox_head(backbone_feats) with torch.no_grad(): t_feats = () t_backbone_feats = self.teacher_detector.backbone(img)", "..single_stage import SingleStageDetector from ...registry import DETECTORS from ...builder import", "in self.train_cfg.teacher.backbone_at_idxes: feats += (backbone_feats[i],) if self.with_neck: neck_feats = self.neck(backbone_feats)" ]
[ "dial_radius = 0.05 offset *= dial_radius return dial_center + offset", "= np.linalg.norm(target_to_obj_init) in_place = reward_utils.tolerance( target_to_obj, bounds=(0, self.TARGET_RADIUS), margin=abs(target_to_obj_init -", "= reward_utils.tolerance( target_to_obj, bounds=(0, self.TARGET_RADIUS), margin=abs(target_to_obj_init - self.TARGET_RADIUS), sigmoid='long_tail', )", "= self.get_body_com('dial').copy() dial_angle_rad = self.data.get_joint_qpos('knob_Joint_1') offset = np.array([ np.sin(dial_angle_rad), -np.cos(dial_angle_rad),", "return self.sim.data.get_body_xquat('dial') def reset_model(self): self._reset_hand() self._target_pos = self.goal.copy() self.obj_init_pos =", "self.TARGET_RADIUS), 'near_object': float(tcp_to_obj <= 0.01), 'grasp_success': 1., 'grasp_reward': object_grasped, 'in_place_reward':", "= self.init_config['obj_init_pos'] self.prev_obs = self._get_curr_obs_combined_no_goal() if self.random_init: goal_pos = self._get_state_rand_vec()", "final_pos = goal_pos.copy() + np.array([0, 0.03, 0.03]) self._target_pos = final_pos", "self._target_pos.copy() target_to_obj = (obj - target) target_to_obj = np.linalg.norm(target_to_obj) target_to_obj_init", "reward_utils.tolerance( target_to_obj, bounds=(0, self.TARGET_RADIUS), margin=abs(target_to_obj_init - self.TARGET_RADIUS), sigmoid='long_tail', ) dial_reach_radius", "min(max(0, action[-1]), 1) reach = reward_utils.hamacher_product(reach, gripper_closed) tcp_opened = 0", "gripper_closed) tcp_opened = 0 object_grasped = reach reward = 10", "= (0.1, 0.8, 0.0) goal_low = (-0.1, 0.73, 0.0299) goal_high", "+ np.array([0, 0.03, 0.03]) self._target_pos = final_pos self.sim.model.body_pos[self.model.body_name2id('dial')] = self.obj_init_pos", "- target) target_to_obj_init = np.linalg.norm(target_to_obj_init) in_place = reward_utils.tolerance( target_to_obj, bounds=(0,", "reward_utils.tolerance( tcp_to_obj, bounds=(0, dial_reach_radius), margin=abs(tcp_to_obj_init-dial_reach_radius), sigmoid='gaussian', ) gripper_closed = min(max(0,", "import Box from metaworld.envs import reward_utils from metaworld.envs.asset_path_utils import full_v2_path_for", "= (0.1, 0.83, 0.0301) super().__init__( self.model_name, hand_low=hand_low, hand_high=hand_high, ) self.init_config", "= self.obj_init_pos self.dial_push_position = self._get_pos_objects() + np.array([0.05, 0.02, 0.09]) return", ") dial_reach_radius = 0.005 tcp_to_obj = np.linalg.norm(dial_push_position - tcp) tcp_to_obj_init", "-np.cos(dial_angle_rad), 0 ]) dial_radius = 0.05 offset *= dial_radius return", "gripper_closed = min(max(0, action[-1]), 1) reach = reward_utils.hamacher_product(reach, gripper_closed) tcp_opened", "metaworld.envs.asset_path_utils import full_v2_path_for from metaworld.envs.mujoco.sawyer_xyz.sawyer_xyz_env import SawyerXYZEnv, _assert_task_is_set class SawyerDialTurnEnvV2(SawyerXYZEnv):", "return self._get_obs() def compute_reward(self, action, obs): obj = self._get_pos_objects() dial_push_position", "self._get_pos_objects() dial_push_position = self._get_pos_objects() + np.array([0.05, 0.02, 0.09]) tcp =", "(-0.5, 0.40, 0.05) hand_high = (0.5, 1, 0.5) obj_low =", "bounds=(0, dial_reach_radius), margin=abs(tcp_to_obj_init-dial_reach_radius), sigmoid='gaussian', ) gripper_closed = min(max(0, action[-1]), 1)", "np.array([0, 0.03, 0.03]) self._target_pos = final_pos self.sim.model.body_pos[self.model.body_name2id('dial')] = self.obj_init_pos self.dial_push_position", "= (obj - target) target_to_obj = np.linalg.norm(target_to_obj) target_to_obj_init = (self.dial_push_position", "metaworld.envs import reward_utils from metaworld.envs.asset_path_utils import full_v2_path_for from metaworld.envs.mujoco.sawyer_xyz.sawyer_xyz_env import", "= (0.5, 1, 0.5) obj_low = (-0.1, 0.7, 0.0) obj_high", "full_v2_path_for from metaworld.envs.mujoco.sawyer_xyz.sawyer_xyz_env import SawyerXYZEnv, _assert_task_is_set class SawyerDialTurnEnvV2(SawyerXYZEnv): TARGET_RADIUS =", "offset def _get_quat_objects(self): return self.sim.data.get_body_xquat('dial') def reset_model(self): self._reset_hand() self._target_pos =", "self._get_pos_objects() + np.array([0.05, 0.02, 0.09]) tcp = self.tcp_center target =", "_get_quat_objects(self): return self.sim.data.get_body_xquat('dial') def reset_model(self): self._reset_hand() self._target_pos = self.goal.copy() self.obj_init_pos", "0.05 offset *= dial_radius return dial_center + offset def _get_quat_objects(self):", "target_to_obj, 'unscaled_reward': reward, } return reward, info def _get_pos_objects(self): dial_center", "- self.init_tcp) reach = reward_utils.tolerance( tcp_to_obj, bounds=(0, dial_reach_radius), margin=abs(tcp_to_obj_init-dial_reach_radius), sigmoid='gaussian',", "10 * reward_utils.hamacher_product(reach, in_place) return (reward, tcp_to_obj, tcp_opened, target_to_obj, object_grasped,", "info = { 'success': float(target_to_obj <= self.TARGET_RADIUS), 'near_object': float(tcp_to_obj <=", "= Box( np.array(obj_low), np.array(obj_high), ) self.goal_space = Box(np.array(goal_low), np.array(goal_high)) @property", "]) dial_radius = 0.05 offset *= dial_radius return dial_center +", "0.0) obj_high = (0.1, 0.8, 0.0) goal_low = (-0.1, 0.73,", "0.2], dtype=np.float32), } self.goal = np.array([0., 0.73, 0.08]) self.obj_init_pos =", "0.0299) goal_high = (0.1, 0.83, 0.0301) super().__init__( self.model_name, hand_low=hand_low, hand_high=hand_high,", "obs, action): (reward, tcp_to_obj, _, target_to_obj, object_grasped, in_place) = self.compute_reward(action,", "<= self.TARGET_RADIUS), 'near_object': float(tcp_to_obj <= 0.01), 'grasp_success': 1., 'grasp_reward': object_grasped,", "'grasp_success': 1., 'grasp_reward': object_grasped, 'in_place_reward': in_place, 'obj_to_target': target_to_obj, 'unscaled_reward': reward,", "hand_low=hand_low, hand_high=hand_high, ) self.init_config = { 'obj_init_pos': np.array([0, 0.7, 0.0]),", "np.linalg.norm(dial_push_position - tcp) tcp_to_obj_init = np.linalg.norm(self.dial_push_position - self.init_tcp) reach =", "{ 'obj_init_pos': np.array([0, 0.7, 0.0]), 'hand_init_pos': np.array([0, 0.6, 0.2], dtype=np.float32),", "= (-0.5, 0.40, 0.05) hand_high = (0.5, 1, 0.5) obj_low", "(obj - target) target_to_obj = np.linalg.norm(target_to_obj) target_to_obj_init = (self.dial_push_position -", "reward = 10 * reward_utils.hamacher_product(reach, in_place) return (reward, tcp_to_obj, tcp_opened,", "self.prev_obs = self._get_curr_obs_combined_no_goal() if self.random_init: goal_pos = self._get_state_rand_vec() self.obj_init_pos =", "dial_reach_radius = 0.005 tcp_to_obj = np.linalg.norm(dial_push_position - tcp) tcp_to_obj_init =", "(0.1, 0.83, 0.0301) super().__init__( self.model_name, hand_low=hand_low, hand_high=hand_high, ) self.init_config =", "= 0.05 offset *= dial_radius return dial_center + offset def", "reach = reward_utils.tolerance( tcp_to_obj, bounds=(0, dial_reach_radius), margin=abs(tcp_to_obj_init-dial_reach_radius), sigmoid='gaussian', ) gripper_closed", "'grasp_reward': object_grasped, 'in_place_reward': in_place, 'obj_to_target': target_to_obj, 'unscaled_reward': reward, } return", "= goal_pos[:3] final_pos = goal_pos.copy() + np.array([0, 0.03, 0.03]) self._target_pos", "as np from gym.spaces import Box from metaworld.envs import reward_utils", "np.array([0., 0.73, 0.08]) self.obj_init_pos = self.init_config['obj_init_pos'] self.hand_init_pos = self.init_config['hand_init_pos'] self._random_reset_space", "in_place, 'obj_to_target': target_to_obj, 'unscaled_reward': reward, } return reward, info def", "self.obj_init_pos self.dial_push_position = self._get_pos_objects() + np.array([0.05, 0.02, 0.09]) return self._get_obs()", "<gh_stars>100-1000 import numpy as np from gym.spaces import Box from", "0.02, 0.09]) return self._get_obs() def compute_reward(self, action, obs): obj =", "np.array(goal_high)) @property def model_name(self): return full_v2_path_for('sawyer_xyz/sawyer_dial.xml') @_assert_task_is_set def evaluate_state(self, obs,", "TARGET_RADIUS = 0.07 def __init__(self): hand_low = (-0.5, 0.40, 0.05)", "self.random_init: goal_pos = self._get_state_rand_vec() self.obj_init_pos = goal_pos[:3] final_pos = goal_pos.copy()", "target) target_to_obj = np.linalg.norm(target_to_obj) target_to_obj_init = (self.dial_push_position - target) target_to_obj_init", "obj_high = (0.1, 0.8, 0.0) goal_low = (-0.1, 0.73, 0.0299)", "info def _get_pos_objects(self): dial_center = self.get_body_com('dial').copy() dial_angle_rad = self.data.get_joint_qpos('knob_Joint_1') offset", "= np.linalg.norm(self.dial_push_position - self.init_tcp) reach = reward_utils.tolerance( tcp_to_obj, bounds=(0, dial_reach_radius),", "from metaworld.envs.asset_path_utils import full_v2_path_for from metaworld.envs.mujoco.sawyer_xyz.sawyer_xyz_env import SawyerXYZEnv, _assert_task_is_set class", ") self.init_config = { 'obj_init_pos': np.array([0, 0.7, 0.0]), 'hand_init_pos': np.array([0,", "import reward_utils from metaworld.envs.asset_path_utils import full_v2_path_for from metaworld.envs.mujoco.sawyer_xyz.sawyer_xyz_env import SawyerXYZEnv,", "tcp_to_obj_init = np.linalg.norm(self.dial_push_position - self.init_tcp) reach = reward_utils.tolerance( tcp_to_obj, bounds=(0,", "sigmoid='gaussian', ) gripper_closed = min(max(0, action[-1]), 1) reach = reward_utils.hamacher_product(reach,", "reward_utils from metaworld.envs.asset_path_utils import full_v2_path_for from metaworld.envs.mujoco.sawyer_xyz.sawyer_xyz_env import SawyerXYZEnv, _assert_task_is_set", "0.03, 0.03]) self._target_pos = final_pos self.sim.model.body_pos[self.model.body_name2id('dial')] = self.obj_init_pos self.dial_push_position =", "'near_object': float(tcp_to_obj <= 0.01), 'grasp_success': 1., 'grasp_reward': object_grasped, 'in_place_reward': in_place,", "self.obj_init_pos = self.init_config['obj_init_pos'] self.hand_init_pos = self.init_config['hand_init_pos'] self._random_reset_space = Box( np.array(obj_low),", "'hand_init_pos': np.array([0, 0.6, 0.2], dtype=np.float32), } self.goal = np.array([0., 0.73,", "np from gym.spaces import Box from metaworld.envs import reward_utils from", "gym.spaces import Box from metaworld.envs import reward_utils from metaworld.envs.asset_path_utils import", "SawyerDialTurnEnvV2(SawyerXYZEnv): TARGET_RADIUS = 0.07 def __init__(self): hand_low = (-0.5, 0.40,", "margin=abs(target_to_obj_init - self.TARGET_RADIUS), sigmoid='long_tail', ) dial_reach_radius = 0.005 tcp_to_obj =", "np.linalg.norm(self.dial_push_position - self.init_tcp) reach = reward_utils.tolerance( tcp_to_obj, bounds=(0, dial_reach_radius), margin=abs(tcp_to_obj_init-dial_reach_radius),", "(0.1, 0.8, 0.0) goal_low = (-0.1, 0.73, 0.0299) goal_high =", "self.sim.model.body_pos[self.model.body_name2id('dial')] = self.obj_init_pos self.dial_push_position = self._get_pos_objects() + np.array([0.05, 0.02, 0.09])", "0.09]) tcp = self.tcp_center target = self._target_pos.copy() target_to_obj = (obj", "0.0301) super().__init__( self.model_name, hand_low=hand_low, hand_high=hand_high, ) self.init_config = { 'obj_init_pos':", "'obj_init_pos': np.array([0, 0.7, 0.0]), 'hand_init_pos': np.array([0, 0.6, 0.2], dtype=np.float32), }", "np.array([0, 0.7, 0.0]), 'hand_init_pos': np.array([0, 0.6, 0.2], dtype=np.float32), } self.goal", "obs): obj = self._get_pos_objects() dial_push_position = self._get_pos_objects() + np.array([0.05, 0.02,", "def __init__(self): hand_low = (-0.5, 0.40, 0.05) hand_high = (0.5,", "'unscaled_reward': reward, } return reward, info def _get_pos_objects(self): dial_center =", "target_to_obj, object_grasped, in_place) = self.compute_reward(action, obs) info = { 'success':", "= reach reward = 10 * reward_utils.hamacher_product(reach, in_place) return (reward,", "(self.dial_push_position - target) target_to_obj_init = np.linalg.norm(target_to_obj_init) in_place = reward_utils.tolerance( target_to_obj,", "= self.init_config['hand_init_pos'] self._random_reset_space = Box( np.array(obj_low), np.array(obj_high), ) self.goal_space =", "dial_radius return dial_center + offset def _get_quat_objects(self): return self.sim.data.get_body_xquat('dial') def", "'success': float(target_to_obj <= self.TARGET_RADIUS), 'near_object': float(tcp_to_obj <= 0.01), 'grasp_success': 1.,", "sigmoid='long_tail', ) dial_reach_radius = 0.005 tcp_to_obj = np.linalg.norm(dial_push_position - tcp)", "0.03]) self._target_pos = final_pos self.sim.model.body_pos[self.model.body_name2id('dial')] = self.obj_init_pos self.dial_push_position = self._get_pos_objects()", "= np.linalg.norm(dial_push_position - tcp) tcp_to_obj_init = np.linalg.norm(self.dial_push_position - self.init_tcp) reach", "obj_low = (-0.1, 0.7, 0.0) obj_high = (0.1, 0.8, 0.0)", "dtype=np.float32), } self.goal = np.array([0., 0.73, 0.08]) self.obj_init_pos = self.init_config['obj_init_pos']", "Box(np.array(goal_low), np.array(goal_high)) @property def model_name(self): return full_v2_path_for('sawyer_xyz/sawyer_dial.xml') @_assert_task_is_set def evaluate_state(self,", "target_to_obj, bounds=(0, self.TARGET_RADIUS), margin=abs(target_to_obj_init - self.TARGET_RADIUS), sigmoid='long_tail', ) dial_reach_radius =", "+ offset def _get_quat_objects(self): return self.sim.data.get_body_xquat('dial') def reset_model(self): self._reset_hand() self._target_pos", "self.goal_space = Box(np.array(goal_low), np.array(goal_high)) @property def model_name(self): return full_v2_path_for('sawyer_xyz/sawyer_dial.xml') @_assert_task_is_set", "action, obs): obj = self._get_pos_objects() dial_push_position = self._get_pos_objects() + np.array([0.05,", "0.8, 0.0) goal_low = (-0.1, 0.73, 0.0299) goal_high = (0.1,", "= goal_pos.copy() + np.array([0, 0.03, 0.03]) self._target_pos = final_pos self.sim.model.body_pos[self.model.body_name2id('dial')]", "from metaworld.envs import reward_utils from metaworld.envs.asset_path_utils import full_v2_path_for from metaworld.envs.mujoco.sawyer_xyz.sawyer_xyz_env", "bounds=(0, self.TARGET_RADIUS), margin=abs(target_to_obj_init - self.TARGET_RADIUS), sigmoid='long_tail', ) dial_reach_radius = 0.005", "def reset_model(self): self._reset_hand() self._target_pos = self.goal.copy() self.obj_init_pos = self.init_config['obj_init_pos'] self.prev_obs", "= (-0.1, 0.73, 0.0299) goal_high = (0.1, 0.83, 0.0301) super().__init__(", "np.linalg.norm(target_to_obj_init) in_place = reward_utils.tolerance( target_to_obj, bounds=(0, self.TARGET_RADIUS), margin=abs(target_to_obj_init - self.TARGET_RADIUS),", "offset = np.array([ np.sin(dial_angle_rad), -np.cos(dial_angle_rad), 0 ]) dial_radius = 0.05", "0.73, 0.0299) goal_high = (0.1, 0.83, 0.0301) super().__init__( self.model_name, hand_low=hand_low,", "} self.goal = np.array([0., 0.73, 0.08]) self.obj_init_pos = self.init_config['obj_init_pos'] self.hand_init_pos", "0.02, 0.09]) tcp = self.tcp_center target = self._target_pos.copy() target_to_obj =", "1) reach = reward_utils.hamacher_product(reach, gripper_closed) tcp_opened = 0 object_grasped =", "0.08]) self.obj_init_pos = self.init_config['obj_init_pos'] self.hand_init_pos = self.init_config['hand_init_pos'] self._random_reset_space = Box(", "np.array(obj_low), np.array(obj_high), ) self.goal_space = Box(np.array(goal_low), np.array(goal_high)) @property def model_name(self):", "@property def model_name(self): return full_v2_path_for('sawyer_xyz/sawyer_dial.xml') @_assert_task_is_set def evaluate_state(self, obs, action):", "self.TARGET_RADIUS), sigmoid='long_tail', ) dial_reach_radius = 0.005 tcp_to_obj = np.linalg.norm(dial_push_position -", "0.83, 0.0301) super().__init__( self.model_name, hand_low=hand_low, hand_high=hand_high, ) self.init_config = {", "self._get_curr_obs_combined_no_goal() if self.random_init: goal_pos = self._get_state_rand_vec() self.obj_init_pos = goal_pos[:3] final_pos", "= reward_utils.tolerance( tcp_to_obj, bounds=(0, dial_reach_radius), margin=abs(tcp_to_obj_init-dial_reach_radius), sigmoid='gaussian', ) gripper_closed =", "0.01), 'grasp_success': 1., 'grasp_reward': object_grasped, 'in_place_reward': in_place, 'obj_to_target': target_to_obj, 'unscaled_reward':", "hand_high = (0.5, 1, 0.5) obj_low = (-0.1, 0.7, 0.0)", "* reward_utils.hamacher_product(reach, in_place) return (reward, tcp_to_obj, tcp_opened, target_to_obj, object_grasped, in_place)", ") self.goal_space = Box(np.array(goal_low), np.array(goal_high)) @property def model_name(self): return full_v2_path_for('sawyer_xyz/sawyer_dial.xml')", "0.7, 0.0]), 'hand_init_pos': np.array([0, 0.6, 0.2], dtype=np.float32), } self.goal =", "self.init_config['obj_init_pos'] self.hand_init_pos = self.init_config['hand_init_pos'] self._random_reset_space = Box( np.array(obj_low), np.array(obj_high), )", "= self.tcp_center target = self._target_pos.copy() target_to_obj = (obj - target)", "obs) info = { 'success': float(target_to_obj <= self.TARGET_RADIUS), 'near_object': float(tcp_to_obj", "= self._get_state_rand_vec() self.obj_init_pos = goal_pos[:3] final_pos = goal_pos.copy() + np.array([0,", "tcp_opened = 0 object_grasped = reach reward = 10 *", "0.05) hand_high = (0.5, 1, 0.5) obj_low = (-0.1, 0.7,", "(-0.1, 0.73, 0.0299) goal_high = (0.1, 0.83, 0.0301) super().__init__( self.model_name,", "= np.array([ np.sin(dial_angle_rad), -np.cos(dial_angle_rad), 0 ]) dial_radius = 0.05 offset", "self.dial_push_position = self._get_pos_objects() + np.array([0.05, 0.02, 0.09]) return self._get_obs() def", "0.40, 0.05) hand_high = (0.5, 1, 0.5) obj_low = (-0.1,", "in_place = reward_utils.tolerance( target_to_obj, bounds=(0, self.TARGET_RADIUS), margin=abs(target_to_obj_init - self.TARGET_RADIUS), sigmoid='long_tail',", "np.linalg.norm(target_to_obj) target_to_obj_init = (self.dial_push_position - target) target_to_obj_init = np.linalg.norm(target_to_obj_init) in_place", "(reward, tcp_to_obj, _, target_to_obj, object_grasped, in_place) = self.compute_reward(action, obs) info", "metaworld.envs.mujoco.sawyer_xyz.sawyer_xyz_env import SawyerXYZEnv, _assert_task_is_set class SawyerDialTurnEnvV2(SawyerXYZEnv): TARGET_RADIUS = 0.07 def", "self._get_obs() def compute_reward(self, action, obs): obj = self._get_pos_objects() dial_push_position =", "self.init_config['hand_init_pos'] self._random_reset_space = Box( np.array(obj_low), np.array(obj_high), ) self.goal_space = Box(np.array(goal_low),", "= final_pos self.sim.model.body_pos[self.model.body_name2id('dial')] = self.obj_init_pos self.dial_push_position = self._get_pos_objects() + np.array([0.05,", "= self.compute_reward(action, obs) info = { 'success': float(target_to_obj <= self.TARGET_RADIUS),", "target = self._target_pos.copy() target_to_obj = (obj - target) target_to_obj =", "= 10 * reward_utils.hamacher_product(reach, in_place) return (reward, tcp_to_obj, tcp_opened, target_to_obj,", "reach = reward_utils.hamacher_product(reach, gripper_closed) tcp_opened = 0 object_grasped = reach", "1., 'grasp_reward': object_grasped, 'in_place_reward': in_place, 'obj_to_target': target_to_obj, 'unscaled_reward': reward, }", "_get_pos_objects(self): dial_center = self.get_body_com('dial').copy() dial_angle_rad = self.data.get_joint_qpos('knob_Joint_1') offset = np.array([", "self.obj_init_pos = goal_pos[:3] final_pos = goal_pos.copy() + np.array([0, 0.03, 0.03])", "0.0) goal_low = (-0.1, 0.73, 0.0299) goal_high = (0.1, 0.83,", "full_v2_path_for('sawyer_xyz/sawyer_dial.xml') @_assert_task_is_set def evaluate_state(self, obs, action): (reward, tcp_to_obj, _, target_to_obj,", "def compute_reward(self, action, obs): obj = self._get_pos_objects() dial_push_position = self._get_pos_objects()", "target_to_obj = np.linalg.norm(target_to_obj) target_to_obj_init = (self.dial_push_position - target) target_to_obj_init =", "return dial_center + offset def _get_quat_objects(self): return self.sim.data.get_body_xquat('dial') def reset_model(self):", "= self._get_curr_obs_combined_no_goal() if self.random_init: goal_pos = self._get_state_rand_vec() self.obj_init_pos = goal_pos[:3]", "self._get_state_rand_vec() self.obj_init_pos = goal_pos[:3] final_pos = goal_pos.copy() + np.array([0, 0.03,", "= (-0.1, 0.7, 0.0) obj_high = (0.1, 0.8, 0.0) goal_low", "return reward, info def _get_pos_objects(self): dial_center = self.get_body_com('dial').copy() dial_angle_rad =", "goal_high = (0.1, 0.83, 0.0301) super().__init__( self.model_name, hand_low=hand_low, hand_high=hand_high, )", "compute_reward(self, action, obs): obj = self._get_pos_objects() dial_push_position = self._get_pos_objects() +", "SawyerXYZEnv, _assert_task_is_set class SawyerDialTurnEnvV2(SawyerXYZEnv): TARGET_RADIUS = 0.07 def __init__(self): hand_low", "self.model_name, hand_low=hand_low, hand_high=hand_high, ) self.init_config = { 'obj_init_pos': np.array([0, 0.7,", "object_grasped, 'in_place_reward': in_place, 'obj_to_target': target_to_obj, 'unscaled_reward': reward, } return reward,", "self.data.get_joint_qpos('knob_Joint_1') offset = np.array([ np.sin(dial_angle_rad), -np.cos(dial_angle_rad), 0 ]) dial_radius =", "0 ]) dial_radius = 0.05 offset *= dial_radius return dial_center", "= min(max(0, action[-1]), 1) reach = reward_utils.hamacher_product(reach, gripper_closed) tcp_opened =", "reach reward = 10 * reward_utils.hamacher_product(reach, in_place) return (reward, tcp_to_obj,", "self.init_config = { 'obj_init_pos': np.array([0, 0.7, 0.0]), 'hand_init_pos': np.array([0, 0.6,", "self.tcp_center target = self._target_pos.copy() target_to_obj = (obj - target) target_to_obj", "def model_name(self): return full_v2_path_for('sawyer_xyz/sawyer_dial.xml') @_assert_task_is_set def evaluate_state(self, obs, action): (reward,", "target_to_obj_init = (self.dial_push_position - target) target_to_obj_init = np.linalg.norm(target_to_obj_init) in_place =", "0.005 tcp_to_obj = np.linalg.norm(dial_push_position - tcp) tcp_to_obj_init = np.linalg.norm(self.dial_push_position -", "= np.linalg.norm(target_to_obj) target_to_obj_init = (self.dial_push_position - target) target_to_obj_init = np.linalg.norm(target_to_obj_init)", "obj = self._get_pos_objects() dial_push_position = self._get_pos_objects() + np.array([0.05, 0.02, 0.09])", "(0.5, 1, 0.5) obj_low = (-0.1, 0.7, 0.0) obj_high =", "margin=abs(tcp_to_obj_init-dial_reach_radius), sigmoid='gaussian', ) gripper_closed = min(max(0, action[-1]), 1) reach =", "class SawyerDialTurnEnvV2(SawyerXYZEnv): TARGET_RADIUS = 0.07 def __init__(self): hand_low = (-0.5,", "0.07 def __init__(self): hand_low = (-0.5, 0.40, 0.05) hand_high =", "= { 'success': float(target_to_obj <= self.TARGET_RADIUS), 'near_object': float(tcp_to_obj <= 0.01),", "return full_v2_path_for('sawyer_xyz/sawyer_dial.xml') @_assert_task_is_set def evaluate_state(self, obs, action): (reward, tcp_to_obj, _,", "0.73, 0.08]) self.obj_init_pos = self.init_config['obj_init_pos'] self.hand_init_pos = self.init_config['hand_init_pos'] self._random_reset_space =", "= self._get_pos_objects() + np.array([0.05, 0.02, 0.09]) tcp = self.tcp_center target", "numpy as np from gym.spaces import Box from metaworld.envs import", "target_to_obj_init = np.linalg.norm(target_to_obj_init) in_place = reward_utils.tolerance( target_to_obj, bounds=(0, self.TARGET_RADIUS), margin=abs(target_to_obj_init", "import numpy as np from gym.spaces import Box from metaworld.envs", "def _get_quat_objects(self): return self.sim.data.get_body_xquat('dial') def reset_model(self): self._reset_hand() self._target_pos = self.goal.copy()", "action): (reward, tcp_to_obj, _, target_to_obj, object_grasped, in_place) = self.compute_reward(action, obs)", "0.09]) return self._get_obs() def compute_reward(self, action, obs): obj = self._get_pos_objects()", "self.init_tcp) reach = reward_utils.tolerance( tcp_to_obj, bounds=(0, dial_reach_radius), margin=abs(tcp_to_obj_init-dial_reach_radius), sigmoid='gaussian', )", "final_pos self.sim.model.body_pos[self.model.body_name2id('dial')] = self.obj_init_pos self.dial_push_position = self._get_pos_objects() + np.array([0.05, 0.02,", "= self.goal.copy() self.obj_init_pos = self.init_config['obj_init_pos'] self.prev_obs = self._get_curr_obs_combined_no_goal() if self.random_init:", "np.array([0.05, 0.02, 0.09]) tcp = self.tcp_center target = self._target_pos.copy() target_to_obj", "dial_reach_radius), margin=abs(tcp_to_obj_init-dial_reach_radius), sigmoid='gaussian', ) gripper_closed = min(max(0, action[-1]), 1) reach", "= self._target_pos.copy() target_to_obj = (obj - target) target_to_obj = np.linalg.norm(target_to_obj)", "= { 'obj_init_pos': np.array([0, 0.7, 0.0]), 'hand_init_pos': np.array([0, 0.6, 0.2],", "_assert_task_is_set class SawyerDialTurnEnvV2(SawyerXYZEnv): TARGET_RADIUS = 0.07 def __init__(self): hand_low =", "- target) target_to_obj = np.linalg.norm(target_to_obj) target_to_obj_init = (self.dial_push_position - target)", "reset_model(self): self._reset_hand() self._target_pos = self.goal.copy() self.obj_init_pos = self.init_config['obj_init_pos'] self.prev_obs =", "= self.init_config['obj_init_pos'] self.hand_init_pos = self.init_config['hand_init_pos'] self._random_reset_space = Box( np.array(obj_low), np.array(obj_high),", "tcp = self.tcp_center target = self._target_pos.copy() target_to_obj = (obj -", "= reward_utils.hamacher_product(reach, gripper_closed) tcp_opened = 0 object_grasped = reach reward", "self._target_pos = final_pos self.sim.model.body_pos[self.model.body_name2id('dial')] = self.obj_init_pos self.dial_push_position = self._get_pos_objects() +", "0.7, 0.0) obj_high = (0.1, 0.8, 0.0) goal_low = (-0.1,", "model_name(self): return full_v2_path_for('sawyer_xyz/sawyer_dial.xml') @_assert_task_is_set def evaluate_state(self, obs, action): (reward, tcp_to_obj,", "target) target_to_obj_init = np.linalg.norm(target_to_obj_init) in_place = reward_utils.tolerance( target_to_obj, bounds=(0, self.TARGET_RADIUS),", "0.6, 0.2], dtype=np.float32), } self.goal = np.array([0., 0.73, 0.08]) self.obj_init_pos", "self._random_reset_space = Box( np.array(obj_low), np.array(obj_high), ) self.goal_space = Box(np.array(goal_low), np.array(goal_high))", "self.goal.copy() self.obj_init_pos = self.init_config['obj_init_pos'] self.prev_obs = self._get_curr_obs_combined_no_goal() if self.random_init: goal_pos", "target_to_obj = (obj - target) target_to_obj = np.linalg.norm(target_to_obj) target_to_obj_init =", "goal_pos[:3] final_pos = goal_pos.copy() + np.array([0, 0.03, 0.03]) self._target_pos =", "from metaworld.envs.mujoco.sawyer_xyz.sawyer_xyz_env import SawyerXYZEnv, _assert_task_is_set class SawyerDialTurnEnvV2(SawyerXYZEnv): TARGET_RADIUS = 0.07", "from gym.spaces import Box from metaworld.envs import reward_utils from metaworld.envs.asset_path_utils", "np.array([0, 0.6, 0.2], dtype=np.float32), } self.goal = np.array([0., 0.73, 0.08])", "= 0.07 def __init__(self): hand_low = (-0.5, 0.40, 0.05) hand_high", "+ np.array([0.05, 0.02, 0.09]) return self._get_obs() def compute_reward(self, action, obs):", "0.5) obj_low = (-0.1, 0.7, 0.0) obj_high = (0.1, 0.8,", "if self.random_init: goal_pos = self._get_state_rand_vec() self.obj_init_pos = goal_pos[:3] final_pos =", "in_place) = self.compute_reward(action, obs) info = { 'success': float(target_to_obj <=", "goal_low = (-0.1, 0.73, 0.0299) goal_high = (0.1, 0.83, 0.0301)", "def _get_pos_objects(self): dial_center = self.get_body_com('dial').copy() dial_angle_rad = self.data.get_joint_qpos('knob_Joint_1') offset =", "= self.data.get_joint_qpos('knob_Joint_1') offset = np.array([ np.sin(dial_angle_rad), -np.cos(dial_angle_rad), 0 ]) dial_radius", "import full_v2_path_for from metaworld.envs.mujoco.sawyer_xyz.sawyer_xyz_env import SawyerXYZEnv, _assert_task_is_set class SawyerDialTurnEnvV2(SawyerXYZEnv): TARGET_RADIUS", "0.0]), 'hand_init_pos': np.array([0, 0.6, 0.2], dtype=np.float32), } self.goal = np.array([0.,", "self.goal = np.array([0., 0.73, 0.08]) self.obj_init_pos = self.init_config['obj_init_pos'] self.hand_init_pos =", "= self._get_pos_objects() dial_push_position = self._get_pos_objects() + np.array([0.05, 0.02, 0.09]) tcp", "np.array(obj_high), ) self.goal_space = Box(np.array(goal_low), np.array(goal_high)) @property def model_name(self): return", "reward, } return reward, info def _get_pos_objects(self): dial_center = self.get_body_com('dial').copy()", "+ np.array([0.05, 0.02, 0.09]) tcp = self.tcp_center target = self._target_pos.copy()", "- self.TARGET_RADIUS), sigmoid='long_tail', ) dial_reach_radius = 0.005 tcp_to_obj = np.linalg.norm(dial_push_position", "hand_low = (-0.5, 0.40, 0.05) hand_high = (0.5, 1, 0.5)", "= (self.dial_push_position - target) target_to_obj_init = np.linalg.norm(target_to_obj_init) in_place = reward_utils.tolerance(", "<= 0.01), 'grasp_success': 1., 'grasp_reward': object_grasped, 'in_place_reward': in_place, 'obj_to_target': target_to_obj,", "tcp_to_obj = np.linalg.norm(dial_push_position - tcp) tcp_to_obj_init = np.linalg.norm(self.dial_push_position - self.init_tcp)", "'obj_to_target': target_to_obj, 'unscaled_reward': reward, } return reward, info def _get_pos_objects(self):", "dial_center = self.get_body_com('dial').copy() dial_angle_rad = self.data.get_joint_qpos('knob_Joint_1') offset = np.array([ np.sin(dial_angle_rad),", "= np.array([0., 0.73, 0.08]) self.obj_init_pos = self.init_config['obj_init_pos'] self.hand_init_pos = self.init_config['hand_init_pos']", "self._get_pos_objects() + np.array([0.05, 0.02, 0.09]) return self._get_obs() def compute_reward(self, action,", "self.init_config['obj_init_pos'] self.prev_obs = self._get_curr_obs_combined_no_goal() if self.random_init: goal_pos = self._get_state_rand_vec() self.obj_init_pos", "np.sin(dial_angle_rad), -np.cos(dial_angle_rad), 0 ]) dial_radius = 0.05 offset *= dial_radius", "_, target_to_obj, object_grasped, in_place) = self.compute_reward(action, obs) info = {", "'in_place_reward': in_place, 'obj_to_target': target_to_obj, 'unscaled_reward': reward, } return reward, info", "import SawyerXYZEnv, _assert_task_is_set class SawyerDialTurnEnvV2(SawyerXYZEnv): TARGET_RADIUS = 0.07 def __init__(self):", "= Box(np.array(goal_low), np.array(goal_high)) @property def model_name(self): return full_v2_path_for('sawyer_xyz/sawyer_dial.xml') @_assert_task_is_set def", "evaluate_state(self, obs, action): (reward, tcp_to_obj, _, target_to_obj, object_grasped, in_place) =", "object_grasped, in_place) = self.compute_reward(action, obs) info = { 'success': float(target_to_obj", "self.compute_reward(action, obs) info = { 'success': float(target_to_obj <= self.TARGET_RADIUS), 'near_object':", "= 0 object_grasped = reach reward = 10 * reward_utils.hamacher_product(reach,", "reward, info def _get_pos_objects(self): dial_center = self.get_body_com('dial').copy() dial_angle_rad = self.data.get_joint_qpos('knob_Joint_1')", "object_grasped = reach reward = 10 * reward_utils.hamacher_product(reach, in_place) return", "float(tcp_to_obj <= 0.01), 'grasp_success': 1., 'grasp_reward': object_grasped, 'in_place_reward': in_place, 'obj_to_target':", "hand_high=hand_high, ) self.init_config = { 'obj_init_pos': np.array([0, 0.7, 0.0]), 'hand_init_pos':", "(-0.1, 0.7, 0.0) obj_high = (0.1, 0.8, 0.0) goal_low =", "dial_angle_rad = self.data.get_joint_qpos('knob_Joint_1') offset = np.array([ np.sin(dial_angle_rad), -np.cos(dial_angle_rad), 0 ])", "@_assert_task_is_set def evaluate_state(self, obs, action): (reward, tcp_to_obj, _, target_to_obj, object_grasped,", "= self._get_pos_objects() + np.array([0.05, 0.02, 0.09]) return self._get_obs() def compute_reward(self,", ") gripper_closed = min(max(0, action[-1]), 1) reach = reward_utils.hamacher_product(reach, gripper_closed)", "action[-1]), 1) reach = reward_utils.hamacher_product(reach, gripper_closed) tcp_opened = 0 object_grasped", "reward_utils.hamacher_product(reach, gripper_closed) tcp_opened = 0 object_grasped = reach reward =", "= 0.005 tcp_to_obj = np.linalg.norm(dial_push_position - tcp) tcp_to_obj_init = np.linalg.norm(self.dial_push_position", "tcp) tcp_to_obj_init = np.linalg.norm(self.dial_push_position - self.init_tcp) reach = reward_utils.tolerance( tcp_to_obj,", "offset *= dial_radius return dial_center + offset def _get_quat_objects(self): return", "float(target_to_obj <= self.TARGET_RADIUS), 'near_object': float(tcp_to_obj <= 0.01), 'grasp_success': 1., 'grasp_reward':", "self.TARGET_RADIUS), margin=abs(target_to_obj_init - self.TARGET_RADIUS), sigmoid='long_tail', ) dial_reach_radius = 0.005 tcp_to_obj", "np.array([ np.sin(dial_angle_rad), -np.cos(dial_angle_rad), 0 ]) dial_radius = 0.05 offset *=", "self.obj_init_pos = self.init_config['obj_init_pos'] self.prev_obs = self._get_curr_obs_combined_no_goal() if self.random_init: goal_pos =", "tcp_to_obj, bounds=(0, dial_reach_radius), margin=abs(tcp_to_obj_init-dial_reach_radius), sigmoid='gaussian', ) gripper_closed = min(max(0, action[-1]),", "np.array([0.05, 0.02, 0.09]) return self._get_obs() def compute_reward(self, action, obs): obj", "} return reward, info def _get_pos_objects(self): dial_center = self.get_body_com('dial').copy() dial_angle_rad", "Box from metaworld.envs import reward_utils from metaworld.envs.asset_path_utils import full_v2_path_for from", "Box( np.array(obj_low), np.array(obj_high), ) self.goal_space = Box(np.array(goal_low), np.array(goal_high)) @property def", "*= dial_radius return dial_center + offset def _get_quat_objects(self): return self.sim.data.get_body_xquat('dial')", "super().__init__( self.model_name, hand_low=hand_low, hand_high=hand_high, ) self.init_config = { 'obj_init_pos': np.array([0,", "{ 'success': float(target_to_obj <= self.TARGET_RADIUS), 'near_object': float(tcp_to_obj <= 0.01), 'grasp_success':", "__init__(self): hand_low = (-0.5, 0.40, 0.05) hand_high = (0.5, 1,", "goal_pos = self._get_state_rand_vec() self.obj_init_pos = goal_pos[:3] final_pos = goal_pos.copy() +", "goal_pos.copy() + np.array([0, 0.03, 0.03]) self._target_pos = final_pos self.sim.model.body_pos[self.model.body_name2id('dial')] =", "self.sim.data.get_body_xquat('dial') def reset_model(self): self._reset_hand() self._target_pos = self.goal.copy() self.obj_init_pos = self.init_config['obj_init_pos']", "self._target_pos = self.goal.copy() self.obj_init_pos = self.init_config['obj_init_pos'] self.prev_obs = self._get_curr_obs_combined_no_goal() if", "dial_push_position = self._get_pos_objects() + np.array([0.05, 0.02, 0.09]) tcp = self.tcp_center", "1, 0.5) obj_low = (-0.1, 0.7, 0.0) obj_high = (0.1,", "self.get_body_com('dial').copy() dial_angle_rad = self.data.get_joint_qpos('knob_Joint_1') offset = np.array([ np.sin(dial_angle_rad), -np.cos(dial_angle_rad), 0", "def evaluate_state(self, obs, action): (reward, tcp_to_obj, _, target_to_obj, object_grasped, in_place)", "0 object_grasped = reach reward = 10 * reward_utils.hamacher_product(reach, in_place)", "dial_center + offset def _get_quat_objects(self): return self.sim.data.get_body_xquat('dial') def reset_model(self): self._reset_hand()", "self._reset_hand() self._target_pos = self.goal.copy() self.obj_init_pos = self.init_config['obj_init_pos'] self.prev_obs = self._get_curr_obs_combined_no_goal()", "self.hand_init_pos = self.init_config['hand_init_pos'] self._random_reset_space = Box( np.array(obj_low), np.array(obj_high), ) self.goal_space", "- tcp) tcp_to_obj_init = np.linalg.norm(self.dial_push_position - self.init_tcp) reach = reward_utils.tolerance(", "tcp_to_obj, _, target_to_obj, object_grasped, in_place) = self.compute_reward(action, obs) info =" ]
[ "self.peek_token.type == token_type: self.next_token() return True else: return False def", "None statement = Statement(line) return statement def get_participant(self, value): if", "def parse_line_statement(self): participant_literal = self.current_token.literal if not self.peek_token.type in [TokenType.SOLID_LINE,", "self.current_token.type != TokenType.EOF: statement = self.parse_statement() if statement: program.statements.append(statement) self.next_token()", "if self.peek_token.type not in [TokenType.NEWLINE, TokenType.EOF]: return None statement =", "parse_title(self): if not self.expect_peek(TokenType.IDENTIFIER): return None title = Title(self.current_token.literal) return", "program = Program() while self.current_token.type != TokenType.EOF: statement = self.parse_statement()", "== TokenType.TITLE: return self.parse_title() return None def parse_line_statement(self): participant_literal =", "not self.expect_peek(TokenType.IDENTIFIER): return None target = Participant(self.current_token.literal) line.set_target(target) if not", "from yezdi.parser.ast import Program, Statement, Participant, Title, LineStatement class Parser:", "TokenType.TITLE: return self.parse_title() return None def parse_line_statement(self): participant_literal = self.current_token.literal", "not self.peek_token.type in [TokenType.SOLID_LINE, TokenType.DASHED_LINE]: return None self.next_token() participant =", "Statement, Participant, Title, LineStatement class Parser: def __init__(self, lexer): self.lexer", "return None self.next_token() participant = Participant(participant_literal) line = LineStatement(self.current_token.type) line.set_source(participant)", "LineStatement class Parser: def __init__(self, lexer): self.lexer = lexer self.current_token", "while self.current_token.type != TokenType.EOF: statement = self.parse_statement() if statement: program.statements.append(statement)", "else: return False def parse_title(self): if not self.expect_peek(TokenType.IDENTIFIER): return None", "else: participant = Participant(value) self.participants[value] = participant return participant def", "self.current_token.literal if not self.peek_token.type in [TokenType.SOLID_LINE, TokenType.DASHED_LINE]: return None self.next_token()", "yezdi.parser.ast import Program, Statement, Participant, Title, LineStatement class Parser: def", "target = Participant(self.current_token.literal) line.set_target(target) if not self.expect_peek(TokenType.COLON): return None if", "Program, Statement, Participant, Title, LineStatement class Parser: def __init__(self, lexer):", "LineStatement(self.current_token.type) line.set_source(participant) if not self.expect_peek(TokenType.IDENTIFIER): return None target = Participant(self.current_token.literal)", "return program def parse_statement(self): if self.current_token.type == TokenType.IDENTIFIER: return self.parse_line_statement()", "None if self.expect_peek(TokenType.IDENTIFIER): line.set_info(self.current_token.literal) if self.peek_token.type not in [TokenType.NEWLINE, TokenType.EOF]:", "{} def next_token(self): self.current_token, self.peek_token = self.peek_token, self.lexer.next_token() def parse_program(self):", "self.peek_token.type in [TokenType.SOLID_LINE, TokenType.DASHED_LINE]: return None self.next_token() participant = Participant(participant_literal)", "if not self.peek_token.type in [TokenType.SOLID_LINE, TokenType.DASHED_LINE]: return None self.next_token() participant", "self.current_token.type == TokenType.IDENTIFIER: return self.parse_line_statement() elif self.current_token.type == TokenType.TITLE: return", "value in self.participants: return self.participants[value] else: participant = Participant(value) self.participants[value]", "= LineStatement(self.current_token.type) line.set_source(participant) if not self.expect_peek(TokenType.IDENTIFIER): return None target =", "self.participants[value] = participant return participant def expect_peek(self, token_type): if self.peek_token.type", "self.current_token, self.peek_token = self.peek_token, self.lexer.next_token() def parse_program(self): program = Program()", "TokenType.EOF: statement = self.parse_statement() if statement: program.statements.append(statement) self.next_token() return program", "if value in self.participants: return self.participants[value] else: participant = Participant(value)", "participant = Participant(value) self.participants[value] = participant return participant def expect_peek(self,", "line = LineStatement(self.current_token.type) line.set_source(participant) if not self.expect_peek(TokenType.IDENTIFIER): return None target", "== token_type: self.next_token() return True else: return False def parse_title(self):", "token_type: self.next_token() return True else: return False def parse_title(self): if", "yezdi.lexer.token import TokenType from yezdi.parser.ast import Program, Statement, Participant, Title,", "self.next_token() participant = Participant(participant_literal) line = LineStatement(self.current_token.type) line.set_source(participant) if not", "self.next_token() return True else: return False def parse_title(self): if not", "Participant, Title, LineStatement class Parser: def __init__(self, lexer): self.lexer =", "Participant(value) self.participants[value] = participant return participant def expect_peek(self, token_type): if", "self.parse_title() return None def parse_line_statement(self): participant_literal = self.current_token.literal if not", "line.set_source(participant) if not self.expect_peek(TokenType.IDENTIFIER): return None target = Participant(self.current_token.literal) line.set_target(target)", "return True else: return False def parse_title(self): if not self.expect_peek(TokenType.IDENTIFIER):", "= None self.peek_token = None self.next_token() self.next_token() self.participants = {}", "self.parse_statement() if statement: program.statements.append(statement) self.next_token() return program def parse_statement(self): if", "participant return participant def expect_peek(self, token_type): if self.peek_token.type == token_type:", "self.peek_token.type not in [TokenType.NEWLINE, TokenType.EOF]: return None statement = Statement(line)", "= self.peek_token, self.lexer.next_token() def parse_program(self): program = Program() while self.current_token.type", "line.set_info(self.current_token.literal) if self.peek_token.type not in [TokenType.NEWLINE, TokenType.EOF]: return None statement", "__init__(self, lexer): self.lexer = lexer self.current_token = None self.peek_token =", "participant = Participant(participant_literal) line = LineStatement(self.current_token.type) line.set_source(participant) if not self.expect_peek(TokenType.IDENTIFIER):", "== TokenType.IDENTIFIER: return self.parse_line_statement() elif self.current_token.type == TokenType.TITLE: return self.parse_title()", "Participant(self.current_token.literal) line.set_target(target) if not self.expect_peek(TokenType.COLON): return None if self.expect_peek(TokenType.IDENTIFIER): line.set_info(self.current_token.literal)", "return None if self.expect_peek(TokenType.IDENTIFIER): line.set_info(self.current_token.literal) if self.peek_token.type not in [TokenType.NEWLINE,", "def next_token(self): self.current_token, self.peek_token = self.peek_token, self.lexer.next_token() def parse_program(self): program", "False def parse_title(self): if not self.expect_peek(TokenType.IDENTIFIER): return None title =", "def parse_program(self): program = Program() while self.current_token.type != TokenType.EOF: statement", "in [TokenType.NEWLINE, TokenType.EOF]: return None statement = Statement(line) return statement", "return statement def get_participant(self, value): if value in self.participants: return", "statement = Statement(line) return statement def get_participant(self, value): if value", "participant_literal = self.current_token.literal if not self.peek_token.type in [TokenType.SOLID_LINE, TokenType.DASHED_LINE]: return", "self.next_token() return program def parse_statement(self): if self.current_token.type == TokenType.IDENTIFIER: return", "expect_peek(self, token_type): if self.peek_token.type == token_type: self.next_token() return True else:", "self.lexer = lexer self.current_token = None self.peek_token = None self.next_token()", "if not self.expect_peek(TokenType.IDENTIFIER): return None title = Title(self.current_token.literal) return Statement(title)", "import TokenType from yezdi.parser.ast import Program, Statement, Participant, Title, LineStatement", "= None self.next_token() self.next_token() self.participants = {} def next_token(self): self.current_token,", "return None title = Title(self.current_token.literal) return Statement(title) class ParserError(Exception): pass", "Participant(participant_literal) line = LineStatement(self.current_token.type) line.set_source(participant) if not self.expect_peek(TokenType.IDENTIFIER): return None", "= self.parse_statement() if statement: program.statements.append(statement) self.next_token() return program def parse_statement(self):", "= Participant(self.current_token.literal) line.set_target(target) if not self.expect_peek(TokenType.COLON): return None if self.expect_peek(TokenType.IDENTIFIER):", "return self.parse_title() return None def parse_line_statement(self): participant_literal = self.current_token.literal if", "self.expect_peek(TokenType.IDENTIFIER): return None target = Participant(self.current_token.literal) line.set_target(target) if not self.expect_peek(TokenType.COLON):", "self.expect_peek(TokenType.COLON): return None if self.expect_peek(TokenType.IDENTIFIER): line.set_info(self.current_token.literal) if self.peek_token.type not in", "if not self.expect_peek(TokenType.IDENTIFIER): return None target = Participant(self.current_token.literal) line.set_target(target) if", "TokenType.DASHED_LINE]: return None self.next_token() participant = Participant(participant_literal) line = LineStatement(self.current_token.type)", "True else: return False def parse_title(self): if not self.expect_peek(TokenType.IDENTIFIER): return", "self.current_token = None self.peek_token = None self.next_token() self.next_token() self.participants =", "self.next_token() self.participants = {} def next_token(self): self.current_token, self.peek_token = self.peek_token,", "def __init__(self, lexer): self.lexer = lexer self.current_token = None self.peek_token", "from yezdi.lexer.token import TokenType from yezdi.parser.ast import Program, Statement, Participant,", "return None target = Participant(self.current_token.literal) line.set_target(target) if not self.expect_peek(TokenType.COLON): return", "None target = Participant(self.current_token.literal) line.set_target(target) if not self.expect_peek(TokenType.COLON): return None", "def parse_statement(self): if self.current_token.type == TokenType.IDENTIFIER: return self.parse_line_statement() elif self.current_token.type", "if self.peek_token.type == token_type: self.next_token() return True else: return False", "self.participants = {} def next_token(self): self.current_token, self.peek_token = self.peek_token, self.lexer.next_token()", "= lexer self.current_token = None self.peek_token = None self.next_token() self.next_token()", "None self.next_token() participant = Participant(participant_literal) line = LineStatement(self.current_token.type) line.set_source(participant) if", "self.peek_token = None self.next_token() self.next_token() self.participants = {} def next_token(self):", "statement = self.parse_statement() if statement: program.statements.append(statement) self.next_token() return program def", "None def parse_line_statement(self): participant_literal = self.current_token.literal if not self.peek_token.type in", "Statement(line) return statement def get_participant(self, value): if value in self.participants:", "= Participant(value) self.participants[value] = participant return participant def expect_peek(self, token_type):", "line.set_target(target) if not self.expect_peek(TokenType.COLON): return None if self.expect_peek(TokenType.IDENTIFIER): line.set_info(self.current_token.literal) if", "token_type): if self.peek_token.type == token_type: self.next_token() return True else: return", "[TokenType.SOLID_LINE, TokenType.DASHED_LINE]: return None self.next_token() participant = Participant(participant_literal) line =", "None self.peek_token = None self.next_token() self.next_token() self.participants = {} def", "def get_participant(self, value): if value in self.participants: return self.participants[value] else:", "class Parser: def __init__(self, lexer): self.lexer = lexer self.current_token =", "if self.current_token.type == TokenType.IDENTIFIER: return self.parse_line_statement() elif self.current_token.type == TokenType.TITLE:", "= Program() while self.current_token.type != TokenType.EOF: statement = self.parse_statement() if", "None self.next_token() self.next_token() self.participants = {} def next_token(self): self.current_token, self.peek_token", "def parse_title(self): if not self.expect_peek(TokenType.IDENTIFIER): return None title = Title(self.current_token.literal)", "= {} def next_token(self): self.current_token, self.peek_token = self.peek_token, self.lexer.next_token() def", "self.next_token() self.next_token() self.participants = {} def next_token(self): self.current_token, self.peek_token =", "self.parse_line_statement() elif self.current_token.type == TokenType.TITLE: return self.parse_title() return None def", "TokenType from yezdi.parser.ast import Program, Statement, Participant, Title, LineStatement class", "self.expect_peek(TokenType.IDENTIFIER): line.set_info(self.current_token.literal) if self.peek_token.type not in [TokenType.NEWLINE, TokenType.EOF]: return None", "program.statements.append(statement) self.next_token() return program def parse_statement(self): if self.current_token.type == TokenType.IDENTIFIER:", "return False def parse_title(self): if not self.expect_peek(TokenType.IDENTIFIER): return None title", "lexer): self.lexer = lexer self.current_token = None self.peek_token = None", "self.participants: return self.participants[value] else: participant = Participant(value) self.participants[value] = participant", "if statement: program.statements.append(statement) self.next_token() return program def parse_statement(self): if self.current_token.type", "statement: program.statements.append(statement) self.next_token() return program def parse_statement(self): if self.current_token.type ==", "get_participant(self, value): if value in self.participants: return self.participants[value] else: participant", "statement def get_participant(self, value): if value in self.participants: return self.participants[value]", "self.participants[value] else: participant = Participant(value) self.participants[value] = participant return participant", "self.expect_peek(TokenType.IDENTIFIER): return None title = Title(self.current_token.literal) return Statement(title) class ParserError(Exception):", "!= TokenType.EOF: statement = self.parse_statement() if statement: program.statements.append(statement) self.next_token() return", "parse_statement(self): if self.current_token.type == TokenType.IDENTIFIER: return self.parse_line_statement() elif self.current_token.type ==", "not self.expect_peek(TokenType.COLON): return None if self.expect_peek(TokenType.IDENTIFIER): line.set_info(self.current_token.literal) if self.peek_token.type not", "return None def parse_line_statement(self): participant_literal = self.current_token.literal if not self.peek_token.type", "TokenType.EOF]: return None statement = Statement(line) return statement def get_participant(self,", "self.current_token.type == TokenType.TITLE: return self.parse_title() return None def parse_line_statement(self): participant_literal", "in self.participants: return self.participants[value] else: participant = Participant(value) self.participants[value] =", "= Statement(line) return statement def get_participant(self, value): if value in", "[TokenType.NEWLINE, TokenType.EOF]: return None statement = Statement(line) return statement def", "= self.current_token.literal if not self.peek_token.type in [TokenType.SOLID_LINE, TokenType.DASHED_LINE]: return None", "program def parse_statement(self): if self.current_token.type == TokenType.IDENTIFIER: return self.parse_line_statement() elif", "return self.participants[value] else: participant = Participant(value) self.participants[value] = participant return", "import Program, Statement, Participant, Title, LineStatement class Parser: def __init__(self,", "in [TokenType.SOLID_LINE, TokenType.DASHED_LINE]: return None self.next_token() participant = Participant(participant_literal) line", "Program() while self.current_token.type != TokenType.EOF: statement = self.parse_statement() if statement:", "parse_line_statement(self): participant_literal = self.current_token.literal if not self.peek_token.type in [TokenType.SOLID_LINE, TokenType.DASHED_LINE]:", "not in [TokenType.NEWLINE, TokenType.EOF]: return None statement = Statement(line) return", "value): if value in self.participants: return self.participants[value] else: participant =", "not self.expect_peek(TokenType.IDENTIFIER): return None title = Title(self.current_token.literal) return Statement(title) class", "def expect_peek(self, token_type): if self.peek_token.type == token_type: self.next_token() return True", "= participant return participant def expect_peek(self, token_type): if self.peek_token.type ==", "return None statement = Statement(line) return statement def get_participant(self, value):", "next_token(self): self.current_token, self.peek_token = self.peek_token, self.lexer.next_token() def parse_program(self): program =", "self.peek_token, self.lexer.next_token() def parse_program(self): program = Program() while self.current_token.type !=", "self.lexer.next_token() def parse_program(self): program = Program() while self.current_token.type != TokenType.EOF:", "participant def expect_peek(self, token_type): if self.peek_token.type == token_type: self.next_token() return", "TokenType.IDENTIFIER: return self.parse_line_statement() elif self.current_token.type == TokenType.TITLE: return self.parse_title() return", "if not self.expect_peek(TokenType.COLON): return None if self.expect_peek(TokenType.IDENTIFIER): line.set_info(self.current_token.literal) if self.peek_token.type", "return participant def expect_peek(self, token_type): if self.peek_token.type == token_type: self.next_token()", "if self.expect_peek(TokenType.IDENTIFIER): line.set_info(self.current_token.literal) if self.peek_token.type not in [TokenType.NEWLINE, TokenType.EOF]: return", "parse_program(self): program = Program() while self.current_token.type != TokenType.EOF: statement =", "return self.parse_line_statement() elif self.current_token.type == TokenType.TITLE: return self.parse_title() return None", "self.peek_token = self.peek_token, self.lexer.next_token() def parse_program(self): program = Program() while", "Parser: def __init__(self, lexer): self.lexer = lexer self.current_token = None", "Title, LineStatement class Parser: def __init__(self, lexer): self.lexer = lexer", "= Participant(participant_literal) line = LineStatement(self.current_token.type) line.set_source(participant) if not self.expect_peek(TokenType.IDENTIFIER): return", "lexer self.current_token = None self.peek_token = None self.next_token() self.next_token() self.participants", "elif self.current_token.type == TokenType.TITLE: return self.parse_title() return None def parse_line_statement(self):" ]
[ "pardir categories_folder = abspath(join(__file__,pardir,pardir,\"category\")) post_folder = abspath(join(__file__,pardir,pardir,\"_posts\")) site_categories = []", "list categories in category folder from os import walk from", "f in files: site_categories.append(f.split(\".md\")[0]) site_categories = set(site_categories) for root,directories,files in", "files: with open(join(root,f),'r',encoding=\"utf-8\") as fi: lines = fi.readlines() for l", "l.find(\"categories\")==0: categories = l.split(\":\")[1] for c in [\" \",\"[\",\"]\",\"\\n\"]: categories", "l.split(\":\")[1] for c in [\" \",\"[\",\"]\",\"\\n\"]: categories = categories.replace(c,\"\") categories=categories.split(\",\")", "c in [\" \",\"[\",\"]\",\"\\n\"]: categories = categories.replace(c,\"\") categories=categories.split(\",\") if len(set(categories)-site_categories)>0:", "= set(site_categories) for root,directories,files in walk(post_folder): for f in files:", "site_categories = set(site_categories) for root,directories,files in walk(post_folder): for f in", "os.path import abspath,join, pardir categories_folder = abspath(join(__file__,pardir,pardir,\"category\")) post_folder = abspath(join(__file__,pardir,pardir,\"_posts\"))", "lines = fi.readlines() for l in lines: if l.find(\"categories\")==0: categories", "walk(categories_folder): for f in files: site_categories.append(f.split(\".md\")[0]) site_categories = set(site_categories) for", "in walk(categories_folder): for f in files: site_categories.append(f.split(\".md\")[0]) site_categories = set(site_categories)", "if l.find(\"categories\")==0: categories = l.split(\":\")[1] for c in [\" \",\"[\",\"]\",\"\\n\"]:", "categories = l.split(\":\")[1] for c in [\" \",\"[\",\"]\",\"\\n\"]: categories =", "as fi: lines = fi.readlines() for l in lines: if", "\",\"[\",\"]\",\"\\n\"]: categories = categories.replace(c,\"\") categories=categories.split(\",\") if len(set(categories)-site_categories)>0: print(f,set(categories)-site_categories) break print(\"done\")", "site_categories = [] for root,directories,files in walk(categories_folder): for f in", "root,directories,files in walk(post_folder): for f in files: with open(join(root,f),'r',encoding=\"utf-8\") as", "site_categories.append(f.split(\".md\")[0]) site_categories = set(site_categories) for root,directories,files in walk(post_folder): for f", "post_folder = abspath(join(__file__,pardir,pardir,\"_posts\")) site_categories = [] for root,directories,files in walk(categories_folder):", "import abspath,join, pardir categories_folder = abspath(join(__file__,pardir,pardir,\"category\")) post_folder = abspath(join(__file__,pardir,pardir,\"_posts\")) site_categories", "fi.readlines() for l in lines: if l.find(\"categories\")==0: categories = l.split(\":\")[1]", "abspath(join(__file__,pardir,pardir,\"_posts\")) site_categories = [] for root,directories,files in walk(categories_folder): for f", "in files: with open(join(root,f),'r',encoding=\"utf-8\") as fi: lines = fi.readlines() for", "[\" \",\"[\",\"]\",\"\\n\"]: categories = categories.replace(c,\"\") categories=categories.split(\",\") if len(set(categories)-site_categories)>0: print(f,set(categories)-site_categories) break", "= l.split(\":\")[1] for c in [\" \",\"[\",\"]\",\"\\n\"]: categories = categories.replace(c,\"\")", "in [\" \",\"[\",\"]\",\"\\n\"]: categories = categories.replace(c,\"\") categories=categories.split(\",\") if len(set(categories)-site_categories)>0: print(f,set(categories)-site_categories)", "[] for root,directories,files in walk(categories_folder): for f in files: site_categories.append(f.split(\".md\")[0])", "categories in category folder from os import walk from os.path", "open(join(root,f),'r',encoding=\"utf-8\") as fi: lines = fi.readlines() for l in lines:", "= [] for root,directories,files in walk(categories_folder): for f in files:", "l in lines: if l.find(\"categories\")==0: categories = l.split(\":\")[1] for c", "categories_folder = abspath(join(__file__,pardir,pardir,\"category\")) post_folder = abspath(join(__file__,pardir,pardir,\"_posts\")) site_categories = [] for", "in lines: if l.find(\"categories\")==0: categories = l.split(\":\")[1] for c in", "walk(post_folder): for f in files: with open(join(root,f),'r',encoding=\"utf-8\") as fi: lines", "for f in files: with open(join(root,f),'r',encoding=\"utf-8\") as fi: lines =", "files: site_categories.append(f.split(\".md\")[0]) site_categories = set(site_categories) for root,directories,files in walk(post_folder): for", "walk from os.path import abspath,join, pardir categories_folder = abspath(join(__file__,pardir,pardir,\"category\")) post_folder", "lines: if l.find(\"categories\")==0: categories = l.split(\":\")[1] for c in [\"", "root,directories,files in walk(categories_folder): for f in files: site_categories.append(f.split(\".md\")[0]) site_categories =", "= abspath(join(__file__,pardir,pardir,\"category\")) post_folder = abspath(join(__file__,pardir,pardir,\"_posts\")) site_categories = [] for root,directories,files", "for f in files: site_categories.append(f.split(\".md\")[0]) site_categories = set(site_categories) for root,directories,files", "fi: lines = fi.readlines() for l in lines: if l.find(\"categories\")==0:", "abspath(join(__file__,pardir,pardir,\"category\")) post_folder = abspath(join(__file__,pardir,pardir,\"_posts\")) site_categories = [] for root,directories,files in", "# list categories in category folder from os import walk", "category folder from os import walk from os.path import abspath,join,", "set(site_categories) for root,directories,files in walk(post_folder): for f in files: with", "for root,directories,files in walk(post_folder): for f in files: with open(join(root,f),'r',encoding=\"utf-8\")", "for c in [\" \",\"[\",\"]\",\"\\n\"]: categories = categories.replace(c,\"\") categories=categories.split(\",\") if", "from os import walk from os.path import abspath,join, pardir categories_folder", "for root,directories,files in walk(categories_folder): for f in files: site_categories.append(f.split(\".md\")[0]) site_categories", "in category folder from os import walk from os.path import", "= abspath(join(__file__,pardir,pardir,\"_posts\")) site_categories = [] for root,directories,files in walk(categories_folder): for", "in files: site_categories.append(f.split(\".md\")[0]) site_categories = set(site_categories) for root,directories,files in walk(post_folder):", "import walk from os.path import abspath,join, pardir categories_folder = abspath(join(__file__,pardir,pardir,\"category\"))", "for l in lines: if l.find(\"categories\")==0: categories = l.split(\":\")[1] for", "folder from os import walk from os.path import abspath,join, pardir", "from os.path import abspath,join, pardir categories_folder = abspath(join(__file__,pardir,pardir,\"category\")) post_folder =", "f in files: with open(join(root,f),'r',encoding=\"utf-8\") as fi: lines = fi.readlines()", "with open(join(root,f),'r',encoding=\"utf-8\") as fi: lines = fi.readlines() for l in", "= fi.readlines() for l in lines: if l.find(\"categories\")==0: categories =", "in walk(post_folder): for f in files: with open(join(root,f),'r',encoding=\"utf-8\") as fi:", "os import walk from os.path import abspath,join, pardir categories_folder =", "abspath,join, pardir categories_folder = abspath(join(__file__,pardir,pardir,\"category\")) post_folder = abspath(join(__file__,pardir,pardir,\"_posts\")) site_categories =" ]
[ "various formats, including the web site and pdf. \"\"\" import", "'\\\\begin{tabulary}{\\\\textwidth}{lJ}').replace('\\\\begin{longtable}[]{@{}lll@{}}', '\\\\begin{tabulary}{\\\\textwidth}{lJJ}').replace('\\\\begin{longtable}[]{@{}llll@{}}', '\\\\begin{tabulary}{\\\\textwidth}{lJJJ}').replace('\\\\endhead','').replace('\\\\end{longtable}','\\\\end{tabulary}')) print(\"- -- --- -- - Generating pdf", "\"foreign_interface.mmd\", \"c_api.mmd\", \"python_api.mmd\", \"ruby_api.mmd\", \"rpgmaker_api.mmd\", \"bmx_api.mmd\", \"gamemaker_api.mmd\", \"cs_api.mmd\", \"d_api.mmd\", \"codegen.mmd\",", "\"-f\", \"markdown-smart\", \"--metadata\", 'title=\"SoLoud ' + datestring + '\"', \"-H\",", "\"downloads.mmd\", \"quickstart.mmd\", \"faq.mmd\", \"dirstruct.mmd\", \"premake.mmd\", \"legal.mmd\", \"concepts.mmd\", \"concepts3d.mmd\", \"voicemanagement.mmd\", \"examples.mmd\",", "datestring + \".epub\", \"title.txt\"] for x in src: if x", "0 for file in glob.glob(\"*.mmd\"): if file not in src:", "\"sfxr.mmd\", \"modplug.mmd\", \"monotone.mmd\", \"tedsid.mmd\", \"vizsn.mmd\", \"vic.mmd\", \"filters.mmd\", \"biquadfilter.mmd\", \"echofilter.mmd\", \"lofifilter.mmd\",", "not os.path.exists(\"temp/\"): os.makedirs(\"temp/\") print(\"- -- --- -- - Generating single-file", "HTML docs\") callp = [\"pandoc\", \"-s\", \"-t\", \"html5\", \"-f\", \"markdown-smart\",", "\"-o\", datestring + \"/soloud_\" + datestring + \".html\"] for x", "x[:len(x)-3]+\"tex.orig\", \"r\") as file_in: for line in file_in: file_out.write(line.replace('\\\\begin{longtable}[]{@{}ll@{}}', '\\\\begin{tabulary}{\\\\textwidth}{lJ}').replace('\\\\begin{longtable}[]{@{}lll@{}}',", "\"c_api.mmd\", \"python_api.mmd\", \"ruby_api.mmd\", \"rpgmaker_api.mmd\", \"bmx_api.mmd\", \"gamemaker_api.mmd\", \"cs_api.mmd\", \"d_api.mmd\", \"codegen.mmd\", \"basics.mmd\",", "subprocess.call(callp) print(\"- -- --- -- - Converting epub -> mobi", "in src: if x not in website_only: subprocess.call([\"pandoc\", \"-t\", \"latex\",", "in src: unknown = 1 print(file + \" not included", "for file in glob.glob(\"*.mmd\"): if file not in src: unknown", "not included in docs!\") if unknown: print(\"Add the new files", "\"--self-contained\", \"--default-image-extension=png\", \"-o\", datestring + \"/soloud_\" + datestring + \".html\"]", "Generating epub\") callp = [\"pandoc\", \"-N\", \"--toc\", \"--epub-cover-image=images/cover.png\", \"-t\", \"epub3\",", "#!/usr/bin/env python3 \"\"\" builds documentation files from multimarkdown (mmd) source", "as file_in: for line in file_in: file_out.write(line.replace('\\\\begin{longtable}[]{@{}ll@{}}', '\\\\begin{tabulary}{\\\\textwidth}{lJ}').replace('\\\\begin{longtable}[]{@{}lll@{}}', '\\\\begin{tabulary}{\\\\textwidth}{lJJ}').replace('\\\\begin{longtable}[]{@{}llll@{}}', '\\\\begin{tabulary}{\\\\textwidth}{lJJJ}').replace('\\\\endhead','').replace('\\\\end{longtable}','\\\\end{tabulary}'))", "\"/web/\" + x[:len(x)-3]+\"html\", \"w\") as file_out: with open(datestring + \"/web/\"", "'\"', \"-B\", \"htmlpre.txt\", \"-A\", \"htmlpost.txt\", \"--default-image-extension=png\", x, \"-o\", datestring +", "file_in: for line in file_in: file_out.write(line.replace('code>', 'code>\\n').replace('::','::<wbr>').replace('\\xc2','').replace('\\xa0','')) if x ==", "open(\"temp/\" + x[:len(x)-3]+\"tex\", \"w\") as file_out: with open(\"temp/\" + x[:len(x)-3]+\"tex.orig\",", "\"/web/\" + x[:len(x)-3]+\"html.bak\"]) with open(datestring + \"/web/\" + x[:len(x)-3]+\"html\", \"w\")", "\"/soloud_\" + datestring + \".pdf\") print(\"- -- --- -- -", "+ \"/web/*.\"+suffix): os.remove(file) for file in glob.glob(\"temp/*\"): os.remove(file) os.rmdir(\"temp\") print(\"-", "shutil.move(\"SoLoud.pdf\", datestring + \"/soloud_\" + datestring + \".pdf\") print(\"- --", "= [\"pandoc\", \"-N\", \"--toc\", \"--epub-cover-image=images/cover.png\", \"-t\", \"epub3\", \"--default-image-extension=png\", \"-f\", \"markdown-smart\",", "subprocess.call([\"kindlegen\", datestring + \"/soloud_\" + datestring + \".epub\", \"-c2\"], stdout=outfile)", "if file not in src: unknown = 1 print(file +", "in website_only: callp.append(x) subprocess.call(callp) print(\"- -- --- -- - Converting", "not in website_only: callp.append(x) subprocess.call(callp) print(\"- -- --- -- -", "to various formats, including the web site and pdf. \"\"\"", "time.strftime(\"%Y%m%d\") if not os.path.exists(datestring + \"/web\"): os.makedirs(datestring + \"/web\") if", "+ \"/soloud_\" + datestring + \".html\"] for x in src:", "'w') as outfile: subprocess.call([\"kindlegen\", datestring + \"/soloud_\" + datestring +", "subprocess.call([\"pandoc\", \"--template=html.pandoc\", \"-f\", \"markdown-smart\", \"--metadata\", 'title=\"SoLoud ' + datestring +", "+ x[:len(x)-3]+\"tex\", \"w\") as file_out: with open(\"temp/\" + x[:len(x)-3]+\"tex.orig\", \"r\")", "subprocess.call([\"pandoc\", \"-t\", \"latex\", \"--listings\", \"--default-image-extension=pdf\", \"--top-level-division=chapter\", x, \"-o\", \"temp/\" +", "with open('xelatex_output.txt', 'w') as outfile: subprocess.call([\"xelatex\", \"SoLoud.tex\"], stdout=outfile) print(\"- --", "in file_in: file_out.write(line.replace('\\\\begin{longtable}[]{@{}ll@{}}', '\\\\begin{tabulary}{\\\\textwidth}{lJ}').replace('\\\\begin{longtable}[]{@{}lll@{}}', '\\\\begin{tabulary}{\\\\textwidth}{lJJ}').replace('\\\\begin{longtable}[]{@{}llll@{}}', '\\\\begin{tabulary}{\\\\textwidth}{lJJJ}').replace('\\\\endhead','').replace('\\\\end{longtable}','\\\\end{tabulary}')) print(\"- -- --- --", "+ \".epub\", \"title.txt\"] for x in src: if x not", "x[:len(x)-3]+\"html\", \"w\") as file_out: with open(datestring + \"/web/\" + x[:len(x)-3]+\"html.bak\",", "-- --- -- - Generating single-file HTML docs\") callp =", "\"faders.mmd\", \"voicegroups.mmd\", \"coremisc.mmd\", \"core3d.mmd\", \"audiosource.mmd\", \"newsoundsources.mmd\", \"wav.mmd\", \"wavstream.mmd\", \"speech.mmd\", \"sfxr.mmd\",", "-- --- -- - Cleanup..\") tempsuffix = [\"aux\", \"toc\", \"out\",", "\"attributes.mmd\", \"faders.mmd\", \"voicegroups.mmd\", \"coremisc.mmd\", \"core3d.mmd\", \"audiosource.mmd\", \"newsoundsources.mmd\", \"wav.mmd\", \"wavstream.mmd\", \"speech.mmd\",", "LaTex\") for x in src: if x not in website_only:", "import subprocess import glob import os import sys import time", "- Generating single-file HTML docs\") callp = [\"pandoc\", \"-s\", \"-t\",", "\"--default-image-extension=png\", x, \"-o\", datestring + \"/web/\" + x[:len(x)-3]+\"html.bak\"]) with open(datestring", "\"-H\", \"singlehtml_head.txt\", \"-B\", \"singlehtml_body.txt\", \"--toc\", \"--self-contained\", \"--default-image-extension=png\", \"-o\", datestring +", "\"/web\") if not os.path.exists(\"temp/\"): os.makedirs(\"temp/\") print(\"- -- --- -- -", "\"mixbus.mmd\", \"queue.mmd\", \"collider.mmd\", \"attenuator.mmd\", \"file.mmd\", \"backends.mmd\" ] website_only = [", "glob.glob(\"*.mmd\"): if file not in src: unknown = 1 print(file", "\"--template=html.pandoc\", \"-f\", \"markdown-smart\", \"--metadata\", 'title=\"SoLoud ' + datestring + '", "\".pdf\") print(\"- -- --- -- - Cleanup..\") tempsuffix = [\"aux\",", "\"bak\"] for suffix in tempsuffix: for file in glob.glob(\"*.\"+suffix): os.remove(file)", "python3 \"\"\" builds documentation files from multimarkdown (mmd) source to", "if os.path.isfile(datestring + \"/web/index.html\"): os.remove(datestring + \"/web/index.html\") os.rename(datestring + \"/web/intro.html\",", "+ datestring + '\"', \"-H\", \"singlehtml_head.txt\", \"-B\", \"singlehtml_body.txt\", \"--toc\", \"--self-contained\",", "open('kindlegen_output.txt', 'w') as outfile: subprocess.call([\"kindlegen\", datestring + \"/soloud_\" + datestring", "] unknown = 0 for file in glob.glob(\"*.mmd\"): if file", "\"\"\" import subprocess import glob import os import sys import", "web site\") for x in src: subprocess.call([\"pandoc\", \"--template=html.pandoc\", \"-f\", \"markdown-smart\",", "as outfile: subprocess.call([\"kindlegen\", datestring + \"/soloud_\" + datestring + \".epub\",", "\".epub\", \"-c2\"], stdout=outfile) print(\"- -- --- -- - Generating LaTex\")", "\"xdv\", \"xref\", \"bak\"] for suffix in tempsuffix: for file in", "datestring + \".html\"] for x in src: if x not", "subprocess.call([\"xelatex\", \"SoLoud.tex\"], stdout=outfile) shutil.move(\"SoLoud.pdf\", datestring + \"/soloud_\" + datestring +", "\"4ct\", \"4tc\", \"idv\", \"tmp\", \"xdv\", \"xref\", \"bak\"] for suffix in", "mobi (kindlegen_output.txt)\") with open('kindlegen_output.txt', 'w') as outfile: subprocess.call([\"kindlegen\", datestring +", "\"rpgmaker_api.mmd\", \"bmx_api.mmd\", \"gamemaker_api.mmd\", \"cs_api.mmd\", \"d_api.mmd\", \"codegen.mmd\", \"basics.mmd\", \"attributes.mmd\", \"faders.mmd\", \"voicegroups.mmd\",", "--- -- - Generating pdf (xelatex_output.txt)\") with open('xelatex_output.txt', 'w') as", "print(\"- -- --- -- - Generating pdf pass 2..\") subprocess.call([\"xelatex\",", "x, \"-o\", \"temp/\" + x[:len(x)-3]+\"tex.orig\"]) with open(\"temp/\" + x[:len(x)-3]+\"tex\", \"w\")", "\"--toc\", \"--self-contained\", \"--default-image-extension=png\", \"-o\", datestring + \"/soloud_\" + datestring +", "+ \"/soloud_\" + datestring + \".pdf\") print(\"- -- --- --", "open(datestring + \"/web/\" + x[:len(x)-3]+\"html\", \"w\") as file_out: with open(datestring", "\"dirstruct.mmd\", \"premake.mmd\", \"legal.mmd\", \"concepts.mmd\", \"concepts3d.mmd\", \"voicemanagement.mmd\", \"examples.mmd\", \"foreign_interface.mmd\", \"c_api.mmd\", \"python_api.mmd\",", "\"htmlpost.txt\", \"--default-image-extension=png\", x, \"-o\", datestring + \"/web/\" + x[:len(x)-3]+\"html.bak\"]) with", "+ datestring + \".pdf\") print(\"- -- --- -- - Cleanup..\")", "\"-o\", datestring + \"/soloud_\" + datestring + \".epub\", \"title.txt\"] for", "--- -- - Generating pdf pass 2..\") subprocess.call([\"xelatex\", \"SoLoud.tex\"], stdout=outfile)", "from multimarkdown (mmd) source to various formats, including the web", "sys.exit() datestring = time.strftime(\"%Y%m%d\") if not os.path.exists(datestring + \"/web\"): os.makedirs(datestring", "print(\"- -- --- -- - Generating epub\") callp = [\"pandoc\",", "\"SoLoud.tex\"], stdout=outfile) shutil.move(\"SoLoud.pdf\", datestring + \"/soloud_\" + datestring + \".pdf\")", "\"epub3\", \"--default-image-extension=png\", \"-f\", \"markdown-smart\", \"--css=epub.css\", \"--epub-metadata=metadata.xml\", \"-o\", datestring + \"/soloud_\"", "in tempsuffix: for file in glob.glob(\"*.\"+suffix): os.remove(file) for file in", "files to makedoc.py, soloud.tex and htmlpre.txt.\") sys.exit() datestring = time.strftime(\"%Y%m%d\")", "[\"pandoc\", \"-s\", \"-t\", \"html5\", \"-f\", \"markdown-smart\", \"--metadata\", 'title=\"SoLoud ' +", "\"waveshaperfilter.mmd\", \"mixbus.mmd\", \"queue.mmd\", \"collider.mmd\", \"attenuator.mmd\", \"file.mmd\", \"backends.mmd\" ] website_only =", "-- --- -- - Generating epub\") callp = [\"pandoc\", \"-N\",", "2..\") subprocess.call([\"xelatex\", \"SoLoud.tex\"], stdout=outfile) shutil.move(\"SoLoud.pdf\", datestring + \"/soloud_\" + datestring", "file_out.write(line.replace('code>', 'code>\\n').replace('::','::<wbr>').replace('\\xc2','').replace('\\xa0','')) if x == \"intro.mmd\": if os.path.isfile(datestring + \"/web/index.html\"):", "suffix in tempsuffix: for file in glob.glob(\"*.\"+suffix): os.remove(file) for file", "docs!\") if unknown: print(\"Add the new files to makedoc.py, soloud.tex", "-> mobi (kindlegen_output.txt)\") with open('kindlegen_output.txt', 'w') as outfile: subprocess.call([\"kindlegen\", datestring", "\"/web/index.html\"): os.remove(datestring + \"/web/index.html\") os.rename(datestring + \"/web/intro.html\", datestring + \"/web/index.html\")", "\"--listings\", \"--default-image-extension=pdf\", \"--top-level-division=chapter\", x, \"-o\", \"temp/\" + x[:len(x)-3]+\"tex.orig\"]) with open(\"temp/\"", "single-file HTML docs\") callp = [\"pandoc\", \"-s\", \"-t\", \"html5\", \"-f\",", "x[:len(x)-4] + '\"', \"-B\", \"htmlpre.txt\", \"-A\", \"htmlpost.txt\", \"--default-image-extension=png\", x, \"-o\",", "\"dcremovalfilter.mmd\", \"fftfilter.mmd\", \"bassboostfilter.mmd\", \"waveshaperfilter.mmd\", \"mixbus.mmd\", \"queue.mmd\", \"collider.mmd\", \"attenuator.mmd\", \"file.mmd\", \"backends.mmd\"", "src: if x not in website_only: callp.append(x) subprocess.call(callp) print(\"- --", "\"voicemanagement.mmd\", \"examples.mmd\", \"foreign_interface.mmd\", \"c_api.mmd\", \"python_api.mmd\", \"ruby_api.mmd\", \"rpgmaker_api.mmd\", \"bmx_api.mmd\", \"gamemaker_api.mmd\", \"cs_api.mmd\",", "for line in file_in: file_out.write(line.replace('\\\\begin{longtable}[]{@{}ll@{}}', '\\\\begin{tabulary}{\\\\textwidth}{lJ}').replace('\\\\begin{longtable}[]{@{}lll@{}}', '\\\\begin{tabulary}{\\\\textwidth}{lJJ}').replace('\\\\begin{longtable}[]{@{}llll@{}}', '\\\\begin{tabulary}{\\\\textwidth}{lJJJ}').replace('\\\\endhead','').replace('\\\\end{longtable}','\\\\end{tabulary}')) print(\"- --", "unknown: print(\"Add the new files to makedoc.py, soloud.tex and htmlpre.txt.\")", "\"/web\"): os.makedirs(datestring + \"/web\") if not os.path.exists(\"temp/\"): os.makedirs(\"temp/\") print(\"- --", "+ x[:len(x)-3]+\"html\", \"w\") as file_out: with open(datestring + \"/web/\" +", "\"-c2\"], stdout=outfile) print(\"- -- --- -- - Generating LaTex\") for", "\"flangerfilter.mmd\", \"dcremovalfilter.mmd\", \"fftfilter.mmd\", \"bassboostfilter.mmd\", \"waveshaperfilter.mmd\", \"mixbus.mmd\", \"queue.mmd\", \"collider.mmd\", \"attenuator.mmd\", \"file.mmd\",", "os.remove(datestring + \"/web/index.html\") os.rename(datestring + \"/web/intro.html\", datestring + \"/web/index.html\") print(\"-", "src: if x not in website_only: subprocess.call([\"pandoc\", \"-t\", \"latex\", \"--listings\",", "in glob.glob(\"temp/*\"): os.remove(file) os.rmdir(\"temp\") print(\"- -- --- -- - Done", "pdf pass 2..\") subprocess.call([\"xelatex\", \"SoLoud.tex\"], stdout=outfile) shutil.move(\"SoLoud.pdf\", datestring + \"/soloud_\"", "\"--default-image-extension=png\", \"-o\", datestring + \"/soloud_\" + datestring + \".html\"] for", "website_only: subprocess.call([\"pandoc\", \"-t\", \"latex\", \"--listings\", \"--default-image-extension=pdf\", \"--top-level-division=chapter\", x, \"-o\", \"temp/\"", "in glob.glob(datestring + \"/web/*.\"+suffix): os.remove(file) for file in glob.glob(\"temp/*\"): os.remove(file)", "\"markdown-smart\", \"--metadata\", 'title=\"SoLoud ' + datestring + '\"', \"-H\", \"singlehtml_head.txt\",", "as file_out: with open(datestring + \"/web/\" + x[:len(x)-3]+\"html.bak\", \"r\") as", "file_in: for line in file_in: file_out.write(line.replace('\\\\begin{longtable}[]{@{}ll@{}}', '\\\\begin{tabulary}{\\\\textwidth}{lJ}').replace('\\\\begin{longtable}[]{@{}lll@{}}', '\\\\begin{tabulary}{\\\\textwidth}{lJJ}').replace('\\\\begin{longtable}[]{@{}llll@{}}', '\\\\begin{tabulary}{\\\\textwidth}{lJJJ}').replace('\\\\endhead','').replace('\\\\end{longtable}','\\\\end{tabulary}')) print(\"-", "[\"aux\", \"toc\", \"out\", \"log\", \"lg\", \"4ct\", \"4tc\", \"idv\", \"tmp\", \"xdv\",", "file_out: with open(datestring + \"/web/\" + x[:len(x)-3]+\"html.bak\", \"r\") as file_in:", "--- -- - Generating web site\") for x in src:", "\"singlehtml_body.txt\", \"--toc\", \"--self-contained\", \"--default-image-extension=png\", \"-o\", datestring + \"/soloud_\" + datestring", "'\"', \"-H\", \"singlehtml_head.txt\", \"-B\", \"singlehtml_body.txt\", \"--toc\", \"--self-contained\", \"--default-image-extension=png\", \"-o\", datestring", "the web site and pdf. \"\"\" import subprocess import glob", "os.remove(file) for file in glob.glob(datestring + \"/web/*.\"+suffix): os.remove(file) for file", "x not in website_only: callp.append(x) subprocess.call(callp) print(\"- -- --- --", "included in docs!\") if unknown: print(\"Add the new files to", "= [ \"intro.mmd\", \"downloads.mmd\", \"quickstart.mmd\", \"faq.mmd\", \"dirstruct.mmd\", \"premake.mmd\", \"legal.mmd\", \"concepts.mmd\",", "+ \".pdf\") print(\"- -- --- -- - Cleanup..\") tempsuffix =", "+ datestring + ' ' + x[:len(x)-4] + '\"', \"-B\",", "\"latex\", \"--listings\", \"--default-image-extension=pdf\", \"--top-level-division=chapter\", x, \"-o\", \"temp/\" + x[:len(x)-3]+\"tex.orig\"]) with", "print(\"- -- --- -- - Done - \" + datestring)", "\"r\") as file_in: for line in file_in: file_out.write(line.replace('\\\\begin{longtable}[]{@{}ll@{}}', '\\\\begin{tabulary}{\\\\textwidth}{lJ}').replace('\\\\begin{longtable}[]{@{}lll@{}}', '\\\\begin{tabulary}{\\\\textwidth}{lJJ}').replace('\\\\begin{longtable}[]{@{}llll@{}}',", "callp.append(x) subprocess.call(callp) print(\"- -- --- -- - Converting epub ->", "to makedoc.py, soloud.tex and htmlpre.txt.\") sys.exit() datestring = time.strftime(\"%Y%m%d\") if", "time import shutil src = [ \"intro.mmd\", \"downloads.mmd\", \"quickstart.mmd\", \"faq.mmd\",", "line in file_in: file_out.write(line.replace('code>', 'code>\\n').replace('::','::<wbr>').replace('\\xc2','').replace('\\xa0','')) if x == \"intro.mmd\": if", "\"markdown-smart\", \"--css=epub.css\", \"--epub-metadata=metadata.xml\", \"-o\", datestring + \"/soloud_\" + datestring +", "--- -- - Generating epub\") callp = [\"pandoc\", \"-N\", \"--toc\",", "subprocess.call([\"xelatex\", \"SoLoud.tex\"], stdout=outfile) print(\"- -- --- -- - Generating pdf", "\"htmlpre.txt\", \"-A\", \"htmlpost.txt\", \"--default-image-extension=png\", x, \"-o\", datestring + \"/web/\" +", "with open(\"temp/\" + x[:len(x)-3]+\"tex\", \"w\") as file_out: with open(\"temp/\" +", "\"out\", \"log\", \"lg\", \"4ct\", \"4tc\", \"idv\", \"tmp\", \"xdv\", \"xref\", \"bak\"]", "-- - Converting epub -> mobi (kindlegen_output.txt)\") with open('kindlegen_output.txt', 'w')", "- Converting epub -> mobi (kindlegen_output.txt)\") with open('kindlegen_output.txt', 'w') as", "'w') as outfile: subprocess.call([\"xelatex\", \"SoLoud.tex\"], stdout=outfile) print(\"- -- --- --", "website_only: callp.append(x) subprocess.call(callp) print(\"- -- --- -- - Generating web", "+ \"/soloud_\" + datestring + \".epub\", \"title.txt\"] for x in", "import time import shutil src = [ \"intro.mmd\", \"downloads.mmd\", \"quickstart.mmd\",", "\"temp/\" + x[:len(x)-3]+\"tex.orig\"]) with open(\"temp/\" + x[:len(x)-3]+\"tex\", \"w\") as file_out:", "\"voicegroups.mmd\", \"coremisc.mmd\", \"core3d.mmd\", \"audiosource.mmd\", \"newsoundsources.mmd\", \"wav.mmd\", \"wavstream.mmd\", \"speech.mmd\", \"sfxr.mmd\", \"modplug.mmd\",", "\"premake.mmd\", \"legal.mmd\", \"concepts.mmd\", \"concepts3d.mmd\", \"voicemanagement.mmd\", \"examples.mmd\", \"foreign_interface.mmd\", \"c_api.mmd\", \"python_api.mmd\", \"ruby_api.mmd\",", "-- - Generating pdf pass 2..\") subprocess.call([\"xelatex\", \"SoLoud.tex\"], stdout=outfile) shutil.move(\"SoLoud.pdf\",", "\"gamemaker_api.mmd\", \"cs_api.mmd\", \"d_api.mmd\", \"codegen.mmd\", \"basics.mmd\", \"attributes.mmd\", \"faders.mmd\", \"voicegroups.mmd\", \"coremisc.mmd\", \"core3d.mmd\",", "\"tmp\", \"xdv\", \"xref\", \"bak\"] for suffix in tempsuffix: for file", "file not in src: unknown = 1 print(file + \"", "\"--metadata\", 'title=\"SoLoud ' + datestring + ' ' + x[:len(x)-4]", "stdout=outfile) print(\"- -- --- -- - Generating LaTex\") for x", "if x not in website_only: subprocess.call([\"pandoc\", \"-t\", \"latex\", \"--listings\", \"--default-image-extension=pdf\",", "\"--default-image-extension=pdf\", \"--top-level-division=chapter\", x, \"-o\", \"temp/\" + x[:len(x)-3]+\"tex.orig\"]) with open(\"temp/\" +", "\"quickstart.mmd\", \"faq.mmd\", \"dirstruct.mmd\", \"premake.mmd\", \"legal.mmd\", \"concepts.mmd\", \"concepts3d.mmd\", \"voicemanagement.mmd\", \"examples.mmd\", \"foreign_interface.mmd\",", "Generating pdf pass 2..\") subprocess.call([\"xelatex\", \"SoLoud.tex\"], stdout=outfile) shutil.move(\"SoLoud.pdf\", datestring +", "\"--metadata\", 'title=\"SoLoud ' + datestring + '\"', \"-H\", \"singlehtml_head.txt\", \"-B\",", "\"/web/intro.html\", datestring + \"/web/index.html\") print(\"- -- --- -- - Generating", "\".html\"] for x in src: if x not in website_only:", "datestring + \"/soloud_\" + datestring + \".epub\", \"-c2\"], stdout=outfile) print(\"-", "stdout=outfile) print(\"- -- --- -- - Generating pdf pass 2..\")", "os.rename(datestring + \"/web/intro.html\", datestring + \"/web/index.html\") print(\"- -- --- --", "documentation files from multimarkdown (mmd) source to various formats, including", "site and pdf. \"\"\" import subprocess import glob import os", "\"-B\", \"singlehtml_body.txt\", \"--toc\", \"--self-contained\", \"--default-image-extension=png\", \"-o\", datestring + \"/soloud_\" +", "as file_in: for line in file_in: file_out.write(line.replace('code>', 'code>\\n').replace('::','::<wbr>').replace('\\xc2','').replace('\\xa0','')) if x", "new files to makedoc.py, soloud.tex and htmlpre.txt.\") sys.exit() datestring =", "os.rmdir(\"temp\") print(\"- -- --- -- - Done - \" +", "for line in file_in: file_out.write(line.replace('code>', 'code>\\n').replace('::','::<wbr>').replace('\\xc2','').replace('\\xa0','')) if x == \"intro.mmd\":", "\"biquadfilter.mmd\", \"echofilter.mmd\", \"lofifilter.mmd\", \"flangerfilter.mmd\", \"dcremovalfilter.mmd\", \"fftfilter.mmd\", \"bassboostfilter.mmd\", \"waveshaperfilter.mmd\", \"mixbus.mmd\", \"queue.mmd\",", "os.path.exists(datestring + \"/web\"): os.makedirs(datestring + \"/web\") if not os.path.exists(\"temp/\"): os.makedirs(\"temp/\")", "-- --- -- - Generating LaTex\") for x in src:", "builds documentation files from multimarkdown (mmd) source to various formats,", "\"--toc\", \"--epub-cover-image=images/cover.png\", \"-t\", \"epub3\", \"--default-image-extension=png\", \"-f\", \"markdown-smart\", \"--css=epub.css\", \"--epub-metadata=metadata.xml\", \"-o\",", "= [\"pandoc\", \"-s\", \"-t\", \"html5\", \"-f\", \"markdown-smart\", \"--metadata\", 'title=\"SoLoud '", "\"-o\", \"temp/\" + x[:len(x)-3]+\"tex.orig\"]) with open(\"temp/\" + x[:len(x)-3]+\"tex\", \"w\") as", "+ \"/web\") if not os.path.exists(\"temp/\"): os.makedirs(\"temp/\") print(\"- -- --- --", "\"tedsid.mmd\", \"vizsn.mmd\", \"vic.mmd\", \"filters.mmd\", \"biquadfilter.mmd\", \"echofilter.mmd\", \"lofifilter.mmd\", \"flangerfilter.mmd\", \"dcremovalfilter.mmd\", \"fftfilter.mmd\",", "\"lg\", \"4ct\", \"4tc\", \"idv\", \"tmp\", \"xdv\", \"xref\", \"bak\"] for suffix", "\"\"\" builds documentation files from multimarkdown (mmd) source to various", "\"backends.mmd\" ] website_only = [ \"downloads.mmd\" ] unknown = 0", "in website_only: subprocess.call([\"pandoc\", \"-t\", \"latex\", \"--listings\", \"--default-image-extension=pdf\", \"--top-level-division=chapter\", x, \"-o\",", "\"-t\", \"html5\", \"-f\", \"markdown-smart\", \"--metadata\", 'title=\"SoLoud ' + datestring +", "htmlpre.txt.\") sys.exit() datestring = time.strftime(\"%Y%m%d\") if not os.path.exists(datestring + \"/web\"):", "print(file + \" not included in docs!\") if unknown: print(\"Add", "Generating LaTex\") for x in src: if x not in", "\"-f\", \"markdown-smart\", \"--css=epub.css\", \"--epub-metadata=metadata.xml\", \"-o\", datestring + \"/soloud_\" + datestring", "x in src: subprocess.call([\"pandoc\", \"--template=html.pandoc\", \"-f\", \"markdown-smart\", \"--metadata\", 'title=\"SoLoud '", "1 print(file + \" not included in docs!\") if unknown:", "\"modplug.mmd\", \"monotone.mmd\", \"tedsid.mmd\", \"vizsn.mmd\", \"vic.mmd\", \"filters.mmd\", \"biquadfilter.mmd\", \"echofilter.mmd\", \"lofifilter.mmd\", \"flangerfilter.mmd\",", "multimarkdown (mmd) source to various formats, including the web site", "unknown = 1 print(file + \" not included in docs!\")", "tempsuffix: for file in glob.glob(\"*.\"+suffix): os.remove(file) for file in glob.glob(datestring", "src = [ \"intro.mmd\", \"downloads.mmd\", \"quickstart.mmd\", \"faq.mmd\", \"dirstruct.mmd\", \"premake.mmd\", \"legal.mmd\",", "glob.glob(\"*.\"+suffix): os.remove(file) for file in glob.glob(datestring + \"/web/*.\"+suffix): os.remove(file) for", "= 0 for file in glob.glob(\"*.mmd\"): if file not in", "\"--epub-metadata=metadata.xml\", \"-o\", datestring + \"/soloud_\" + datestring + \".epub\", \"title.txt\"]", "subprocess.call(callp) print(\"- -- --- -- - Generating web site\") for", "'\\\\begin{tabulary}{\\\\textwidth}{lJJJ}').replace('\\\\endhead','').replace('\\\\end{longtable}','\\\\end{tabulary}')) print(\"- -- --- -- - Generating pdf (xelatex_output.txt)\") with", "+ x[:len(x)-3]+\"tex.orig\", \"r\") as file_in: for line in file_in: file_out.write(line.replace('\\\\begin{longtable}[]{@{}ll@{}}',", "in docs!\") if unknown: print(\"Add the new files to makedoc.py,", "website_only: callp.append(x) subprocess.call(callp) print(\"- -- --- -- - Converting epub", "import glob import os import sys import time import shutil", "as file_out: with open(\"temp/\" + x[:len(x)-3]+\"tex.orig\", \"r\") as file_in: for", "+ x[:len(x)-3]+\"html.bak\", \"r\") as file_in: for line in file_in: file_out.write(line.replace('code>',", "for x in src: if x not in website_only: subprocess.call([\"pandoc\",", "file_out: with open(\"temp/\" + x[:len(x)-3]+\"tex.orig\", \"r\") as file_in: for line", "\".epub\", \"title.txt\"] for x in src: if x not in", "site\") for x in src: subprocess.call([\"pandoc\", \"--template=html.pandoc\", \"-f\", \"markdown-smart\", \"--metadata\",", "x[:len(x)-3]+\"tex\", \"w\") as file_out: with open(\"temp/\" + x[:len(x)-3]+\"tex.orig\", \"r\") as", "-- - Generating pdf (xelatex_output.txt)\") with open('xelatex_output.txt', 'w') as outfile:", "\"basics.mmd\", \"attributes.mmd\", \"faders.mmd\", \"voicegroups.mmd\", \"coremisc.mmd\", \"core3d.mmd\", \"audiosource.mmd\", \"newsoundsources.mmd\", \"wav.mmd\", \"wavstream.mmd\",", "datestring + \".epub\", \"-c2\"], stdout=outfile) print(\"- -- --- -- -", "and pdf. \"\"\" import subprocess import glob import os import", "if not os.path.exists(\"temp/\"): os.makedirs(\"temp/\") print(\"- -- --- -- - Generating", "Generating single-file HTML docs\") callp = [\"pandoc\", \"-s\", \"-t\", \"html5\",", "callp = [\"pandoc\", \"-s\", \"-t\", \"html5\", \"-f\", \"markdown-smart\", \"--metadata\", 'title=\"SoLoud", "-- - Generating single-file HTML docs\") callp = [\"pandoc\", \"-s\",", "\"-B\", \"htmlpre.txt\", \"-A\", \"htmlpost.txt\", \"--default-image-extension=png\", x, \"-o\", datestring + \"/web/\"", "+ x[:len(x)-3]+\"tex.orig\"]) with open(\"temp/\" + x[:len(x)-3]+\"tex\", \"w\") as file_out: with", "\"ruby_api.mmd\", \"rpgmaker_api.mmd\", \"bmx_api.mmd\", \"gamemaker_api.mmd\", \"cs_api.mmd\", \"d_api.mmd\", \"codegen.mmd\", \"basics.mmd\", \"attributes.mmd\", \"faders.mmd\",", "os.makedirs(\"temp/\") print(\"- -- --- -- - Generating single-file HTML docs\")", "+ \"/web/index.html\") print(\"- -- --- -- - Generating epub\") callp", "+ \"/web/\" + x[:len(x)-3]+\"html.bak\"]) with open(datestring + \"/web/\" + x[:len(x)-3]+\"html\",", "- Generating LaTex\") for x in src: if x not", "+ x[:len(x)-3]+\"html.bak\"]) with open(datestring + \"/web/\" + x[:len(x)-3]+\"html\", \"w\") as", "outfile: subprocess.call([\"kindlegen\", datestring + \"/soloud_\" + datestring + \".epub\", \"-c2\"],", "not in website_only: subprocess.call([\"pandoc\", \"-t\", \"latex\", \"--listings\", \"--default-image-extension=pdf\", \"--top-level-division=chapter\", x,", "epub -> mobi (kindlegen_output.txt)\") with open('kindlegen_output.txt', 'w') as outfile: subprocess.call([\"kindlegen\",", "' + datestring + ' ' + x[:len(x)-4] + '\"',", "-- --- -- - Generating pdf pass 2..\") subprocess.call([\"xelatex\", \"SoLoud.tex\"],", "\"/soloud_\" + datestring + \".html\"] for x in src: if", "for file in glob.glob(\"*.\"+suffix): os.remove(file) for file in glob.glob(datestring +", "pass 2..\") subprocess.call([\"xelatex\", \"SoLoud.tex\"], stdout=outfile) shutil.move(\"SoLoud.pdf\", datestring + \"/soloud_\" +", "\"/soloud_\" + datestring + \".epub\", \"-c2\"], stdout=outfile) print(\"- -- ---", "\"newsoundsources.mmd\", \"wav.mmd\", \"wavstream.mmd\", \"speech.mmd\", \"sfxr.mmd\", \"modplug.mmd\", \"monotone.mmd\", \"tedsid.mmd\", \"vizsn.mmd\", \"vic.mmd\",", "' + x[:len(x)-4] + '\"', \"-B\", \"htmlpre.txt\", \"-A\", \"htmlpost.txt\", \"--default-image-extension=png\",", "- Generating web site\") for x in src: subprocess.call([\"pandoc\", \"--template=html.pandoc\",", "- Cleanup..\") tempsuffix = [\"aux\", \"toc\", \"out\", \"log\", \"lg\", \"4ct\",", "== \"intro.mmd\": if os.path.isfile(datestring + \"/web/index.html\"): os.remove(datestring + \"/web/index.html\") os.rename(datestring", "\"speech.mmd\", \"sfxr.mmd\", \"modplug.mmd\", \"monotone.mmd\", \"tedsid.mmd\", \"vizsn.mmd\", \"vic.mmd\", \"filters.mmd\", \"biquadfilter.mmd\", \"echofilter.mmd\",", "-- --- -- - Generating web site\") for x in", "file in glob.glob(\"temp/*\"): os.remove(file) os.rmdir(\"temp\") print(\"- -- --- -- -", "datestring + \"/web/index.html\") print(\"- -- --- -- - Generating epub\")", "\"-t\", \"latex\", \"--listings\", \"--default-image-extension=pdf\", \"--top-level-division=chapter\", x, \"-o\", \"temp/\" + x[:len(x)-3]+\"tex.orig\"])", "\"downloads.mmd\" ] unknown = 0 for file in glob.glob(\"*.mmd\"): if", "website_only = [ \"downloads.mmd\" ] unknown = 0 for file", "x in src: if x not in website_only: subprocess.call([\"pandoc\", \"-t\",", "+ '\"', \"-B\", \"htmlpre.txt\", \"-A\", \"htmlpost.txt\", \"--default-image-extension=png\", x, \"-o\", datestring", "\"html5\", \"-f\", \"markdown-smart\", \"--metadata\", 'title=\"SoLoud ' + datestring + '\"',", "datestring = time.strftime(\"%Y%m%d\") if not os.path.exists(datestring + \"/web\"): os.makedirs(datestring +", "- Generating epub\") callp = [\"pandoc\", \"-N\", \"--toc\", \"--epub-cover-image=images/cover.png\", \"-t\",", "\"--css=epub.css\", \"--epub-metadata=metadata.xml\", \"-o\", datestring + \"/soloud_\" + datestring + \".epub\",", "\"wav.mmd\", \"wavstream.mmd\", \"speech.mmd\", \"sfxr.mmd\", \"modplug.mmd\", \"monotone.mmd\", \"tedsid.mmd\", \"vizsn.mmd\", \"vic.mmd\", \"filters.mmd\",", "+ \"/web/\" + x[:len(x)-3]+\"html\", \"w\") as file_out: with open(datestring +", "x, \"-o\", datestring + \"/web/\" + x[:len(x)-3]+\"html.bak\"]) with open(datestring +", "datestring + \"/soloud_\" + datestring + \".epub\", \"title.txt\"] for x", "datestring + \".pdf\") print(\"- -- --- -- - Cleanup..\") tempsuffix", "callp.append(x) subprocess.call(callp) print(\"- -- --- -- - Generating web site\")", "-- --- -- - Generating pdf (xelatex_output.txt)\") with open('xelatex_output.txt', 'w')", "[\"pandoc\", \"-N\", \"--toc\", \"--epub-cover-image=images/cover.png\", \"-t\", \"epub3\", \"--default-image-extension=png\", \"-f\", \"markdown-smart\", \"--css=epub.css\",", "+ \".epub\", \"-c2\"], stdout=outfile) print(\"- -- --- -- - Generating", "\"wavstream.mmd\", \"speech.mmd\", \"sfxr.mmd\", \"modplug.mmd\", \"monotone.mmd\", \"tedsid.mmd\", \"vizsn.mmd\", \"vic.mmd\", \"filters.mmd\", \"biquadfilter.mmd\",", "\"vizsn.mmd\", \"vic.mmd\", \"filters.mmd\", \"biquadfilter.mmd\", \"echofilter.mmd\", \"lofifilter.mmd\", \"flangerfilter.mmd\", \"dcremovalfilter.mmd\", \"fftfilter.mmd\", \"bassboostfilter.mmd\",", "--- -- - Converting epub -> mobi (kindlegen_output.txt)\") with open('kindlegen_output.txt',", "if not os.path.exists(datestring + \"/web\"): os.makedirs(datestring + \"/web\") if not", "Cleanup..\") tempsuffix = [\"aux\", \"toc\", \"out\", \"log\", \"lg\", \"4ct\", \"4tc\",", "in glob.glob(\"*.mmd\"): if file not in src: unknown = 1", "\"echofilter.mmd\", \"lofifilter.mmd\", \"flangerfilter.mmd\", \"dcremovalfilter.mmd\", \"fftfilter.mmd\", \"bassboostfilter.mmd\", \"waveshaperfilter.mmd\", \"mixbus.mmd\", \"queue.mmd\", \"collider.mmd\",", "datestring + \"/web/\" + x[:len(x)-3]+\"html.bak\"]) with open(datestring + \"/web/\" +", "\"--default-image-extension=png\", \"-f\", \"markdown-smart\", \"--css=epub.css\", \"--epub-metadata=metadata.xml\", \"-o\", datestring + \"/soloud_\" +", "print(\"- -- --- -- - Cleanup..\") tempsuffix = [\"aux\", \"toc\",", "open(\"temp/\" + x[:len(x)-3]+\"tex.orig\", \"r\") as file_in: for line in file_in:", "\"/web/index.html\") print(\"- -- --- -- - Generating epub\") callp =", "\"filters.mmd\", \"biquadfilter.mmd\", \"echofilter.mmd\", \"lofifilter.mmd\", \"flangerfilter.mmd\", \"dcremovalfilter.mmd\", \"fftfilter.mmd\", \"bassboostfilter.mmd\", \"waveshaperfilter.mmd\", \"mixbus.mmd\",", "file in glob.glob(\"*.\"+suffix): os.remove(file) for file in glob.glob(datestring + \"/web/*.\"+suffix):", "print(\"- -- --- -- - Generating LaTex\") for x in", "os.path.isfile(datestring + \"/web/index.html\"): os.remove(datestring + \"/web/index.html\") os.rename(datestring + \"/web/intro.html\", datestring", "\"-N\", \"--toc\", \"--epub-cover-image=images/cover.png\", \"-t\", \"epub3\", \"--default-image-extension=png\", \"-f\", \"markdown-smart\", \"--css=epub.css\", \"--epub-metadata=metadata.xml\",", "subprocess import glob import os import sys import time import", "-- --- -- - Converting epub -> mobi (kindlegen_output.txt)\") with", "--- -- - Generating LaTex\") for x in src: if", "\"/soloud_\" + datestring + \".epub\", \"title.txt\"] for x in src:", "\"concepts.mmd\", \"concepts3d.mmd\", \"voicemanagement.mmd\", \"examples.mmd\", \"foreign_interface.mmd\", \"c_api.mmd\", \"python_api.mmd\", \"ruby_api.mmd\", \"rpgmaker_api.mmd\", \"bmx_api.mmd\",", "+ \"/web/index.html\"): os.remove(datestring + \"/web/index.html\") os.rename(datestring + \"/web/intro.html\", datestring +", "\"singlehtml_head.txt\", \"-B\", \"singlehtml_body.txt\", \"--toc\", \"--self-contained\", \"--default-image-extension=png\", \"-o\", datestring + \"/soloud_\"", "= [\"aux\", \"toc\", \"out\", \"log\", \"lg\", \"4ct\", \"4tc\", \"idv\", \"tmp\",", "shutil src = [ \"intro.mmd\", \"downloads.mmd\", \"quickstart.mmd\", \"faq.mmd\", \"dirstruct.mmd\", \"premake.mmd\",", "if unknown: print(\"Add the new files to makedoc.py, soloud.tex and", "not os.path.exists(datestring + \"/web\"): os.makedirs(datestring + \"/web\") if not os.path.exists(\"temp/\"):", "+ datestring + \".epub\", \"-c2\"], stdout=outfile) print(\"- -- --- --", "print(\"Add the new files to makedoc.py, soloud.tex and htmlpre.txt.\") sys.exit()", "in glob.glob(\"*.\"+suffix): os.remove(file) for file in glob.glob(datestring + \"/web/*.\"+suffix): os.remove(file)", "Converting epub -> mobi (kindlegen_output.txt)\") with open('kindlegen_output.txt', 'w') as outfile:", "open(datestring + \"/web/\" + x[:len(x)-3]+\"html.bak\", \"r\") as file_in: for line", "epub\") callp = [\"pandoc\", \"-N\", \"--toc\", \"--epub-cover-image=images/cover.png\", \"-t\", \"epub3\", \"--default-image-extension=png\",", "\"SoLoud.tex\"], stdout=outfile) print(\"- -- --- -- - Generating pdf pass", "\"queue.mmd\", \"collider.mmd\", \"attenuator.mmd\", \"file.mmd\", \"backends.mmd\" ] website_only = [ \"downloads.mmd\"", "\"intro.mmd\", \"downloads.mmd\", \"quickstart.mmd\", \"faq.mmd\", \"dirstruct.mmd\", \"premake.mmd\", \"legal.mmd\", \"concepts.mmd\", \"concepts3d.mmd\", \"voicemanagement.mmd\",", "\"/web/\" + x[:len(x)-3]+\"html.bak\", \"r\") as file_in: for line in file_in:", "for x in src: if x not in website_only: callp.append(x)", "\"-A\", \"htmlpost.txt\", \"--default-image-extension=png\", x, \"-o\", datestring + \"/web/\" + x[:len(x)-3]+\"html.bak\"])", "web site and pdf. \"\"\" import subprocess import glob import", "-- - Cleanup..\") tempsuffix = [\"aux\", \"toc\", \"out\", \"log\", \"lg\",", "\"/web/*.\"+suffix): os.remove(file) for file in glob.glob(\"temp/*\"): os.remove(file) os.rmdir(\"temp\") print(\"- --", "src: unknown = 1 print(file + \" not included in", "\"title.txt\"] for x in src: if x not in website_only:", "\" not included in docs!\") if unknown: print(\"Add the new", "\"lofifilter.mmd\", \"flangerfilter.mmd\", \"dcremovalfilter.mmd\", \"fftfilter.mmd\", \"bassboostfilter.mmd\", \"waveshaperfilter.mmd\", \"mixbus.mmd\", \"queue.mmd\", \"collider.mmd\", \"attenuator.mmd\",", "\"monotone.mmd\", \"tedsid.mmd\", \"vizsn.mmd\", \"vic.mmd\", \"filters.mmd\", \"biquadfilter.mmd\", \"echofilter.mmd\", \"lofifilter.mmd\", \"flangerfilter.mmd\", \"dcremovalfilter.mmd\",", "including the web site and pdf. \"\"\" import subprocess import", "datestring + \"/soloud_\" + datestring + \".html\"] for x in", "\"fftfilter.mmd\", \"bassboostfilter.mmd\", \"waveshaperfilter.mmd\", \"mixbus.mmd\", \"queue.mmd\", \"collider.mmd\", \"attenuator.mmd\", \"file.mmd\", \"backends.mmd\" ]", "for file in glob.glob(\"temp/*\"): os.remove(file) os.rmdir(\"temp\") print(\"- -- --- --", "\"concepts3d.mmd\", \"voicemanagement.mmd\", \"examples.mmd\", \"foreign_interface.mmd\", \"c_api.mmd\", \"python_api.mmd\", \"ruby_api.mmd\", \"rpgmaker_api.mmd\", \"bmx_api.mmd\", \"gamemaker_api.mmd\",", "-- - Generating epub\") callp = [\"pandoc\", \"-N\", \"--toc\", \"--epub-cover-image=images/cover.png\",", "x[:len(x)-3]+\"html.bak\", \"r\") as file_in: for line in file_in: file_out.write(line.replace('code>', 'code>\\n').replace('::','::<wbr>').replace('\\xc2','').replace('\\xa0',''))", "file in glob.glob(\"*.mmd\"): if file not in src: unknown =", "'title=\"SoLoud ' + datestring + ' ' + x[:len(x)-4] +", "x in src: if x not in website_only: callp.append(x) subprocess.call(callp)", "(mmd) source to various formats, including the web site and", "os.remove(file) for file in glob.glob(\"temp/*\"): os.remove(file) os.rmdir(\"temp\") print(\"- -- ---", "- Generating pdf (xelatex_output.txt)\") with open('xelatex_output.txt', 'w') as outfile: subprocess.call([\"xelatex\",", "print(\"- -- --- -- - Converting epub -> mobi (kindlegen_output.txt)\")", "print(\"- -- --- -- - Generating pdf (xelatex_output.txt)\") with open('xelatex_output.txt',", "\"bmx_api.mmd\", \"gamemaker_api.mmd\", \"cs_api.mmd\", \"d_api.mmd\", \"codegen.mmd\", \"basics.mmd\", \"attributes.mmd\", \"faders.mmd\", \"voicegroups.mmd\", \"coremisc.mmd\",", "file in glob.glob(datestring + \"/web/*.\"+suffix): os.remove(file) for file in glob.glob(\"temp/*\"):", "import os import sys import time import shutil src =", "\"attenuator.mmd\", \"file.mmd\", \"backends.mmd\" ] website_only = [ \"downloads.mmd\" ] unknown", "- Generating pdf pass 2..\") subprocess.call([\"xelatex\", \"SoLoud.tex\"], stdout=outfile) shutil.move(\"SoLoud.pdf\", datestring", "with open(datestring + \"/web/\" + x[:len(x)-3]+\"html.bak\", \"r\") as file_in: for", "datestring + '\"', \"-H\", \"singlehtml_head.txt\", \"-B\", \"singlehtml_body.txt\", \"--toc\", \"--self-contained\", \"--default-image-extension=png\",", "pdf (xelatex_output.txt)\") with open('xelatex_output.txt', 'w') as outfile: subprocess.call([\"xelatex\", \"SoLoud.tex\"], stdout=outfile)", "+ x[:len(x)-4] + '\"', \"-B\", \"htmlpre.txt\", \"-A\", \"htmlpost.txt\", \"--default-image-extension=png\", x,", "\"r\") as file_in: for line in file_in: file_out.write(line.replace('code>', 'code>\\n').replace('::','::<wbr>').replace('\\xc2','').replace('\\xa0','')) if", "= 1 print(file + \" not included in docs!\") if", "\"vic.mmd\", \"filters.mmd\", \"biquadfilter.mmd\", \"echofilter.mmd\", \"lofifilter.mmd\", \"flangerfilter.mmd\", \"dcremovalfilter.mmd\", \"fftfilter.mmd\", \"bassboostfilter.mmd\", \"waveshaperfilter.mmd\",", "for x in src: subprocess.call([\"pandoc\", \"--template=html.pandoc\", \"-f\", \"markdown-smart\", \"--metadata\", 'title=\"SoLoud", "+ \"/web/index.html\") os.rename(datestring + \"/web/intro.html\", datestring + \"/web/index.html\") print(\"- --", "soloud.tex and htmlpre.txt.\") sys.exit() datestring = time.strftime(\"%Y%m%d\") if not os.path.exists(datestring", "+ '\"', \"-H\", \"singlehtml_head.txt\", \"-B\", \"singlehtml_body.txt\", \"--toc\", \"--self-contained\", \"--default-image-extension=png\", \"-o\",", "\"coremisc.mmd\", \"core3d.mmd\", \"audiosource.mmd\", \"newsoundsources.mmd\", \"wav.mmd\", \"wavstream.mmd\", \"speech.mmd\", \"sfxr.mmd\", \"modplug.mmd\", \"monotone.mmd\",", "not in src: unknown = 1 print(file + \" not", "Generating web site\") for x in src: subprocess.call([\"pandoc\", \"--template=html.pandoc\", \"-f\",", "os.makedirs(datestring + \"/web\") if not os.path.exists(\"temp/\"): os.makedirs(\"temp/\") print(\"- -- ---", "for file in glob.glob(datestring + \"/web/*.\"+suffix): os.remove(file) for file in", "import shutil src = [ \"intro.mmd\", \"downloads.mmd\", \"quickstart.mmd\", \"faq.mmd\", \"dirstruct.mmd\",", "\"w\") as file_out: with open(datestring + \"/web/\" + x[:len(x)-3]+\"html.bak\", \"r\")", "\"-f\", \"markdown-smart\", \"--metadata\", 'title=\"SoLoud ' + datestring + ' '", "makedoc.py, soloud.tex and htmlpre.txt.\") sys.exit() datestring = time.strftime(\"%Y%m%d\") if not", "+ \"/web\"): os.makedirs(datestring + \"/web\") if not os.path.exists(\"temp/\"): os.makedirs(\"temp/\") print(\"-", "the new files to makedoc.py, soloud.tex and htmlpre.txt.\") sys.exit() datestring", "\"4tc\", \"idv\", \"tmp\", \"xdv\", \"xref\", \"bak\"] for suffix in tempsuffix:", "with open(datestring + \"/web/\" + x[:len(x)-3]+\"html\", \"w\") as file_out: with", "import sys import time import shutil src = [ \"intro.mmd\",", "os.remove(file) os.rmdir(\"temp\") print(\"- -- --- -- - Done - \"", "\"faq.mmd\", \"dirstruct.mmd\", \"premake.mmd\", \"legal.mmd\", \"concepts.mmd\", \"concepts3d.mmd\", \"voicemanagement.mmd\", \"examples.mmd\", \"foreign_interface.mmd\", \"c_api.mmd\",", "--- -- - Generating single-file HTML docs\") callp = [\"pandoc\",", "source to various formats, including the web site and pdf.", "] website_only = [ \"downloads.mmd\" ] unknown = 0 for", "(kindlegen_output.txt)\") with open('kindlegen_output.txt', 'w') as outfile: subprocess.call([\"kindlegen\", datestring + \"/soloud_\"", "datestring + ' ' + x[:len(x)-4] + '\"', \"-B\", \"htmlpre.txt\",", "+ ' ' + x[:len(x)-4] + '\"', \"-B\", \"htmlpre.txt\", \"-A\",", "x == \"intro.mmd\": if os.path.isfile(datestring + \"/web/index.html\"): os.remove(datestring + \"/web/index.html\")", "+ \"/web/intro.html\", datestring + \"/web/index.html\") print(\"- -- --- -- -", "\"--epub-cover-image=images/cover.png\", \"-t\", \"epub3\", \"--default-image-extension=png\", \"-f\", \"markdown-smart\", \"--css=epub.css\", \"--epub-metadata=metadata.xml\", \"-o\", datestring", "\"audiosource.mmd\", \"newsoundsources.mmd\", \"wav.mmd\", \"wavstream.mmd\", \"speech.mmd\", \"sfxr.mmd\", \"modplug.mmd\", \"monotone.mmd\", \"tedsid.mmd\", \"vizsn.mmd\",", "if x not in website_only: callp.append(x) subprocess.call(callp) print(\"- -- ---", "in src: subprocess.call([\"pandoc\", \"--template=html.pandoc\", \"-f\", \"markdown-smart\", \"--metadata\", 'title=\"SoLoud ' +", "in website_only: callp.append(x) subprocess.call(callp) print(\"- -- --- -- - Generating", "Generating pdf (xelatex_output.txt)\") with open('xelatex_output.txt', 'w') as outfile: subprocess.call([\"xelatex\", \"SoLoud.tex\"],", "' ' + x[:len(x)-4] + '\"', \"-B\", \"htmlpre.txt\", \"-A\", \"htmlpost.txt\",", "x not in website_only: subprocess.call([\"pandoc\", \"-t\", \"latex\", \"--listings\", \"--default-image-extension=pdf\", \"--top-level-division=chapter\",", "\"d_api.mmd\", \"codegen.mmd\", \"basics.mmd\", \"attributes.mmd\", \"faders.mmd\", \"voicegroups.mmd\", \"coremisc.mmd\", \"core3d.mmd\", \"audiosource.mmd\", \"newsoundsources.mmd\",", "\"-t\", \"epub3\", \"--default-image-extension=png\", \"-f\", \"markdown-smart\", \"--css=epub.css\", \"--epub-metadata=metadata.xml\", \"-o\", datestring +", "print(\"- -- --- -- - Generating single-file HTML docs\") callp", "\"-s\", \"-t\", \"html5\", \"-f\", \"markdown-smart\", \"--metadata\", 'title=\"SoLoud ' + datestring", "tempsuffix = [\"aux\", \"toc\", \"out\", \"log\", \"lg\", \"4ct\", \"4tc\", \"idv\",", "docs\") callp = [\"pandoc\", \"-s\", \"-t\", \"html5\", \"-f\", \"markdown-smart\", \"--metadata\",", "and htmlpre.txt.\") sys.exit() datestring = time.strftime(\"%Y%m%d\") if not os.path.exists(datestring +", "glob.glob(\"temp/*\"): os.remove(file) os.rmdir(\"temp\") print(\"- -- --- -- - Done -", "= time.strftime(\"%Y%m%d\") if not os.path.exists(datestring + \"/web\"): os.makedirs(datestring + \"/web\")", "\"markdown-smart\", \"--metadata\", 'title=\"SoLoud ' + datestring + ' ' +", "+ datestring + \".html\"] for x in src: if x", "'\\\\begin{tabulary}{\\\\textwidth}{lJJ}').replace('\\\\begin{longtable}[]{@{}llll@{}}', '\\\\begin{tabulary}{\\\\textwidth}{lJJJ}').replace('\\\\endhead','').replace('\\\\end{longtable}','\\\\end{tabulary}')) print(\"- -- --- -- - Generating pdf (xelatex_output.txt)\")", "file_out.write(line.replace('\\\\begin{longtable}[]{@{}ll@{}}', '\\\\begin{tabulary}{\\\\textwidth}{lJ}').replace('\\\\begin{longtable}[]{@{}lll@{}}', '\\\\begin{tabulary}{\\\\textwidth}{lJJ}').replace('\\\\begin{longtable}[]{@{}llll@{}}', '\\\\begin{tabulary}{\\\\textwidth}{lJJJ}').replace('\\\\endhead','').replace('\\\\end{longtable}','\\\\end{tabulary}')) print(\"- -- --- -- - Generating", "as outfile: subprocess.call([\"xelatex\", \"SoLoud.tex\"], stdout=outfile) print(\"- -- --- -- -", "os.path.exists(\"temp/\"): os.makedirs(\"temp/\") print(\"- -- --- -- - Generating single-file HTML", "\"/web/index.html\") os.rename(datestring + \"/web/intro.html\", datestring + \"/web/index.html\") print(\"- -- ---", "= [ \"downloads.mmd\" ] unknown = 0 for file in", "files from multimarkdown (mmd) source to various formats, including the", "src: subprocess.call([\"pandoc\", \"--template=html.pandoc\", \"-f\", \"markdown-smart\", \"--metadata\", 'title=\"SoLoud ' + datestring", "'code>\\n').replace('::','::<wbr>').replace('\\xc2','').replace('\\xa0','')) if x == \"intro.mmd\": if os.path.isfile(datestring + \"/web/index.html\"): os.remove(datestring", "\"core3d.mmd\", \"audiosource.mmd\", \"newsoundsources.mmd\", \"wav.mmd\", \"wavstream.mmd\", \"speech.mmd\", \"sfxr.mmd\", \"modplug.mmd\", \"monotone.mmd\", \"tedsid.mmd\",", "+ \".html\"] for x in src: if x not in", "\"intro.mmd\": if os.path.isfile(datestring + \"/web/index.html\"): os.remove(datestring + \"/web/index.html\") os.rename(datestring +", "+ \"/web/\" + x[:len(x)-3]+\"html.bak\", \"r\") as file_in: for line in", "print(\"- -- --- -- - Generating web site\") for x", "'title=\"SoLoud ' + datestring + '\"', \"-H\", \"singlehtml_head.txt\", \"-B\", \"singlehtml_body.txt\",", "unknown = 0 for file in glob.glob(\"*.mmd\"): if file not", "-- - Generating web site\") for x in src: subprocess.call([\"pandoc\",", "file_in: file_out.write(line.replace('code>', 'code>\\n').replace('::','::<wbr>').replace('\\xc2','').replace('\\xa0','')) if x == \"intro.mmd\": if os.path.isfile(datestring +", "\"python_api.mmd\", \"ruby_api.mmd\", \"rpgmaker_api.mmd\", \"bmx_api.mmd\", \"gamemaker_api.mmd\", \"cs_api.mmd\", \"d_api.mmd\", \"codegen.mmd\", \"basics.mmd\", \"attributes.mmd\",", "if x == \"intro.mmd\": if os.path.isfile(datestring + \"/web/index.html\"): os.remove(datestring +", "\"codegen.mmd\", \"basics.mmd\", \"attributes.mmd\", \"faders.mmd\", \"voicegroups.mmd\", \"coremisc.mmd\", \"core3d.mmd\", \"audiosource.mmd\", \"newsoundsources.mmd\", \"wav.mmd\",", "x[:len(x)-3]+\"html.bak\"]) with open(datestring + \"/web/\" + x[:len(x)-3]+\"html\", \"w\") as file_out:", "line in file_in: file_out.write(line.replace('\\\\begin{longtable}[]{@{}ll@{}}', '\\\\begin{tabulary}{\\\\textwidth}{lJ}').replace('\\\\begin{longtable}[]{@{}lll@{}}', '\\\\begin{tabulary}{\\\\textwidth}{lJJ}').replace('\\\\begin{longtable}[]{@{}llll@{}}', '\\\\begin{tabulary}{\\\\textwidth}{lJJJ}').replace('\\\\endhead','').replace('\\\\end{longtable}','\\\\end{tabulary}')) print(\"- -- ---", "\"file.mmd\", \"backends.mmd\" ] website_only = [ \"downloads.mmd\" ] unknown =", "formats, including the web site and pdf. \"\"\" import subprocess", "with open(\"temp/\" + x[:len(x)-3]+\"tex.orig\", \"r\") as file_in: for line in", "[ \"downloads.mmd\" ] unknown = 0 for file in glob.glob(\"*.mmd\"):", "glob import os import sys import time import shutil src", "+ datestring + \".epub\", \"title.txt\"] for x in src: if", "\"log\", \"lg\", \"4ct\", \"4tc\", \"idv\", \"tmp\", \"xdv\", \"xref\", \"bak\"] for", "glob.glob(datestring + \"/web/*.\"+suffix): os.remove(file) for file in glob.glob(\"temp/*\"): os.remove(file) os.rmdir(\"temp\")", "\"--top-level-division=chapter\", x, \"-o\", \"temp/\" + x[:len(x)-3]+\"tex.orig\"]) with open(\"temp/\" + x[:len(x)-3]+\"tex\",", "\"-o\", datestring + \"/web/\" + x[:len(x)-3]+\"html.bak\"]) with open(datestring + \"/web/\"", "outfile: subprocess.call([\"xelatex\", \"SoLoud.tex\"], stdout=outfile) print(\"- -- --- -- - Generating", "os import sys import time import shutil src = [", "x[:len(x)-3]+\"tex.orig\"]) with open(\"temp/\" + x[:len(x)-3]+\"tex\", \"w\") as file_out: with open(\"temp/\"", "for suffix in tempsuffix: for file in glob.glob(\"*.\"+suffix): os.remove(file) for", "\"examples.mmd\", \"foreign_interface.mmd\", \"c_api.mmd\", \"python_api.mmd\", \"ruby_api.mmd\", \"rpgmaker_api.mmd\", \"bmx_api.mmd\", \"gamemaker_api.mmd\", \"cs_api.mmd\", \"d_api.mmd\",", "file_in: file_out.write(line.replace('\\\\begin{longtable}[]{@{}ll@{}}', '\\\\begin{tabulary}{\\\\textwidth}{lJ}').replace('\\\\begin{longtable}[]{@{}lll@{}}', '\\\\begin{tabulary}{\\\\textwidth}{lJJ}').replace('\\\\begin{longtable}[]{@{}llll@{}}', '\\\\begin{tabulary}{\\\\textwidth}{lJJJ}').replace('\\\\endhead','').replace('\\\\end{longtable}','\\\\end{tabulary}')) print(\"- -- --- -- -", "in src: if x not in website_only: callp.append(x) subprocess.call(callp) print(\"-", "datestring + \"/soloud_\" + datestring + \".pdf\") print(\"- -- ---", "open('xelatex_output.txt', 'w') as outfile: subprocess.call([\"xelatex\", \"SoLoud.tex\"], stdout=outfile) print(\"- -- ---", "sys import time import shutil src = [ \"intro.mmd\", \"downloads.mmd\",", "' + datestring + '\"', \"-H\", \"singlehtml_head.txt\", \"-B\", \"singlehtml_body.txt\", \"--toc\",", "\"xref\", \"bak\"] for suffix in tempsuffix: for file in glob.glob(\"*.\"+suffix):", "\"cs_api.mmd\", \"d_api.mmd\", \"codegen.mmd\", \"basics.mmd\", \"attributes.mmd\", \"faders.mmd\", \"voicegroups.mmd\", \"coremisc.mmd\", \"core3d.mmd\", \"audiosource.mmd\",", "stdout=outfile) shutil.move(\"SoLoud.pdf\", datestring + \"/soloud_\" + datestring + \".pdf\") print(\"-", "+ \" not included in docs!\") if unknown: print(\"Add the", "\"legal.mmd\", \"concepts.mmd\", \"concepts3d.mmd\", \"voicemanagement.mmd\", \"examples.mmd\", \"foreign_interface.mmd\", \"c_api.mmd\", \"python_api.mmd\", \"ruby_api.mmd\", \"rpgmaker_api.mmd\",", "\"w\") as file_out: with open(\"temp/\" + x[:len(x)-3]+\"tex.orig\", \"r\") as file_in:", "(xelatex_output.txt)\") with open('xelatex_output.txt', 'w') as outfile: subprocess.call([\"xelatex\", \"SoLoud.tex\"], stdout=outfile) print(\"-", "<reponame>syoyo/soloud<filename>docsrc/makedoc.py #!/usr/bin/env python3 \"\"\" builds documentation files from multimarkdown (mmd)", "+ \"/soloud_\" + datestring + \".epub\", \"-c2\"], stdout=outfile) print(\"- --", "--- -- - Cleanup..\") tempsuffix = [\"aux\", \"toc\", \"out\", \"log\",", "callp = [\"pandoc\", \"-N\", \"--toc\", \"--epub-cover-image=images/cover.png\", \"-t\", \"epub3\", \"--default-image-extension=png\", \"-f\",", "-- - Generating LaTex\") for x in src: if x", "pdf. \"\"\" import subprocess import glob import os import sys", "in file_in: file_out.write(line.replace('code>', 'code>\\n').replace('::','::<wbr>').replace('\\xc2','').replace('\\xa0','')) if x == \"intro.mmd\": if os.path.isfile(datestring", "with open('kindlegen_output.txt', 'w') as outfile: subprocess.call([\"kindlegen\", datestring + \"/soloud_\" +", "\"idv\", \"tmp\", \"xdv\", \"xref\", \"bak\"] for suffix in tempsuffix: for", "\"bassboostfilter.mmd\", \"waveshaperfilter.mmd\", \"mixbus.mmd\", \"queue.mmd\", \"collider.mmd\", \"attenuator.mmd\", \"file.mmd\", \"backends.mmd\" ] website_only", "[ \"intro.mmd\", \"downloads.mmd\", \"quickstart.mmd\", \"faq.mmd\", \"dirstruct.mmd\", \"premake.mmd\", \"legal.mmd\", \"concepts.mmd\", \"concepts3d.mmd\",", "\"toc\", \"out\", \"log\", \"lg\", \"4ct\", \"4tc\", \"idv\", \"tmp\", \"xdv\", \"xref\",", "\"collider.mmd\", \"attenuator.mmd\", \"file.mmd\", \"backends.mmd\" ] website_only = [ \"downloads.mmd\" ]" ]
[ "== other.party_id and self.role == other.role def to_pb(self): from arch.api.proto", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "the License. # class Party(object): \"\"\" Uniquely identify \"\"\" def", "# # Licensed under the Apache License, Version 2.0 (the", "compliance with the License. # You may obtain a copy", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "All Rights Reserved. # # Licensed under the Apache License,", "2.0 (the \"License\"); # you may not use this file", "file except in compliance with the License. # You may", "agreed to in writing, software # distributed under the License", "Unless required by applicable law or agreed to in writing,", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "__repr__(self): return self.__str__() def __lt__(self, other): return (self.role, self.party_id) <", "distributed under the License is distributed on an \"AS IS\"", "Copyright 2019 The FATE Authors. All Rights Reserved. # #", "def __eq__(self, other): return self.party_id == other.party_id and self.role ==", "role, party_id): self.role = role self.party_id = party_id def __hash__(self):", "return (self.role, self.party_id).__hash__() def __str__(self): return f\"Party(role={self.role}, party_id={self.party_id})\" def __repr__(self):", "# Copyright 2019 The FATE Authors. All Rights Reserved. #", "the specific language governing permissions and # limitations under the", "self.party_id).__hash__() def __str__(self): return f\"Party(role={self.role}, party_id={self.party_id})\" def __repr__(self): return self.__str__()", "self.role == other.role def to_pb(self): from arch.api.proto import federation_pb2 return", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "other.party_id and self.role == other.role def to_pb(self): from arch.api.proto import", "and self.role == other.role def to_pb(self): from arch.api.proto import federation_pb2", "express or implied. # See the License for the specific", "applicable law or agreed to in writing, software # distributed", "except in compliance with the License. # You may obtain", "party_id={self.party_id})\" def __repr__(self): return self.__str__() def __lt__(self, other): return (self.role,", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "\"\"\" Uniquely identify \"\"\" def __init__(self, role, party_id): self.role =", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "self.party_id == other.party_id and self.role == other.role def to_pb(self): from", "__init__(self, role, party_id): self.role = role self.party_id = party_id def", "not use this file except in compliance with the License.", "governing permissions and # limitations under the License. # class", "Party(object): \"\"\" Uniquely identify \"\"\" def __init__(self, role, party_id): self.role", "writing, software # distributed under the License is distributed on", "in writing, software # distributed under the License is distributed", "you may not use this file except in compliance with", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "limitations under the License. # class Party(object): \"\"\" Uniquely identify", "self.role = role self.party_id = party_id def __hash__(self): return (self.role,", "use this file except in compliance with the License. #", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "= party_id def __hash__(self): return (self.role, self.party_id).__hash__() def __str__(self): return", "CONDITIONS OF ANY KIND, either express or implied. # See", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "or implied. # See the License for the specific language", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "Rights Reserved. # # Licensed under the Apache License, Version", "License. # You may obtain a copy of the License", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "License, Version 2.0 (the \"License\"); # you may not use", "= role self.party_id = party_id def __hash__(self): return (self.role, self.party_id).__hash__()", "# You may obtain a copy of the License at", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "under the License is distributed on an \"AS IS\" BASIS,", "def __str__(self): return f\"Party(role={self.role}, party_id={self.party_id})\" def __repr__(self): return self.__str__() def", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "return f\"Party(role={self.role}, party_id={self.party_id})\" def __repr__(self): return self.__str__() def __lt__(self, other):", "and # limitations under the License. # class Party(object): \"\"\"", "License for the specific language governing permissions and # limitations", "Authors. All Rights Reserved. # # Licensed under the Apache", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "# limitations under the License. # class Party(object): \"\"\" Uniquely", "self.party_id = party_id def __hash__(self): return (self.role, self.party_id).__hash__() def __str__(self):", "other.party_id) def __eq__(self, other): return self.party_id == other.party_id and self.role", "\"\"\" def __init__(self, role, party_id): self.role = role self.party_id =", "Reserved. # # Licensed under the Apache License, Version 2.0", "self.__str__() def __lt__(self, other): return (self.role, self.party_id) < (other.role, other.party_id)", "the License for the specific language governing permissions and #", "(the \"License\"); # you may not use this file except", "Apache License, Version 2.0 (the \"License\"); # you may not", "# you may not use this file except in compliance", "The FATE Authors. All Rights Reserved. # # Licensed under", "either express or implied. # See the License for the", "(other.role, other.party_id) def __eq__(self, other): return self.party_id == other.party_id and", "OR CONDITIONS OF ANY KIND, either express or implied. #", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "the License is distributed on an \"AS IS\" BASIS, #", "2019 The FATE Authors. All Rights Reserved. # # Licensed", "__lt__(self, other): return (self.role, self.party_id) < (other.role, other.party_id) def __eq__(self,", "in compliance with the License. # You may obtain a", "identify \"\"\" def __init__(self, role, party_id): self.role = role self.party_id", "software # distributed under the License is distributed on an", "other): return self.party_id == other.party_id and self.role == other.role def", "def __init__(self, role, party_id): self.role = role self.party_id = party_id", "# # Unless required by applicable law or agreed to", "def __lt__(self, other): return (self.role, self.party_id) < (other.role, other.party_id) def", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "License. # class Party(object): \"\"\" Uniquely identify \"\"\" def __init__(self,", "permissions and # limitations under the License. # class Party(object):", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "FATE Authors. All Rights Reserved. # # Licensed under the", "Version 2.0 (the \"License\"); # you may not use this", "law or agreed to in writing, software # distributed under", "Uniquely identify \"\"\" def __init__(self, role, party_id): self.role = role", "# # Copyright 2019 The FATE Authors. All Rights Reserved.", "party_id): self.role = role self.party_id = party_id def __hash__(self): return", "return self.party_id == other.party_id and self.role == other.role def to_pb(self):", "<filename>arch/api/base/utils/party.py # # Copyright 2019 The FATE Authors. All Rights", "== other.role def to_pb(self): from arch.api.proto import federation_pb2 return federation_pb2.Party(partyId=f\"{self.party_id}\",", "implied. # See the License for the specific language governing", "def __repr__(self): return self.__str__() def __lt__(self, other): return (self.role, self.party_id)", "under the Apache License, Version 2.0 (the \"License\"); # you", "\"License\"); # you may not use this file except in", "return (self.role, self.party_id) < (other.role, other.party_id) def __eq__(self, other): return", "__hash__(self): return (self.role, self.party_id).__hash__() def __str__(self): return f\"Party(role={self.role}, party_id={self.party_id})\" def", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "return self.__str__() def __lt__(self, other): return (self.role, self.party_id) < (other.role,", "# class Party(object): \"\"\" Uniquely identify \"\"\" def __init__(self, role,", "by applicable law or agreed to in writing, software #", "# distributed under the License is distributed on an \"AS", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "role self.party_id = party_id def __hash__(self): return (self.role, self.party_id).__hash__() def", "party_id def __hash__(self): return (self.role, self.party_id).__hash__() def __str__(self): return f\"Party(role={self.role},", "may obtain a copy of the License at # #", "# Unless required by applicable law or agreed to in", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "__eq__(self, other): return self.party_id == other.party_id and self.role == other.role", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "__str__(self): return f\"Party(role={self.role}, party_id={self.party_id})\" def __repr__(self): return self.__str__() def __lt__(self,", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "under the License. # class Party(object): \"\"\" Uniquely identify \"\"\"", "to in writing, software # distributed under the License is", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "# See the License for the specific language governing permissions", "class Party(object): \"\"\" Uniquely identify \"\"\" def __init__(self, role, party_id):", "def __hash__(self): return (self.role, self.party_id).__hash__() def __str__(self): return f\"Party(role={self.role}, party_id={self.party_id})\"", "(self.role, self.party_id).__hash__() def __str__(self): return f\"Party(role={self.role}, party_id={self.party_id})\" def __repr__(self): return", "You may obtain a copy of the License at #", "language governing permissions and # limitations under the License. #", "may not use this file except in compliance with the", "or agreed to in writing, software # distributed under the", "self.party_id) < (other.role, other.party_id) def __eq__(self, other): return self.party_id ==", "other.role def to_pb(self): from arch.api.proto import federation_pb2 return federation_pb2.Party(partyId=f\"{self.party_id}\", name=self.role)", "required by applicable law or agreed to in writing, software", "< (other.role, other.party_id) def __eq__(self, other): return self.party_id == other.party_id", "(self.role, self.party_id) < (other.role, other.party_id) def __eq__(self, other): return self.party_id", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "other): return (self.role, self.party_id) < (other.role, other.party_id) def __eq__(self, other):", "with the License. # You may obtain a copy of", "this file except in compliance with the License. # You", "f\"Party(role={self.role}, party_id={self.party_id})\" def __repr__(self): return self.__str__() def __lt__(self, other): return", "the Apache License, Version 2.0 (the \"License\"); # you may" ]
[ "| FLAG_PRIORITIZE_DISK) register('u2f.facets', default=(), type=Sequence, flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('auth.ip-rate-limit', default=0,", "# register('cache.backend', flags=FLAG_NOSTORE) # register('cache.options', type=Dict, flags=FLAG_NOSTORE) # System register('system.admin-email',", "default='localhost', flags=FLAG_NOSTORE) register('mail.enable-replies', default=False, flags=FLAG_PRIORITIZE_DISK) register('mail.reply-hostname', default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK)", "FLAG_PRIORITIZE_DISK) register('sms.twilio-token', default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('sms.twilio-number', default='', flags=FLAG_ALLOW_EMPTY |", "}, }, flags=FLAG_NOSTORE | FLAG_IMMUTABLE ) register('redis.options', type=Dict, flags=FLAG_NOSTORE) #", "Redis register( 'redis.clusters', type=Dict, default={ 'default': { 'hosts': { 0:", "flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('system.secret-key', flags=FLAG_NOSTORE) # Absolute URL to the", "2010-2014 by the Sentry Team, see AUTHORS for more details.", "FLAG_PRIORITIZE_DISK, FLAG_REQUIRED, FLAG_ALLOW_EMPTY, register, ) from sentry.utils.types import Dict, String,", "'hosts': { 0: { 'host': '127.0.0.1', 'port': 6379, } },", "FLAG_PRIORITIZE_DISK) register('mail.list-namespace', type=String, default='localhost', flags=FLAG_NOSTORE) register('mail.enable-replies', default=False, flags=FLAG_PRIORITIZE_DISK) register('mail.reply-hostname', default='',", "FLAG_PRIORITIZE_DISK) # SMS register('sms.twilio-account', default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('sms.twilio-token', default='',", "default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('sms.twilio-number', default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) #", "default=0, flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('auth.user-rate-limit', default=0, flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('api.rate-limit.org-create',", "flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) # Filestore register('filestore.backend', default='filesystem', flags=FLAG_NOSTORE) register('filestore.options', default={'location':", "for more details. \"\"\" from __future__ import absolute_import, print_function from", "directory. Should not include a trailing slash. register('system.url-prefix', ttl=60, grace=3600,", "register('mail.username', flags=FLAG_REQUIRED | FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('mail.password', flags=FLAG_REQUIRED | FLAG_ALLOW_EMPTY", ") register('redis.options', type=Dict, flags=FLAG_NOSTORE) # symbolizer specifics register('dsym.cache-path', type=String, default='/tmp/sentry-dsym-cache')", "register('mail.mailgun-api-key', default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) # SMS register('sms.twilio-account', default='', flags=FLAG_ALLOW_EMPTY", "FLAG_ALLOW_EMPTY, register, ) from sentry.utils.types import Dict, String, Sequence #", "register('mail.port', default=25, flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK) register('mail.username', flags=FLAG_REQUIRED | FLAG_ALLOW_EMPTY |", "flags=FLAG_NOSTORE) # register('system.debug', default=False, flags=FLAG_NOSTORE) register('system.rate-limit', default=0, flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK)", "register('mail.use-tls', default=False, flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK) register('mail.subject-prefix', default='[Sentry] ', flags=FLAG_PRIORITIZE_DISK) register('mail.from',", "register('mail.subject-prefix', default='[Sentry] ', flags=FLAG_PRIORITIZE_DISK) register('mail.from', default='root@localhost', flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK) register('mail.list-namespace',", "Dict, String, Sequence # Cache # register('cache.backend', flags=FLAG_NOSTORE) # register('cache.options',", "default=0, flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('system.secret-key', flags=FLAG_NOSTORE) # Absolute URL to", "default=25, flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK) register('mail.username', flags=FLAG_REQUIRED | FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK)", "flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('sms.twilio-number', default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) # U2F", "register('cache.backend', flags=FLAG_NOSTORE) # register('cache.options', type=Dict, flags=FLAG_NOSTORE) # System register('system.admin-email', flags=FLAG_REQUIRED)", "register('system.rate-limit', default=0, flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('system.secret-key', flags=FLAG_NOSTORE) # Absolute URL", "Should not include a trailing slash. register('system.url-prefix', ttl=60, grace=3600, flags=FLAG_REQUIRED", "'127.0.0.1', 'port': 6379, } }, }, }, flags=FLAG_NOSTORE | FLAG_IMMUTABLE", "more details. \"\"\" from __future__ import absolute_import, print_function from sentry.logging", "register('system.debug', default=False, flags=FLAG_NOSTORE) register('system.rate-limit', default=0, flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('system.secret-key', flags=FLAG_NOSTORE)", "register( 'redis.clusters', type=Dict, default={ 'default': { 'hosts': { 0: {", "register('mail.password', flags=FLAG_REQUIRED | FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('mail.use-tls', default=False, flags=FLAG_REQUIRED |", "flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) # U2F register('u2f.app-id', default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK)", ":license: BSD, see LICENSE for more details. \"\"\" from __future__", "flags=FLAG_REQUIRED | FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('mail.password', flags=FLAG_REQUIRED | FLAG_ALLOW_EMPTY |", "FLAG_PRIORITIZE_DISK) register('u2f.facets', default=(), type=Sequence, flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('auth.ip-rate-limit', default=0, flags=FLAG_ALLOW_EMPTY", "default=False, flags=FLAG_PRIORITIZE_DISK) register('mail.reply-hostname', default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('mail.mailgun-api-key', default='', flags=FLAG_ALLOW_EMPTY", "flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) # SMS register('sms.twilio-account', default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK)", "'port': 6379, } }, }, }, flags=FLAG_NOSTORE | FLAG_IMMUTABLE )", "sentry.logging import LoggingFormat from sentry.options import ( FLAG_IMMUTABLE, FLAG_NOSTORE, FLAG_PRIORITIZE_DISK,", "FLAG_PRIORITIZE_DISK) register('mail.port', default=25, flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK) register('mail.username', flags=FLAG_REQUIRED | FLAG_ALLOW_EMPTY", "flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('mail.mailgun-api-key', default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) # SMS", "| FLAG_PRIORITIZE_DISK) # Filestore register('filestore.backend', default='filesystem', flags=FLAG_NOSTORE) register('filestore.options', default={'location': '/tmp/sentry-files'},", "U2F register('u2f.app-id', default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('u2f.facets', default=(), type=Sequence, flags=FLAG_ALLOW_EMPTY", "import Dict, String, Sequence # Cache # register('cache.backend', flags=FLAG_NOSTORE) #", "String, Sequence # Cache # register('cache.backend', flags=FLAG_NOSTORE) # register('cache.options', type=Dict,", "import ( FLAG_IMMUTABLE, FLAG_NOSTORE, FLAG_PRIORITIZE_DISK, FLAG_REQUIRED, FLAG_ALLOW_EMPTY, register, ) from", "| FLAG_PRIORITIZE_DISK) register('mail.list-namespace', type=String, default='localhost', flags=FLAG_NOSTORE) register('mail.enable-replies', default=False, flags=FLAG_PRIORITIZE_DISK) register('mail.reply-hostname',", "flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('auth.ip-rate-limit', default=0, flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('auth.user-rate-limit', default=0,", "symbolizer specifics register('dsym.cache-path', type=String, default='/tmp/sentry-dsym-cache') # Mail register('mail.backend', default='smtp', flags=FLAG_NOSTORE)", "register('system.logging-format', default=LoggingFormat.HUMAN, flags=FLAG_NOSTORE) # Redis register( 'redis.clusters', type=Dict, default={ 'default':", "FLAG_PRIORITIZE_DISK) register('sms.twilio-number', default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) # U2F register('u2f.app-id', default='',", "type=Sequence, flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('auth.ip-rate-limit', default=0, flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('auth.user-rate-limit',", "default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) # SMS register('sms.twilio-account', default='', flags=FLAG_ALLOW_EMPTY |", "URL to the sentry root directory. Should not include a", "type=Dict, flags=FLAG_NOSTORE) # register('system.debug', default=False, flags=FLAG_NOSTORE) register('system.rate-limit', default=0, flags=FLAG_ALLOW_EMPTY |", "from sentry.logging import LoggingFormat from sentry.options import ( FLAG_IMMUTABLE, FLAG_NOSTORE,", "LoggingFormat from sentry.options import ( FLAG_IMMUTABLE, FLAG_NOSTORE, FLAG_PRIORITIZE_DISK, FLAG_REQUIRED, FLAG_ALLOW_EMPTY,", "FLAG_PRIORITIZE_DISK) register('system.root-api-key', flags=FLAG_PRIORITIZE_DISK) register('system.logging-format', default=LoggingFormat.HUMAN, flags=FLAG_NOSTORE) # Redis register( 'redis.clusters',", "type=String, default='localhost', flags=FLAG_NOSTORE) register('mail.enable-replies', default=False, flags=FLAG_PRIORITIZE_DISK) register('mail.reply-hostname', default='', flags=FLAG_ALLOW_EMPTY |", "register('sms.twilio-account', default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('sms.twilio-token', default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK)", "| FLAG_IMMUTABLE ) register('redis.options', type=Dict, flags=FLAG_NOSTORE) # symbolizer specifics register('dsym.cache-path',", "FLAG_PRIORITIZE_DISK) register('system.secret-key', flags=FLAG_NOSTORE) # Absolute URL to the sentry root", "| FLAG_PRIORITIZE_DISK) register('mail.username', flags=FLAG_REQUIRED | FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('mail.password', flags=FLAG_REQUIRED", "register('auth.ip-rate-limit', default=0, flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('auth.user-rate-limit', default=0, flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK)", "| FLAG_PRIORITIZE_DISK) register('api.rate-limit.org-create', default=5, flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) # Filestore register('filestore.backend',", "# Absolute URL to the sentry root directory. Should not", "\"\"\" sentry.options.defaults ~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team,", "import LoggingFormat from sentry.options import ( FLAG_IMMUTABLE, FLAG_NOSTORE, FLAG_PRIORITIZE_DISK, FLAG_REQUIRED,", "flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK) register('mail.port', default=25, flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK) register('mail.username', flags=FLAG_REQUIRED", "flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('sms.twilio-token', default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('sms.twilio-number', default='',", "root directory. Should not include a trailing slash. register('system.url-prefix', ttl=60,", "specifics register('dsym.cache-path', type=String, default='/tmp/sentry-dsym-cache') # Mail register('mail.backend', default='smtp', flags=FLAG_NOSTORE) register('mail.host',", "default=(), type=Sequence, flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('auth.ip-rate-limit', default=0, flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK)", "flags=FLAG_NOSTORE) # register('cache.options', type=Dict, flags=FLAG_NOSTORE) # System register('system.admin-email', flags=FLAG_REQUIRED) register('system.support-email',", "FLAG_IMMUTABLE, FLAG_NOSTORE, FLAG_PRIORITIZE_DISK, FLAG_REQUIRED, FLAG_ALLOW_EMPTY, register, ) from sentry.utils.types import", "| FLAG_PRIORITIZE_DISK) register('mail.use-tls', default=False, flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK) register('mail.subject-prefix', default='[Sentry] ',", "default=False, flags=FLAG_NOSTORE) register('system.rate-limit', default=0, flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('system.secret-key', flags=FLAG_NOSTORE) #", "default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('u2f.facets', default=(), type=Sequence, flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK)", "from sentry.options import ( FLAG_IMMUTABLE, FLAG_NOSTORE, FLAG_PRIORITIZE_DISK, FLAG_REQUIRED, FLAG_ALLOW_EMPTY, register,", "type=Dict, flags=FLAG_NOSTORE) # symbolizer specifics register('dsym.cache-path', type=String, default='/tmp/sentry-dsym-cache') # Mail", "default='[Sentry] ', flags=FLAG_PRIORITIZE_DISK) register('mail.from', default='root@localhost', flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK) register('mail.list-namespace', type=String,", "default=0, flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('api.rate-limit.org-create', default=5, flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) #", "# SMS register('sms.twilio-account', default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('sms.twilio-token', default='', flags=FLAG_ALLOW_EMPTY", "SMS register('sms.twilio-account', default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('sms.twilio-token', default='', flags=FLAG_ALLOW_EMPTY |", "details. :license: BSD, see LICENSE for more details. \"\"\" from", "sentry.options import ( FLAG_IMMUTABLE, FLAG_NOSTORE, FLAG_PRIORITIZE_DISK, FLAG_REQUIRED, FLAG_ALLOW_EMPTY, register, )", "default='localhost', flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK) register('mail.port', default=25, flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK) register('mail.username',", "', flags=FLAG_PRIORITIZE_DISK) register('mail.from', default='root@localhost', flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK) register('mail.list-namespace', type=String, default='localhost',", "flags=FLAG_NOSTORE) # Redis register( 'redis.clusters', type=Dict, default={ 'default': { 'hosts':", "FLAG_NOSTORE, FLAG_PRIORITIZE_DISK, FLAG_REQUIRED, FLAG_ALLOW_EMPTY, register, ) from sentry.utils.types import Dict,", "trailing slash. register('system.url-prefix', ttl=60, grace=3600, flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK) register('system.root-api-key', flags=FLAG_PRIORITIZE_DISK)", "slash. register('system.url-prefix', ttl=60, grace=3600, flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK) register('system.root-api-key', flags=FLAG_PRIORITIZE_DISK) register('system.logging-format',", "LICENSE for more details. \"\"\" from __future__ import absolute_import, print_function", "default='smtp', flags=FLAG_NOSTORE) register('mail.host', default='localhost', flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK) register('mail.port', default=25, flags=FLAG_REQUIRED", "flags=FLAG_REQUIRED | FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('mail.use-tls', default=False, flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK)", "register('auth.user-rate-limit', default=0, flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('api.rate-limit.org-create', default=5, flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK)", "register('sms.twilio-token', default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('sms.twilio-number', default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK)", "print_function from sentry.logging import LoggingFormat from sentry.options import ( FLAG_IMMUTABLE,", "not include a trailing slash. register('system.url-prefix', ttl=60, grace=3600, flags=FLAG_REQUIRED |", "# Cache # register('cache.backend', flags=FLAG_NOSTORE) # register('cache.options', type=Dict, flags=FLAG_NOSTORE) #", "Sentry Team, see AUTHORS for more details. :license: BSD, see", "BSD, see LICENSE for more details. \"\"\" from __future__ import", "flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK) register('mail.subject-prefix', default='[Sentry] ', flags=FLAG_PRIORITIZE_DISK) register('mail.from', default='root@localhost', flags=FLAG_REQUIRED", "register('mail.list-namespace', type=String, default='localhost', flags=FLAG_NOSTORE) register('mail.enable-replies', default=False, flags=FLAG_PRIORITIZE_DISK) register('mail.reply-hostname', default='', flags=FLAG_ALLOW_EMPTY", "register('u2f.app-id', default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('u2f.facets', default=(), type=Sequence, flags=FLAG_ALLOW_EMPTY |", "| FLAG_PRIORITIZE_DISK) register('mail.password', flags=FLAG_REQUIRED | FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('mail.use-tls', default=False,", "flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK) register('mail.list-namespace', type=String, default='localhost', flags=FLAG_NOSTORE) register('mail.enable-replies', default=False, flags=FLAG_PRIORITIZE_DISK)", ":copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for", "flags=FLAG_PRIORITIZE_DISK) register('mail.from', default='root@localhost', flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK) register('mail.list-namespace', type=String, default='localhost', flags=FLAG_NOSTORE)", "0: { 'host': '127.0.0.1', 'port': 6379, } }, }, },", "type=Dict, default={ 'default': { 'hosts': { 0: { 'host': '127.0.0.1',", "flags=FLAG_NOSTORE | FLAG_IMMUTABLE ) register('redis.options', type=Dict, flags=FLAG_NOSTORE) # symbolizer specifics", "\"\"\" from __future__ import absolute_import, print_function from sentry.logging import LoggingFormat", "FLAG_PRIORITIZE_DISK) register('mail.use-tls', default=False, flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK) register('mail.subject-prefix', default='[Sentry] ', flags=FLAG_PRIORITIZE_DISK)", "# System register('system.admin-email', flags=FLAG_REQUIRED) register('system.support-email', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('system.security-email', flags=FLAG_ALLOW_EMPTY", "{ 'hosts': { 0: { 'host': '127.0.0.1', 'port': 6379, }", "to the sentry root directory. Should not include a trailing", "| FLAG_PRIORITIZE_DISK) register('mail.subject-prefix', default='[Sentry] ', flags=FLAG_PRIORITIZE_DISK) register('mail.from', default='root@localhost', flags=FLAG_REQUIRED |", "flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('api.rate-limit.org-create', default=5, flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) # Filestore", "register('sms.twilio-number', default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) # U2F register('u2f.app-id', default='', flags=FLAG_ALLOW_EMPTY", "default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('mail.mailgun-api-key', default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) #", "include a trailing slash. register('system.url-prefix', ttl=60, grace=3600, flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK)", "flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('u2f.facets', default=(), type=Sequence, flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('auth.ip-rate-limit',", "register('mail.reply-hostname', default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('mail.mailgun-api-key', default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK)", "register('system.databases', type=Dict, flags=FLAG_NOSTORE) # register('system.debug', default=False, flags=FLAG_NOSTORE) register('system.rate-limit', default=0, flags=FLAG_ALLOW_EMPTY", "flags=FLAG_NOSTORE) register('system.rate-limit', default=0, flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('system.secret-key', flags=FLAG_NOSTORE) # Absolute", "}, }, }, flags=FLAG_NOSTORE | FLAG_IMMUTABLE ) register('redis.options', type=Dict, flags=FLAG_NOSTORE)", "FLAG_PRIORITIZE_DISK) register('mail.mailgun-api-key', default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) # SMS register('sms.twilio-account', default='',", "( FLAG_IMMUTABLE, FLAG_NOSTORE, FLAG_PRIORITIZE_DISK, FLAG_REQUIRED, FLAG_ALLOW_EMPTY, register, ) from sentry.utils.types", "default=LoggingFormat.HUMAN, flags=FLAG_NOSTORE) # Redis register( 'redis.clusters', type=Dict, default={ 'default': {", "FLAG_PRIORITIZE_DISK) register('auth.ip-rate-limit', default=0, flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('auth.user-rate-limit', default=0, flags=FLAG_ALLOW_EMPTY |", "(c) 2010-2014 by the Sentry Team, see AUTHORS for more", "| FLAG_PRIORITIZE_DISK) register('system.security-email', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('system.databases', type=Dict, flags=FLAG_NOSTORE) #", "type=String, default='/tmp/sentry-dsym-cache') # Mail register('mail.backend', default='smtp', flags=FLAG_NOSTORE) register('mail.host', default='localhost', flags=FLAG_REQUIRED", "ttl=60, grace=3600, flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK) register('system.root-api-key', flags=FLAG_PRIORITIZE_DISK) register('system.logging-format', default=LoggingFormat.HUMAN, flags=FLAG_NOSTORE)", "FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('mail.use-tls', default=False, flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK) register('mail.subject-prefix', default='[Sentry]", "FLAG_PRIORITIZE_DISK) register('mail.password', flags=FLAG_REQUIRED | FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('mail.use-tls', default=False, flags=FLAG_REQUIRED", "register('mail.enable-replies', default=False, flags=FLAG_PRIORITIZE_DISK) register('mail.reply-hostname', default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('mail.mailgun-api-key', default='',", "sentry.options.defaults ~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team, see", "| FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('mail.password', flags=FLAG_REQUIRED | FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK)", "register('u2f.facets', default=(), type=Sequence, flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('auth.ip-rate-limit', default=0, flags=FLAG_ALLOW_EMPTY |", "sentry.utils.types import Dict, String, Sequence # Cache # register('cache.backend', flags=FLAG_NOSTORE)", "Team, see AUTHORS for more details. :license: BSD, see LICENSE", "register('system.secret-key', flags=FLAG_NOSTORE) # Absolute URL to the sentry root directory.", "flags=FLAG_NOSTORE) # Absolute URL to the sentry root directory. Should", "the sentry root directory. Should not include a trailing slash.", "| FLAG_PRIORITIZE_DISK) register('system.root-api-key', flags=FLAG_PRIORITIZE_DISK) register('system.logging-format', default=LoggingFormat.HUMAN, flags=FLAG_NOSTORE) # Redis register(", "FLAG_PRIORITIZE_DISK) register('mail.subject-prefix', default='[Sentry] ', flags=FLAG_PRIORITIZE_DISK) register('mail.from', default='root@localhost', flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK)", "# symbolizer specifics register('dsym.cache-path', type=String, default='/tmp/sentry-dsym-cache') # Mail register('mail.backend', default='smtp',", "the Sentry Team, see AUTHORS for more details. :license: BSD,", "| FLAG_PRIORITIZE_DISK) # U2F register('u2f.app-id', default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('u2f.facets',", "type=Dict, flags=FLAG_NOSTORE) # System register('system.admin-email', flags=FLAG_REQUIRED) register('system.support-email', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK)", "Mail register('mail.backend', default='smtp', flags=FLAG_NOSTORE) register('mail.host', default='localhost', flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK) register('mail.port',", "Sequence # Cache # register('cache.backend', flags=FLAG_NOSTORE) # register('cache.options', type=Dict, flags=FLAG_NOSTORE)", "register('mail.from', default='root@localhost', flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK) register('mail.list-namespace', type=String, default='localhost', flags=FLAG_NOSTORE) register('mail.enable-replies',", "absolute_import, print_function from sentry.logging import LoggingFormat from sentry.options import (", "'host': '127.0.0.1', 'port': 6379, } }, }, }, flags=FLAG_NOSTORE |", "flags=FLAG_REQUIRED) register('system.support-email', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('system.security-email', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('system.databases',", "| FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('mail.use-tls', default=False, flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK) register('mail.subject-prefix',", "| FLAG_PRIORITIZE_DISK) register('mail.port', default=25, flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK) register('mail.username', flags=FLAG_REQUIRED |", "details. \"\"\" from __future__ import absolute_import, print_function from sentry.logging import", "for more details. :license: BSD, see LICENSE for more details.", "System register('system.admin-email', flags=FLAG_REQUIRED) register('system.support-email', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('system.security-email', flags=FLAG_ALLOW_EMPTY |", "flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('auth.user-rate-limit', default=0, flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('api.rate-limit.org-create', default=5,", "flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('system.databases', type=Dict, flags=FLAG_NOSTORE) # register('system.debug', default=False, flags=FLAG_NOSTORE)", "# register('cache.options', type=Dict, flags=FLAG_NOSTORE) # System register('system.admin-email', flags=FLAG_REQUIRED) register('system.support-email', flags=FLAG_ALLOW_EMPTY", "register('system.root-api-key', flags=FLAG_PRIORITIZE_DISK) register('system.logging-format', default=LoggingFormat.HUMAN, flags=FLAG_NOSTORE) # Redis register( 'redis.clusters', type=Dict,", "default=False, flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK) register('mail.subject-prefix', default='[Sentry] ', flags=FLAG_PRIORITIZE_DISK) register('mail.from', default='root@localhost',", "| FLAG_PRIORITIZE_DISK) register('mail.mailgun-api-key', default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) # SMS register('sms.twilio-account',", "FLAG_PRIORITIZE_DISK) # U2F register('u2f.app-id', default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('u2f.facets', default=(),", "a trailing slash. register('system.url-prefix', ttl=60, grace=3600, flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK) register('system.root-api-key',", "FLAG_PRIORITIZE_DISK) # Filestore register('filestore.backend', default='filesystem', flags=FLAG_NOSTORE) register('filestore.options', default={'location': '/tmp/sentry-files'}, flags=FLAG_NOSTORE)", "'default': { 'hosts': { 0: { 'host': '127.0.0.1', 'port': 6379,", "see AUTHORS for more details. :license: BSD, see LICENSE for", "'redis.clusters', type=Dict, default={ 'default': { 'hosts': { 0: { 'host':", "| FLAG_PRIORITIZE_DISK) register('sms.twilio-number', default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) # U2F register('u2f.app-id',", "register('system.support-email', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('system.security-email', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('system.databases', type=Dict,", ") from sentry.utils.types import Dict, String, Sequence # Cache #", "default=5, flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) # Filestore register('filestore.backend', default='filesystem', flags=FLAG_NOSTORE) register('filestore.options',", "grace=3600, flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK) register('system.root-api-key', flags=FLAG_PRIORITIZE_DISK) register('system.logging-format', default=LoggingFormat.HUMAN, flags=FLAG_NOSTORE) #", "FLAG_PRIORITIZE_DISK) register('system.security-email', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('system.databases', type=Dict, flags=FLAG_NOSTORE) # register('system.debug',", "default={ 'default': { 'hosts': { 0: { 'host': '127.0.0.1', 'port':", "register('system.admin-email', flags=FLAG_REQUIRED) register('system.support-email', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('system.security-email', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK)", "import absolute_import, print_function from sentry.logging import LoggingFormat from sentry.options import", "sentry root directory. Should not include a trailing slash. register('system.url-prefix',", "{ 'host': '127.0.0.1', 'port': 6379, } }, }, }, flags=FLAG_NOSTORE", "} }, }, }, flags=FLAG_NOSTORE | FLAG_IMMUTABLE ) register('redis.options', type=Dict,", "from sentry.utils.types import Dict, String, Sequence # Cache # register('cache.backend',", "~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS", "register('dsym.cache-path', type=String, default='/tmp/sentry-dsym-cache') # Mail register('mail.backend', default='smtp', flags=FLAG_NOSTORE) register('mail.host', default='localhost',", "FLAG_PRIORITIZE_DISK) register('system.databases', type=Dict, flags=FLAG_NOSTORE) # register('system.debug', default=False, flags=FLAG_NOSTORE) register('system.rate-limit', default=0,", "flags=FLAG_NOSTORE) # symbolizer specifics register('dsym.cache-path', type=String, default='/tmp/sentry-dsym-cache') # Mail register('mail.backend',", "# Redis register( 'redis.clusters', type=Dict, default={ 'default': { 'hosts': {", "| FLAG_PRIORITIZE_DISK) register('system.secret-key', flags=FLAG_NOSTORE) # Absolute URL to the sentry", "by the Sentry Team, see AUTHORS for more details. :license:", "| FLAG_PRIORITIZE_DISK) register('auth.ip-rate-limit', default=0, flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('auth.user-rate-limit', default=0, flags=FLAG_ALLOW_EMPTY", "default='root@localhost', flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK) register('mail.list-namespace', type=String, default='localhost', flags=FLAG_NOSTORE) register('mail.enable-replies', default=False,", "flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('system.security-email', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('system.databases', type=Dict, flags=FLAG_NOSTORE)", "FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('mail.password', flags=FLAG_REQUIRED | FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('mail.use-tls',", "| FLAG_PRIORITIZE_DISK) register('system.databases', type=Dict, flags=FLAG_NOSTORE) # register('system.debug', default=False, flags=FLAG_NOSTORE) register('system.rate-limit',", "register('api.rate-limit.org-create', default=5, flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) # Filestore register('filestore.backend', default='filesystem', flags=FLAG_NOSTORE)", "# Mail register('mail.backend', default='smtp', flags=FLAG_NOSTORE) register('mail.host', default='localhost', flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK)", "| FLAG_PRIORITIZE_DISK) register('sms.twilio-token', default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('sms.twilio-number', default='', flags=FLAG_ALLOW_EMPTY", "register('system.security-email', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('system.databases', type=Dict, flags=FLAG_NOSTORE) # register('system.debug', default=False,", "flags=FLAG_NOSTORE) register('mail.enable-replies', default=False, flags=FLAG_PRIORITIZE_DISK) register('mail.reply-hostname', default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('mail.mailgun-api-key',", "register('mail.host', default='localhost', flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK) register('mail.port', default=25, flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK)", "from __future__ import absolute_import, print_function from sentry.logging import LoggingFormat from", "register, ) from sentry.utils.types import Dict, String, Sequence # Cache", "register('redis.options', type=Dict, flags=FLAG_NOSTORE) # symbolizer specifics register('dsym.cache-path', type=String, default='/tmp/sentry-dsym-cache') #", "flags=FLAG_PRIORITIZE_DISK) register('system.logging-format', default=LoggingFormat.HUMAN, flags=FLAG_NOSTORE) # Redis register( 'redis.clusters', type=Dict, default={", "flags=FLAG_PRIORITIZE_DISK) register('mail.reply-hostname', default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('mail.mailgun-api-key', default='', flags=FLAG_ALLOW_EMPTY |", "register('cache.options', type=Dict, flags=FLAG_NOSTORE) # System register('system.admin-email', flags=FLAG_REQUIRED) register('system.support-email', flags=FLAG_ALLOW_EMPTY |", "| FLAG_PRIORITIZE_DISK) register('auth.user-rate-limit', default=0, flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('api.rate-limit.org-create', default=5, flags=FLAG_ALLOW_EMPTY", "Absolute URL to the sentry root directory. Should not include", "6379, } }, }, }, flags=FLAG_NOSTORE | FLAG_IMMUTABLE ) register('redis.options',", "FLAG_PRIORITIZE_DISK) register('mail.username', flags=FLAG_REQUIRED | FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('mail.password', flags=FLAG_REQUIRED |", "{ 0: { 'host': '127.0.0.1', 'port': 6379, } }, },", "AUTHORS for more details. :license: BSD, see LICENSE for more", "}, flags=FLAG_NOSTORE | FLAG_IMMUTABLE ) register('redis.options', type=Dict, flags=FLAG_NOSTORE) # symbolizer", "flags=FLAG_NOSTORE) # System register('system.admin-email', flags=FLAG_REQUIRED) register('system.support-email', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('system.security-email',", "flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK) register('mail.username', flags=FLAG_REQUIRED | FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('mail.password',", "FLAG_PRIORITIZE_DISK) register('api.rate-limit.org-create', default=5, flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) # Filestore register('filestore.backend', default='filesystem',", "FLAG_IMMUTABLE ) register('redis.options', type=Dict, flags=FLAG_NOSTORE) # symbolizer specifics register('dsym.cache-path', type=String,", "# register('system.debug', default=False, flags=FLAG_NOSTORE) register('system.rate-limit', default=0, flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('system.secret-key',", "# U2F register('u2f.app-id', default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('u2f.facets', default=(), type=Sequence,", "FLAG_REQUIRED, FLAG_ALLOW_EMPTY, register, ) from sentry.utils.types import Dict, String, Sequence", "__future__ import absolute_import, print_function from sentry.logging import LoggingFormat from sentry.options", "flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK) register('system.root-api-key', flags=FLAG_PRIORITIZE_DISK) register('system.logging-format', default=LoggingFormat.HUMAN, flags=FLAG_NOSTORE) # Redis", "| FLAG_PRIORITIZE_DISK) # SMS register('sms.twilio-account', default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('sms.twilio-token',", "default='/tmp/sentry-dsym-cache') # Mail register('mail.backend', default='smtp', flags=FLAG_NOSTORE) register('mail.host', default='localhost', flags=FLAG_REQUIRED |", "register('system.url-prefix', ttl=60, grace=3600, flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK) register('system.root-api-key', flags=FLAG_PRIORITIZE_DISK) register('system.logging-format', default=LoggingFormat.HUMAN,", "default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('sms.twilio-token', default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('sms.twilio-number',", "flags=FLAG_NOSTORE) register('mail.host', default='localhost', flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK) register('mail.port', default=25, flags=FLAG_REQUIRED |", "more details. :license: BSD, see LICENSE for more details. \"\"\"", "default='', flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) # U2F register('u2f.app-id', default='', flags=FLAG_ALLOW_EMPTY |", "FLAG_PRIORITIZE_DISK) register('auth.user-rate-limit', default=0, flags=FLAG_ALLOW_EMPTY | FLAG_PRIORITIZE_DISK) register('api.rate-limit.org-create', default=5, flags=FLAG_ALLOW_EMPTY |", "Cache # register('cache.backend', flags=FLAG_NOSTORE) # register('cache.options', type=Dict, flags=FLAG_NOSTORE) # System", "see LICENSE for more details. \"\"\" from __future__ import absolute_import,", "register('mail.backend', default='smtp', flags=FLAG_NOSTORE) register('mail.host', default='localhost', flags=FLAG_REQUIRED | FLAG_PRIORITIZE_DISK) register('mail.port', default=25," ]
[ "+ __version__) parser.add_argument('--output', default=HOME, help='Output file.') parser.add_argument('--unicode-version', default=None, help='Force a", "any. Zip if required. download_unicodedata(version, output, no_zip) if __name__ ==", "try: print('Downloading: %s --> %s' % (furl, file_location)) response =", "= os.path.join(output, 'unicodedata', version) print('Unzipping %s.zip...' % version) os.makedirs(target) for", "'unicodedata', version) print('Zipping %s.zip...' % version) for root, dirs, files", "%s' % url) continue with codecs.open(file_location, 'w', encoding='utf-8') as uf:", "f in unzipper.namelist(): # Do I need backslash on windows?", "'DerivedAge.txt', 'auxiliary/WordBreakProperty.txt', 'auxiliary/SentenceBreakProperty.txt', 'auxiliary/GraphemeBreakProperty.txt', 'extracted/DerivedDecompositionType.txt', 'extracted/DerivedNumericType.txt', 'extracted/DerivedNumericValues.txt', 'extracted/DerivedJoiningType.txt', 'extracted/DerivedJoiningGroup.txt', 'extracted/DerivedCombiningClass.txt',", "is None: version = unicodedata.unidata_version else: version = args.unicode_version get_unicodedata(version,", "not os.path.exists(file_location): for url in (ftp_url, http_url): furl = url", "response = urlopen(furl, timeout=30) data = response.read() except Exception: print('Failed:", "if ver >= (11, 0, 0): files.append('VerticalOrientation.txt') http_url = 'http://www.unicode.org/Public/%s/ucd/'", "if not retrieved: print('Failed to acquire all needed Unicode files!')", "# Do I need backslash on windows? Or is it", "'EastAsianWidth.txt', 'LineBreak.txt', 'HangulSyllableType.txt', 'DerivedAge.txt', 'auxiliary/WordBreakProperty.txt', 'auxiliary/SentenceBreakProperty.txt', 'auxiliary/GraphemeBreakProperty.txt', 'extracted/DerivedDecompositionType.txt', 'extracted/DerivedNumericType.txt', 'extracted/DerivedNumericValues.txt',", "'auxiliary/WordBreakProperty.txt', 'auxiliary/SentenceBreakProperty.txt', 'auxiliary/GraphemeBreakProperty.txt', 'extracted/DerivedDecompositionType.txt', 'extracted/DerivedNumericType.txt', 'extracted/DerivedNumericValues.txt', 'extracted/DerivedJoiningType.txt', 'extracted/DerivedJoiningGroup.txt', 'extracted/DerivedCombiningClass.txt', 'emoji/emoji-data.txt'", "'w', zipfile.ZIP_DEFLATED) target = os.path.join(output, 'unicodedata', version) print('Zipping %s.zip...' %", "no_zip) if __name__ == '__main__': import argparse import unicodedata parser", "True print('Skipping: found %s' % file_location) if not retrieved: zip_data", "file_location)) response = urlopen(furl, timeout=30) data = response.read() except Exception:", "def get_unicodedata(version, output=HOME, no_zip=False): \"\"\"Ensure we have Unicode data to", "files.append('VerticalOrientation.txt') http_url = 'http://www.unicode.org/Public/%s/ucd/' % version ftp_url = 'ftp://ftp.unicode.org/Public/%s/ucd/' %", "for f in unzipper.namelist(): # Do I need backslash on", "os.path.exists(file_location): for url in (ftp_url, http_url): furl = url +", "if required. download_unicodedata(version, output, no_zip) if __name__ == '__main__': import", "if file.endswith('.txt'): zipper.write(os.path.join(root, file), arcname=file) def unzip_unicode(output, version): \"\"\"Unzip the", "found %s' % file_location) if not retrieved: zip_data = False", "version)): zip_unicode(output, version) def get_unicodedata(version, output=HOME, no_zip=False): \"\"\"Ensure we have", "0, 0): files.append('VerticalOrientation.txt') http_url = 'http://www.unicode.org/Public/%s/ucd/' % version ftp_url =", "retrieved = False if not os.path.exists(file_location): for url in (ftp_url,", "in (ftp_url, http_url): furl = url + f try: print('Downloading:", "for url in (ftp_url, http_url): furl = url + f", "__version__) parser.add_argument('--output', default=HOME, help='Output file.') parser.add_argument('--unicode-version', default=None, help='Force a specific", "if not os.path.exists(target) and os.path.exists(zip_target): unzip_unicode(output, version) # Download missing", "Do I need backslash on windows? Or is it forward", "root, dirs, files in os.walk(target): for file in files: if", "data to generate Unicode tables.\"\"\" target = os.path.join(output, 'unicodedata', version)", "if any. Zip if required. download_unicodedata(version, output, no_zip) if __name__", "'ftp://ftp.unicode.org/Public/%s/ucd/' % version destination = os.path.join(output, 'unicodedata', version) if not", "urllib.request import urlopen __version__ = '2.2.0' HOME = os.path.dirname(os.path.abspath(__file__)) def", "files in os.walk(target): for file in files: if file.endswith('.txt'): zipper.write(os.path.join(root,", "version) if not os.path.exists(destination): os.makedirs(destination) zip_data = not no_zip for", "zipfile.ZipFile(os.path.join(output, 'unicodedata', '%s.zip' % version)) target = os.path.join(output, 'unicodedata', version)", "Unicode data to generate Unicode tables.\"\"\" target = os.path.join(output, 'unicodedata',", "unicodedata parser = argparse.ArgumentParser(prog='unidatadownload', description='Generate a unicode property table.') parser.add_argument('--version',", "we have Unicode data to generate Unicode tables.\"\"\" target =", "= 'ftp://ftp.unicode.org/Public/%s/ucd/' % version destination = os.path.join(output, 'unicodedata', version) if", "version) print('Unzipping %s.zip...' % version) os.makedirs(target) for f in unzipper.namelist():", "__name__ == '__main__': import argparse import unicodedata parser = argparse.ArgumentParser(prog='unidatadownload',", "continue with codecs.open(file_location, 'w', encoding='utf-8') as uf: uf.write(data.decode('utf-8')) retrieved =", "os.path.exists(zip_target): unzip_unicode(output, version) # Download missing files if any. Zip", "files: file_location = os.path.join(destination, os.path.basename(f)) retrieved = False if not", "property table.') parser.add_argument('--version', action='version', version=\"%(prog)s \" + __version__) parser.add_argument('--output', default=HOME,", "dirs, files in os.walk(target): for file in files: if file.endswith('.txt'):", "zipfile import codecs from urllib.request import urlopen __version__ = '2.2.0'", "%s.zip...' % version) for root, dirs, files in os.walk(target): for", "Download missing files if any. Zip if required. download_unicodedata(version, output,", "'LineBreak.txt', 'HangulSyllableType.txt', 'DerivedAge.txt', 'auxiliary/WordBreakProperty.txt', 'auxiliary/SentenceBreakProperty.txt', 'auxiliary/GraphemeBreakProperty.txt', 'extracted/DerivedDecompositionType.txt', 'extracted/DerivedNumericType.txt', 'extracted/DerivedNumericValues.txt', 'extracted/DerivedJoiningType.txt',", "retrieved: zip_data = False break if zip_data and not os.path.exists(os.path.join(output,", "'extracted/DerivedCombiningClass.txt', 'emoji/emoji-data.txt' ] files.append('ScriptExtensions.txt') files.append('IndicPositionalCategory.txt') files.append('IndicSyllabicCategory.txt') files.append('BidiBrackets.txt') if ver >=", "'extracted/DerivedJoiningGroup.txt', 'extracted/DerivedCombiningClass.txt', 'emoji/emoji-data.txt' ] files.append('ScriptExtensions.txt') files.append('IndicPositionalCategory.txt') files.append('IndicSyllabicCategory.txt') files.append('BidiBrackets.txt') if ver", "'__main__': import argparse import unicodedata parser = argparse.ArgumentParser(prog='unidatadownload', description='Generate a", "import unicodedata parser = argparse.ArgumentParser(prog='unidatadownload', description='Generate a unicode property table.')", "% version)): zip_unicode(output, version) def get_unicodedata(version, output=HOME, no_zip=False): \"\"\"Ensure we", "os.walk(target): for file in files: if file.endswith('.txt'): zipper.write(os.path.join(root, file), arcname=file)", "os.path.join(output, 'unicodedata', '%s.zip' % version) if not os.path.exists(target) and os.path.exists(zip_target):", "if not retrieved: zip_data = False break if zip_data and", "Unicode files.\"\"\" unzipper = zipfile.ZipFile(os.path.join(output, 'unicodedata', '%s.zip' % version)) target", "0): files.append('VerticalOrientation.txt') http_url = 'http://www.unicode.org/Public/%s/ucd/' % version ftp_url = 'ftp://ftp.unicode.org/Public/%s/ucd/'", "os.path.basename(f)) retrieved = False if not os.path.exists(file_location): for url in", "files.\"\"\" from __future__ import unicode_literals import os import zipfile import", "(ftp_url, http_url): furl = url + f try: print('Downloading: %s", "import unicode_literals import os import zipfile import codecs from urllib.request", "files.append('IndicPositionalCategory.txt') files.append('IndicSyllabicCategory.txt') files.append('BidiBrackets.txt') if ver >= (11, 0, 0): files.append('VerticalOrientation.txt')", "scripts and blocks.\"\"\" ver = tuple([int(x) for x in version.split('.')])", "print('Failed to acquire all needed Unicode files!') break else: retrieved", "encoding='utf-8') as uf: uf.write(data.decode('utf-8')) retrieved = True break if not", "as well? unzipper.extract(f, target) def download_unicodedata(version, output=HOME, no_zip=False): \"\"\"Download Unicode", "output, no_zip) if __name__ == '__main__': import argparse import unicodedata", "os.path.dirname(os.path.abspath(__file__)) def zip_unicode(output, version): \"\"\"Zip the Unicode files.\"\"\" zipper =", "files.append('BidiBrackets.txt') if ver >= (11, 0, 0): files.append('VerticalOrientation.txt') http_url =", "download_unicodedata(version, output, no_zip) if __name__ == '__main__': import argparse import", "target = os.path.join(output, 'unicodedata', version) print('Unzipping %s.zip...' % version) os.makedirs(target)", "% version), 'w', zipfile.ZIP_DEFLATED) target = os.path.join(output, 'unicodedata', version) print('Zipping", "print('Failed: %s' % url) continue with codecs.open(file_location, 'w', encoding='utf-8') as", "version) # Download missing files if any. Zip if required.", "False if not os.path.exists(file_location): for url in (ftp_url, http_url): furl", "__future__ import unicode_literals import os import zipfile import codecs from", "(11, 0, 0): files.append('VerticalOrientation.txt') http_url = 'http://www.unicode.org/Public/%s/ucd/' % version ftp_url", "version): \"\"\"Unzip the Unicode files.\"\"\" unzipper = zipfile.ZipFile(os.path.join(output, 'unicodedata', '%s.zip'", "os.path.join(output, 'unicodedata', version) print('Unzipping %s.zip...' % version) os.makedirs(target) for f", "blocks.\"\"\" ver = tuple([int(x) for x in version.split('.')]) files =", "version.') args = parser.parse_args() if args.unicode_version is None: version =", "files = [ 'UnicodeData.txt', 'Scripts.txt', 'Blocks.txt', 'PropList.txt', 'DerivedCoreProperties.txt', 'DerivedNormalizationProps.txt', 'CompositionExclusions.txt',", "action='version', version=\"%(prog)s \" + __version__) parser.add_argument('--output', default=HOME, help='Output file.') parser.add_argument('--unicode-version',", "os.path.exists(target) and os.path.exists(zip_target): unzip_unicode(output, version) # Download missing files if", "it forward as well? unzipper.extract(f, target) def download_unicodedata(version, output=HOME, no_zip=False):", "on windows? Or is it forward as well? unzipper.extract(f, target)", "file_location = os.path.join(destination, os.path.basename(f)) retrieved = False if not os.path.exists(file_location):", "= tuple([int(x) for x in version.split('.')]) files = [ 'UnicodeData.txt',", "def unzip_unicode(output, version): \"\"\"Unzip the Unicode files.\"\"\" unzipper = zipfile.ZipFile(os.path.join(output,", "description='Generate a unicode property table.') parser.add_argument('--version', action='version', version=\"%(prog)s \" +", "'unicodedata', '%s.zip' % version)) target = os.path.join(output, 'unicodedata', version) print('Unzipping", "= zipfile.ZipFile(os.path.join(output, 'unicodedata', '%s.zip' % version), 'w', zipfile.ZIP_DEFLATED) target =", "in unzipper.namelist(): # Do I need backslash on windows? Or", "'auxiliary/GraphemeBreakProperty.txt', 'extracted/DerivedDecompositionType.txt', 'extracted/DerivedNumericType.txt', 'extracted/DerivedNumericValues.txt', 'extracted/DerivedJoiningType.txt', 'extracted/DerivedJoiningGroup.txt', 'extracted/DerivedCombiningClass.txt', 'emoji/emoji-data.txt' ] files.append('ScriptExtensions.txt')", "= urlopen(furl, timeout=30) data = response.read() except Exception: print('Failed: %s'", "= zipfile.ZipFile(os.path.join(output, 'unicodedata', '%s.zip' % version)) target = os.path.join(output, 'unicodedata',", "files.\"\"\" zipper = zipfile.ZipFile(os.path.join(output, 'unicodedata', '%s.zip' % version), 'w', zipfile.ZIP_DEFLATED)", "= not no_zip for f in files: file_location = os.path.join(destination,", "Zip if required. download_unicodedata(version, output, no_zip) if __name__ == '__main__':", "files.append('ScriptExtensions.txt') files.append('IndicPositionalCategory.txt') files.append('IndicSyllabicCategory.txt') files.append('BidiBrackets.txt') if ver >= (11, 0, 0):", "'PropertyValueAliases.txt', 'PropertyAliases.txt', 'EastAsianWidth.txt', 'LineBreak.txt', 'HangulSyllableType.txt', 'DerivedAge.txt', 'auxiliary/WordBreakProperty.txt', 'auxiliary/SentenceBreakProperty.txt', 'auxiliary/GraphemeBreakProperty.txt', 'extracted/DerivedDecompositionType.txt',", "no_zip for f in files: file_location = os.path.join(destination, os.path.basename(f)) retrieved", "= '2.2.0' HOME = os.path.dirname(os.path.abspath(__file__)) def zip_unicode(output, version): \"\"\"Zip the", "and blocks.\"\"\" ver = tuple([int(x) for x in version.split('.')]) files", "zip_unicode(output, version): \"\"\"Zip the Unicode files.\"\"\" zipper = zipfile.ZipFile(os.path.join(output, 'unicodedata',", "download_unicodedata(version, output=HOME, no_zip=False): \"\"\"Download Unicode data scripts and blocks.\"\"\" ver", "required. download_unicodedata(version, output, no_zip) if __name__ == '__main__': import argparse", "# Download missing files if any. Zip if required. download_unicodedata(version,", "zipper = zipfile.ZipFile(os.path.join(output, 'unicodedata', '%s.zip' % version), 'w', zipfile.ZIP_DEFLATED) target", "not os.path.exists(destination): os.makedirs(destination) zip_data = not no_zip for f in", "not no_zip for f in files: file_location = os.path.join(destination, os.path.basename(f))", "print('Skipping: found %s' % file_location) if not retrieved: zip_data =", "version)) target = os.path.join(output, 'unicodedata', version) print('Unzipping %s.zip...' % version)", "zipper.write(os.path.join(root, file), arcname=file) def unzip_unicode(output, version): \"\"\"Unzip the Unicode files.\"\"\"", "= os.path.join(output, 'unicodedata', version) if not os.path.exists(destination): os.makedirs(destination) zip_data =", "version) for root, dirs, files in os.walk(target): for file in", "data scripts and blocks.\"\"\" ver = tuple([int(x) for x in", "'2.2.0' HOME = os.path.dirname(os.path.abspath(__file__)) def zip_unicode(output, version): \"\"\"Zip the Unicode", "'http://www.unicode.org/Public/%s/ucd/' % version ftp_url = 'ftp://ftp.unicode.org/Public/%s/ucd/' % version destination =", "no_zip=False): \"\"\"Ensure we have Unicode data to generate Unicode tables.\"\"\"", "'CompositionExclusions.txt', 'PropertyValueAliases.txt', 'PropertyAliases.txt', 'EastAsianWidth.txt', 'LineBreak.txt', 'HangulSyllableType.txt', 'DerivedAge.txt', 'auxiliary/WordBreakProperty.txt', 'auxiliary/SentenceBreakProperty.txt', 'auxiliary/GraphemeBreakProperty.txt',", "http_url = 'http://www.unicode.org/Public/%s/ucd/' % version ftp_url = 'ftp://ftp.unicode.org/Public/%s/ucd/' % version", "HOME = os.path.dirname(os.path.abspath(__file__)) def zip_unicode(output, version): \"\"\"Zip the Unicode files.\"\"\"", "specific Unicode version.') args = parser.parse_args() if args.unicode_version is None:", "get_unicodedata(version, output=HOME, no_zip=False): \"\"\"Ensure we have Unicode data to generate", "'%s.zip' % version) if not os.path.exists(target) and os.path.exists(zip_target): unzip_unicode(output, version)", "= 'http://www.unicode.org/Public/%s/ucd/' % version ftp_url = 'ftp://ftp.unicode.org/Public/%s/ucd/' % version destination", "except Exception: print('Failed: %s' % url) continue with codecs.open(file_location, 'w',", "and not os.path.exists(os.path.join(output, 'unicodedata', '%s.zip' % version)): zip_unicode(output, version) def", "\"\"\"Download Unicode data scripts and blocks.\"\"\" ver = tuple([int(x) for", "if zip_data and not os.path.exists(os.path.join(output, 'unicodedata', '%s.zip' % version)): zip_unicode(output,", "a specific Unicode version.') args = parser.parse_args() if args.unicode_version is", "windows? Or is it forward as well? unzipper.extract(f, target) def", "version destination = os.path.join(output, 'unicodedata', version) if not os.path.exists(destination): os.makedirs(destination)", "Unicode files.\"\"\" zipper = zipfile.ZipFile(os.path.join(output, 'unicodedata', '%s.zip' % version), 'w',", "a unicode property table.') parser.add_argument('--version', action='version', version=\"%(prog)s \" + __version__)", "os.makedirs(destination) zip_data = not no_zip for f in files: file_location", "version) zip_target = os.path.join(output, 'unicodedata', '%s.zip' % version) if not", "in files: file_location = os.path.join(destination, os.path.basename(f)) retrieved = False if", "os import zipfile import codecs from urllib.request import urlopen __version__", "% version)) target = os.path.join(output, 'unicodedata', version) print('Unzipping %s.zip...' %", "retrieved = True print('Skipping: found %s' % file_location) if not", "version) def get_unicodedata(version, output=HOME, no_zip=False): \"\"\"Ensure we have Unicode data", "in files: if file.endswith('.txt'): zipper.write(os.path.join(root, file), arcname=file) def unzip_unicode(output, version):", "version ftp_url = 'ftp://ftp.unicode.org/Public/%s/ucd/' % version destination = os.path.join(output, 'unicodedata',", "'emoji/emoji-data.txt' ] files.append('ScriptExtensions.txt') files.append('IndicPositionalCategory.txt') files.append('IndicSyllabicCategory.txt') files.append('BidiBrackets.txt') if ver >= (11,", "\"\"\"Unzip the Unicode files.\"\"\" unzipper = zipfile.ZipFile(os.path.join(output, 'unicodedata', '%s.zip' %", "output=HOME, no_zip=False): \"\"\"Download Unicode data scripts and blocks.\"\"\" ver =", "parser.add_argument('--unicode-version', default=None, help='Force a specific Unicode version.') args = parser.parse_args()", "well? unzipper.extract(f, target) def download_unicodedata(version, output=HOME, no_zip=False): \"\"\"Download Unicode data", "zip_data and not os.path.exists(os.path.join(output, 'unicodedata', '%s.zip' % version)): zip_unicode(output, version)", "Exception: print('Failed: %s' % url) continue with codecs.open(file_location, 'w', encoding='utf-8')", "Or is it forward as well? unzipper.extract(f, target) def download_unicodedata(version,", "'%s.zip' % version)): zip_unicode(output, version) def get_unicodedata(version, output=HOME, no_zip=False): \"\"\"Ensure", "table.') parser.add_argument('--version', action='version', version=\"%(prog)s \" + __version__) parser.add_argument('--output', default=HOME, help='Output", "Unicode tables.\"\"\" target = os.path.join(output, 'unicodedata', version) zip_target = os.path.join(output,", "'Blocks.txt', 'PropList.txt', 'DerivedCoreProperties.txt', 'DerivedNormalizationProps.txt', 'CompositionExclusions.txt', 'PropertyValueAliases.txt', 'PropertyAliases.txt', 'EastAsianWidth.txt', 'LineBreak.txt', 'HangulSyllableType.txt',", "files!') break else: retrieved = True print('Skipping: found %s' %", "= os.path.join(output, 'unicodedata', version) zip_target = os.path.join(output, 'unicodedata', '%s.zip' %", "as uf: uf.write(data.decode('utf-8')) retrieved = True break if not retrieved:", "files.\"\"\" unzipper = zipfile.ZipFile(os.path.join(output, 'unicodedata', '%s.zip' % version)) target =", "= argparse.ArgumentParser(prog='unidatadownload', description='Generate a unicode property table.') parser.add_argument('--version', action='version', version=\"%(prog)s", "http_url): furl = url + f try: print('Downloading: %s -->", "need backslash on windows? Or is it forward as well?", "None: version = unicodedata.unidata_version else: version = args.unicode_version get_unicodedata(version, output=args.output)", "tables.\"\"\" target = os.path.join(output, 'unicodedata', version) zip_target = os.path.join(output, 'unicodedata',", "= [ 'UnicodeData.txt', 'Scripts.txt', 'Blocks.txt', 'PropList.txt', 'DerivedCoreProperties.txt', 'DerivedNormalizationProps.txt', 'CompositionExclusions.txt', 'PropertyValueAliases.txt',", "retrieved = True break if not retrieved: print('Failed to acquire", "'PropList.txt', 'DerivedCoreProperties.txt', 'DerivedNormalizationProps.txt', 'CompositionExclusions.txt', 'PropertyValueAliases.txt', 'PropertyAliases.txt', 'EastAsianWidth.txt', 'LineBreak.txt', 'HangulSyllableType.txt', 'DerivedAge.txt',", "] files.append('ScriptExtensions.txt') files.append('IndicPositionalCategory.txt') files.append('IndicSyllabicCategory.txt') files.append('BidiBrackets.txt') if ver >= (11, 0,", "not os.path.exists(os.path.join(output, 'unicodedata', '%s.zip' % version)): zip_unicode(output, version) def get_unicodedata(version,", "urlopen(furl, timeout=30) data = response.read() except Exception: print('Failed: %s' %", "Unicode version.') args = parser.parse_args() if args.unicode_version is None: version", "version) os.makedirs(target) for f in unzipper.namelist(): # Do I need", "with codecs.open(file_location, 'w', encoding='utf-8') as uf: uf.write(data.decode('utf-8')) retrieved = True", "is it forward as well? unzipper.extract(f, target) def download_unicodedata(version, output=HOME,", "forward as well? unzipper.extract(f, target) def download_unicodedata(version, output=HOME, no_zip=False): \"\"\"Download", "% version ftp_url = 'ftp://ftp.unicode.org/Public/%s/ucd/' % version destination = os.path.join(output,", "= url + f try: print('Downloading: %s --> %s' %", "% version) os.makedirs(target) for f in unzipper.namelist(): # Do I", "parser.add_argument('--version', action='version', version=\"%(prog)s \" + __version__) parser.add_argument('--output', default=HOME, help='Output file.')", "response.read() except Exception: print('Failed: %s' % url) continue with codecs.open(file_location,", "'UnicodeData.txt', 'Scripts.txt', 'Blocks.txt', 'PropList.txt', 'DerivedCoreProperties.txt', 'DerivedNormalizationProps.txt', 'CompositionExclusions.txt', 'PropertyValueAliases.txt', 'PropertyAliases.txt', 'EastAsianWidth.txt',", "needed Unicode files!') break else: retrieved = True print('Skipping: found", "x in version.split('.')]) files = [ 'UnicodeData.txt', 'Scripts.txt', 'Blocks.txt', 'PropList.txt',", "= True break if not retrieved: print('Failed to acquire all", "argparse import unicodedata parser = argparse.ArgumentParser(prog='unidatadownload', description='Generate a unicode property", "if args.unicode_version is None: version = unicodedata.unidata_version else: version =", "= response.read() except Exception: print('Failed: %s' % url) continue with", "arcname=file) def unzip_unicode(output, version): \"\"\"Unzip the Unicode files.\"\"\" unzipper =", "zip_data = not no_zip for f in files: file_location =", "= False break if zip_data and not os.path.exists(os.path.join(output, 'unicodedata', '%s.zip'", "= True print('Skipping: found %s' % file_location) if not retrieved:", "for x in version.split('.')]) files = [ 'UnicodeData.txt', 'Scripts.txt', 'Blocks.txt',", "f in files: file_location = os.path.join(destination, os.path.basename(f)) retrieved = False", "= os.path.join(output, 'unicodedata', '%s.zip' % version) if not os.path.exists(target) and", "urlopen __version__ = '2.2.0' HOME = os.path.dirname(os.path.abspath(__file__)) def zip_unicode(output, version):", "Unicode files!') break else: retrieved = True print('Skipping: found %s'", "url) continue with codecs.open(file_location, 'w', encoding='utf-8') as uf: uf.write(data.decode('utf-8')) retrieved", "import urlopen __version__ = '2.2.0' HOME = os.path.dirname(os.path.abspath(__file__)) def zip_unicode(output,", "url in (ftp_url, http_url): furl = url + f try:", "'extracted/DerivedNumericType.txt', 'extracted/DerivedNumericValues.txt', 'extracted/DerivedJoiningType.txt', 'extracted/DerivedJoiningGroup.txt', 'extracted/DerivedCombiningClass.txt', 'emoji/emoji-data.txt' ] files.append('ScriptExtensions.txt') files.append('IndicPositionalCategory.txt') files.append('IndicSyllabicCategory.txt')", "'extracted/DerivedNumericValues.txt', 'extracted/DerivedJoiningType.txt', 'extracted/DerivedJoiningGroup.txt', 'extracted/DerivedCombiningClass.txt', 'emoji/emoji-data.txt' ] files.append('ScriptExtensions.txt') files.append('IndicPositionalCategory.txt') files.append('IndicSyllabicCategory.txt') files.append('BidiBrackets.txt')", "% version destination = os.path.join(output, 'unicodedata', version) if not os.path.exists(destination):", "unzipper.namelist(): # Do I need backslash on windows? Or is", "%s' % (furl, file_location)) response = urlopen(furl, timeout=30) data =", "furl = url + f try: print('Downloading: %s --> %s'", "args = parser.parse_args() if args.unicode_version is None: version = unicodedata.unidata_version", "version.split('.')]) files = [ 'UnicodeData.txt', 'Scripts.txt', 'Blocks.txt', 'PropList.txt', 'DerivedCoreProperties.txt', 'DerivedNormalizationProps.txt',", "`Unicodedata` files.\"\"\" from __future__ import unicode_literals import os import zipfile", "the Unicode files.\"\"\" zipper = zipfile.ZipFile(os.path.join(output, 'unicodedata', '%s.zip' % version),", "import argparse import unicodedata parser = argparse.ArgumentParser(prog='unidatadownload', description='Generate a unicode", "os.makedirs(target) for f in unzipper.namelist(): # Do I need backslash", "have Unicode data to generate Unicode tables.\"\"\" target = os.path.join(output,", "not os.path.exists(target) and os.path.exists(zip_target): unzip_unicode(output, version) # Download missing files", "'unicodedata', version) zip_target = os.path.join(output, 'unicodedata', '%s.zip' % version) if", "= parser.parse_args() if args.unicode_version is None: version = unicodedata.unidata_version else:", "__version__ = '2.2.0' HOME = os.path.dirname(os.path.abspath(__file__)) def zip_unicode(output, version): \"\"\"Zip", "zipfile.ZipFile(os.path.join(output, 'unicodedata', '%s.zip' % version), 'w', zipfile.ZIP_DEFLATED) target = os.path.join(output,", "'PropertyAliases.txt', 'EastAsianWidth.txt', 'LineBreak.txt', 'HangulSyllableType.txt', 'DerivedAge.txt', 'auxiliary/WordBreakProperty.txt', 'auxiliary/SentenceBreakProperty.txt', 'auxiliary/GraphemeBreakProperty.txt', 'extracted/DerivedDecompositionType.txt', 'extracted/DerivedNumericType.txt',", "import codecs from urllib.request import urlopen __version__ = '2.2.0' HOME", "% version) for root, dirs, files in os.walk(target): for file", "'%s.zip' % version), 'w', zipfile.ZIP_DEFLATED) target = os.path.join(output, 'unicodedata', version)", "os.path.join(output, 'unicodedata', version) zip_target = os.path.join(output, 'unicodedata', '%s.zip' % version)", "zip_unicode(output, version) def get_unicodedata(version, output=HOME, no_zip=False): \"\"\"Ensure we have Unicode", "file in files: if file.endswith('.txt'): zipper.write(os.path.join(root, file), arcname=file) def unzip_unicode(output,", "file), arcname=file) def unzip_unicode(output, version): \"\"\"Unzip the Unicode files.\"\"\" unzipper", "% file_location) if not retrieved: zip_data = False break if", "= os.path.join(output, 'unicodedata', version) print('Zipping %s.zip...' % version) for root,", "%s' % file_location) if not retrieved: zip_data = False break", "break if zip_data and not os.path.exists(os.path.join(output, 'unicodedata', '%s.zip' % version)):", "files if any. Zip if required. download_unicodedata(version, output, no_zip) if", "import zipfile import codecs from urllib.request import urlopen __version__ =", "unzipper = zipfile.ZipFile(os.path.join(output, 'unicodedata', '%s.zip' % version)) target = os.path.join(output,", "def zip_unicode(output, version): \"\"\"Zip the Unicode files.\"\"\" zipper = zipfile.ZipFile(os.path.join(output,", "print('Unzipping %s.zip...' % version) os.makedirs(target) for f in unzipper.namelist(): #", "files: if file.endswith('.txt'): zipper.write(os.path.join(root, file), arcname=file) def unzip_unicode(output, version): \"\"\"Unzip", "to acquire all needed Unicode files!') break else: retrieved =", "args.unicode_version is None: version = unicodedata.unidata_version else: version = args.unicode_version", "to generate Unicode tables.\"\"\" target = os.path.join(output, 'unicodedata', version) zip_target", "timeout=30) data = response.read() except Exception: print('Failed: %s' % url)", "'unicodedata', version) if not os.path.exists(destination): os.makedirs(destination) zip_data = not no_zip", "+ f try: print('Downloading: %s --> %s' % (furl, file_location))", "retrieved: print('Failed to acquire all needed Unicode files!') break else:", "output=HOME, no_zip=False): \"\"\"Ensure we have Unicode data to generate Unicode", "'unicodedata', '%s.zip' % version) if not os.path.exists(target) and os.path.exists(zip_target): unzip_unicode(output,", "'extracted/DerivedJoiningType.txt', 'extracted/DerivedJoiningGroup.txt', 'extracted/DerivedCombiningClass.txt', 'emoji/emoji-data.txt' ] files.append('ScriptExtensions.txt') files.append('IndicPositionalCategory.txt') files.append('IndicSyllabicCategory.txt') files.append('BidiBrackets.txt') if", "break if not retrieved: print('Failed to acquire all needed Unicode", "\"\"\"Download `Unicodedata` files.\"\"\" from __future__ import unicode_literals import os import", "files.append('IndicSyllabicCategory.txt') files.append('BidiBrackets.txt') if ver >= (11, 0, 0): files.append('VerticalOrientation.txt') http_url", "--> %s' % (furl, file_location)) response = urlopen(furl, timeout=30) data", "uf: uf.write(data.decode('utf-8')) retrieved = True break if not retrieved: print('Failed", "parser.parse_args() if args.unicode_version is None: version = unicodedata.unidata_version else: version", "'w', encoding='utf-8') as uf: uf.write(data.decode('utf-8')) retrieved = True break if", "unzip_unicode(output, version) # Download missing files if any. Zip if", "def download_unicodedata(version, output=HOME, no_zip=False): \"\"\"Download Unicode data scripts and blocks.\"\"\"", "if not os.path.exists(destination): os.makedirs(destination) zip_data = not no_zip for f", "(furl, file_location)) response = urlopen(furl, timeout=30) data = response.read() except", "'auxiliary/SentenceBreakProperty.txt', 'auxiliary/GraphemeBreakProperty.txt', 'extracted/DerivedDecompositionType.txt', 'extracted/DerivedNumericType.txt', 'extracted/DerivedNumericValues.txt', 'extracted/DerivedJoiningType.txt', 'extracted/DerivedJoiningGroup.txt', 'extracted/DerivedCombiningClass.txt', 'emoji/emoji-data.txt' ]", "= os.path.dirname(os.path.abspath(__file__)) def zip_unicode(output, version): \"\"\"Zip the Unicode files.\"\"\" zipper", "tuple([int(x) for x in version.split('.')]) files = [ 'UnicodeData.txt', 'Scripts.txt',", "unicode property table.') parser.add_argument('--version', action='version', version=\"%(prog)s \" + __version__) parser.add_argument('--output',", "parser = argparse.ArgumentParser(prog='unidatadownload', description='Generate a unicode property table.') parser.add_argument('--version', action='version',", "data = response.read() except Exception: print('Failed: %s' % url) continue", "no_zip=False): \"\"\"Download Unicode data scripts and blocks.\"\"\" ver = tuple([int(x)", "help='Force a specific Unicode version.') args = parser.parse_args() if args.unicode_version", "url + f try: print('Downloading: %s --> %s' % (furl,", "% (furl, file_location)) response = urlopen(furl, timeout=30) data = response.read()", "== '__main__': import argparse import unicodedata parser = argparse.ArgumentParser(prog='unidatadownload', description='Generate", "True break if not retrieved: print('Failed to acquire all needed", "break else: retrieved = True print('Skipping: found %s' % file_location)", "file.endswith('.txt'): zipper.write(os.path.join(root, file), arcname=file) def unzip_unicode(output, version): \"\"\"Unzip the Unicode", "backslash on windows? Or is it forward as well? unzipper.extract(f,", "print('Downloading: %s --> %s' % (furl, file_location)) response = urlopen(furl,", "ver = tuple([int(x) for x in version.split('.')]) files = [", "version) print('Zipping %s.zip...' % version) for root, dirs, files in", "from __future__ import unicode_literals import os import zipfile import codecs", "'Scripts.txt', 'Blocks.txt', 'PropList.txt', 'DerivedCoreProperties.txt', 'DerivedNormalizationProps.txt', 'CompositionExclusions.txt', 'PropertyValueAliases.txt', 'PropertyAliases.txt', 'EastAsianWidth.txt', 'LineBreak.txt',", "file.') parser.add_argument('--unicode-version', default=None, help='Force a specific Unicode version.') args =", "'HangulSyllableType.txt', 'DerivedAge.txt', 'auxiliary/WordBreakProperty.txt', 'auxiliary/SentenceBreakProperty.txt', 'auxiliary/GraphemeBreakProperty.txt', 'extracted/DerivedDecompositionType.txt', 'extracted/DerivedNumericType.txt', 'extracted/DerivedNumericValues.txt', 'extracted/DerivedJoiningType.txt', 'extracted/DerivedJoiningGroup.txt',", "codecs from urllib.request import urlopen __version__ = '2.2.0' HOME =", "from urllib.request import urlopen __version__ = '2.2.0' HOME = os.path.dirname(os.path.abspath(__file__))", "version): \"\"\"Zip the Unicode files.\"\"\" zipper = zipfile.ZipFile(os.path.join(output, 'unicodedata', '%s.zip'", "else: retrieved = True print('Skipping: found %s' % file_location) if", "for file in files: if file.endswith('.txt'): zipper.write(os.path.join(root, file), arcname=file) def", "\"\"\"Ensure we have Unicode data to generate Unicode tables.\"\"\" target", "'%s.zip' % version)) target = os.path.join(output, 'unicodedata', version) print('Unzipping %s.zip...'", "unzip_unicode(output, version): \"\"\"Unzip the Unicode files.\"\"\" unzipper = zipfile.ZipFile(os.path.join(output, 'unicodedata',", "False break if zip_data and not os.path.exists(os.path.join(output, 'unicodedata', '%s.zip' %", "os.path.join(destination, os.path.basename(f)) retrieved = False if not os.path.exists(file_location): for url", "target = os.path.join(output, 'unicodedata', version) print('Zipping %s.zip...' % version) for", "in os.walk(target): for file in files: if file.endswith('.txt'): zipper.write(os.path.join(root, file),", "%s --> %s' % (furl, file_location)) response = urlopen(furl, timeout=30)", "not retrieved: zip_data = False break if zip_data and not", "file_location) if not retrieved: zip_data = False break if zip_data", "unicode_literals import os import zipfile import codecs from urllib.request import", "version), 'w', zipfile.ZIP_DEFLATED) target = os.path.join(output, 'unicodedata', version) print('Zipping %s.zip...'", "missing files if any. Zip if required. download_unicodedata(version, output, no_zip)", "'DerivedNormalizationProps.txt', 'CompositionExclusions.txt', 'PropertyValueAliases.txt', 'PropertyAliases.txt', 'EastAsianWidth.txt', 'LineBreak.txt', 'HangulSyllableType.txt', 'DerivedAge.txt', 'auxiliary/WordBreakProperty.txt', 'auxiliary/SentenceBreakProperty.txt',", "% url) continue with codecs.open(file_location, 'w', encoding='utf-8') as uf: uf.write(data.decode('utf-8'))", "'unicodedata', '%s.zip' % version)): zip_unicode(output, version) def get_unicodedata(version, output=HOME, no_zip=False):", "print('Zipping %s.zip...' % version) for root, dirs, files in os.walk(target):", "help='Output file.') parser.add_argument('--unicode-version', default=None, help='Force a specific Unicode version.') args", "%s.zip...' % version) os.makedirs(target) for f in unzipper.namelist(): # Do", "ver >= (11, 0, 0): files.append('VerticalOrientation.txt') http_url = 'http://www.unicode.org/Public/%s/ucd/' %", "uf.write(data.decode('utf-8')) retrieved = True break if not retrieved: print('Failed to", "for root, dirs, files in os.walk(target): for file in files:", "not retrieved: print('Failed to acquire all needed Unicode files!') break", "zip_target = os.path.join(output, 'unicodedata', '%s.zip' % version) if not os.path.exists(target)", "in version.split('.')]) files = [ 'UnicodeData.txt', 'Scripts.txt', 'Blocks.txt', 'PropList.txt', 'DerivedCoreProperties.txt',", "version) if not os.path.exists(target) and os.path.exists(zip_target): unzip_unicode(output, version) # Download", "for f in files: file_location = os.path.join(destination, os.path.basename(f)) retrieved =", "'unicodedata', '%s.zip' % version), 'w', zipfile.ZIP_DEFLATED) target = os.path.join(output, 'unicodedata',", "acquire all needed Unicode files!') break else: retrieved = True", "'extracted/DerivedDecompositionType.txt', 'extracted/DerivedNumericType.txt', 'extracted/DerivedNumericValues.txt', 'extracted/DerivedJoiningType.txt', 'extracted/DerivedJoiningGroup.txt', 'extracted/DerivedCombiningClass.txt', 'emoji/emoji-data.txt' ] files.append('ScriptExtensions.txt') files.append('IndicPositionalCategory.txt')", "zip_data = False break if zip_data and not os.path.exists(os.path.join(output, 'unicodedata',", "zipfile.ZIP_DEFLATED) target = os.path.join(output, 'unicodedata', version) print('Zipping %s.zip...' % version)", "and os.path.exists(zip_target): unzip_unicode(output, version) # Download missing files if any.", "argparse.ArgumentParser(prog='unidatadownload', description='Generate a unicode property table.') parser.add_argument('--version', action='version', version=\"%(prog)s \"", "if __name__ == '__main__': import argparse import unicodedata parser =", "% version) if not os.path.exists(target) and os.path.exists(zip_target): unzip_unicode(output, version) #", "Unicode data scripts and blocks.\"\"\" ver = tuple([int(x) for x", "\"\"\"Zip the Unicode files.\"\"\" zipper = zipfile.ZipFile(os.path.join(output, 'unicodedata', '%s.zip' %", "destination = os.path.join(output, 'unicodedata', version) if not os.path.exists(destination): os.makedirs(destination) zip_data", "f try: print('Downloading: %s --> %s' % (furl, file_location)) response", ">= (11, 0, 0): files.append('VerticalOrientation.txt') http_url = 'http://www.unicode.org/Public/%s/ucd/' % version", "os.path.join(output, 'unicodedata', version) if not os.path.exists(destination): os.makedirs(destination) zip_data = not", "default=None, help='Force a specific Unicode version.') args = parser.parse_args() if", "os.path.join(output, 'unicodedata', version) print('Zipping %s.zip...' % version) for root, dirs,", "os.path.exists(destination): os.makedirs(destination) zip_data = not no_zip for f in files:", "generate Unicode tables.\"\"\" target = os.path.join(output, 'unicodedata', version) zip_target =", "parser.add_argument('--output', default=HOME, help='Output file.') parser.add_argument('--unicode-version', default=None, help='Force a specific Unicode", "version=\"%(prog)s \" + __version__) parser.add_argument('--output', default=HOME, help='Output file.') parser.add_argument('--unicode-version', default=None,", "default=HOME, help='Output file.') parser.add_argument('--unicode-version', default=None, help='Force a specific Unicode version.')", "target) def download_unicodedata(version, output=HOME, no_zip=False): \"\"\"Download Unicode data scripts and", "if not os.path.exists(file_location): for url in (ftp_url, http_url): furl =", "unzipper.extract(f, target) def download_unicodedata(version, output=HOME, no_zip=False): \"\"\"Download Unicode data scripts", "'unicodedata', version) print('Unzipping %s.zip...' % version) os.makedirs(target) for f in", "ftp_url = 'ftp://ftp.unicode.org/Public/%s/ucd/' % version destination = os.path.join(output, 'unicodedata', version)", "= os.path.join(destination, os.path.basename(f)) retrieved = False if not os.path.exists(file_location): for", "= False if not os.path.exists(file_location): for url in (ftp_url, http_url):", "\" + __version__) parser.add_argument('--output', default=HOME, help='Output file.') parser.add_argument('--unicode-version', default=None, help='Force", "I need backslash on windows? Or is it forward as", "codecs.open(file_location, 'w', encoding='utf-8') as uf: uf.write(data.decode('utf-8')) retrieved = True break", "import os import zipfile import codecs from urllib.request import urlopen", "os.path.exists(os.path.join(output, 'unicodedata', '%s.zip' % version)): zip_unicode(output, version) def get_unicodedata(version, output=HOME,", "target = os.path.join(output, 'unicodedata', version) zip_target = os.path.join(output, 'unicodedata', '%s.zip'", "the Unicode files.\"\"\" unzipper = zipfile.ZipFile(os.path.join(output, 'unicodedata', '%s.zip' % version))", "[ 'UnicodeData.txt', 'Scripts.txt', 'Blocks.txt', 'PropList.txt', 'DerivedCoreProperties.txt', 'DerivedNormalizationProps.txt', 'CompositionExclusions.txt', 'PropertyValueAliases.txt', 'PropertyAliases.txt',", "'DerivedCoreProperties.txt', 'DerivedNormalizationProps.txt', 'CompositionExclusions.txt', 'PropertyValueAliases.txt', 'PropertyAliases.txt', 'EastAsianWidth.txt', 'LineBreak.txt', 'HangulSyllableType.txt', 'DerivedAge.txt', 'auxiliary/WordBreakProperty.txt',", "all needed Unicode files!') break else: retrieved = True print('Skipping:" ]
[ "# (acting for and on behalf of Oklahoma State University)", "files...\") # Write the config files start_time = datetime.datetime.now() cpaths", "import associativity from globals import OPTS, print_time class cache: \"\"\"", "+ \"_config.py\", \"use\": OPTS.output_path + OPTS.use_array_name + \"_config.py\" } if", "config files. \"\"\" self.c.config_write(paths) def verilog_write(self, path): \"\"\" Save the", "OPTS.replacement_policy.has_sram_array(): del cpaths[\"use\"] for k, cpath in cpaths.items(): debug.print_raw(\"Config: Writing", "datetime from policy import associativity from globals import OPTS, print_time", "Save the Verilog file. \"\"\" self.c.verilog_write(path) def save(self): \"\"\" Save", "OPTS.tag_array_name + \"_config.py\", \"use\": OPTS.output_path + OPTS.use_array_name + \"_config.py\" }", "= OPTS.output_path + self.c.name + \".v\" debug.print_raw(\"Verilog: Writing to {}\".format(vpath))", "and Mechanical College # (acting for and on behalf of", "\"\"\" def __init__(self, cache_config, name): cache_config.set_local_config(self) self.name = name #", "associative cache is not supported at the moment.\", -1) else:", "= name # Import the design module of the cache", "cache(cache_config, name) def config_write(self, paths): \"\"\" Save the config files.", "\"\"\" self.c.verilog_write(path) def save(self): \"\"\" Save all the output files.", "cache elif OPTS.associativity == associativity.N_WAY: from n_way_cache import n_way_cache as", "licensing information. # # Copyright (c) 2021 Regents of the", "of the cache if OPTS.associativity == associativity.DIRECT: from direct_cache import", "from policy import associativity from globals import OPTS, print_time class", "Verilog file. \"\"\" self.c.verilog_write(path) def save(self): \"\"\" Save all the", "associativity.FULLY: # TODO: from full_cache import full_cache as cache debug.error(\"Fully", "files start_time = datetime.datetime.now() cpaths = { \"data\": OPTS.output_path +", "the config files start_time = datetime.datetime.now() cpaths = { \"data\":", "Write the config files start_time = datetime.datetime.now() cpaths = {", "def save(self): \"\"\" Save all the output files. \"\"\" debug.print_raw(\"Saving", "start_time = datetime.datetime.now() vpath = OPTS.output_path + self.c.name + \".v\"", "config files start_time = datetime.datetime.now() cpaths = { \"data\": OPTS.output_path", "This is not a design module, but contains a cache", "module, but contains a cache design instance. \"\"\" def __init__(self,", "OPTS.output_path + OPTS.use_array_name + \"_config.py\" } if not OPTS.replacement_policy.has_sram_array(): del", "datetime.datetime.now() vpath = OPTS.output_path + self.c.name + \".v\" debug.print_raw(\"Verilog: Writing", "OPTS.associativity == associativity.FULLY: # TODO: from full_cache import full_cache as", "== associativity.FULLY: # TODO: from full_cache import full_cache as cache", "output files. \"\"\" debug.print_raw(\"Saving output files...\") # Write the config", "information. # # Copyright (c) 2021 Regents of the University", "the design module of the cache if OPTS.associativity == associativity.DIRECT:", "associativity.DIRECT: from direct_cache import direct_cache as cache elif OPTS.associativity ==", "cpath in cpaths.items(): debug.print_raw(\"Config: Writing to {}\".format(cpath)) self.config_write(cpaths) print_time(\"Config\", datetime.datetime.now(),", "path): \"\"\" Save the Verilog file. \"\"\" self.c.verilog_write(path) def save(self):", "(c) 2021 Regents of the University of California and The", "import datetime from policy import associativity from globals import OPTS,", "cpaths.items(): debug.print_raw(\"Config: Writing to {}\".format(cpath)) self.config_write(cpaths) print_time(\"Config\", datetime.datetime.now(), start_time) #", "The Board # of Regents for the Oklahoma Agricultural and", "# import debug import datetime from policy import associativity from", "class cache: \"\"\" This is not a design module, but", "associativity from globals import OPTS, print_time class cache: \"\"\" This", "associativity.\", -1) self.c = cache(cache_config, name) def config_write(self, paths): \"\"\"", "# of Regents for the Oklahoma Agricultural and Mechanical College", "not OPTS.replacement_policy.has_sram_array(): del cpaths[\"use\"] for k, cpath in cpaths.items(): debug.print_raw(\"Config:", "{ \"data\": OPTS.output_path + OPTS.data_array_name + \"_config.py\", \"tag\": OPTS.output_path +", "__init__(self, cache_config, name): cache_config.set_local_config(self) self.name = name # Import the", "+ \"_config.py\" } if not OPTS.replacement_policy.has_sram_array(): del cpaths[\"use\"] for k,", "to {}\".format(cpath)) self.config_write(cpaths) print_time(\"Config\", datetime.datetime.now(), start_time) # Write the Verilog", "datetime.datetime.now() cpaths = { \"data\": OPTS.output_path + OPTS.data_array_name + \"_config.py\",", "cache_config, name): cache_config.set_local_config(self) self.name = name # Import the design", "the cache if OPTS.associativity == associativity.DIRECT: from direct_cache import direct_cache", "if not OPTS.replacement_policy.has_sram_array(): del cpaths[\"use\"] for k, cpath in cpaths.items():", "the Verilog file start_time = datetime.datetime.now() vpath = OPTS.output_path +", "save(self): \"\"\" Save all the output files. \"\"\" debug.print_raw(\"Saving output", "University) # All rights reserved. # import debug import datetime", "debug.error(\"Fully associative cache is not supported at the moment.\", -1)", "\"\"\" debug.print_raw(\"Saving output files...\") # Write the config files start_time", "# # Copyright (c) 2021 Regents of the University of", "full_cache import full_cache as cache debug.error(\"Fully associative cache is not", "See LICENSE for licensing information. # # Copyright (c) 2021", "of the University of California and The Board # of", "name) def config_write(self, paths): \"\"\" Save the config files. \"\"\"", "All rights reserved. # import debug import datetime from policy", "OPTS.associativity == associativity.DIRECT: from direct_cache import direct_cache as cache elif", "cache is not supported at the moment.\", -1) else: debug.error(\"Invalid", "design module of the cache if OPTS.associativity == associativity.DIRECT: from", "name # Import the design module of the cache if", "is not supported at the moment.\", -1) else: debug.error(\"Invalid associativity.\",", "cache debug.error(\"Fully associative cache is not supported at the moment.\",", "cpaths[\"use\"] for k, cpath in cpaths.items(): debug.print_raw(\"Config: Writing to {}\".format(cpath))", "def verilog_write(self, path): \"\"\" Save the Verilog file. \"\"\" self.c.verilog_write(path)", "# All rights reserved. # import debug import datetime from", "California and The Board # of Regents for the Oklahoma", "import full_cache as cache debug.error(\"Fully associative cache is not supported", "cache_config.set_local_config(self) self.name = name # Import the design module of", "for the Oklahoma Agricultural and Mechanical College # (acting for", "import debug import datetime from policy import associativity from globals", "associativity.N_WAY: from n_way_cache import n_way_cache as cache elif OPTS.associativity ==", "= { \"data\": OPTS.output_path + OPTS.data_array_name + \"_config.py\", \"tag\": OPTS.output_path", "Verilog file start_time = datetime.datetime.now() vpath = OPTS.output_path + self.c.name", "and The Board # of Regents for the Oklahoma Agricultural", "= datetime.datetime.now() vpath = OPTS.output_path + self.c.name + \".v\" debug.print_raw(\"Verilog:", "Regents for the Oklahoma Agricultural and Mechanical College # (acting", "OPTS.output_path + OPTS.data_array_name + \"_config.py\", \"tag\": OPTS.output_path + OPTS.tag_array_name +", "cache elif OPTS.associativity == associativity.FULLY: # TODO: from full_cache import", "debug.print_raw(\"Config: Writing to {}\".format(cpath)) self.config_write(cpaths) print_time(\"Config\", datetime.datetime.now(), start_time) # Write", "{}\".format(cpath)) self.config_write(cpaths) print_time(\"Config\", datetime.datetime.now(), start_time) # Write the Verilog file", "k, cpath in cpaths.items(): debug.print_raw(\"Config: Writing to {}\".format(cpath)) self.config_write(cpaths) print_time(\"Config\",", "+ OPTS.use_array_name + \"_config.py\" } if not OPTS.replacement_policy.has_sram_array(): del cpaths[\"use\"]", "n_way_cache import n_way_cache as cache elif OPTS.associativity == associativity.FULLY: #", "all the output files. \"\"\" debug.print_raw(\"Saving output files...\") # Write", "instance. \"\"\" def __init__(self, cache_config, name): cache_config.set_local_config(self) self.name = name", "at the moment.\", -1) else: debug.error(\"Invalid associativity.\", -1) self.c =", "verilog_write(self, path): \"\"\" Save the Verilog file. \"\"\" self.c.verilog_write(path) def", "of California and The Board # of Regents for the", "direct_cache import direct_cache as cache elif OPTS.associativity == associativity.N_WAY: from", "2021 Regents of the University of California and The Board", "print_time class cache: \"\"\" This is not a design module,", "for and on behalf of Oklahoma State University) # All", "name): cache_config.set_local_config(self) self.name = name # Import the design module", "a cache design instance. \"\"\" def __init__(self, cache_config, name): cache_config.set_local_config(self)", "for k, cpath in cpaths.items(): debug.print_raw(\"Config: Writing to {}\".format(cpath)) self.config_write(cpaths)", "Board # of Regents for the Oklahoma Agricultural and Mechanical", "file start_time = datetime.datetime.now() vpath = OPTS.output_path + self.c.name +", "on behalf of Oklahoma State University) # All rights reserved.", "a design module, but contains a cache design instance. \"\"\"", "# Write the config files start_time = datetime.datetime.now() cpaths =", "print_time(\"Config\", datetime.datetime.now(), start_time) # Write the Verilog file start_time =", "import n_way_cache as cache elif OPTS.associativity == associativity.FULLY: # TODO:", "not a design module, but contains a cache design instance.", "\"\"\" Save the config files. \"\"\" self.c.config_write(paths) def verilog_write(self, path):", "Save the config files. \"\"\" self.c.config_write(paths) def verilog_write(self, path): \"\"\"", "\"\"\" self.c.config_write(paths) def verilog_write(self, path): \"\"\" Save the Verilog file.", "elif OPTS.associativity == associativity.N_WAY: from n_way_cache import n_way_cache as cache", "self.c.verilog_write(path) def save(self): \"\"\" Save all the output files. \"\"\"", "+ OPTS.data_array_name + \"_config.py\", \"tag\": OPTS.output_path + OPTS.tag_array_name + \"_config.py\",", "+ \"_config.py\", \"tag\": OPTS.output_path + OPTS.tag_array_name + \"_config.py\", \"use\": OPTS.output_path", "datetime.datetime.now(), start_time) # Write the Verilog file start_time = datetime.datetime.now()", "paths): \"\"\" Save the config files. \"\"\" self.c.config_write(paths) def verilog_write(self,", "supported at the moment.\", -1) else: debug.error(\"Invalid associativity.\", -1) self.c", "# TODO: from full_cache import full_cache as cache debug.error(\"Fully associative", "\"\"\" Save all the output files. \"\"\" debug.print_raw(\"Saving output files...\")", "OPTS.use_array_name + \"_config.py\" } if not OPTS.replacement_policy.has_sram_array(): del cpaths[\"use\"] for", "University of California and The Board # of Regents for", "+ OPTS.tag_array_name + \"_config.py\", \"use\": OPTS.output_path + OPTS.use_array_name + \"_config.py\"", "from direct_cache import direct_cache as cache elif OPTS.associativity == associativity.N_WAY:", "debug import datetime from policy import associativity from globals import", "reserved. # import debug import datetime from policy import associativity", "def config_write(self, paths): \"\"\" Save the config files. \"\"\" self.c.config_write(paths)", "from globals import OPTS, print_time class cache: \"\"\" This is", "files. \"\"\" debug.print_raw(\"Saving output files...\") # Write the config files", "design instance. \"\"\" def __init__(self, cache_config, name): cache_config.set_local_config(self) self.name =", "Mechanical College # (acting for and on behalf of Oklahoma", "del cpaths[\"use\"] for k, cpath in cpaths.items(): debug.print_raw(\"Config: Writing to", "Oklahoma Agricultural and Mechanical College # (acting for and on", "Writing to {}\".format(cpath)) self.config_write(cpaths) print_time(\"Config\", datetime.datetime.now(), start_time) # Write the", "policy import associativity from globals import OPTS, print_time class cache:", "the Oklahoma Agricultural and Mechanical College # (acting for and", "== associativity.N_WAY: from n_way_cache import n_way_cache as cache elif OPTS.associativity", "n_way_cache as cache elif OPTS.associativity == associativity.FULLY: # TODO: from", "design module, but contains a cache design instance. \"\"\" def", "the config files. \"\"\" self.c.config_write(paths) def verilog_write(self, path): \"\"\" Save", "\"_config.py\", \"tag\": OPTS.output_path + OPTS.tag_array_name + \"_config.py\", \"use\": OPTS.output_path +", "State University) # All rights reserved. # import debug import", "\"data\": OPTS.output_path + OPTS.data_array_name + \"_config.py\", \"tag\": OPTS.output_path + OPTS.tag_array_name", "moment.\", -1) else: debug.error(\"Invalid associativity.\", -1) self.c = cache(cache_config, name)", "+ self.c.name + \".v\" debug.print_raw(\"Verilog: Writing to {}\".format(vpath)) self.verilog_write(vpath) print_time(\"Verilog\",", "file. \"\"\" self.c.verilog_write(path) def save(self): \"\"\" Save all the output", "OPTS.output_path + self.c.name + \".v\" debug.print_raw(\"Verilog: Writing to {}\".format(vpath)) self.verilog_write(vpath)", "of Regents for the Oklahoma Agricultural and Mechanical College #", "globals import OPTS, print_time class cache: \"\"\" This is not", "start_time = datetime.datetime.now() cpaths = { \"data\": OPTS.output_path + OPTS.data_array_name", "OPTS.associativity == associativity.N_WAY: from n_way_cache import n_way_cache as cache elif", "the University of California and The Board # of Regents", "module of the cache if OPTS.associativity == associativity.DIRECT: from direct_cache", "\"use\": OPTS.output_path + OPTS.use_array_name + \"_config.py\" } if not OPTS.replacement_policy.has_sram_array():", "self.config_write(cpaths) print_time(\"Config\", datetime.datetime.now(), start_time) # Write the Verilog file start_time", "debug.print_raw(\"Saving output files...\") # Write the config files start_time =", "as cache elif OPTS.associativity == associativity.FULLY: # TODO: from full_cache", "Agricultural and Mechanical College # (acting for and on behalf", "the Verilog file. \"\"\" self.c.verilog_write(path) def save(self): \"\"\" Save all", "Save all the output files. \"\"\" debug.print_raw(\"Saving output files...\") #", "rights reserved. # import debug import datetime from policy import", "as cache elif OPTS.associativity == associativity.N_WAY: from n_way_cache import n_way_cache", "as cache debug.error(\"Fully associative cache is not supported at the", "the moment.\", -1) else: debug.error(\"Invalid associativity.\", -1) self.c = cache(cache_config,", "import direct_cache as cache elif OPTS.associativity == associativity.N_WAY: from n_way_cache", "Import the design module of the cache if OPTS.associativity ==", "in cpaths.items(): debug.print_raw(\"Config: Writing to {}\".format(cpath)) self.config_write(cpaths) print_time(\"Config\", datetime.datetime.now(), start_time)", "LICENSE for licensing information. # # Copyright (c) 2021 Regents", "behalf of Oklahoma State University) # All rights reserved. #", "OPTS.output_path + OPTS.tag_array_name + \"_config.py\", \"use\": OPTS.output_path + OPTS.use_array_name +", "files. \"\"\" self.c.config_write(paths) def verilog_write(self, path): \"\"\" Save the Verilog", "\"\"\" Save the Verilog file. \"\"\" self.c.verilog_write(path) def save(self): \"\"\"", "full_cache as cache debug.error(\"Fully associative cache is not supported at", "-1) self.c = cache(cache_config, name) def config_write(self, paths): \"\"\" Save", "# See LICENSE for licensing information. # # Copyright (c)", "not supported at the moment.\", -1) else: debug.error(\"Invalid associativity.\", -1)", "} if not OPTS.replacement_policy.has_sram_array(): del cpaths[\"use\"] for k, cpath in", "\"\"\" This is not a design module, but contains a", "from full_cache import full_cache as cache debug.error(\"Fully associative cache is", "# Write the Verilog file start_time = datetime.datetime.now() vpath =", "OPTS.data_array_name + \"_config.py\", \"tag\": OPTS.output_path + OPTS.tag_array_name + \"_config.py\", \"use\":", "Regents of the University of California and The Board #", "start_time) # Write the Verilog file start_time = datetime.datetime.now() vpath", "OPTS, print_time class cache: \"\"\" This is not a design", "Write the Verilog file start_time = datetime.datetime.now() vpath = OPTS.output_path", "self.c = cache(cache_config, name) def config_write(self, paths): \"\"\" Save the", "the output files. \"\"\" debug.print_raw(\"Saving output files...\") # Write the", "direct_cache as cache elif OPTS.associativity == associativity.N_WAY: from n_way_cache import", "(acting for and on behalf of Oklahoma State University) #", "TODO: from full_cache import full_cache as cache debug.error(\"Fully associative cache", "Oklahoma State University) # All rights reserved. # import debug", "else: debug.error(\"Invalid associativity.\", -1) self.c = cache(cache_config, name) def config_write(self,", "import OPTS, print_time class cache: \"\"\" This is not a", "self.name = name # Import the design module of the", "cache: \"\"\" This is not a design module, but contains", "elif OPTS.associativity == associativity.FULLY: # TODO: from full_cache import full_cache", "== associativity.DIRECT: from direct_cache import direct_cache as cache elif OPTS.associativity", "config_write(self, paths): \"\"\" Save the config files. \"\"\" self.c.config_write(paths) def", "output files...\") # Write the config files start_time = datetime.datetime.now()", "# Copyright (c) 2021 Regents of the University of California", "if OPTS.associativity == associativity.DIRECT: from direct_cache import direct_cache as cache", "Copyright (c) 2021 Regents of the University of California and", "College # (acting for and on behalf of Oklahoma State", "\"_config.py\", \"use\": OPTS.output_path + OPTS.use_array_name + \"_config.py\" } if not", "+ \".v\" debug.print_raw(\"Verilog: Writing to {}\".format(vpath)) self.verilog_write(vpath) print_time(\"Verilog\", datetime.datetime.now(), start_time)", "cache design instance. \"\"\" def __init__(self, cache_config, name): cache_config.set_local_config(self) self.name", "vpath = OPTS.output_path + self.c.name + \".v\" debug.print_raw(\"Verilog: Writing to", "is not a design module, but contains a cache design", "self.c.config_write(paths) def verilog_write(self, path): \"\"\" Save the Verilog file. \"\"\"", "-1) else: debug.error(\"Invalid associativity.\", -1) self.c = cache(cache_config, name) def", "for licensing information. # # Copyright (c) 2021 Regents of", "self.c.name + \".v\" debug.print_raw(\"Verilog: Writing to {}\".format(vpath)) self.verilog_write(vpath) print_time(\"Verilog\", datetime.datetime.now(),", "debug.error(\"Invalid associativity.\", -1) self.c = cache(cache_config, name) def config_write(self, paths):", "contains a cache design instance. \"\"\" def __init__(self, cache_config, name):", "of Oklahoma State University) # All rights reserved. # import", "def __init__(self, cache_config, name): cache_config.set_local_config(self) self.name = name # Import", "# Import the design module of the cache if OPTS.associativity", "= cache(cache_config, name) def config_write(self, paths): \"\"\" Save the config", "= datetime.datetime.now() cpaths = { \"data\": OPTS.output_path + OPTS.data_array_name +", "cache if OPTS.associativity == associativity.DIRECT: from direct_cache import direct_cache as", "cpaths = { \"data\": OPTS.output_path + OPTS.data_array_name + \"_config.py\", \"tag\":", "\"tag\": OPTS.output_path + OPTS.tag_array_name + \"_config.py\", \"use\": OPTS.output_path + OPTS.use_array_name", "and on behalf of Oklahoma State University) # All rights", "but contains a cache design instance. \"\"\" def __init__(self, cache_config,", "from n_way_cache import n_way_cache as cache elif OPTS.associativity == associativity.FULLY:", "\"_config.py\" } if not OPTS.replacement_policy.has_sram_array(): del cpaths[\"use\"] for k, cpath" ]
[ "label_data.shape[0] print('The number of anomaly instances is %d' % sum(label_data))", "cur_time else: start_end_pair=tuple((start_index,end_index)) start_end_index_list.append(start_end_pair) break # move the start and", "dataset' % inst_number) # get all the log indexes in", "+= 1 #print(\"Among all instances, %d are anomalies\"%sum(labels)) return event_count_matrix", "first start, end index, end time for cur_time in time_data:", "raw_data, event_mapping_data): \"\"\" split logs into sliding windows, built an", "= para['path'] + para['log_seq_file_name'] label_path = para['path'] + para['label_file_name'] #", "until next sliding window while end_index < log_size: start_time =", "time_data[i] < start_time: i+=1 else: break for j in range(end_index,", "inst_number = len(start_end_index_list) print('there are %d instances (sliding windows) in", "interval since the start time data_df['seconds_since'] = (data_df['time']-data_df['time'][0]).dt.total_seconds().astype(int) # get", "log_size: start_time = start_time + para['step_size']*3600 end_time = end_time +", "cur_time in time_data: if cur_time < start_time + para['window_size']*3600: end_index", "# load data data_df = pd.read_csv(file_path, delimiter=r'\\s+', header=None, names =", "label_df = pd.read_csv(label_path, delimiter=r'\\s+', header=None, usecols = [0], dtype =int)", "= [] expanded_indexes_list.append(index_list) for i in range(inst_number): start_index = start_end_index_list[i][0]", "into sliding window start_time = time_data[0] start_index = 0 end_index", "= data_df[['seconds_since']].as_matrix() # load the event mapping list event_mapping =", "-------- para: the parameters dictionary Returns: -------- raw_data: list of", "- data_df['time'][0]).dt.total_seconds().astype(int) # get the label for each log #", "-------- raw_data: list of (label, time) event_mapping_data: a list of", "start_index to end_index expanded_indexes_list=[] for t in range(inst_number): index_list =", "__author__ = '<NAME>' import pandas as pd import os import", "start and end of sliding time window label_data, time_data =", "the time interval since the start time data_df['seconds_since'] = (data_df['time']", "axis=1) # data_df['time'] = pd.to_datetime(data_df['time'], format=\"%b-%d-%H:%M:%S\") # calculate the time", "dictionary raw_data: list of (label, time) event_mapping_data: a list of", "load data data_df = pd.read_csv(file_path, delimiter=r'\\s+', header=None, names = ['label','time'],", "usecols = [0], dtype =int) event_mapping_data = event_mapping.as_matrix() print(\"The raw", "to date time format data_df['time'] = pd.to_datetime(data_df['time'], format=\"%Y-%m-%d-%H.%M.%S.%f\") # calculate", "since the start time data_df['seconds_since'] = (data_df['time'] - data_df['time'][0]).dt.total_seconds().astype(int) #", "%d, but it requires further processing' % sum(raw_data[:, 0])) return", "are %d instances (sliding windows) in this dataset\\n'%inst_number) np.savetxt(sliding_file_path,start_end_index_list,delimiter=',',fmt='%d') else:", "instances is %d' % sum(label_data)) return raw_data, label_data def bgl_data_loader(para):", "para['log_event_mapping'] # load data data_df = pd.read_csv(file_path, delimiter=r'\\s+', header=None, names", "names = ['label','time'], usecols = para['select_column']) #, parse_dates = [1],", "range(inst_number): start_index = start_end_index_list[i][0] end_index = start_end_index_list[i][1] for l in", "log events'%event_num) #=================get labels and event count of each sliding", "i end_index = j start_end_pair = tuple((start_index, end_index)) start_end_index_list.append(start_end_pair) inst_number", "< log_size: start_time = start_time + para['step_size']*3600 end_time = end_time", "+ para['log_seq_file_name'] label_path = para['path'] + para['label_file_name'] # load log", "len(list(set(event_mapping_data))) print('There are %d log events'%event_num) #=================get labels and event", "expanded_indexes_list[j]: event_index = event_mapping_data[k] event_count_matrix[j, event_index] += 1 #print(\"Among all", "[0], dtype =int) event_mapping_data = event_mapping.as_matrix() print(\"The raw data shape", "print('The number of anomaly logs is %d, but it requires", "data_df = pd.read_csv(file_path, delimiter=r'\\s+', header=None, names=['month', 'day', 'hour'], usecols=para['select_column']) #", "+= 1 end_time = cur_time else: start_end_pair=tuple((start_index,end_index)) start_end_index_list.append(start_end_pair) break #", "= [row[0] for row in event_mapping_data] event_num = len(list(set(event_mapping_data))) print('There", "#0 represent success, 1 represent failure for k in expanded_indexes_list[j]:", "index indicates a corresponding log \"\"\" file_path = para['path'] +", "np def hdfs_data_loader(para): \"\"\" load the log sequence matrix and", "parse_dates = [1], date_parser=dateparse) # convert to date time format", "the log indexes in each time window by ranging from", "raw_data, event_mapping_data def deepia_preprocess_data(para, raw_data, event_mapping_data): \"\"\" split logs into", "corresponding log Returns: -------- event_count_matrix: event count matrix, where each", "corresponding log \"\"\" file_path = para['path'] + para['log_file_name'] event_mapping_path =", "= start_end_index_list[i][1] for l in range(start_index, end_index): expanded_indexes_list[i].append(l) event_mapping_data =", "raw_data = data_df[['label','seconds_since']].as_matrix() # load the event mapping list event_mapping", "list of (label, time) event_mapping_data: a list of event index,", "data_df[['month', 'day', 'hour']].apply(lambda x: list(map(str, x))) data_df['time'] = data_df[['month', 'day',", "format data_df = data_df[['month', 'day', 'hour']].apply(lambda x: list(map(str, x))) data_df['time']", "next sliding window while end_index < log_size: start_time = start_time", "[] expanded_indexes_list.append(index_list) for i in range(inst_number): start_index = start_end_index_list[i][0] end_index", "get all the log indexes in each time window by", "sliding time window label_data, time_data = raw_data[:,0], raw_data[:, 1] if", "log sequences matrix label_data: labels matrix \"\"\" file_path = para['path']", "get the label for each log data_df['label'] = (data_df['label'] !=", "[1], date_parser=dateparse) # convert to date time format data_df =", "+ para['label_file_name'] # load log sequence matrix pre_df = pd.read_csv(file_path,", "data data_df = pd.read_csv(file_path, delimiter=r'\\s+', header=None, names = ['label','time'], usecols", "data_df['label'] = (data_df['label'] != '-').astype(int) raw_data = data_df[['label','seconds_since']].as_matrix() # load", "and end index until next sliding window while end_index <", "window while end_index < log_size: start_time = start_time + para['step_size']*3600", "expanded_indexes_list=[] for t in range(inst_number): index_list = [] expanded_indexes_list.append(index_list) for", "pd import os import numpy as np def hdfs_data_loader(para): \"\"\"", "list of tuples, tuple contains two number, which represent the", "represent the start and end of sliding time window label_data,", "assert raw_data.shape[0] == label_data.shape[0] print('The number of anomaly instances is", "end_index += 1 end_time = cur_time else: start_end_pair=tuple((start_index,end_index)) start_end_index_list.append(start_end_pair) break", "each sliding window =============# labels = [] event_count_matrix = np.zeros((inst_number,event_num))", "logs and the log_event_mapping from the file path. Args: --------", "in range(inst_number): for k in expanded_indexes_list[j]: event_index = event_mapping_data[k] event_count_matrix[j,", "tuples, tuple contains two number, which represent the start and", "[1], date_parser=dateparse) # convert to date time format data_df['time'] =", "in range(end_index, log_size): if time_data[j] < end_time: j+=1 else: break", "print('there are %d instances (sliding windows) in this dataset\\n'%inst_number) np.savetxt(sliding_file_path,start_end_index_list,delimiter=',',fmt='%d')", "#=================get labels and event count of each sliding window =============#", "window =============# event_count_matrix = np.zeros((inst_number,event_num)) for j in range(inst_number): for", "labels from the file path. Args: -------- para: the parameters", "for k in expanded_indexes_list[j]: event_index = event_mapping_data[k] event_count_matrix[j, event_index] +=", "failure for k in expanded_indexes_list[j]: event_index = event_mapping_data[k] event_count_matrix[j, event_index]", "+ para['log_file_name'] event_mapping_path = para['path'] + para['log_event_mapping'] # load data", "start_end_index_list.append(start_end_pair) break # move the start and end index until", "label shape is {}\".format(raw_data.shape, event_mapping_data.shape)) assert raw_data.shape[0] == event_mapping_data.shape[0] print('The", "raw_data[:, 1] if not os.path.exists(sliding_file_path): # split into sliding window", "\"\"\" file_path = para['path'] + para['log_seq_file_name'] label_path = para['path'] +", "for i in range(start_index,end_index): if time_data[i] < start_time: i+=1 else:", "columns[:-1] data_df = pd.read_csv(file_path, delimiter=r'\\s+', header=None, usecols =use_cols, dtype =int)", "< start_time: i+=1 else: break for j in range(end_index, log_size):", "event_count_matrix[j, event_index] += 1 if label_data[k]: label = 1 continue", "= pd.to_datetime(data_df['time'], format=\"%b-%d-%H:%M:%S\") # calculate the time interval since the", "=============# event_count_matrix = np.zeros((inst_number,event_num)) for j in range(inst_number): for k", "since the start time data_df['seconds_since'] = (data_df['time']-data_df['time'][0]).dt.total_seconds().astype(int) # get the", "[] # list of tuples, tuple contains two number, which", "window by ranging from start_index to end_index expanded_indexes_list=[] for t", "windows) in this dataset\\n'%inst_number) np.savetxt(sliding_file_path,start_end_index_list,delimiter=',',fmt='%d') else: print('Loading start_end_index_list from file')", "a list of labels, 1 represents anomaly \"\"\" # create", "label_path = para['path'] + para['label_file_name'] # load log sequence matrix", "time data_df['seconds_since'] = (data_df['time'] - data_df['time'][0]).dt.total_seconds().astype(int) # get the label", "in this dataset\\n'%inst_number) np.savetxt(sliding_file_path,start_end_index_list,delimiter=',',fmt='%d') else: print('Loading start_end_index_list from file') start_end_index_list", "window =============# labels = [] event_count_matrix = np.zeros((inst_number,event_num)) for j", "event_mapping_data = event_mapping.as_matrix() print(\"The raw data shape is {} and", "header=None).as_matrix() inst_number = len(start_end_index_list) print('there are %d instances (sliding windows)", "window label_data, time_data = raw_data[:,0], raw_data[:, 1] if not os.path.exists(sliding_file_path):", "delimiter=r'\\s+', header=None, usecols =use_cols, dtype =int) raw_data = data_df.as_matrix() #", "< start_time + para['window_size']*3600: end_index += 1 end_time = cur_time", "event_mapping_path = para['path'] + para['log_event_mapping'] # load data data_df =", "(sliding windows) in this dataset' % inst_number) # get all", "time window by ranging from start_index to end_index expanded_indexes_list=[] for", "= raw_data[:,0], raw_data[:, 1] if not os.path.exists(sliding_file_path): # split into", "Returns: -------- event_count_matrix: event count matrix, where each row is", "event_num = len(list(set(event_mapping_data))) print('There are %d log events'%event_num) #=================get labels", "'hour'], usecols=para['select_column']) # , parse_dates = [1], date_parser=dateparse) # convert", "requires further processing' % sum(raw_data[:, 0])) return raw_data, event_mapping_data def", "of anomaly instances is %d' % sum(label_data)) return raw_data, label_data", "i in range(start_index,end_index): if time_data[i] < start_time: i+=1 else: break", "a corresponding log \"\"\" file_path = para['path'] + para['log_file_name'] event_mapping_path", "= pd.to_datetime(data_df['time'], format=\"%Y-%m-%d-%H.%M.%S.%f\") # calculate the time interval since the", "usecols=para['select_column']) # , parse_dates = [1], date_parser=dateparse) # convert to", "format=\"%Y-%m-%d-%H.%M.%S.%f\") # calculate the time interval since the start time", "# get the first start, end index, end time for", "raw data shape is {} and label shape is {}\".format(raw_data.shape,", "parameters dictionary Returns: -------- raw_data: list of (label, time) event_mapping_data:", "move the start and end index until next sliding window", "a list of event index, where each row index indicates", "assert event_count_matrix.shape[0] == len(labels) return event_count_matrix, labels def deepia_data_loader(para): \"\"\"", "list of event index, where each row index indicates a", "delimiter=r'\\s+', header=None, names=['month', 'day', 'hour'], usecols=para['select_column']) # , parse_dates =", "raw_data, event_mapping_data def bgl_preprocess_data(para, raw_data, event_mapping_data): \"\"\" split logs into", "start_time + para['window_size']*3600: end_index += 1 end_time = cur_time else:", "1 represent failure for k in expanded_indexes_list[j]: event_index = event_mapping_data[k]", "in range(inst_number): label = 0 #0 represent success, 1 represent", "data data_df = pd.read_csv(file_path, delimiter=r'\\s+', header=None, names=['month', 'day', 'hour'], usecols=para['select_column'])", "'day', 'hour']].apply(lambda x: '-'.join(x), axis=1) # data_df['time'] = pd.to_datetime(data_df['time'], format=\"%b-%d-%H:%M:%S\")", "list event_mapping = pd.read_csv(event_mapping_path, delimiter=r'\\s+', header=None, usecols = [0], dtype", "%d log events'%event_num) #=================get labels and event count of each", "= (data_df['time'] - data_df['time'][0]).dt.total_seconds().astype(int) # get the label for each", "# -*- coding: utf-8 -*- __author__ = '<NAME>' import pandas", "time window label_data, time_data = raw_data[:,0], raw_data[:, 1] if not", "for j in range(inst_number): for k in expanded_indexes_list[j]: event_index =", "labels = [] event_count_matrix = np.zeros((inst_number,event_num)) for j in range(inst_number):", "= i end_index = j start_end_pair = tuple((start_index, end_index)) start_end_index_list.append(start_end_pair)", "an event count matrix and get the corresponding label Args:", "bgl_preprocess_data(para, raw_data, event_mapping_data): \"\"\" split logs into sliding windows, built", "pd.read_csv(file_path, delimiter=r'\\s+', header=None, usecols =use_cols, dtype =int) raw_data = data_df.as_matrix()", "!= '-').astype(int) raw_data = data_df[['label','seconds_since']].as_matrix() # load the event mapping", "= tuple((start_index, end_index)) start_end_index_list.append(start_end_pair) inst_number = len(start_end_index_list) print('there are %d", "0])) return raw_data, event_mapping_data def deepia_preprocess_data(para, raw_data, event_mapping_data): \"\"\" split", "= len(list(set(event_mapping_data))) print('There are %d log events'%event_num) #=================get labels and", "# convert to date time format data_df = data_df[['month', 'day',", "para['window_size']*3600: end_index += 1 end_time = cur_time else: start_end_pair=tuple((start_index,end_index)) start_end_index_list.append(start_end_pair)", "corresponding label Args: -------- para: the parameters dictionary raw_data: list", "t in range(inst_number): index_list = [] expanded_indexes_list.append(index_list) for i in", "running if not os.path.exists(para['save_path']): os.mkdir(para['save_path']) log_size = raw_data.shape[0] sliding_file_path =", "event count of each sliding window =============# labels = []", "matrix and get the corresponding label Args: -------- para: the", "print('Loading start_end_index_list from file') start_end_index_list = pd.read_csv(sliding_file_path, header=None).as_matrix() inst_number =", "nrows=1, header=None, delimiter=r'\\s+') columns = pre_df.columns.tolist() # remove the last", "the start time data_df['seconds_since'] = (data_df['time'] - data_df['time'][0]).dt.total_seconds().astype(int) # get", "all the log indexes in each time window by ranging", "the parameters dictionary raw_data: list of (label, time) event_mapping_data: a", "{} and label shape is {}\".format(raw_data.shape, event_mapping_data.shape)) assert raw_data.shape[0] ==", "and get the corresponding label Args: -------- para: the parameters", "\"\"\" load the log sequence matrix and labels from the", "expanded_indexes_list[i].append(l) event_mapping_data = [row[0] for row in event_mapping_data] event_num =", "python # -*- coding: utf-8 -*- __author__ = '<NAME>' import", "windows (start_index, end_index), which can be directly loaded in future", "= (data_df['label'] != '-').astype(int) raw_data = data_df[['label','seconds_since']].as_matrix() # load the", "for l in range(start_index, end_index): expanded_indexes_list[i].append(l) event_mapping_data = [row[0] for", "x))) data_df['time'] = data_df[['month', 'day', 'hour']].apply(lambda x: '-'.join(x), axis=1) #", "processing' % sum(raw_data[:, 0])) return raw_data, event_mapping_data def deepia_preprocess_data(para, raw_data,", "Args: -------- para: the parameters dictionary Returns: -------- raw_data: log", "# convert to date time format data_df['time'] = pd.to_datetime(data_df['time'], format=\"%Y-%m-%d-%H.%M.%S.%f\")", "pd.to_datetime(data_df['time'], format=\"%Y-%m-%d-%H.%M.%S.%f\") # calculate the time interval since the start", "can be directly loaded in future running if not os.path.exists(para['save_path']):", "labels: a list of labels, 1 represents anomaly \"\"\" #", "as np def hdfs_data_loader(para): \"\"\" load the log sequence matrix", "time_data: if cur_time < start_time + para['window_size']*3600: end_index += 1", "interval since the start time data_df['seconds_since'] = (data_df['time'] - data_df['time'][0]).dt.total_seconds().astype(int)", "built an event count matrix and get the corresponding label", "delimiter=r'\\s+') columns = pre_df.columns.tolist() # remove the last column of", "the file path. Args: -------- para: the parameters dictionary Returns:", "return event_count_matrix, labels def deepia_data_loader(para): \"\"\" load the logs and", "end_index < log_size: start_time = start_time + para['step_size']*3600 end_time =", "= pd.read_csv(file_path, nrows=1, header=None, delimiter=r'\\s+') columns = pre_df.columns.tolist() # remove", "index until next sliding window while end_index < log_size: start_time", "label = 1 continue labels.append(label) assert inst_number == len(labels) print(\"Among", "return raw_data, event_mapping_data def deepia_preprocess_data(para, raw_data, event_mapping_data): \"\"\" split logs", "the directory for saving the sliding windows (start_index, end_index), which", "the event mapping list event_mapping = pd.read_csv(event_mapping_path, delimiter=r'\\s+', header=None, usecols", "bgl_data_loader(para): \"\"\" load the logs and the log_event_mapping from the", "sum(raw_data[:, 0])) return raw_data, event_mapping_data def bgl_preprocess_data(para, raw_data, event_mapping_data): \"\"\"", "log_size): if time_data[j] < end_time: j+=1 else: break start_index =", "are %d log events'%event_num) #=================get labels and event count of", "'hour']].apply(lambda x: '-'.join(x), axis=1) # data_df['time'] = pd.to_datetime(data_df['time'], format=\"%b-%d-%H:%M:%S\") #", "event_mapping_data: a list of event index, where each row index", "1 if label_data[k]: label = 1 continue labels.append(label) assert inst_number", "break start_index = i end_index = j start_end_pair = tuple((start_index,", "for each log data_df['label'] = (data_df['label'] != '-').astype(int) raw_data =", "# get all the log indexes in each time window", "1 continue labels.append(label) assert inst_number == len(labels) print(\"Among all instances,", "== len(labels) return event_count_matrix, labels def deepia_data_loader(para): \"\"\" load the", "return raw_data, label_data def bgl_data_loader(para): \"\"\" load the logs and", "each row index indicates a corresponding log \"\"\" file_path =", "from start_index to end_index expanded_indexes_list=[] for t in range(inst_number): index_list", "pre_df = pd.read_csv(file_path, nrows=1, header=None, delimiter=r'\\s+') columns = pre_df.columns.tolist() #", "=int) # usecols must be a list label_data = label_df.as_matrix()", "para: the parameters dictionary Returns: -------- raw_data: list of (label,", "= 0 #0 represent success, 1 represent failure for k", "into sliding windows, built an event count matrix and get", "the parameters dictionary Returns: -------- raw_data: log sequences matrix label_data:", "row index indicates a corresponding log \"\"\" file_path = para['path']", "loaded in future running if not os.path.exists(para['save_path']): os.mkdir(para['save_path']) log_size =", "instances (sliding windows) in this dataset\\n'%inst_number) np.savetxt(sliding_file_path,start_end_index_list,delimiter=',',fmt='%d') else: print('Loading start_end_index_list", "usecols = [0], dtype =int) # usecols must be a", "row is an instance (log sequence vector) labels: a list", "where each row is an instance (log sequence vector) labels:", "continue labels.append(label) assert inst_number == len(labels) print(\"Among all instances, %d", "'hour']].apply(lambda x: list(map(str, x))) data_df['time'] = data_df[['month', 'day', 'hour']].apply(lambda x:", "1 end_time = cur_time else: start_end_pair=tuple((start_index,end_index)) start_end_index_list.append(start_end_pair) break # move", "time_data[j] < end_time: j+=1 else: break start_index = i end_index", "directory for saving the sliding windows (start_index, end_index), which can", "pd.read_csv(sliding_file_path, header=None).as_matrix() inst_number = len(start_end_index_list) print('there are %d instances (sliding", "= para['path'] + para['log_file_name'] event_mapping_path = para['path'] + para['log_event_mapping'] #", "usecols = para['select_column']) #, parse_dates = [1], date_parser=dateparse) # convert", "success, 1 represent failure for k in expanded_indexes_list[j]: event_index =", "this dataset' % inst_number) # get all the log indexes", "labels and event count of each sliding window =============# labels", "ranging from start_index to end_index expanded_indexes_list=[] for t in range(inst_number):", "= [0], dtype =int) # usecols must be a list", "return raw_data, event_mapping_data def bgl_preprocess_data(para, raw_data, event_mapping_data): \"\"\" split logs", "usecols =use_cols, dtype =int) raw_data = data_df.as_matrix() # load lables", "label_data = label_df.as_matrix() print(\"The raw data shape is {} and", "= j start_end_pair = tuple((start_index, end_index)) start_end_index_list.append(start_end_pair) inst_number = len(start_end_index_list)", "label for each log data_df['label'] = (data_df['label'] != '-').astype(int) raw_data", "index, where each row index indicates a corresponding log Returns:", "by ranging from start_index to end_index expanded_indexes_list=[] for t in", "sum(label_data)) return raw_data, label_data def bgl_data_loader(para): \"\"\" load the logs", "end_index = 0 # get the first start, end index,", "'-').astype(int) raw_data = data_df[['label','seconds_since']].as_matrix() # load the event mapping list", "break # move the start and end index until next", "data_df['seconds_since'] = (data_df['time']-data_df['time'][0]).dt.total_seconds().astype(int) # get the label for each log", "split logs into sliding windows, built an event count matrix", "time for cur_time in time_data: if cur_time < start_time +", "l in range(start_index, end_index): expanded_indexes_list[i].append(l) event_mapping_data = [row[0] for row", "delimiter=r'\\s+', header=None, usecols = [0], dtype =int) # usecols must", "1 represents anomaly \"\"\" # create the directory for saving", "event_mapping_data): \"\"\" split logs into sliding windows, built an event", "be directly loaded in future running if not os.path.exists(para['save_path']): os.mkdir(para['save_path'])", "must be a list label_data = label_df.as_matrix() print(\"The raw data", "event count matrix and get the corresponding label Args: --------", "event_count_matrix[j, event_index] += 1 #print(\"Among all instances, %d are anomalies\"%sum(labels))", "to date time format data_df = data_df[['month', 'day', 'hour']].apply(lambda x:", "dataset\\n'%inst_number) np.savetxt(sliding_file_path,start_end_index_list,delimiter=',',fmt='%d') else: print('Loading start_end_index_list from file') start_end_index_list = pd.read_csv(sliding_file_path,", "event_count_matrix = np.zeros((inst_number,event_num)) for j in range(inst_number): for k in", "end_index expanded_indexes_list=[] for t in range(inst_number): index_list = [] expanded_indexes_list.append(index_list)", "start_end_index_list = [] # list of tuples, tuple contains two", "event_mapping_data.shape)) assert raw_data.shape[0] == event_mapping_data.shape[0] #print('The number of anomaly logs", "event_count_matrix, labels def deepia_data_loader(para): \"\"\" load the logs and the", "is {}\".format(raw_data.shape, label_data.shape)) assert raw_data.shape[0] == label_data.shape[0] print('The number of", "+ para['log_event_mapping'] # load data data_df = pd.read_csv(file_path, delimiter=r'\\s+', header=None,", "{} and label shape is {}\".format(raw_data.shape, label_data.shape)) assert raw_data.shape[0] ==", "load the logs and the log_event_mapping from the file path.", "def hdfs_data_loader(para): \"\"\" load the log sequence matrix and labels", "convert to date time format data_df = data_df[['month', 'day', 'hour']].apply(lambda", "para['log_file_name'] event_mapping_path = para['path'] + para['log_event_mapping'] # load data data_df", "dtype =int) raw_data = data_df.as_matrix() # load lables label_df =", "header=None, usecols = [0], dtype =int) # usecols must be", "= '<NAME>' import pandas as pd import os import numpy", "= 0 end_index = 0 # get the first start,", "list of labels, 1 represents anomaly \"\"\" # create the", "get the first start, end index, end time for cur_time", "len(start_end_index_list) print('there are %d instances (sliding windows) in this dataset'", "cur_time < start_time + para['window_size']*3600: end_index += 1 end_time =", "= label_df.as_matrix() print(\"The raw data shape is {} and label", "label shape is {}\".format(raw_data.shape, event_mapping_data.shape)) assert raw_data.shape[0] == event_mapping_data.shape[0] #print('The", "{}\".format(raw_data.shape, event_mapping_data.shape)) assert raw_data.shape[0] == event_mapping_data.shape[0] print('The number of anomaly", "logs into sliding windows, built an event count matrix and", "end_time + para['step_size']*3600 for i in range(start_index,end_index): if time_data[i] <", "= event_mapping_data[k] event_count_matrix[j, event_index] += 1 #print(\"Among all instances, %d", "in this dataset' % inst_number) # get all the log", "# list of tuples, tuple contains two number, which represent", "end_time: j+=1 else: break start_index = i end_index = j", "a list label_data = label_df.as_matrix() print(\"The raw data shape is", "event_count_matrix = np.zeros((inst_number,event_num)) for j in range(inst_number): label = 0", "Args: -------- para: the parameters dictionary raw_data: list of (label,", "else: print('Loading start_end_index_list from file') start_end_index_list = pd.read_csv(sliding_file_path, header=None).as_matrix() inst_number", "print(\"The raw data shape is {} and label shape is", "= np.zeros((inst_number,event_num)) for j in range(inst_number): for k in expanded_indexes_list[j]:", "from file') start_end_index_list = pd.read_csv(sliding_file_path, header=None).as_matrix() inst_number = len(start_end_index_list) print('there", "anomalies\"%sum(labels)) assert event_count_matrix.shape[0] == len(labels) return event_count_matrix, labels def deepia_data_loader(para):", "load data data_df = pd.read_csv(file_path, delimiter=r'\\s+', header=None, names=['month', 'day', 'hour'],", "j in range(inst_number): for k in expanded_indexes_list[j]: event_index = event_mapping_data[k]", "represent failure for k in expanded_indexes_list[j]: event_index = event_mapping_data[k] event_count_matrix[j,", "directly loaded in future running if not os.path.exists(para['save_path']): os.mkdir(para['save_path']) log_size", "= raw_data[:,0] if not os.path.exists(sliding_file_path): # split into sliding window", "usecols must be a list label_data = label_df.as_matrix() print(\"The raw", "in range(inst_number): index_list = [] expanded_indexes_list.append(index_list) for i in range(inst_number):", "header=None, names=['month', 'day', 'hour'], usecols=para['select_column']) # , parse_dates = [1],", "== event_mapping_data.shape[0] #print('The number of anomaly logs is %d, but", "== label_data.shape[0] print('The number of anomaly instances is %d' %", "range(start_index, end_index): expanded_indexes_list[i].append(l) event_mapping_data = [row[0] for row in event_mapping_data]", "(start_index, end_index), which can be directly loaded in future running", "0])) return raw_data, event_mapping_data def bgl_preprocess_data(para, raw_data, event_mapping_data): \"\"\" split", "start_time + para['step_size']*3600 end_time = end_time + para['step_size']*3600 for i", "is {}\".format(raw_data.shape, event_mapping_data.shape)) assert raw_data.shape[0] == event_mapping_data.shape[0] #print('The number of", "(label, time) event_mapping_data: a list of event index, where each", "start_end_index_list.append(start_end_pair) inst_number = len(start_end_index_list) print('there are %d instances (sliding windows)", "sliding time window time_data = raw_data[:,0] if not os.path.exists(sliding_file_path): #", "Returns: -------- raw_data: list of (label, time) event_mapping_data: a list", "+ para['step_size']*3600 end_time = end_time + para['step_size']*3600 for i in", "# load data data_df = pd.read_csv(file_path, delimiter=r'\\s+', header=None, names=['month', 'day',", "is {}\".format(raw_data.shape, event_mapping_data.shape)) assert raw_data.shape[0] == event_mapping_data.shape[0] print('The number of", "utf-8 -*- __author__ = '<NAME>' import pandas as pd import", "matrix pre_df = pd.read_csv(file_path, nrows=1, header=None, delimiter=r'\\s+') columns = pre_df.columns.tolist()", "j+=1 else: break start_index = i end_index = j start_end_pair", "print('There are %d log events'%event_num) #=================get labels and event count", "sliding window start_time = time_data[0] start_index = 0 end_index =", "create the directory for saving the sliding windows (start_index, end_index),", "path. Args: -------- para: the parameters dictionary Returns: -------- raw_data:", "# create the directory for saving the sliding windows (start_index,", "anomaly \"\"\" # create the directory for saving the sliding", "= time_data[0] start_index = 0 end_index = 0 # get", "pre_df.columns.tolist() # remove the last column of block name use_cols", "the time interval since the start time data_df['seconds_since'] = (data_df['time']-data_df['time'][0]).dt.total_seconds().astype(int)", "=use_cols, dtype =int) raw_data = data_df.as_matrix() # load lables label_df", "anomaly instances is %d' % sum(label_data)) return raw_data, label_data def", "header=None, delimiter=r'\\s+') columns = pre_df.columns.tolist() # remove the last column", "end_time = end_time + para['step_size']*3600 for i in range(start_index,end_index): if", "deepia_data_loader(para): \"\"\" load the logs and the log_event_mapping from the", "start and end of sliding time window time_data = raw_data[:,0]", "event_mapping_data] event_num = len(list(set(event_mapping_data))) print('There are %d log events'%event_num) #=================get", "event_mapping.as_matrix() print(\"The raw data shape is {} and label shape", "log # data_df['label'] = (data_df['label'] != '-').astype(int) raw_data = data_df[['seconds_since']].as_matrix()", "time window time_data = raw_data[:,0] if not os.path.exists(sliding_file_path): # split", "but it requires further processing' % sum(raw_data[:, 0])) return raw_data,", "of tuples, tuple contains two number, which represent the start", "contains two number, which represent the start and end of", "def deepia_preprocess_data(para, raw_data, event_mapping_data): \"\"\" split logs into sliding windows,", "in expanded_indexes_list[j]: event_index = event_mapping_data[k] event_count_matrix[j, event_index] += 1 #print(\"Among", "len(start_end_index_list) print('there are %d instances (sliding windows) in this dataset\\n'%inst_number)", "expanded_indexes_list[j]: event_index = event_mapping_data[k] event_count_matrix[j, event_index] += 1 if label_data[k]:", "delimiter=r'\\s+', header=None, usecols = [0], dtype =int) event_mapping_data = event_mapping.as_matrix()", "processing' % sum(raw_data[:, 0])) return raw_data, event_mapping_data def bgl_preprocess_data(para, raw_data,", "para: the parameters dictionary Returns: -------- raw_data: log sequences matrix", "is an instance (log sequence vector) labels: a list of", "[row[0] for row in event_mapping_data] event_num = len(list(set(event_mapping_data))) print('There are", "np.savetxt(sliding_file_path,start_end_index_list,delimiter=',',fmt='%d') else: print('Loading start_end_index_list from file') start_end_index_list = pd.read_csv(sliding_file_path, header=None).as_matrix()", "else: start_end_pair=tuple((start_index,end_index)) start_end_index_list.append(start_end_pair) break # move the start and end", "while end_index < log_size: start_time = start_time + para['step_size']*3600 end_time", "para['step_size']*3600 for i in range(start_index,end_index): if time_data[i] < start_time: i+=1", "% sum(raw_data[:, 0])) return raw_data, event_mapping_data def deepia_preprocess_data(para, raw_data, event_mapping_data):", "dtype =int) # usecols must be a list label_data =", "label shape is {}\".format(raw_data.shape, label_data.shape)) assert raw_data.shape[0] == label_data.shape[0] print('The", "% sum(raw_data[:, 0])) return raw_data, event_mapping_data def bgl_preprocess_data(para, raw_data, event_mapping_data):", "matrix and labels from the file path. Args: -------- para:", "count of each sliding window =============# labels = [] event_count_matrix", "event_mapping_data[k] event_count_matrix[j, event_index] += 1 if label_data[k]: label = 1", "start_index = start_end_index_list[i][0] end_index = start_end_index_list[i][1] for l in range(start_index,", "for row in event_mapping_data] event_num = len(list(set(event_mapping_data))) print('There are %d", "deepia_preprocess_data(para, raw_data, event_mapping_data): \"\"\" split logs into sliding windows, built", "inst_number == len(labels) print(\"Among all instances, %d are anomalies\"%sum(labels)) assert", "data_df['time'] = pd.to_datetime(data_df['time'], format=\"%b-%d-%H:%M:%S\") # calculate the time interval since", "time_data = raw_data[:,0], raw_data[:, 1] if not os.path.exists(sliding_file_path): # split", "each time window by ranging from start_index to end_index expanded_indexes_list=[]", "%d instances (sliding windows) in this dataset' % inst_number) #", "labels, 1 represents anomaly \"\"\" # create the directory for", "if time_data[i] < start_time: i+=1 else: break for j in", "= data_df.as_matrix() # load lables label_df = pd.read_csv(label_path, delimiter=r'\\s+', header=None,", "i in range(inst_number): start_index = start_end_index_list[i][0] end_index = start_end_index_list[i][1] for", "time interval since the start time data_df['seconds_since'] = (data_df['time'] -", "(log sequence vector) labels: a list of labels, 1 represents", "= [1], date_parser=dateparse) # convert to date time format data_df", "a corresponding log Returns: -------- event_count_matrix: event count matrix, where", "para['log_seq_file_name'] label_path = para['path'] + para['label_file_name'] # load log sequence", "raw_data: list of (label, time) event_mapping_data: a list of event", "= para['save_path']+'sliding_'+str(para['window_size'])+'h_'+str(para['step_size'])+'h.csv' #=================divide into sliding windows=============# start_end_index_list = [] #", "is {} and label shape is {}\".format(raw_data.shape, label_data.shape)) assert raw_data.shape[0]", "if cur_time < start_time + para['window_size']*3600: end_index += 1 end_time", "labels matrix \"\"\" file_path = para['path'] + para['log_seq_file_name'] label_path =", "1] if not os.path.exists(sliding_file_path): # split into sliding window start_time", "raw_data[:,0], raw_data[:, 1] if not os.path.exists(sliding_file_path): # split into sliding", "data_df = pd.read_csv(file_path, delimiter=r'\\s+', header=None, names = ['label','time'], usecols =", "para['label_file_name'] # load log sequence matrix pre_df = pd.read_csv(file_path, nrows=1,", "remove the last column of block name use_cols = columns[:-1]", "para['path'] + para['log_file_name'] event_mapping_path = para['path'] + para['log_event_mapping'] # load", "windows=============# start_end_index_list = [] # list of tuples, tuple contains", "[0], dtype =int) # usecols must be a list label_data", "time interval since the start time data_df['seconds_since'] = (data_df['time']-data_df['time'][0]).dt.total_seconds().astype(int) #", "= 1 continue labels.append(label) assert inst_number == len(labels) print(\"Among all", "log \"\"\" file_path = para['path'] + para['log_file_name'] event_mapping_path = para['path']", "date time format data_df['time'] = pd.to_datetime(data_df['time'], format=\"%Y-%m-%d-%H.%M.%S.%f\") # calculate the", "count matrix, where each row is an instance (log sequence", "header=None, usecols = [0], dtype =int) event_mapping_data = event_mapping.as_matrix() print(\"The", "=int) raw_data = data_df.as_matrix() # load lables label_df = pd.read_csv(label_path,", "np.zeros((inst_number,event_num)) for j in range(inst_number): for k in expanded_indexes_list[j]: event_index", ", parse_dates = [1], date_parser=dateparse) # convert to date time", "j in range(end_index, log_size): if time_data[j] < end_time: j+=1 else:", "index, end time for cur_time in time_data: if cur_time <", "j in range(inst_number): label = 0 #0 represent success, 1", "of sliding time window time_data = raw_data[:,0] if not os.path.exists(sliding_file_path):", "label_df.as_matrix() print(\"The raw data shape is {} and label shape", "label = 0 #0 represent success, 1 represent failure for", "% sum(label_data)) return raw_data, label_data def bgl_data_loader(para): \"\"\" load the", "para: the parameters dictionary raw_data: list of (label, time) event_mapping_data:", "parameters dictionary raw_data: list of (label, time) event_mapping_data: a list", "each sliding window =============# event_count_matrix = np.zeros((inst_number,event_num)) for j in", "\"\"\" load the logs and the log_event_mapping from the file", "the log_event_mapping from the file path. Args: -------- para: the", "pandas as pd import os import numpy as np def", "file path. Args: -------- para: the parameters dictionary Returns: --------", "an instance (log sequence vector) labels: a list of labels,", "start_end_index_list[i][1] for l in range(start_index, end_index): expanded_indexes_list[i].append(l) event_mapping_data = [row[0]", "instances, %d are anomalies\"%sum(labels)) assert event_count_matrix.shape[0] == len(labels) return event_count_matrix,", "as pd import os import numpy as np def hdfs_data_loader(para):", "para['path'] + para['log_event_mapping'] # load data data_df = pd.read_csv(file_path, delimiter=r'\\s+',", "event_mapping_data.shape[0] print('The number of anomaly logs is %d, but it", "start time data_df['seconds_since'] = (data_df['time']-data_df['time'][0]).dt.total_seconds().astype(int) # get the label for", "data_df['time'][0]).dt.total_seconds().astype(int) # get the label for each log # data_df['label']", "and event count of each sliding window =============# event_count_matrix =", "index, where each row index indicates a corresponding log \"\"\"", "# remove the last column of block name use_cols =", "start time data_df['seconds_since'] = (data_df['time'] - data_df['time'][0]).dt.total_seconds().astype(int) # get the", "log_size = raw_data.shape[0] sliding_file_path = para['save_path']+'sliding_'+str(para['window_size'])+'h_'+str(para['step_size'])+'h.csv' #=================divide into sliding windows=============#", "end_index = j start_end_pair = tuple((start_index, end_index)) start_end_index_list.append(start_end_pair) inst_number =", "print('there are %d instances (sliding windows) in this dataset' %", "date_parser=dateparse) # convert to date time format data_df = data_df[['month',", "end of sliding time window time_data = raw_data[:,0] if not", "the label for each log data_df['label'] = (data_df['label'] != '-').astype(int)", "names=['month', 'day', 'hour'], usecols=para['select_column']) # , parse_dates = [1], date_parser=dateparse)", "list(map(str, x))) data_df['time'] = data_df[['month', 'day', 'hour']].apply(lambda x: '-'.join(x), axis=1)", "== len(labels) print(\"Among all instances, %d are anomalies\"%sum(labels)) assert event_count_matrix.shape[0]", "import numpy as np def hdfs_data_loader(para): \"\"\" load the log", "# load lables label_df = pd.read_csv(label_path, delimiter=r'\\s+', header=None, usecols =", "the last column of block name use_cols = columns[:-1] data_df", "event mapping list event_mapping = pd.read_csv(event_mapping_path, delimiter=r'\\s+', header=None, usecols =", "time) event_mapping_data: a list of event index, where each row", "for cur_time in time_data: if cur_time < start_time + para['window_size']*3600:", "load the log sequence matrix and labels from the file", "'-').astype(int) raw_data = data_df[['seconds_since']].as_matrix() # load the event mapping list", "of event index, where each row index indicates a corresponding", "= raw_data.shape[0] sliding_file_path = para['save_path']+'sliding_'+str(para['window_size'])+'h_'+str(para['step_size'])+'h.csv' #=================divide into sliding windows=============# start_end_index_list", "<gh_stars>0 #!/usr/bin/env python # -*- coding: utf-8 -*- __author__ =", "each row index indicates a corresponding log Returns: -------- event_count_matrix:", "data_df[['label','seconds_since']].as_matrix() # load the event mapping list event_mapping = pd.read_csv(event_mapping_path,", "and the log_event_mapping from the file path. Args: -------- para:", "labels def deepia_data_loader(para): \"\"\" load the logs and the log_event_mapping", "lables label_df = pd.read_csv(label_path, delimiter=r'\\s+', header=None, usecols = [0], dtype", "and labels from the file path. Args: -------- para: the", "event count of each sliding window =============# event_count_matrix = np.zeros((inst_number,event_num))", "raw_data = data_df[['seconds_since']].as_matrix() # load the event mapping list event_mapping", "end index until next sliding window while end_index < log_size:", "range(start_index,end_index): if time_data[i] < start_time: i+=1 else: break for j", "log data_df['label'] = (data_df['label'] != '-').astype(int) raw_data = data_df[['label','seconds_since']].as_matrix() #", "log sequence matrix and labels from the file path. Args:", "-------- raw_data: log sequences matrix label_data: labels matrix \"\"\" file_path", "sequences matrix label_data: labels matrix \"\"\" file_path = para['path'] +", "= pd.read_csv(label_path, delimiter=r'\\s+', header=None, usecols = [0], dtype =int) #", "-*- __author__ = '<NAME>' import pandas as pd import os", "matrix \"\"\" file_path = para['path'] + para['log_seq_file_name'] label_path = para['path']", "(data_df['time']-data_df['time'][0]).dt.total_seconds().astype(int) # get the label for each log data_df['label'] =", "future running if not os.path.exists(para['save_path']): os.mkdir(para['save_path']) log_size = raw_data.shape[0] sliding_file_path", "para['save_path']+'sliding_'+str(para['window_size'])+'h_'+str(para['step_size'])+'h.csv' #=================divide into sliding windows=============# start_end_index_list = [] # list", "tuple((start_index, end_index)) start_end_index_list.append(start_end_pair) inst_number = len(start_end_index_list) print('there are %d instances", "event index, where each row index indicates a corresponding log", "this dataset\\n'%inst_number) np.savetxt(sliding_file_path,start_end_index_list,delimiter=',',fmt='%d') else: print('Loading start_end_index_list from file') start_end_index_list =", "def bgl_preprocess_data(para, raw_data, event_mapping_data): \"\"\" split logs into sliding windows,", "load log sequence matrix pre_df = pd.read_csv(file_path, nrows=1, header=None, delimiter=r'\\s+')", "len(labels) print(\"Among all instances, %d are anomalies\"%sum(labels)) assert event_count_matrix.shape[0] ==", "print(\"Among all instances, %d are anomalies\"%sum(labels)) assert event_count_matrix.shape[0] == len(labels)", "import pandas as pd import os import numpy as np", "the label for each log # data_df['label'] = (data_df['label'] !=", "event_mapping_data def bgl_preprocess_data(para, raw_data, event_mapping_data): \"\"\" split logs into sliding", "x: list(map(str, x))) data_df['time'] = data_df[['month', 'day', 'hour']].apply(lambda x: '-'.join(x),", "event_index] += 1 if label_data[k]: label = 1 continue labels.append(label)", "(data_df['label'] != '-').astype(int) raw_data = data_df[['label','seconds_since']].as_matrix() # load the event", "end of sliding time window label_data, time_data = raw_data[:,0], raw_data[:,", "inst_number) # get all the log indexes in each time", "are %d instances (sliding windows) in this dataset' % inst_number)", "shape is {}\".format(raw_data.shape, label_data.shape)) assert raw_data.shape[0] == label_data.shape[0] print('The number", "= len(start_end_index_list) print('there are %d instances (sliding windows) in this", "in event_mapping_data] event_num = len(list(set(event_mapping_data))) print('There are %d log events'%event_num)", "x: '-'.join(x), axis=1) # data_df['time'] = pd.to_datetime(data_df['time'], format=\"%b-%d-%H:%M:%S\") # calculate", "(data_df['time'] - data_df['time'][0]).dt.total_seconds().astype(int) # get the label for each log", "data shape is {} and label shape is {}\".format(raw_data.shape, label_data.shape))", "the start and end of sliding time window label_data, time_data", "into sliding windows=============# start_end_index_list = [] # list of tuples,", "the start and end of sliding time window time_data =", "is %d, but it requires further processing' % sum(raw_data[:, 0]))", "index indicates a corresponding log Returns: -------- event_count_matrix: event count", "= np.zeros((inst_number,event_num)) for j in range(inst_number): label = 0 #0", "= pd.read_csv(file_path, delimiter=r'\\s+', header=None, usecols =use_cols, dtype =int) raw_data =", "sliding windows, built an event count matrix and get the", "range(end_index, log_size): if time_data[j] < end_time: j+=1 else: break start_index", "log indexes in each time window by ranging from start_index", "list label_data = label_df.as_matrix() print(\"The raw data shape is {}", "para['path'] + para['label_file_name'] # load log sequence matrix pre_df =", "= pd.read_csv(sliding_file_path, header=None).as_matrix() inst_number = len(start_end_index_list) print('there are %d instances", "hdfs_data_loader(para): \"\"\" load the log sequence matrix and labels from", "= columns[:-1] data_df = pd.read_csv(file_path, delimiter=r'\\s+', header=None, usecols =use_cols, dtype", "else: break start_index = i end_index = j start_end_pair =", "time_data[0] start_index = 0 end_index = 0 # get the", "the corresponding label Args: -------- para: the parameters dictionary raw_data:", "=int) event_mapping_data = event_mapping.as_matrix() print(\"The raw data shape is {}", "the parameters dictionary Returns: -------- raw_data: list of (label, time)", "pd.read_csv(file_path, nrows=1, header=None, delimiter=r'\\s+') columns = pre_df.columns.tolist() # remove the", "further processing' % sum(raw_data[:, 0])) return raw_data, event_mapping_data def deepia_preprocess_data(para,", "= start_end_index_list[i][0] end_index = start_end_index_list[i][1] for l in range(start_index, end_index):", "header=None, usecols =use_cols, dtype =int) raw_data = data_df.as_matrix() # load", "index_list = [] expanded_indexes_list.append(index_list) for i in range(inst_number): start_index =", "0 #0 represent success, 1 represent failure for k in", "raw_data: log sequences matrix label_data: labels matrix \"\"\" file_path =", "#=================divide into sliding windows=============# start_end_index_list = [] # list of", "event_index = event_mapping_data[k] event_count_matrix[j, event_index] += 1 if label_data[k]: label", "each log # data_df['label'] = (data_df['label'] != '-').astype(int) raw_data =", "data_df = pd.read_csv(file_path, delimiter=r'\\s+', header=None, usecols =use_cols, dtype =int) raw_data", "represents anomaly \"\"\" # create the directory for saving the", "para['select_column']) #, parse_dates = [1], date_parser=dateparse) # convert to date", "indicates a corresponding log Returns: -------- event_count_matrix: event count matrix,", "= start_time + para['step_size']*3600 end_time = end_time + para['step_size']*3600 for", "raw_data, label_data def bgl_data_loader(para): \"\"\" load the logs and the", "event_mapping = pd.read_csv(event_mapping_path, delimiter=r'\\s+', header=None, usecols = [0], dtype =int)", "data_df['label'] = (data_df['label'] != '-').astype(int) raw_data = data_df[['seconds_since']].as_matrix() # load", "pd.to_datetime(data_df['time'], format=\"%b-%d-%H:%M:%S\") # calculate the time interval since the start", "= event_mapping_data[k] event_count_matrix[j, event_index] += 1 if label_data[k]: label =", "k in expanded_indexes_list[j]: event_index = event_mapping_data[k] event_count_matrix[j, event_index] += 1", "convert to date time format data_df['time'] = pd.to_datetime(data_df['time'], format=\"%Y-%m-%d-%H.%M.%S.%f\") #", "log sequence matrix pre_df = pd.read_csv(file_path, nrows=1, header=None, delimiter=r'\\s+') columns", "columns = pre_df.columns.tolist() # remove the last column of block", "and label shape is {}\".format(raw_data.shape, label_data.shape)) assert raw_data.shape[0] == label_data.shape[0]", "(data_df['label'] != '-').astype(int) raw_data = data_df[['seconds_since']].as_matrix() # load the event", "file_path = para['path'] + para['log_seq_file_name'] label_path = para['path'] + para['label_file_name']", "represent the start and end of sliding time window time_data", "-*- coding: utf-8 -*- __author__ = '<NAME>' import pandas as", "windows) in this dataset' % inst_number) # get all the", "end time for cur_time in time_data: if cur_time < start_time", "'day', 'hour'], usecols=para['select_column']) # , parse_dates = [1], date_parser=dateparse) #", "number of anomaly logs is %d, but it requires further", "shape is {}\".format(raw_data.shape, event_mapping_data.shape)) assert raw_data.shape[0] == event_mapping_data.shape[0] #print('The number", "os.path.exists(para['save_path']): os.mkdir(para['save_path']) log_size = raw_data.shape[0] sliding_file_path = para['save_path']+'sliding_'+str(para['window_size'])+'h_'+str(para['step_size'])+'h.csv' #=================divide into", "= data_df[['label','seconds_since']].as_matrix() # load the event mapping list event_mapping =", "matrix, where each row is an instance (log sequence vector)", "in range(start_index, end_index): expanded_indexes_list[i].append(l) event_mapping_data = [row[0] for row in", "< end_time: j+=1 else: break start_index = i end_index =", "\"\"\" file_path = para['path'] + para['log_file_name'] event_mapping_path = para['path'] +", "if not os.path.exists(sliding_file_path): # split into sliding window start_time =", "and label shape is {}\".format(raw_data.shape, event_mapping_data.shape)) assert raw_data.shape[0] == event_mapping_data.shape[0]", "logs is %d, but it requires further processing' % sum(raw_data[:,", "= (data_df['label'] != '-').astype(int) raw_data = data_df[['seconds_since']].as_matrix() # load the", "sliding_file_path = para['save_path']+'sliding_'+str(para['window_size'])+'h_'+str(para['step_size'])+'h.csv' #=================divide into sliding windows=============# start_end_index_list = []", "instance (log sequence vector) labels: a list of labels, 1", "%d instances (sliding windows) in this dataset\\n'%inst_number) np.savetxt(sliding_file_path,start_end_index_list,delimiter=',',fmt='%d') else: print('Loading", "break for j in range(end_index, log_size): if time_data[j] < end_time:", "pd.read_csv(file_path, delimiter=r'\\s+', header=None, names = ['label','time'], usecols = para['select_column']) #,", "instances (sliding windows) in this dataset' % inst_number) # get", "for j in range(inst_number): label = 0 #0 represent success,", "!= '-').astype(int) raw_data = data_df[['seconds_since']].as_matrix() # load the event mapping", "raw_data[:,0] if not os.path.exists(sliding_file_path): # split into sliding window start_time", "data_df = data_df[['month', 'day', 'hour']].apply(lambda x: list(map(str, x))) data_df['time'] =", "import os import numpy as np def hdfs_data_loader(para): \"\"\" load", "data shape is {} and label shape is {}\".format(raw_data.shape, event_mapping_data.shape))", "end_index), which can be directly loaded in future running if", "#print('The number of anomaly logs is %d, but it requires", "column of block name use_cols = columns[:-1] data_df = pd.read_csv(file_path,", "from the file path. Args: -------- para: the parameters dictionary", "time format data_df = data_df[['month', 'day', 'hour']].apply(lambda x: list(map(str, x)))", "data_df['time'] = data_df[['month', 'day', 'hour']].apply(lambda x: '-'.join(x), axis=1) # data_df['time']", "the sliding windows (start_index, end_index), which can be directly loaded", "shape is {}\".format(raw_data.shape, event_mapping_data.shape)) assert raw_data.shape[0] == event_mapping_data.shape[0] print('The number", "numpy as np def hdfs_data_loader(para): \"\"\" load the log sequence", "further processing' % sum(raw_data[:, 0])) return raw_data, event_mapping_data def bgl_preprocess_data(para,", "+ para['window_size']*3600: end_index += 1 end_time = cur_time else: start_end_pair=tuple((start_index,end_index))", "window start_time = time_data[0] start_index = 0 end_index = 0", "print('The number of anomaly instances is %d' % sum(label_data)) return", "start_index = 0 end_index = 0 # get the first", "calculate the time interval since the start time data_df['seconds_since'] =", "'day', 'hour']].apply(lambda x: list(map(str, x))) data_df['time'] = data_df[['month', 'day', 'hour']].apply(lambda", "end_index): expanded_indexes_list[i].append(l) event_mapping_data = [row[0] for row in event_mapping_data] event_num", "assert inst_number == len(labels) print(\"Among all instances, %d are anomalies\"%sum(labels))", "indicates a corresponding log \"\"\" file_path = para['path'] + para['log_file_name']", "start and end index until next sliding window while end_index", "%d are anomalies\"%sum(labels)) assert event_count_matrix.shape[0] == len(labels) return event_count_matrix, labels", "= ['label','time'], usecols = para['select_column']) #, parse_dates = [1], date_parser=dateparse)", "range(inst_number): index_list = [] expanded_indexes_list.append(index_list) for i in range(inst_number): start_index", "= pre_df.columns.tolist() # remove the last column of block name", "load the event mapping list event_mapping = pd.read_csv(event_mapping_path, delimiter=r'\\s+', header=None,", "data_df['time'] = pd.to_datetime(data_df['time'], format=\"%Y-%m-%d-%H.%M.%S.%f\") # calculate the time interval since", "shape is {} and label shape is {}\".format(raw_data.shape, event_mapping_data.shape)) assert", "end index, end time for cur_time in time_data: if cur_time", "-------- para: the parameters dictionary Returns: -------- raw_data: log sequences", "= [] # list of tuples, tuple contains two number,", "raw_data.shape[0] sliding_file_path = para['save_path']+'sliding_'+str(para['window_size'])+'h_'+str(para['step_size'])+'h.csv' #=================divide into sliding windows=============# start_end_index_list =", "matrix label_data: labels matrix \"\"\" file_path = para['path'] + para['log_seq_file_name']", "raw_data = data_df.as_matrix() # load lables label_df = pd.read_csv(label_path, delimiter=r'\\s+',", "for each log # data_df['label'] = (data_df['label'] != '-').astype(int) raw_data", "= 0 # get the first start, end index, end", "be a list label_data = label_df.as_matrix() print(\"The raw data shape", "block name use_cols = columns[:-1] data_df = pd.read_csv(file_path, delimiter=r'\\s+', header=None,", "in time_data: if cur_time < start_time + para['window_size']*3600: end_index +=", "each log data_df['label'] = (data_df['label'] != '-').astype(int) raw_data = data_df[['label','seconds_since']].as_matrix()", "\"\"\" split logs into sliding windows, built an event count", "each row is an instance (log sequence vector) labels: a", "\"\"\" # create the directory for saving the sliding windows", "start_end_index_list from file') start_end_index_list = pd.read_csv(sliding_file_path, header=None).as_matrix() inst_number = len(start_end_index_list)", "for t in range(inst_number): index_list = [] expanded_indexes_list.append(index_list) for i", "start_end_index_list[i][0] end_index = start_end_index_list[i][1] for l in range(start_index, end_index): expanded_indexes_list[i].append(l)", "number, which represent the start and end of sliding time", "para['path'] + para['log_seq_file_name'] label_path = para['path'] + para['label_file_name'] # load", "the start time data_df['seconds_since'] = (data_df['time']-data_df['time'][0]).dt.total_seconds().astype(int) # get the label", "sum(raw_data[:, 0])) return raw_data, event_mapping_data def deepia_preprocess_data(para, raw_data, event_mapping_data): \"\"\"", "last column of block name use_cols = columns[:-1] data_df =", "where each row index indicates a corresponding log \"\"\" file_path", "para['step_size']*3600 end_time = end_time + para['step_size']*3600 for i in range(start_index,end_index):", "def deepia_data_loader(para): \"\"\" load the logs and the log_event_mapping from", "of (label, time) event_mapping_data: a list of event index, where", "of each sliding window =============# event_count_matrix = np.zeros((inst_number,event_num)) for j", "of anomaly logs is %d, but it requires further processing'", "label for each log # data_df['label'] = (data_df['label'] != '-').astype(int)", "is {} and label shape is {}\".format(raw_data.shape, event_mapping_data.shape)) assert raw_data.shape[0]", "# usecols must be a list label_data = label_df.as_matrix() print(\"The", "event count matrix, where each row is an instance (log", "start_time = start_time + para['step_size']*3600 end_time = end_time + para['step_size']*3600", "os import numpy as np def hdfs_data_loader(para): \"\"\" load the", "the first start, end index, end time for cur_time in", "label Args: -------- para: the parameters dictionary raw_data: list of", "load lables label_df = pd.read_csv(label_path, delimiter=r'\\s+', header=None, usecols = [0],", "start_end_pair=tuple((start_index,end_index)) start_end_index_list.append(start_end_pair) break # move the start and end index", "# data_df['time'] = pd.to_datetime(data_df['time'], format=\"%b-%d-%H:%M:%S\") # calculate the time interval", "dictionary Returns: -------- raw_data: list of (label, time) event_mapping_data: a", "# get the label for each log data_df['label'] = (data_df['label']", "the start and end index until next sliding window while", "not os.path.exists(para['save_path']): os.mkdir(para['save_path']) log_size = raw_data.shape[0] sliding_file_path = para['save_path']+'sliding_'+str(para['window_size'])+'h_'+str(para['step_size'])+'h.csv' #=================divide", "end_time = cur_time else: start_end_pair=tuple((start_index,end_index)) start_end_index_list.append(start_end_pair) break # move the", "windows, built an event count matrix and get the corresponding", "label_data.shape)) assert raw_data.shape[0] == label_data.shape[0] print('The number of anomaly instances", "os.path.exists(sliding_file_path): # split into sliding window start_time = time_data[0] start_index", "0 end_index = 0 # get the first start, end", "range(inst_number): label = 0 #0 represent success, 1 represent failure", "= event_mapping.as_matrix() print(\"The raw data shape is {} and label", "event_mapping_data def deepia_preprocess_data(para, raw_data, event_mapping_data): \"\"\" split logs into sliding", "window time_data = raw_data[:,0] if not os.path.exists(sliding_file_path): # split into", "mapping list event_mapping = pd.read_csv(event_mapping_path, delimiter=r'\\s+', header=None, usecols = [0],", "+ para['step_size']*3600 for i in range(start_index,end_index): if time_data[i] < start_time:", "event_index = event_mapping_data[k] event_count_matrix[j, event_index] += 1 #print(\"Among all instances,", "all instances, %d are anomalies\"%sum(labels)) assert event_count_matrix.shape[0] == len(labels) return", "sliding window while end_index < log_size: start_time = start_time +", "of sliding time window label_data, time_data = raw_data[:,0], raw_data[:, 1]", "pd.read_csv(file_path, delimiter=r'\\s+', header=None, names=['month', 'day', 'hour'], usecols=para['select_column']) # , parse_dates", "if not os.path.exists(para['save_path']): os.mkdir(para['save_path']) log_size = raw_data.shape[0] sliding_file_path = para['save_path']+'sliding_'+str(para['window_size'])+'h_'+str(para['step_size'])+'h.csv'", "not os.path.exists(sliding_file_path): # split into sliding window start_time = time_data[0]", "label_data def bgl_data_loader(para): \"\"\" load the logs and the log_event_mapping", "# load log sequence matrix pre_df = pd.read_csv(file_path, nrows=1, header=None,", "len(labels) return event_count_matrix, labels def deepia_data_loader(para): \"\"\" load the logs", "date_parser=dateparse) # convert to date time format data_df['time'] = pd.to_datetime(data_df['time'],", "for i in range(inst_number): start_index = start_end_index_list[i][0] end_index = start_end_index_list[i][1]", "= data_df[['month', 'day', 'hour']].apply(lambda x: list(map(str, x))) data_df['time'] = data_df[['month',", "labels and event count of each sliding window =============# event_count_matrix", "% inst_number) # get all the log indexes in each", "which represent the start and end of sliding time window", "np.zeros((inst_number,event_num)) for j in range(inst_number): label = 0 #0 represent", "which can be directly loaded in future running if not", "events'%event_num) #=================get labels and event count of each sliding window", "get the corresponding label Args: -------- para: the parameters dictionary", "dictionary Returns: -------- raw_data: log sequences matrix label_data: labels matrix", "sequence matrix pre_df = pd.read_csv(file_path, nrows=1, header=None, delimiter=r'\\s+') columns =", "start_time = time_data[0] start_index = 0 end_index = 0 #", "and end of sliding time window time_data = raw_data[:,0] if", "range(inst_number): for k in expanded_indexes_list[j]: event_index = event_mapping_data[k] event_count_matrix[j, event_index]", "in expanded_indexes_list[j]: event_index = event_mapping_data[k] event_count_matrix[j, event_index] += 1 if", "= pd.read_csv(event_mapping_path, delimiter=r'\\s+', header=None, usecols = [0], dtype =int) event_mapping_data", "else: break for j in range(end_index, log_size): if time_data[j] <", "log_event_mapping from the file path. Args: -------- para: the parameters", "labels.append(label) assert inst_number == len(labels) print(\"Among all instances, %d are", "saving the sliding windows (start_index, end_index), which can be directly", "#, parse_dates = [1], date_parser=dateparse) # convert to date time", "= para['path'] + para['log_event_mapping'] # load data data_df = pd.read_csv(file_path,", "row index indicates a corresponding log Returns: -------- event_count_matrix: event", "and event count of each sliding window =============# labels =", "if label_data[k]: label = 1 continue labels.append(label) assert inst_number ==", "os.mkdir(para['save_path']) log_size = raw_data.shape[0] sliding_file_path = para['save_path']+'sliding_'+str(para['window_size'])+'h_'+str(para['step_size'])+'h.csv' #=================divide into sliding", "para['log_event_mapping'] # load data data_df = pd.read_csv(file_path, delimiter=r'\\s+', header=None, names=['month',", "[] event_count_matrix = np.zeros((inst_number,event_num)) for j in range(inst_number): label =", "to end_index expanded_indexes_list=[] for t in range(inst_number): index_list = []", "sliding window =============# labels = [] event_count_matrix = np.zeros((inst_number,event_num)) for", "# get the label for each log # data_df['label'] =", "header=None, names = ['label','time'], usecols = para['select_column']) #, parse_dates =", "count of each sliding window =============# event_count_matrix = np.zeros((inst_number,event_num)) for", "Returns: -------- raw_data: log sequences matrix label_data: labels matrix \"\"\"", "of each sliding window =============# labels = [] event_count_matrix =", "in range(inst_number): start_index = start_end_index_list[i][0] end_index = start_end_index_list[i][1] for l", "event_index] += 1 #print(\"Among all instances, %d are anomalies\"%sum(labels)) return", "event_count_matrix: event count matrix, where each row is an instance", "of labels, 1 represents anomaly \"\"\" # create the directory", "= pd.read_csv(file_path, delimiter=r'\\s+', header=None, names=['month', 'day', 'hour'], usecols=para['select_column']) # ,", "indexes in each time window by ranging from start_index to", "number of anomaly instances is %d' % sum(label_data)) return raw_data,", "format=\"%b-%d-%H:%M:%S\") # calculate the time interval since the start time", "# move the start and end index until next sliding", "parameters dictionary Returns: -------- raw_data: log sequences matrix label_data: labels", "-------- event_count_matrix: event count matrix, where each row is an", "event_mapping_data.shape[0] #print('The number of anomaly logs is %d, but it", "#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = '<NAME>'", "two number, which represent the start and end of sliding", "-------- para: the parameters dictionary raw_data: list of (label, time)", "def bgl_data_loader(para): \"\"\" load the logs and the log_event_mapping from", "['label','time'], usecols = para['select_column']) #, parse_dates = [1], date_parser=dateparse) #", "=============# labels = [] event_count_matrix = np.zeros((inst_number,event_num)) for j in", "is %d' % sum(label_data)) return raw_data, label_data def bgl_data_loader(para): \"\"\"", "for saving the sliding windows (start_index, end_index), which can be", "date time format data_df = data_df[['month', 'day', 'hour']].apply(lambda x: list(map(str,", "j start_end_pair = tuple((start_index, end_index)) start_end_index_list.append(start_end_pair) inst_number = len(start_end_index_list) print('there", "data_df['seconds_since'] = (data_df['time'] - data_df['time'][0]).dt.total_seconds().astype(int) # get the label for", "dtype =int) event_mapping_data = event_mapping.as_matrix() print(\"The raw data shape is", "start, end index, end time for cur_time in time_data: if", "get the label for each log # data_df['label'] = (data_df['label']", "in range(start_index,end_index): if time_data[i] < start_time: i+=1 else: break for", "%d' % sum(label_data)) return raw_data, label_data def bgl_data_loader(para): \"\"\" load", "start_time: i+=1 else: break for j in range(end_index, log_size): if", "= [1], date_parser=dateparse) # convert to date time format data_df['time']", "pd.read_csv(label_path, delimiter=r'\\s+', header=None, usecols = [0], dtype =int) # usecols", "0 # get the first start, end index, end time", "raw_data.shape[0] == label_data.shape[0] print('The number of anomaly instances is %d'", "sliding windows=============# start_end_index_list = [] # list of tuples, tuple", "if time_data[j] < end_time: j+=1 else: break start_index = i", "end_index = start_end_index_list[i][1] for l in range(start_index, end_index): expanded_indexes_list[i].append(l) event_mapping_data", "shape is {} and label shape is {}\".format(raw_data.shape, label_data.shape)) assert", "file_path = para['path'] + para['log_file_name'] event_mapping_path = para['path'] + para['log_event_mapping']", "the log sequence matrix and labels from the file path.", "= para['path'] + para['label_file_name'] # load log sequence matrix pre_df", "Args: -------- para: the parameters dictionary Returns: -------- raw_data: list", "the logs and the log_event_mapping from the file path. Args:", "use_cols = columns[:-1] data_df = pd.read_csv(file_path, delimiter=r'\\s+', header=None, usecols =use_cols,", "row in event_mapping_data] event_num = len(list(set(event_mapping_data))) print('There are %d log", "format data_df['time'] = pd.to_datetime(data_df['time'], format=\"%Y-%m-%d-%H.%M.%S.%f\") # calculate the time interval", "where each row index indicates a corresponding log Returns: --------", "# load the event mapping list event_mapping = pd.read_csv(event_mapping_path, delimiter=r'\\s+',", "time format data_df['time'] = pd.to_datetime(data_df['time'], format=\"%Y-%m-%d-%H.%M.%S.%f\") # calculate the time", "= (data_df['time']-data_df['time'][0]).dt.total_seconds().astype(int) # get the label for each log data_df['label']", "anomaly logs is %d, but it requires further processing' %", "# data_df['label'] = (data_df['label'] != '-').astype(int) raw_data = data_df[['seconds_since']].as_matrix() #", "{}\".format(raw_data.shape, label_data.shape)) assert raw_data.shape[0] == label_data.shape[0] print('The number of anomaly", "= para['select_column']) #, parse_dates = [1], date_parser=dateparse) # convert to", "start_end_pair = tuple((start_index, end_index)) start_end_index_list.append(start_end_pair) inst_number = len(start_end_index_list) print('there are", "# , parse_dates = [1], date_parser=dateparse) # convert to date", "= [0], dtype =int) event_mapping_data = event_mapping.as_matrix() print(\"The raw data", "time_data = raw_data[:,0] if not os.path.exists(sliding_file_path): # split into sliding", "data_df.as_matrix() # load lables label_df = pd.read_csv(label_path, delimiter=r'\\s+', header=None, usecols", "# calculate the time interval since the start time data_df['seconds_since']", "time data_df['seconds_since'] = (data_df['time']-data_df['time'][0]).dt.total_seconds().astype(int) # get the label for each", "assert raw_data.shape[0] == event_mapping_data.shape[0] print('The number of anomaly logs is", "log Returns: -------- event_count_matrix: event count matrix, where each row", "label_data, time_data = raw_data[:,0], raw_data[:, 1] if not os.path.exists(sliding_file_path): #", "= cur_time else: start_end_pair=tuple((start_index,end_index)) start_end_index_list.append(start_end_pair) break # move the start", "expanded_indexes_list.append(index_list) for i in range(inst_number): start_index = start_end_index_list[i][0] end_index =", "= data_df[['month', 'day', 'hour']].apply(lambda x: '-'.join(x), axis=1) # data_df['time'] =", "pd.read_csv(event_mapping_path, delimiter=r'\\s+', header=None, usecols = [0], dtype =int) event_mapping_data =", "'-'.join(x), axis=1) # data_df['time'] = pd.to_datetime(data_df['time'], format=\"%b-%d-%H:%M:%S\") # calculate the", "are anomalies\"%sum(labels)) assert event_count_matrix.shape[0] == len(labels) return event_count_matrix, labels def", "raw_data.shape[0] == event_mapping_data.shape[0] #print('The number of anomaly logs is %d,", "and end of sliding time window label_data, time_data = raw_data[:,0],", "event_mapping_data = [row[0] for row in event_mapping_data] event_num = len(list(set(event_mapping_data)))", "sequence vector) labels: a list of labels, 1 represents anomaly", "count matrix and get the corresponding label Args: -------- para:", "(sliding windows) in this dataset\\n'%inst_number) np.savetxt(sliding_file_path,start_end_index_list,delimiter=',',fmt='%d') else: print('Loading start_end_index_list from", "event_mapping_data[k] event_count_matrix[j, event_index] += 1 #print(\"Among all instances, %d are", "sequence matrix and labels from the file path. Args: --------", "i+=1 else: break for j in range(end_index, log_size): if time_data[j]", "start_index = i end_index = j start_end_pair = tuple((start_index, end_index))", "sliding window =============# event_count_matrix = np.zeros((inst_number,event_num)) for j in range(inst_number):", "name use_cols = columns[:-1] data_df = pd.read_csv(file_path, delimiter=r'\\s+', header=None, usecols", "coding: utf-8 -*- __author__ = '<NAME>' import pandas as pd", "label_data: labels matrix \"\"\" file_path = para['path'] + para['log_seq_file_name'] label_path", "# split into sliding window start_time = time_data[0] start_index =", "for j in range(end_index, log_size): if time_data[j] < end_time: j+=1", "vector) labels: a list of labels, 1 represents anomaly \"\"\"", "end_index)) start_end_index_list.append(start_end_pair) inst_number = len(start_end_index_list) print('there are %d instances (sliding", "= pd.read_csv(file_path, delimiter=r'\\s+', header=None, names = ['label','time'], usecols = para['select_column'])", "= end_time + para['step_size']*3600 for i in range(start_index,end_index): if time_data[i]", "event_count_matrix.shape[0] == len(labels) return event_count_matrix, labels def deepia_data_loader(para): \"\"\" load", "label_data[k]: label = 1 continue labels.append(label) assert inst_number == len(labels)", "{}\".format(raw_data.shape, event_mapping_data.shape)) assert raw_data.shape[0] == event_mapping_data.shape[0] #print('The number of anomaly", "file') start_end_index_list = pd.read_csv(sliding_file_path, header=None).as_matrix() inst_number = len(start_end_index_list) print('there are", "start_end_index_list = pd.read_csv(sliding_file_path, header=None).as_matrix() inst_number = len(start_end_index_list) print('there are %d", "represent success, 1 represent failure for k in expanded_indexes_list[j]: event_index", "in future running if not os.path.exists(para['save_path']): os.mkdir(para['save_path']) log_size = raw_data.shape[0]", "delimiter=r'\\s+', header=None, names = ['label','time'], usecols = para['select_column']) #, parse_dates", "it requires further processing' % sum(raw_data[:, 0])) return raw_data, event_mapping_data", "of block name use_cols = columns[:-1] data_df = pd.read_csv(file_path, delimiter=r'\\s+',", "raw_data.shape[0] == event_mapping_data.shape[0] print('The number of anomaly logs is %d,", "= [] event_count_matrix = np.zeros((inst_number,event_num)) for j in range(inst_number): label", "data_df[['month', 'day', 'hour']].apply(lambda x: '-'.join(x), axis=1) # data_df['time'] = pd.to_datetime(data_df['time'],", "'<NAME>' import pandas as pd import os import numpy as", "event_mapping_data.shape)) assert raw_data.shape[0] == event_mapping_data.shape[0] print('The number of anomaly logs", "in each time window by ranging from start_index to end_index", "tuple contains two number, which represent the start and end", "data_df[['seconds_since']].as_matrix() # load the event mapping list event_mapping = pd.read_csv(event_mapping_path,", "sliding windows (start_index, end_index), which can be directly loaded in", "== event_mapping_data.shape[0] print('The number of anomaly logs is %d, but", "+= 1 if label_data[k]: label = 1 continue labels.append(label) assert", "split into sliding window start_time = time_data[0] start_index = 0", "assert raw_data.shape[0] == event_mapping_data.shape[0] #print('The number of anomaly logs is" ]
[ "try: opts, args = getopt.getopt(sys.argv[1:], \"hd\") except getopt.GetoptError as err:", "print('aspx2url v1.0') print('Usage:') print(sys.argv[0]+' -d -h filename(s)') print('-d : Delete", "deleteOriginal = False for option,value in opts: if option ==", "= False for option,value in opts: if option == '-h':", "origFilename in args: with open(origFilename, \"r\") as f: html_doc =", "filename = re.search('(.*?)\\.aspx',origFilename).group(1) fullFilename = filename+'.url' with open(fullFilename, 'w') as", "help') def main(): try: opts, args = getopt.getopt(sys.argv[1:], \"hd\") except", ": Delete original file') print('-h : This help') def main():", "= f.read() prog = re.compile('\\<mso\\:URL.*?\\>(.*?),.*?\\<\\/mso\\:URL\\>', re.M) result = prog.search(html_doc) url", "deleteOriginal = True for origFilename in args: with open(origFilename, \"r\")", "'-d': deleteOriginal = True for origFilename in args: with open(origFilename,", "= filename+'.url' with open(fullFilename, 'w') as out: out.write('[InternetShortcut]\\n') out.write('URL='+url) out.write('\\n')", "fullFilename = filename+'.url' with open(fullFilename, 'w') as out: out.write('[InternetShortcut]\\n') out.write('URL='+url)", "elif option == '-d': deleteOriginal = True for origFilename in", "-h filename(s)') print('-d : Delete original file') print('-h : This", "original file') print('-h : This help') def main(): try: opts,", "as f: html_doc = f.read() prog = re.compile('\\<mso\\:URL.*?\\>(.*?),.*?\\<\\/mso\\:URL\\>', re.M) result", "opts, args = getopt.getopt(sys.argv[1:], \"hd\") except getopt.GetoptError as err: print(str(err))", "args = getopt.getopt(sys.argv[1:], \"hd\") except getopt.GetoptError as err: print(str(err)) usage()", "for option,value in opts: if option == '-h': usage() sys.exit()", "with open(origFilename, \"r\") as f: html_doc = f.read() prog =", "usage(): print('aspx2url v1.0') print('Usage:') print(sys.argv[0]+' -d -h filename(s)') print('-d :", "= re.compile('\\<mso\\:URL.*?\\>(.*?),.*?\\<\\/mso\\:URL\\>', re.M) result = prog.search(html_doc) url = result.group(1); filename", "if option == '-h': usage() sys.exit() elif option == '-d':", "sys, glob, getopt, os def usage(): print('aspx2url v1.0') print('Usage:') print(sys.argv[0]+'", "getopt.getopt(sys.argv[1:], \"hd\") except getopt.GetoptError as err: print(str(err)) usage() sys.exit(2) deleteOriginal", "= prog.search(html_doc) url = result.group(1); filename = re.search('(.*?)\\.aspx',origFilename).group(1) fullFilename =", "html_doc = f.read() prog = re.compile('\\<mso\\:URL.*?\\>(.*?),.*?\\<\\/mso\\:URL\\>', re.M) result = prog.search(html_doc)", ": This help') def main(): try: opts, args = getopt.getopt(sys.argv[1:],", "This help') def main(): try: opts, args = getopt.getopt(sys.argv[1:], \"hd\")", "<reponame>marcocucinato/aspx2url<filename>aspx2url/aspx2url.py from __future__ import print_function import re, sys, glob, getopt,", "getopt, os def usage(): print('aspx2url v1.0') print('Usage:') print(sys.argv[0]+' -d -h", "with open(fullFilename, 'w') as out: out.write('[InternetShortcut]\\n') out.write('URL='+url) out.write('\\n') if deleteOriginal:", "== '-d': deleteOriginal = True for origFilename in args: with", "err: print(str(err)) usage() sys.exit(2) deleteOriginal = False for option,value in", "usage() sys.exit(2) deleteOriginal = False for option,value in opts: if", "result = prog.search(html_doc) url = result.group(1); filename = re.search('(.*?)\\.aspx',origFilename).group(1) fullFilename", "f: html_doc = f.read() prog = re.compile('\\<mso\\:URL.*?\\>(.*?),.*?\\<\\/mso\\:URL\\>', re.M) result =", "as out: out.write('[InternetShortcut]\\n') out.write('URL='+url) out.write('\\n') if deleteOriginal: os.remove(origFilename) if __name__", "print('Usage:') print(sys.argv[0]+' -d -h filename(s)') print('-d : Delete original file')", "import re, sys, glob, getopt, os def usage(): print('aspx2url v1.0')", "print('-h : This help') def main(): try: opts, args =", "file') print('-h : This help') def main(): try: opts, args", "print(sys.argv[0]+' -d -h filename(s)') print('-d : Delete original file') print('-h", "v1.0') print('Usage:') print(sys.argv[0]+' -d -h filename(s)') print('-d : Delete original", "= result.group(1); filename = re.search('(.*?)\\.aspx',origFilename).group(1) fullFilename = filename+'.url' with open(fullFilename,", "= re.search('(.*?)\\.aspx',origFilename).group(1) fullFilename = filename+'.url' with open(fullFilename, 'w') as out:", "out.write('URL='+url) out.write('\\n') if deleteOriginal: os.remove(origFilename) if __name__ == '__main__': main()", "prog.search(html_doc) url = result.group(1); filename = re.search('(.*?)\\.aspx',origFilename).group(1) fullFilename = filename+'.url'", "'-h': usage() sys.exit() elif option == '-d': deleteOriginal = True", "getopt.GetoptError as err: print(str(err)) usage() sys.exit(2) deleteOriginal = False for", "args: with open(origFilename, \"r\") as f: html_doc = f.read() prog", "result.group(1); filename = re.search('(.*?)\\.aspx',origFilename).group(1) fullFilename = filename+'.url' with open(fullFilename, 'w')", "glob, getopt, os def usage(): print('aspx2url v1.0') print('Usage:') print(sys.argv[0]+' -d", "\"r\") as f: html_doc = f.read() prog = re.compile('\\<mso\\:URL.*?\\>(.*?),.*?\\<\\/mso\\:URL\\>', re.M)", "sys.exit(2) deleteOriginal = False for option,value in opts: if option", "for origFilename in args: with open(origFilename, \"r\") as f: html_doc", "-d -h filename(s)') print('-d : Delete original file') print('-h :", "in opts: if option == '-h': usage() sys.exit() elif option", "Delete original file') print('-h : This help') def main(): try:", "os def usage(): print('aspx2url v1.0') print('Usage:') print(sys.argv[0]+' -d -h filename(s)')", "re.M) result = prog.search(html_doc) url = result.group(1); filename = re.search('(.*?)\\.aspx',origFilename).group(1)", "True for origFilename in args: with open(origFilename, \"r\") as f:", "print_function import re, sys, glob, getopt, os def usage(): print('aspx2url", "option == '-d': deleteOriginal = True for origFilename in args:", "option,value in opts: if option == '-h': usage() sys.exit() elif", "opts: if option == '-h': usage() sys.exit() elif option ==", "re, sys, glob, getopt, os def usage(): print('aspx2url v1.0') print('Usage:')", "open(origFilename, \"r\") as f: html_doc = f.read() prog = re.compile('\\<mso\\:URL.*?\\>(.*?),.*?\\<\\/mso\\:URL\\>',", "option == '-h': usage() sys.exit() elif option == '-d': deleteOriginal", "'w') as out: out.write('[InternetShortcut]\\n') out.write('URL='+url) out.write('\\n') if deleteOriginal: os.remove(origFilename) if", "f.read() prog = re.compile('\\<mso\\:URL.*?\\>(.*?),.*?\\<\\/mso\\:URL\\>', re.M) result = prog.search(html_doc) url =", "from __future__ import print_function import re, sys, glob, getopt, os", "def usage(): print('aspx2url v1.0') print('Usage:') print(sys.argv[0]+' -d -h filename(s)') print('-d", "in args: with open(origFilename, \"r\") as f: html_doc = f.read()", "def main(): try: opts, args = getopt.getopt(sys.argv[1:], \"hd\") except getopt.GetoptError", "import print_function import re, sys, glob, getopt, os def usage():", "filename(s)') print('-d : Delete original file') print('-h : This help')", "usage() sys.exit() elif option == '-d': deleteOriginal = True for", "print(str(err)) usage() sys.exit(2) deleteOriginal = False for option,value in opts:", "prog = re.compile('\\<mso\\:URL.*?\\>(.*?),.*?\\<\\/mso\\:URL\\>', re.M) result = prog.search(html_doc) url = result.group(1);", "main(): try: opts, args = getopt.getopt(sys.argv[1:], \"hd\") except getopt.GetoptError as", "print('-d : Delete original file') print('-h : This help') def", "re.search('(.*?)\\.aspx',origFilename).group(1) fullFilename = filename+'.url' with open(fullFilename, 'w') as out: out.write('[InternetShortcut]\\n')", "\"hd\") except getopt.GetoptError as err: print(str(err)) usage() sys.exit(2) deleteOriginal =", "url = result.group(1); filename = re.search('(.*?)\\.aspx',origFilename).group(1) fullFilename = filename+'.url' with", "= True for origFilename in args: with open(origFilename, \"r\") as", "= getopt.getopt(sys.argv[1:], \"hd\") except getopt.GetoptError as err: print(str(err)) usage() sys.exit(2)", "out: out.write('[InternetShortcut]\\n') out.write('URL='+url) out.write('\\n') if deleteOriginal: os.remove(origFilename) if __name__ ==", "== '-h': usage() sys.exit() elif option == '-d': deleteOriginal =", "__future__ import print_function import re, sys, glob, getopt, os def", "out.write('[InternetShortcut]\\n') out.write('URL='+url) out.write('\\n') if deleteOriginal: os.remove(origFilename) if __name__ == '__main__':", "sys.exit() elif option == '-d': deleteOriginal = True for origFilename", "except getopt.GetoptError as err: print(str(err)) usage() sys.exit(2) deleteOriginal = False", "filename+'.url' with open(fullFilename, 'w') as out: out.write('[InternetShortcut]\\n') out.write('URL='+url) out.write('\\n') if", "as err: print(str(err)) usage() sys.exit(2) deleteOriginal = False for option,value", "re.compile('\\<mso\\:URL.*?\\>(.*?),.*?\\<\\/mso\\:URL\\>', re.M) result = prog.search(html_doc) url = result.group(1); filename =", "open(fullFilename, 'w') as out: out.write('[InternetShortcut]\\n') out.write('URL='+url) out.write('\\n') if deleteOriginal: os.remove(origFilename)", "False for option,value in opts: if option == '-h': usage()" ]
[ "v = \"hello world\" else: v = None \"\"\") self.assertTypesMatchPytd(ty,", "... # type: str \"\"\") def testXRange(self): self.Check(\"\"\" import random", "... # type: int z = ... # type: int", "sys if sys.version_info[0] <= 2: v = 42 else: v", "def testDefaultDict(self): self.Check(\"\"\" import collections import itertools ids = collections.defaultdict(itertools.count(17).next)", "= None \"\"\") self.assertTypesMatchPytd(ty, \"\"\" sys = ... # type:", "types.StringTypes): y = 42 if isinstance(u\"\", types.StringTypes): z = 42", "self.Infer(\"\"\" import sys if sys.version_info[0] <= 2: v = 42", "type: module v = ... # type: str \"\"\") def", "type: str \"\"\") def testSysVersionInfoNamedAttribute(self): ty = self.Infer(\"\"\" import sys", "ty = self.Infer(\"\"\" import types if isinstance(\"\", types.StringTypes): x =", "\"\"\") self.assertTypesMatchPytd(ty, \"\"\" sys: module v: int \"\"\") test_base.main(globals(), __name__", "posix = ... # type: module x = ... #", "testXRange(self): self.Check(\"\"\" import random random.sample(xrange(10), 5) \"\"\") def testStringTypes(self): ty", "v = 42 else: v = \"hello world\" \"\"\") self.assertTypesMatchPytd(ty,", "types.StringTypes): x = 42 if isinstance(False, types.StringTypes): y = 42", "... # type: module x = ... # type: int", "type: int \"\"\") def testDefaultDict(self): self.Check(\"\"\" import collections import itertools", "in typeshed/stdlib.\"\"\" def testPosix(self): ty = self.Infer(\"\"\" import posix x", "else: v = \"hello world\" \"\"\") self.assertTypesMatchPytd(ty, \"\"\" sys: module", "testPosix(self): ty = self.Infer(\"\"\" import posix x = posix.urandom(10) \"\"\")", "isinstance(u\"\", types.StringTypes): z = 42 \"\"\", deep=False) self.assertTypesMatchPytd(ty, \"\"\" types", "z = ... # type: int \"\"\") def testDefaultDict(self): self.Check(\"\"\"", "\"\"\" sys: module v: int \"\"\") test_base.main(globals(), __name__ == \"__main__\")", "StdlibTests(test_base.TargetPython27FeatureTest): \"\"\"Tests for files in typeshed/stdlib.\"\"\" def testPosix(self): ty =", "self.Infer(\"\"\" import sys if sys.version_info[0] < 3: v = 42", "= self.Infer(\"\"\" import posix x = posix.urandom(10) \"\"\") self.assertTypesMatchPytd(ty, \"\"\"", "= ... # type: str \"\"\") def testSysVersionInfoNamedAttribute(self): ty =", "posix.urandom(10) \"\"\") self.assertTypesMatchPytd(ty, \"\"\" posix = ... # type: module", "= posix.urandom(10) \"\"\") self.assertTypesMatchPytd(ty, \"\"\" posix = ... # type:", "42 else: v = \"hello world\" \"\"\") self.assertTypesMatchPytd(ty, \"\"\" sys", ">= 3: v = 42 else: v = \"hello world\"", "class StdlibTests(test_base.TargetPython27FeatureTest): \"\"\"Tests for files in typeshed/stdlib.\"\"\" def testPosix(self): ty", "self.Check(\"\"\" import random random.sample(xrange(10), 5) \"\"\") def testStringTypes(self): ty =", "module x = ... # type: str \"\"\") def testXRange(self):", "self.assertTypesMatchPytd(ty, \"\"\" sys = ... # type: module v =", "# type: int \"\"\") def testSysVersionInfoLe(self): ty = self.Infer(\"\"\" import", "world\" \"\"\") self.assertTypesMatchPytd(ty, \"\"\" sys = ... # type: module", "files in typeshed/stdlib.\"\"\" def testPosix(self): ty = self.Infer(\"\"\" import posix", "self.Check(\"\"\" import collections import itertools ids = collections.defaultdict(itertools.count(17).next) \"\"\") def", "random random.sample(xrange(10), 5) \"\"\") def testStringTypes(self): ty = self.Infer(\"\"\" import", "x = ... # type: str \"\"\") def testXRange(self): self.Check(\"\"\"", "z = 42 \"\"\", deep=False) self.assertTypesMatchPytd(ty, \"\"\" types = ...", "= ... # type: module v = ... # type:", "\"\"\") def testDefaultDict(self): self.Check(\"\"\" import collections import itertools ids =", "ty = self.Infer(\"\"\" import sys if sys.version_info[0] <= 2: v", "\"\"\") def testXRange(self): self.Check(\"\"\" import random random.sample(xrange(10), 5) \"\"\") def", "... # type: int \"\"\") def testSysVersionInfoLe(self): ty = self.Infer(\"\"\"", "self.Infer(\"\"\" import sys if sys.version_info[0] == 2: v = 42", "# type: str \"\"\") def testXRange(self): self.Check(\"\"\" import random random.sample(xrange(10),", "if sys.version_info[0] > 2: v = 42 else: v =", "sys.version_info[0] <= 2: v = 42 else: v = \"hello", "v = ... # type: int \"\"\") def testSysVersionInfoLe(self): ty", "v = ... # type: int \"\"\") def testSysVersionInfoGe(self): ty", "sys.version_info.major == 2: v = 42 else: v = \"hello", "types if isinstance(\"\", types.StringTypes): x = 42 if isinstance(False, types.StringTypes):", "\"\"\") self.assertTypesMatchPytd(ty, \"\"\" sys = ... # type: module v", "typeshed/stdlib.\"\"\" def testPosix(self): ty = self.Infer(\"\"\" import posix x =", "... # type: str \"\"\") def testSysVersionInfoGt(self): ty = self.Infer(\"\"\"", "= self.Infer(\"\"\" import types if isinstance(\"\", types.StringTypes): x = 42", "= self.Infer(\"\"\" import sys if sys.version_info[0] < 3: v =", "v = ... # type: str \"\"\") def testSysVersionInfoGt(self): ty", "itertools ids = collections.defaultdict(itertools.count(17).next) \"\"\") def testSysVersionInfoLt(self): ty = self.Infer(\"\"\"", "module x = ... # type: int z = ...", "# type: str \"\"\") def testSysVersionInfoNamedAttribute(self): ty = self.Infer(\"\"\" import", "int z = ... # type: int \"\"\") def testDefaultDict(self):", "sys if sys.version_info[0] >= 3: v = 42 else: v", "\"hello world\" \"\"\") self.assertTypesMatchPytd(ty, \"\"\" sys = ... # type:", "y = 42 if isinstance(u\"\", types.StringTypes): z = 42 \"\"\",", "= self.Infer(\"\"\" import sys if sys.version_info[0] == 2: v =", "\"\"\" types = ... # type: module x = ...", "def testSysVersionInfoGt(self): ty = self.Infer(\"\"\" import sys if sys.version_info[0] >", "else: v = \"hello world\" \"\"\") self.assertTypesMatchPytd(ty, \"\"\" sys =", "ty = self.Infer(\"\"\" import posix x = posix.urandom(10) \"\"\") self.assertTypesMatchPytd(ty,", "42 else: v = \"hello world\" \"\"\") self.assertTypesMatchPytd(ty, \"\"\" sys:", "world\" \"\"\") self.assertTypesMatchPytd(ty, \"\"\" sys: module v: int \"\"\") test_base.main(globals(),", "x = ... # type: int z = ... #", "testSysVersionInfoGt(self): ty = self.Infer(\"\"\" import sys if sys.version_info[0] > 2:", "\"\"\") def testSysVersionInfoEq(self): ty = self.Infer(\"\"\" import sys if sys.version_info[0]", "== 3: v = \"hello world\" else: v = None", "testDefaultDict(self): self.Check(\"\"\" import collections import itertools ids = collections.defaultdict(itertools.count(17).next) \"\"\")", "if sys.version_info[0] <= 2: v = 42 else: v =", "int \"\"\") def testSysVersionInfoEq(self): ty = self.Infer(\"\"\" import sys if", "\"\"\"Tests of selected stdlib functions.\"\"\" from pytype.tests import test_base class", "= 42 elif sys.version_info[0] == 3: v = \"hello world\"", "sys.version_info[0] == 3: v = \"hello world\" else: v =", "ids = collections.defaultdict(itertools.count(17).next) \"\"\") def testSysVersionInfoLt(self): ty = self.Infer(\"\"\" import", "sys if sys.version_info.major == 2: v = 42 else: v", "testSysVersionInfoLe(self): ty = self.Infer(\"\"\" import sys if sys.version_info[0] <= 2:", "2: v = 42 else: v = \"hello world\" \"\"\")", "str \"\"\") def testSysVersionInfoGt(self): ty = self.Infer(\"\"\" import sys if", "if isinstance(False, types.StringTypes): y = 42 if isinstance(u\"\", types.StringTypes): z", "self.Infer(\"\"\" import sys if sys.version_info[0] >= 3: v = 42", "type: int \"\"\") def testSysVersionInfoLe(self): ty = self.Infer(\"\"\" import sys", "= ... # type: str \"\"\") def testXRange(self): self.Check(\"\"\" import", "x = 42 if isinstance(False, types.StringTypes): y = 42 if", "3: v = \"hello world\" else: v = None \"\"\")", "ty = self.Infer(\"\"\" import sys if sys.version_info.major == 2: v", "= self.Infer(\"\"\" import sys if sys.version_info.major == 2: v =", "def testSysVersionInfoGe(self): ty = self.Infer(\"\"\" import sys if sys.version_info[0] >=", "for files in typeshed/stdlib.\"\"\" def testPosix(self): ty = self.Infer(\"\"\" import", "= ... # type: str \"\"\") def testSysVersionInfoGt(self): ty =", "self.assertTypesMatchPytd(ty, \"\"\" posix = ... # type: module x =", "isinstance(False, types.StringTypes): y = 42 if isinstance(u\"\", types.StringTypes): z =", "= 42 if isinstance(False, types.StringTypes): y = 42 if isinstance(u\"\",", "type: str \"\"\") def testXRange(self): self.Check(\"\"\" import random random.sample(xrange(10), 5)", "int \"\"\") def testSysVersionInfoGe(self): ty = self.Infer(\"\"\" import sys if", "type: int z = ... # type: int \"\"\") def", "... # type: int \"\"\") def testSysVersionInfoEq(self): ty = self.Infer(\"\"\"", "module v = ... # type: str \"\"\") def testSysVersionInfoGt(self):", "import types if isinstance(\"\", types.StringTypes): x = 42 if isinstance(False,", "ty = self.Infer(\"\"\" import sys if sys.version_info[0] >= 3: v", "<reponame>souravbadami/pytype \"\"\"Tests of selected stdlib functions.\"\"\" from pytype.tests import test_base", "if isinstance(u\"\", types.StringTypes): z = 42 \"\"\", deep=False) self.assertTypesMatchPytd(ty, \"\"\"", "# type: int z = ... # type: int \"\"\")", "type: str \"\"\") def testSysVersionInfoGt(self): ty = self.Infer(\"\"\" import sys", "\"\"\") def testSysVersionInfoNamedAttribute(self): ty = self.Infer(\"\"\" import sys if sys.version_info.major", "= ... # type: int \"\"\") def testSysVersionInfoGe(self): ty =", "testSysVersionInfoGe(self): ty = self.Infer(\"\"\" import sys if sys.version_info[0] >= 3:", "else: v = None \"\"\") self.assertTypesMatchPytd(ty, \"\"\" sys = ...", "import sys if sys.version_info[0] <= 2: v = 42 else:", "def testSysVersionInfoEq(self): ty = self.Infer(\"\"\" import sys if sys.version_info[0] ==", "elif sys.version_info[0] == 3: v = \"hello world\" else: v", "types.StringTypes): z = 42 \"\"\", deep=False) self.assertTypesMatchPytd(ty, \"\"\" types =", "self.assertTypesMatchPytd(ty, \"\"\" sys: module v: int \"\"\") test_base.main(globals(), __name__ ==", "42 \"\"\", deep=False) self.assertTypesMatchPytd(ty, \"\"\" types = ... # type:", "if sys.version_info[0] >= 3: v = 42 else: v =", "testSysVersionInfoEq(self): ty = self.Infer(\"\"\" import sys if sys.version_info[0] == 2:", "sys if sys.version_info[0] == 2: v = 42 elif sys.version_info[0]", "import sys if sys.version_info[0] > 2: v = 42 else:", "import sys if sys.version_info[0] >= 3: v = 42 else:", "42 if isinstance(u\"\", types.StringTypes): z = 42 \"\"\", deep=False) self.assertTypesMatchPytd(ty,", "types = ... # type: module x = ... #", "= ... # type: module x = ... # type:", "module v = ... # type: int \"\"\") def testSysVersionInfoLe(self):", "def testSysVersionInfoLe(self): ty = self.Infer(\"\"\" import sys if sys.version_info[0] <=", "= self.Infer(\"\"\" import sys if sys.version_info[0] <= 2: v =", "\"hello world\" \"\"\") self.assertTypesMatchPytd(ty, \"\"\" sys: module v: int \"\"\")", "# type: int \"\"\") def testSysVersionInfoEq(self): ty = self.Infer(\"\"\" import", "self.Infer(\"\"\" import sys if sys.version_info.major == 2: v = 42", "= ... # type: int \"\"\") def testSysVersionInfoLe(self): ty =", "type: int \"\"\") def testSysVersionInfoEq(self): ty = self.Infer(\"\"\" import sys", "testSysVersionInfoNamedAttribute(self): ty = self.Infer(\"\"\" import sys if sys.version_info.major == 2:", "import collections import itertools ids = collections.defaultdict(itertools.count(17).next) \"\"\") def testSysVersionInfoLt(self):", "v = ... # type: int \"\"\") def testSysVersionInfoEq(self): ty", "posix x = posix.urandom(10) \"\"\") self.assertTypesMatchPytd(ty, \"\"\" posix = ...", "if sys.version_info[0] == 2: v = 42 elif sys.version_info[0] ==", "> 2: v = 42 else: v = \"hello world\"", "v = None \"\"\") self.assertTypesMatchPytd(ty, \"\"\" sys = ... #", "< 3: v = 42 else: v = \"hello world\"", "if isinstance(\"\", types.StringTypes): x = 42 if isinstance(False, types.StringTypes): y", "... # type: str \"\"\") def testSysVersionInfoNamedAttribute(self): ty = self.Infer(\"\"\"", "sys = ... # type: module v = ... #", "selected stdlib functions.\"\"\" from pytype.tests import test_base class StdlibTests(test_base.TargetPython27FeatureTest): \"\"\"Tests", "if sys.version_info[0] < 3: v = 42 else: v =", "# type: int \"\"\") def testDefaultDict(self): self.Check(\"\"\" import collections import", "2: v = 42 elif sys.version_info[0] == 3: v =", "= \"hello world\" \"\"\") self.assertTypesMatchPytd(ty, \"\"\" sys: module v: int", "= self.Infer(\"\"\" import sys if sys.version_info[0] >= 3: v =", "= self.Infer(\"\"\" import sys if sys.version_info[0] > 2: v =", "= ... # type: int z = ... # type:", "v = ... # type: str \"\"\") def testSysVersionInfoNamedAttribute(self): ty", "def testSysVersionInfoLt(self): ty = self.Infer(\"\"\" import sys if sys.version_info[0] <", "... # type: module v = ... # type: int", "# type: module x = ... # type: str \"\"\")", "stdlib functions.\"\"\" from pytype.tests import test_base class StdlibTests(test_base.TargetPython27FeatureTest): \"\"\"Tests for", "ty = self.Infer(\"\"\" import sys if sys.version_info[0] < 3: v", "module v = ... # type: str \"\"\") def testSysVersionInfoNamedAttribute(self):", "self.Infer(\"\"\" import posix x = posix.urandom(10) \"\"\") self.assertTypesMatchPytd(ty, \"\"\" posix", "isinstance(\"\", types.StringTypes): x = 42 if isinstance(False, types.StringTypes): y =", "import sys if sys.version_info.major == 2: v = 42 else:", "if sys.version_info.major == 2: v = 42 else: v =", "sys.version_info[0] < 3: v = 42 else: v = \"hello", "= ... # type: int \"\"\") def testSysVersionInfoEq(self): ty =", "\"\"\") self.assertTypesMatchPytd(ty, \"\"\" posix = ... # type: module x", "\"\"\" sys = ... # type: module v = ...", "v = \"hello world\" \"\"\") self.assertTypesMatchPytd(ty, \"\"\" sys = ...", "sys.version_info[0] > 2: v = 42 else: v = \"hello", "import test_base class StdlibTests(test_base.TargetPython27FeatureTest): \"\"\"Tests for files in typeshed/stdlib.\"\"\" def", "42 if isinstance(False, types.StringTypes): y = 42 if isinstance(u\"\", types.StringTypes):", "<= 2: v = 42 else: v = \"hello world\"", "module v = ... # type: int \"\"\") def testSysVersionInfoGe(self):", "\"\"\") def testStringTypes(self): ty = self.Infer(\"\"\" import types if isinstance(\"\",", "== 2: v = 42 elif sys.version_info[0] == 3: v", "def testSysVersionInfoNamedAttribute(self): ty = self.Infer(\"\"\" import sys if sys.version_info.major ==", "\"hello world\" else: v = None \"\"\") self.assertTypesMatchPytd(ty, \"\"\" sys", "# type: module v = ... # type: str \"\"\")", "... # type: int \"\"\") def testSysVersionInfoGe(self): ty = self.Infer(\"\"\"", "sys if sys.version_info[0] < 3: v = 42 else: v", "type: module v = ... # type: int \"\"\") def", "collections.defaultdict(itertools.count(17).next) \"\"\") def testSysVersionInfoLt(self): ty = self.Infer(\"\"\" import sys if", "type: module x = ... # type: int z =", "deep=False) self.assertTypesMatchPytd(ty, \"\"\" types = ... # type: module x", "... # type: int \"\"\") def testDefaultDict(self): self.Check(\"\"\" import collections", "= 42 else: v = \"hello world\" \"\"\") self.assertTypesMatchPytd(ty, \"\"\"", "v = \"hello world\" \"\"\") self.assertTypesMatchPytd(ty, \"\"\" sys: module v:", "import itertools ids = collections.defaultdict(itertools.count(17).next) \"\"\") def testSysVersionInfoLt(self): ty =", "sys.version_info[0] >= 3: v = 42 else: v = \"hello", "\"\"\"Tests for files in typeshed/stdlib.\"\"\" def testPosix(self): ty = self.Infer(\"\"\"", "random.sample(xrange(10), 5) \"\"\") def testStringTypes(self): ty = self.Infer(\"\"\" import types", "5) \"\"\") def testStringTypes(self): ty = self.Infer(\"\"\" import types if", "def testXRange(self): self.Check(\"\"\" import random random.sample(xrange(10), 5) \"\"\") def testStringTypes(self):", "ty = self.Infer(\"\"\" import sys if sys.version_info[0] > 2: v", "sys if sys.version_info[0] > 2: v = 42 else: v", "... # type: module v = ... # type: str", "from pytype.tests import test_base class StdlibTests(test_base.TargetPython27FeatureTest): \"\"\"Tests for files in", "type: int \"\"\") def testSysVersionInfoGe(self): ty = self.Infer(\"\"\" import sys", "\"\"\") def testSysVersionInfoGt(self): ty = self.Infer(\"\"\" import sys if sys.version_info[0]", "import sys if sys.version_info[0] < 3: v = 42 else:", "# type: module v = ... # type: int \"\"\")", "sys.version_info[0] == 2: v = 42 elif sys.version_info[0] == 3:", "str \"\"\") def testXRange(self): self.Check(\"\"\" import random random.sample(xrange(10), 5) \"\"\")", "module v = ... # type: int \"\"\") def testSysVersionInfoEq(self):", "42 elif sys.version_info[0] == 3: v = \"hello world\" else:", "= collections.defaultdict(itertools.count(17).next) \"\"\") def testSysVersionInfoLt(self): ty = self.Infer(\"\"\" import sys", "world\" else: v = None \"\"\") self.assertTypesMatchPytd(ty, \"\"\" sys =", "x = posix.urandom(10) \"\"\") self.assertTypesMatchPytd(ty, \"\"\" posix = ... #", "self.assertTypesMatchPytd(ty, \"\"\" types = ... # type: module x =", "int \"\"\") def testSysVersionInfoLe(self): ty = self.Infer(\"\"\" import sys if", "3: v = 42 else: v = \"hello world\" \"\"\")", "pytype.tests import test_base class StdlibTests(test_base.TargetPython27FeatureTest): \"\"\"Tests for files in typeshed/stdlib.\"\"\"", "\"\"\") def testSysVersionInfoGe(self): ty = self.Infer(\"\"\" import sys if sys.version_info[0]", "# type: int \"\"\") def testSysVersionInfoGe(self): ty = self.Infer(\"\"\" import", "= 42 if isinstance(u\"\", types.StringTypes): z = 42 \"\"\", deep=False)", "None \"\"\") self.assertTypesMatchPytd(ty, \"\"\" sys = ... # type: module", "= \"hello world\" \"\"\") self.assertTypesMatchPytd(ty, \"\"\" sys = ... #", "def testStringTypes(self): ty = self.Infer(\"\"\" import types if isinstance(\"\", types.StringTypes):", "# type: module x = ... # type: int z", "def testPosix(self): ty = self.Infer(\"\"\" import posix x = posix.urandom(10)", "v = 42 elif sys.version_info[0] == 3: v = \"hello", "# type: str \"\"\") def testSysVersionInfoGt(self): ty = self.Infer(\"\"\" import", "= 42 \"\"\", deep=False) self.assertTypesMatchPytd(ty, \"\"\" types = ... #", "... # type: module x = ... # type: str", "of selected stdlib functions.\"\"\" from pytype.tests import test_base class StdlibTests(test_base.TargetPython27FeatureTest):", "\"\"\" posix = ... # type: module x = ...", "collections import itertools ids = collections.defaultdict(itertools.count(17).next) \"\"\") def testSysVersionInfoLt(self): ty", "testStringTypes(self): ty = self.Infer(\"\"\" import types if isinstance(\"\", types.StringTypes): x", "import posix x = posix.urandom(10) \"\"\") self.assertTypesMatchPytd(ty, \"\"\" posix =", "== 2: v = 42 else: v = \"hello world\"", "testSysVersionInfoLt(self): ty = self.Infer(\"\"\" import sys if sys.version_info[0] < 3:", "= \"hello world\" else: v = None \"\"\") self.assertTypesMatchPytd(ty, \"\"\"", "= ... # type: int \"\"\") def testDefaultDict(self): self.Check(\"\"\" import", "import random random.sample(xrange(10), 5) \"\"\") def testStringTypes(self): ty = self.Infer(\"\"\"", "import sys if sys.version_info[0] == 2: v = 42 elif", "self.Infer(\"\"\" import sys if sys.version_info[0] > 2: v = 42", "self.Infer(\"\"\" import types if isinstance(\"\", types.StringTypes): x = 42 if", "\"\"\", deep=False) self.assertTypesMatchPytd(ty, \"\"\" types = ... # type: module", "\"\"\") def testSysVersionInfoLe(self): ty = self.Infer(\"\"\" import sys if sys.version_info[0]", "functions.\"\"\" from pytype.tests import test_base class StdlibTests(test_base.TargetPython27FeatureTest): \"\"\"Tests for files", "int \"\"\") def testDefaultDict(self): self.Check(\"\"\" import collections import itertools ids", "\"\"\") def testSysVersionInfoLt(self): ty = self.Infer(\"\"\" import sys if sys.version_info[0]", "type: module x = ... # type: str \"\"\") def", "test_base class StdlibTests(test_base.TargetPython27FeatureTest): \"\"\"Tests for files in typeshed/stdlib.\"\"\" def testPosix(self):", "ty = self.Infer(\"\"\" import sys if sys.version_info[0] == 2: v", "str \"\"\") def testSysVersionInfoNamedAttribute(self): ty = self.Infer(\"\"\" import sys if" ]
[ "coding: utf-8 -*- \"\"\" Created on Tue Oct 20 16:04:52", "-*- coding: utf-8 -*- \"\"\" Created on Tue Oct 20", "utf-8 -*- \"\"\" Created on Tue Oct 20 16:04:52 2020", "\"\"\" Created on Tue Oct 20 16:04:52 2020 @author: rjovelin", "<reponame>oicr-gsi/pysmmips # -*- coding: utf-8 -*- \"\"\" Created on Tue", "-*- \"\"\" Created on Tue Oct 20 16:04:52 2020 @author:", "# -*- coding: utf-8 -*- \"\"\" Created on Tue Oct", "Created on Tue Oct 20 16:04:52 2020 @author: rjovelin \"\"\"" ]
[ "social_post from mongo def get_custom_social_post(self): doc = list(self.db.socialPosts.aggregate([{'$match': {'source': 'custom", "source): existing_dict = self.db.storeAccessToken.find_one({'source': source}) return existing_dict def get_google_calendar_posts(self): timestamp_var", "Util class MongoDBClient: __instance = None @staticmethod def getInstance(): \"\"\"", "from pymongo.errors import ConnectionFailure from tarentsocialwall.SocialPost import SocialPost from tarentsocialwall.User", "else: MongoDBClient.__instance = self self.update_all_socialposts() # write social_post into mongo", "if existing_dict is None: self.db.socialPosts.insert_one(social_post.__dict__) else: update_identifier = {'externalId': social_post.externalId,", "def get_random_social_post(self) -> SocialPost: if len(self.random_social_post_list) == 0: return None", "User): username_dict = self.db.socialwall_users.find_one({'username': user.username}) if username_dict is None: self.db.socialwall_users.insert_one(user.__dict__)", "shuffle list # so we dont repeat the same circle", "MongoDBClient.__instance != None: raise Exception(\"This class is a singleton!\") else:", "into mongo def write_social_post(self, social_post: SocialPost): existing_dict = None try:", "# write social_post into mongo def write_social_post(self, social_post: SocialPost): existing_dict", "len(self.random_social_post_list) == 0: return None else: if self.reset_counter >= len(self.random_social_post_list):", "self.db.socialwall_users.find_one({'username': username}) def write_user(self, user: User): username_dict = self.db.socialwall_users.find_one({'username': user.username})", "= self.db.storeAccessToken.find_one({'source': access_token}) if existing_dict is None: identifier = {'access_token':", "= Util.randomString() user = User() user.username = 'admin' user.password =", "!= None: raise Exception(\"This class is a singleton!\") else: MongoDBClient.__instance", "list(self.db.socialPosts.aggregate([{'$match': {'source': 'custom post'}}])) print(list(doc)) if doc is None: return", "return None users = [] for item in users_db: if", "= {'externalId': social_post.externalId, 'source': social_post.source} self.db.socialPosts.replace_one(update_identifier, social_post.__dict__) return 0 #", "write_user(self, user: User): username_dict = self.db.socialwall_users.find_one({'username': user.username}) if username_dict is", "and shuffle them in random order def update_all_socialposts(self): timestamp =", "post'}}])) print(list(doc)) if doc is None: return None social_post_list =", "self.db.storeAccessToken.find_one({'source': source}) return existing_dict def get_google_calendar_posts(self): timestamp_var = datetime.utcnow().timestamp() doc", "self.reset_counter = 0 random.shuffle(self.random_social_post_list) post = self.random_social_post_list[self.reset_counter] self.reset_counter = self.reset_counter", "existing_dict = self.db.storeAccessToken.find_one({'source': access_token}) if existing_dict is None: identifier =", "from tarentsocialwall.Util import Util class MongoDBClient: __instance = None @staticmethod", "The ismaster command is cheap and does not require auth.", "is cheap and does not require auth. self.client.admin.command('ismaster') except ConnectionFailure:", "social_post_list.append(custom_post_item) return social_post_list def delete_post(self, external_id): removed = self.db.socialPosts.delete_one({'externalId': external_id})", "of posts every time self.reset_counter = 0 random.shuffle(self.random_social_post_list) post =", "\"\"\" if MongoDBClient.__instance == None: MongoDBClient() client = None db", "import sha256_crypt from pymongo import MongoClient from pymongo.errors import ConnectionFailure", "return social_post_list def get_users(self): users_db = list(self.db.socialwall_users.find()) if users_db is", "None: identifier = {'access_token': access_token, 'source': source} self.db.storeAccessToken.insert_one(identifier) else: update_identifier", "from datetime import datetime from passlib.handlers.sha2_crypt import sha256_crypt from pymongo", "0 def delete_user(self, user: User): self.db.socialwall_users.delete_one({'username': user['username']}) def init_admin(self): random_string", "doc = list(self.db.socialPosts.aggregate([{'$match': {'source': 'custom post'}}])) print(list(doc)) if doc is", "<< MONGODB URL >> to reflect your own connection string", "None @staticmethod def getInstance(): \"\"\" Static access method. \"\"\" if", "in users_db: if item['username'] is not 'admin': user = User()", "user: User): username_dict = self.db.socialwall_users.find_one({'username': user.username}) if username_dict is None:", "update_all_socialposts(self): timestamp = datetime.utcnow().timestamp() self.random_social_post_list = list(self.db.socialPosts.aggregate( [{'$match': {'validFrom': {'$lte':", "is None: return None social_post_list = [] for post in", "= datetime.utcnow().timestamp() doc = list(self.db.socialPosts.aggregate([ {'$match': {'validFrom': {'$lte': timestamp_var}, 'validTo':", "#Get all valid social posts from db and shuffle them", "def delete_post(self, external_id): removed = self.db.socialPosts.delete_one({'externalId': external_id}) print(removed) def write_access_token(self,", "valid social posts from db and shuffle them in random", "return social_post # read custom social_post from mongo def get_custom_social_post(self):", "return existing_dict def get_google_calendar_posts(self): timestamp_var = datetime.utcnow().timestamp() doc = list(self.db.socialPosts.aggregate([", "self.db.socialwall_users.delete_one({'username': user['username']}) def init_admin(self): random_string = Util.randomString() user = User()", "user.username}) if username_dict is None: self.db.socialwall_users.insert_one(user.__dict__) else: update_identifier = {'username':", "existing_dict = self.db.storeAccessToken.find_one({'source': source}) return existing_dict def get_google_calendar_posts(self): timestamp_var =", "through all posts once we reset counter and shuffle list", "{'$sort': {'start': 1}} ])) if doc is None: return None", "init_admin(self): random_string = Util.randomString() user = User() user.username = 'admin'", "social_post into mongo def write_social_post(self, social_post: SocialPost): existing_dict = None", "None try: existing_dict = self.db.socialPosts.find_one({'externalId': social_post.externalId}) except Exception as ex:", "'admin' user.password = <PASSWORD>(<PASSWORD>) print(\"Admin password is '%s'\" % random_string)", "= 'admin' user.lastname = 'admin' self.write_user(user) #Get all valid social", "existing_dict is None: self.db.socialPosts.insert_one(social_post.__dict__) else: update_identifier = {'externalId': social_post.externalId, 'source':", "not available\") if MongoDBClient.__instance != None: raise Exception(\"This class is", "= None reset_counter = None def __init__(self, uri): # connect", "user: User): self.db.socialwall_users.delete_one({'username': user['username']}) def init_admin(self): random_string = Util.randomString() user", "{'$gte': timestamp_var}, 'source': 'Google calendar'}}, {'$sort': {'start': 1}} ])) if", "@staticmethod def getInstance(): \"\"\" Static access method. \"\"\" if MongoDBClient.__instance", "{'source': 'custom post'}}])) print(list(doc)) if doc is None: return None", "social_post = SocialPost() social_post.set_dictionary(post) return social_post # read custom social_post", "'source': source} self.db.storeAccessToken.replace_one(update_identifier, access_token) return 0 def read_access_token(self, source): existing_dict", "posts once we reset counter and shuffle list # so", "self.random_social_post_list = list(self.db.socialPosts.aggregate( [{'$match': {'validFrom': {'$lte': timestamp}, 'validTo': {'$gte': timestamp}}}]))", "social_post.source} self.db.socialPosts.replace_one(update_identifier, social_post.__dict__) return 0 # read random social_post from", ">= len(self.random_social_post_list): # when we went through all posts once", "MongoDB, change the << MONGODB URL >> to reflect your", "write_access_token(self, access_token, source): existing_dict = self.db.storeAccessToken.find_one({'source': access_token}) if existing_dict is", "= self self.update_all_socialposts() # write social_post into mongo def write_social_post(self,", "datetime from passlib.handlers.sha2_crypt import sha256_crypt from pymongo import MongoClient from", "= self.db.socialPosts.find_one({'externalId': social_post.externalId}) except Exception as ex: print(ex) existing_dict =", "as ex: print(ex) existing_dict = None if existing_dict is None:", "import Util class MongoDBClient: __instance = None @staticmethod def getInstance():", "Static access method. \"\"\" if MongoDBClient.__instance == None: MongoDBClient() client", "if len(self.random_social_post_list) == 0: return None else: if self.reset_counter >=", "is None: self.db.socialPosts.insert_one(social_post.__dict__) else: update_identifier = {'externalId': social_post.externalId, 'source': social_post.source}", "User): self.db.socialwall_users.delete_one({'username': user['username']}) def init_admin(self): random_string = Util.randomString() user =", "write_social_post(self, social_post: SocialPost): existing_dict = None try: existing_dict = self.db.socialPosts.find_one({'externalId':", "def get_google_calendar_posts(self): timestamp_var = datetime.utcnow().timestamp() doc = list(self.db.socialPosts.aggregate([ {'$match': {'validFrom':", "existing_dict def get_google_calendar_posts(self): timestamp_var = datetime.utcnow().timestamp() doc = list(self.db.socialPosts.aggregate([ {'$match':", "'Google calendar'}}, {'$sort': {'start': 1}} ])) if doc is None:", "method. \"\"\" if MongoDBClient.__instance == None: MongoDBClient() client = None", "self.write_user(user) #Get all valid social posts from db and shuffle", "if username_dict is None: self.db.socialwall_users.insert_one(user.__dict__) else: update_identifier = {'username': user.username}", "None users = [] for item in users_db: if item['username']", "tarentsocialwall.Util import Util class MongoDBClient: __instance = None @staticmethod def", "ex: print(ex) existing_dict = None if existing_dict is None: self.db.socialPosts.insert_one(social_post.__dict__)", "[] for item in users_db: if item['username'] is not 'admin':", "= list(self.db.socialwall_users.find()) if users_db is None: return None users =", "social_post.externalId, 'source': social_post.source} self.db.socialPosts.replace_one(update_identifier, social_post.__dict__) return 0 # read random", "db = None random_social_post_list = None reset_counter = None def", "available\") if MongoDBClient.__instance != None: raise Exception(\"This class is a", "social_post.set_dictionary(post) return social_post # read custom social_post from mongo def", "circle of posts every time self.reset_counter = 0 random.shuffle(self.random_social_post_list) post", "= SocialPost() custom_post_item.set_dictionary(post) social_post_list.append(custom_post_item) return social_post_list def get_users(self): users_db =", "# read custom social_post from mongo def get_custom_social_post(self): doc =", "custom_post_item = SocialPost() custom_post_item.set_dictionary(post) social_post_list.append(custom_post_item) return social_post_list def delete_post(self, external_id):", "mongo def get_custom_social_post(self): doc = list(self.db.socialPosts.aggregate([{'$match': {'source': 'custom post'}}])) print(list(doc))", "get_custom_social_post(self): doc = list(self.db.socialPosts.aggregate([{'$match': {'source': 'custom post'}}])) print(list(doc)) if doc", "None: return None social_post = SocialPost() social_post.set_dictionary(post) return social_post #", "self.reset_counter >= len(self.random_social_post_list): # when we went through all posts", "def get_users(self): users_db = list(self.db.socialwall_users.find()) if users_db is None: return", "SocialPost from tarentsocialwall.User import User from tarentsocialwall.Util import Util class", "getInstance(): \"\"\" Static access method. \"\"\" if MongoDBClient.__instance == None:", "the same circle of posts every time self.reset_counter = 0", "+ 1 print(post) if post is None: return None social_post", "post is None: return None social_post = SocialPost() social_post.set_dictionary(post) return", "access_token, 'source': source} self.db.storeAccessToken.insert_one(identifier) else: update_identifier = {'access_token': access_token, 'source':", "import random from datetime import datetime from passlib.handlers.sha2_crypt import sha256_crypt", "'admin' self.write_user(user) #Get all valid social posts from db and", "update_identifier = {'username': user.username} self.db.socialwall_users.replace_one(update_identifier, user.__dict__) return 0 def delete_user(self,", "social posts from db and shuffle them in random order", "them in random order def update_all_socialposts(self): timestamp = datetime.utcnow().timestamp() self.random_social_post_list", "% random_string) user.firstname = 'admin' user.lastname = 'admin' self.write_user(user) #Get", "ConnectionFailure from tarentsocialwall.SocialPost import SocialPost from tarentsocialwall.User import User from", "class is a singleton!\") else: MongoDBClient.__instance = self self.update_all_socialposts() #", "SocialPost() custom_post_item.set_dictionary(post) social_post_list.append(custom_post_item) return social_post_list def get_users(self): users_db = list(self.db.socialwall_users.find())", "read random social_post from list def get_random_social_post(self) -> SocialPost: if", "return self.db.socialwall_users.find_one({'username': username}) def write_user(self, user: User): username_dict = self.db.socialwall_users.find_one({'username':", "'%s'\" % random_string) user.firstname = 'admin' user.lastname = 'admin' self.write_user(user)", "if MongoDBClient.__instance != None: raise Exception(\"This class is a singleton!\")", "random_string) user.firstname = 'admin' user.lastname = 'admin' self.write_user(user) #Get all", "self self.update_all_socialposts() # write social_post into mongo def write_social_post(self, social_post:", "SocialPost): existing_dict = None try: existing_dict = self.db.socialPosts.find_one({'externalId': social_post.externalId}) except", "= [] for item in users_db: if item['username'] is not", "command is cheap and does not require auth. self.client.admin.command('ismaster') except", "user.username = 'admin' user.password = <PASSWORD>(<PASSWORD>) print(\"Admin password is '%s'\"", "is None: identifier = {'access_token': access_token, 'source': source} self.db.storeAccessToken.insert_one(identifier) else:", "= list(self.db.socialPosts.aggregate([{'$match': {'source': 'custom post'}}])) print(list(doc)) if doc is None:", "from pymongo import MongoClient from pymongo.errors import ConnectionFailure from tarentsocialwall.SocialPost", "from tarentsocialwall.User import User from tarentsocialwall.Util import Util class MongoDBClient:", "random social_post from list def get_random_social_post(self) -> SocialPost: if len(self.random_social_post_list)", "return 0 # read random social_post from list def get_random_social_post(self)", "print(post) if post is None: return None social_post = SocialPost()", "write social_post into mongo def write_social_post(self, social_post: SocialPost): existing_dict =", "list(self.db.socialPosts.aggregate( [{'$match': {'validFrom': {'$lte': timestamp}, 'validTo': {'$gte': timestamp}}}])) random.shuffle(self.random_social_post_list) self.reset_counter", "ConnectionFailure: print(\"Server not available\") if MongoDBClient.__instance != None: raise Exception(\"This", "and shuffle list # so we dont repeat the same", "return users def read_user(self, username): return self.db.socialwall_users.find_one({'username': username}) def write_user(self,", "user['username']}) def init_admin(self): random_string = Util.randomString() user = User() user.username", "0 random.shuffle(self.random_social_post_list) post = self.random_social_post_list[self.reset_counter] self.reset_counter = self.reset_counter + 1", "shuffle them in random order def update_all_socialposts(self): timestamp = datetime.utcnow().timestamp()", "1}} ])) if doc is None: return None social_post_list =", "doc: custom_post_item = SocialPost() custom_post_item.set_dictionary(post) social_post_list.append(custom_post_item) return social_post_list def delete_post(self,", "def get_custom_social_post(self): doc = list(self.db.socialPosts.aggregate([{'$match': {'source': 'custom post'}}])) print(list(doc)) if", "custom_post_item.set_dictionary(post) social_post_list.append(custom_post_item) return social_post_list def get_users(self): users_db = list(self.db.socialwall_users.find()) if", "pymongo.errors import ConnectionFailure from tarentsocialwall.SocialPost import SocialPost from tarentsocialwall.User import", "timestamp = datetime.utcnow().timestamp() self.random_social_post_list = list(self.db.socialPosts.aggregate( [{'$match': {'validFrom': {'$lte': timestamp},", "timestamp_var}, 'source': 'Google calendar'}}, {'$sort': {'start': 1}} ])) if doc", "{'validFrom': {'$lte': timestamp}, 'validTo': {'$gte': timestamp}}}])) random.shuffle(self.random_social_post_list) self.reset_counter = 0", "for post in doc: custom_post_item = SocialPost() custom_post_item.set_dictionary(post) social_post_list.append(custom_post_item) return", "singleton!\") else: MongoDBClient.__instance = self self.update_all_socialposts() # write social_post into", "username): return self.db.socialwall_users.find_one({'username': username}) def write_user(self, user: User): username_dict =", "we dont repeat the same circle of posts every time", "if self.reset_counter >= len(self.random_social_post_list): # when we went through all", "is None: return None users = [] for item in", "read_access_token(self, source): existing_dict = self.db.storeAccessToken.find_one({'source': source}) return existing_dict def get_google_calendar_posts(self):", "we reset counter and shuffle list # so we dont", "None random_social_post_list = None reset_counter = None def __init__(self, uri):", "else: if self.reset_counter >= len(self.random_social_post_list): # when we went through", "not require auth. self.client.admin.command('ismaster') except ConnectionFailure: print(\"Server not available\") if", "for item in users_db: if item['username'] is not 'admin': user", "post in doc: custom_post_item = SocialPost() custom_post_item.set_dictionary(post) social_post_list.append(custom_post_item) return social_post_list", "def __init__(self, uri): # connect to MongoDB, change the <<", "return None else: if self.reset_counter >= len(self.random_social_post_list): # when we", "MongoDBClient: __instance = None @staticmethod def getInstance(): \"\"\" Static access", "{'access_token': access_token, 'source': source} self.db.storeAccessToken.replace_one(update_identifier, access_token) return 0 def read_access_token(self,", "self.db.socialwall_users.replace_one(update_identifier, user.__dict__) return 0 def delete_user(self, user: User): self.db.socialwall_users.delete_one({'username': user['username']})", "item['username'] is not 'admin': user = User() user.set_dictionary(item) users.append(user) return", "def init_admin(self): random_string = Util.randomString() user = User() user.username =", "connect to MongoDB, change the << MONGODB URL >> to", "external_id}) print(removed) def write_access_token(self, access_token, source): existing_dict = self.db.storeAccessToken.find_one({'source': access_token})", "sha256_crypt from pymongo import MongoClient from pymongo.errors import ConnectionFailure from", "self.reset_counter = self.reset_counter + 1 print(post) if post is None:", "self.db.socialPosts.insert_one(social_post.__dict__) else: update_identifier = {'externalId': social_post.externalId, 'source': social_post.source} self.db.socialPosts.replace_one(update_identifier, social_post.__dict__)", "= SocialPost() social_post.set_dictionary(post) return social_post # read custom social_post from", "= self.db.socialPosts.delete_one({'externalId': external_id}) print(removed) def write_access_token(self, access_token, source): existing_dict =", "def write_user(self, user: User): username_dict = self.db.socialwall_users.find_one({'username': user.username}) if username_dict", "from list def get_random_social_post(self) -> SocialPost: if len(self.random_social_post_list) == 0:", "SocialPost: if len(self.random_social_post_list) == 0: return None else: if self.reset_counter", "access_token, source): existing_dict = self.db.storeAccessToken.find_one({'source': access_token}) if existing_dict is None:", "'admin': user = User() user.set_dictionary(item) users.append(user) return users def read_user(self,", "= 'admin' self.write_user(user) #Get all valid social posts from db", "None: raise Exception(\"This class is a singleton!\") else: MongoDBClient.__instance =", "def write_social_post(self, social_post: SocialPost): existing_dict = None try: existing_dict =", "= None def __init__(self, uri): # connect to MongoDB, change", "else: update_identifier = {'externalId': social_post.externalId, 'source': social_post.source} self.db.socialPosts.replace_one(update_identifier, social_post.__dict__) return", "social_post_list.append(custom_post_item) return social_post_list def get_users(self): users_db = list(self.db.socialwall_users.find()) if users_db", "else: update_identifier = {'username': user.username} self.db.socialwall_users.replace_one(update_identifier, user.__dict__) return 0 def", "__init__(self, uri): # connect to MongoDB, change the << MONGODB", "print(ex) existing_dict = None if existing_dict is None: self.db.socialPosts.insert_one(social_post.__dict__) else:", "source): existing_dict = self.db.storeAccessToken.find_one({'source': access_token}) if existing_dict is None: identifier", "users_db is None: return None users = [] for item", "= {'access_token': access_token, 'source': source} self.db.storeAccessToken.insert_one(identifier) else: update_identifier = {'access_token':", "])) if doc is None: return None social_post_list = []", "if users_db is None: return None users = [] for", "= None random_social_post_list = None reset_counter = None def __init__(self,", "post = self.random_social_post_list[self.reset_counter] self.reset_counter = self.reset_counter + 1 print(post) if", "= self.db.socialwall_users.find_one({'username': user.username}) if username_dict is None: self.db.socialwall_users.insert_one(user.__dict__) else: update_identifier", "users = [] for item in users_db: if item['username'] is", "order def update_all_socialposts(self): timestamp = datetime.utcnow().timestamp() self.random_social_post_list = list(self.db.socialPosts.aggregate( [{'$match':", "== None: MongoDBClient() client = None db = None random_social_post_list", "require auth. self.client.admin.command('ismaster') except ConnectionFailure: print(\"Server not available\") if MongoDBClient.__instance", "\"\"\" Static access method. \"\"\" if MongoDBClient.__instance == None: MongoDBClient()", "= 'admin' user.password = <PASSWORD>(<PASSWORD>) print(\"Admin password is '%s'\" %", "user.password = <PASSWORD>(<PASSWORD>) print(\"Admin password is '%s'\" % random_string) user.firstname", "is '%s'\" % random_string) user.firstname = 'admin' user.lastname = 'admin'", "random_string = Util.randomString() user = User() user.username = 'admin' user.password", "self.update_all_socialposts() # write social_post into mongo def write_social_post(self, social_post: SocialPost):", "len(self.random_social_post_list): # when we went through all posts once we", "delete_post(self, external_id): removed = self.db.socialPosts.delete_one({'externalId': external_id}) print(removed) def write_access_token(self, access_token,", "get_random_social_post(self) -> SocialPost: if len(self.random_social_post_list) == 0: return None else:", "def write_access_token(self, access_token, source): existing_dict = self.db.storeAccessToken.find_one({'source': access_token}) if existing_dict", "auth. self.client.admin.command('ismaster') except ConnectionFailure: print(\"Server not available\") if MongoDBClient.__instance !=", "print(list(doc)) if doc is None: return None social_post_list = []", "= self.client.socialPosts try: # The ismaster command is cheap and", "MongoDBClient() client = None db = None random_social_post_list = None", "URL >> to reflect your own connection string self.client =", "'source': social_post.source} self.db.socialPosts.replace_one(update_identifier, social_post.__dict__) return 0 # read random social_post", "[{'$match': {'validFrom': {'$lte': timestamp}, 'validTo': {'$gte': timestamp}}}])) random.shuffle(self.random_social_post_list) self.reset_counter =", "Util.randomString() user = User() user.username = 'admin' user.password = <PASSWORD>(<PASSWORD>)", "db and shuffle them in random order def update_all_socialposts(self): timestamp", "access_token, 'source': source} self.db.storeAccessToken.replace_one(update_identifier, access_token) return 0 def read_access_token(self, source):", "def update_all_socialposts(self): timestamp = datetime.utcnow().timestamp() self.random_social_post_list = list(self.db.socialPosts.aggregate( [{'$match': {'validFrom':", "time self.reset_counter = 0 random.shuffle(self.random_social_post_list) post = self.random_social_post_list[self.reset_counter] self.reset_counter =", "self.db.storeAccessToken.find_one({'source': access_token}) if existing_dict is None: identifier = {'access_token': access_token,", "self.client.admin.command('ismaster') except ConnectionFailure: print(\"Server not available\") if MongoDBClient.__instance != None:", "when we went through all posts once we reset counter", "SocialPost() custom_post_item.set_dictionary(post) social_post_list.append(custom_post_item) return social_post_list def delete_post(self, external_id): removed =", "posts every time self.reset_counter = 0 random.shuffle(self.random_social_post_list) post = self.random_social_post_list[self.reset_counter]", "import MongoClient from pymongo.errors import ConnectionFailure from tarentsocialwall.SocialPost import SocialPost", "= SocialPost() custom_post_item.set_dictionary(post) social_post_list.append(custom_post_item) return social_post_list def delete_post(self, external_id): removed", "print(removed) def write_access_token(self, access_token, source): existing_dict = self.db.storeAccessToken.find_one({'source': access_token}) if", "datetime.utcnow().timestamp() doc = list(self.db.socialPosts.aggregate([ {'$match': {'validFrom': {'$lte': timestamp_var}, 'validTo': {'$gte':", "custom social_post from mongo def get_custom_social_post(self): doc = list(self.db.socialPosts.aggregate([{'$match': {'source':", "custom_post_item = SocialPost() custom_post_item.set_dictionary(post) social_post_list.append(custom_post_item) return social_post_list def get_users(self): users_db", "reset counter and shuffle list # so we dont repeat", "does not require auth. self.client.admin.command('ismaster') except ConnectionFailure: print(\"Server not available\")", "social_post.__dict__) return 0 # read random social_post from list def", "return social_post_list def delete_post(self, external_id): removed = self.db.socialPosts.delete_one({'externalId': external_id}) print(removed)", "= self.db.storeAccessToken.find_one({'source': source}) return existing_dict def get_google_calendar_posts(self): timestamp_var = datetime.utcnow().timestamp()", "calendar'}}, {'$sort': {'start': 1}} ])) if doc is None: return", "source} self.db.storeAccessToken.replace_one(update_identifier, access_token) return 0 def read_access_token(self, source): existing_dict =", "mongo def write_social_post(self, social_post: SocialPost): existing_dict = None try: existing_dict", "self.db = self.client.socialPosts try: # The ismaster command is cheap", "0: return None else: if self.reset_counter >= len(self.random_social_post_list): # when", "self.client.socialPosts try: # The ismaster command is cheap and does", "self.db.socialPosts.find_one({'externalId': social_post.externalId}) except Exception as ex: print(ex) existing_dict = None", "return None social_post = SocialPost() social_post.set_dictionary(post) return social_post # read", "self.db.socialPosts.delete_one({'externalId': external_id}) print(removed) def write_access_token(self, access_token, source): existing_dict = self.db.storeAccessToken.find_one({'source':", "removed = self.db.socialPosts.delete_one({'externalId': external_id}) print(removed) def write_access_token(self, access_token, source): existing_dict", "class MongoDBClient: __instance = None @staticmethod def getInstance(): \"\"\" Static", "self.db.socialPosts.replace_one(update_identifier, social_post.__dict__) return 0 # read random social_post from list", "None else: if self.reset_counter >= len(self.random_social_post_list): # when we went", "random from datetime import datetime from passlib.handlers.sha2_crypt import sha256_crypt from", "= MongoClient(uri) self.db = self.client.socialPosts try: # The ismaster command", "return 0 def delete_user(self, user: User): self.db.socialwall_users.delete_one({'username': user['username']}) def init_admin(self):", "return None social_post_list = [] for post in doc: custom_post_item", "= self.reset_counter + 1 print(post) if post is None: return", "is a singleton!\") else: MongoDBClient.__instance = self self.update_all_socialposts() # write", "except ConnectionFailure: print(\"Server not available\") if MongoDBClient.__instance != None: raise", "# so we dont repeat the same circle of posts", "= None db = None random_social_post_list = None reset_counter =", "from tarentsocialwall.SocialPost import SocialPost from tarentsocialwall.User import User from tarentsocialwall.Util", "if existing_dict is None: identifier = {'access_token': access_token, 'source': source}", "tarentsocialwall.SocialPost import SocialPost from tarentsocialwall.User import User from tarentsocialwall.Util import", "def getInstance(): \"\"\" Static access method. \"\"\" if MongoDBClient.__instance ==", "users_db: if item['username'] is not 'admin': user = User() user.set_dictionary(item)", "connection string self.client = MongoClient(uri) self.db = self.client.socialPosts try: #", "access method. \"\"\" if MongoDBClient.__instance == None: MongoDBClient() client =", "social_post_list def get_users(self): users_db = list(self.db.socialwall_users.find()) if users_db is None:", "reset_counter = None def __init__(self, uri): # connect to MongoDB,", "social_post_list = [] for post in doc: custom_post_item = SocialPost()", "password is '%s'\" % random_string) user.firstname = 'admin' user.lastname =", "so we dont repeat the same circle of posts every", "-> SocialPost: if len(self.random_social_post_list) == 0: return None else: if", "self.db.socialwall_users.insert_one(user.__dict__) else: update_identifier = {'username': user.username} self.db.socialwall_users.replace_one(update_identifier, user.__dict__) return 0", "item in users_db: if item['username'] is not 'admin': user =", "user = User() user.username = 'admin' user.password = <PASSWORD>(<PASSWORD>) print(\"Admin", "in doc: custom_post_item = SocialPost() custom_post_item.set_dictionary(post) social_post_list.append(custom_post_item) return social_post_list def", "= User() user.username = 'admin' user.password = <PASSWORD>(<PASSWORD>) print(\"Admin password", "if MongoDBClient.__instance == None: MongoDBClient() client = None db =", "= <PASSWORD>(<PASSWORD>) print(\"Admin password is '%s'\" % random_string) user.firstname =", "# The ismaster command is cheap and does not require", "doc: custom_post_item = SocialPost() custom_post_item.set_dictionary(post) social_post_list.append(custom_post_item) return social_post_list def get_users(self):", "update_identifier = {'access_token': access_token, 'source': source} self.db.storeAccessToken.replace_one(update_identifier, access_token) return 0", "users.append(user) return users def read_user(self, username): return self.db.socialwall_users.find_one({'username': username}) def", "return 0 def read_access_token(self, source): existing_dict = self.db.storeAccessToken.find_one({'source': source}) return", "client = None db = None random_social_post_list = None reset_counter", "timestamp_var}, 'validTo': {'$gte': timestamp_var}, 'source': 'Google calendar'}}, {'$sort': {'start': 1}}", "a singleton!\") else: MongoDBClient.__instance = self self.update_all_socialposts() # write social_post", "same circle of posts every time self.reset_counter = 0 random.shuffle(self.random_social_post_list)", "to reflect your own connection string self.client = MongoClient(uri) self.db", "datetime import datetime from passlib.handlers.sha2_crypt import sha256_crypt from pymongo import", "None: self.db.socialPosts.insert_one(social_post.__dict__) else: update_identifier = {'externalId': social_post.externalId, 'source': social_post.source} self.db.socialPosts.replace_one(update_identifier,", "datetime.utcnow().timestamp() self.random_social_post_list = list(self.db.socialPosts.aggregate( [{'$match': {'validFrom': {'$lte': timestamp}, 'validTo': {'$gte':", "'validTo': {'$gte': timestamp_var}, 'source': 'Google calendar'}}, {'$sort': {'start': 1}} ]))", "existing_dict is None: identifier = {'access_token': access_token, 'source': source} self.db.storeAccessToken.insert_one(identifier)", "= list(self.db.socialPosts.aggregate([ {'$match': {'validFrom': {'$lte': timestamp_var}, 'validTo': {'$gte': timestamp_var}, 'source':", "print(\"Admin password is '%s'\" % random_string) user.firstname = 'admin' user.lastname", "= None try: existing_dict = self.db.socialPosts.find_one({'externalId': social_post.externalId}) except Exception as", "self.db.storeAccessToken.insert_one(identifier) else: update_identifier = {'access_token': access_token, 'source': source} self.db.storeAccessToken.replace_one(update_identifier, access_token)", "username_dict = self.db.socialwall_users.find_one({'username': user.username}) if username_dict is None: self.db.socialwall_users.insert_one(user.__dict__) else:", "MongoDBClient.__instance = self self.update_all_socialposts() # write social_post into mongo def", "user.set_dictionary(item) users.append(user) return users def read_user(self, username): return self.db.socialwall_users.find_one({'username': username})", "'custom post'}}])) print(list(doc)) if doc is None: return None social_post_list", "{'access_token': access_token, 'source': source} self.db.storeAccessToken.insert_one(identifier) else: update_identifier = {'access_token': access_token,", "social_post from list def get_random_social_post(self) -> SocialPost: if len(self.random_social_post_list) ==", "ismaster command is cheap and does not require auth. self.client.admin.command('ismaster')", "and does not require auth. self.client.admin.command('ismaster') except ConnectionFailure: print(\"Server not", "we went through all posts once we reset counter and", "read custom social_post from mongo def get_custom_social_post(self): doc = list(self.db.socialPosts.aggregate([{'$match':", "external_id): removed = self.db.socialPosts.delete_one({'externalId': external_id}) print(removed) def write_access_token(self, access_token, source):", "import datetime from passlib.handlers.sha2_crypt import sha256_crypt from pymongo import MongoClient", "in random order def update_all_socialposts(self): timestamp = datetime.utcnow().timestamp() self.random_social_post_list =", "if item['username'] is not 'admin': user = User() user.set_dictionary(item) users.append(user)", "MongoClient(uri) self.db = self.client.socialPosts try: # The ismaster command is", "{'start': 1}} ])) if doc is None: return None social_post_list", "else: update_identifier = {'access_token': access_token, 'source': source} self.db.storeAccessToken.replace_one(update_identifier, access_token) return", "every time self.reset_counter = 0 random.shuffle(self.random_social_post_list) post = self.random_social_post_list[self.reset_counter] self.reset_counter", "Exception as ex: print(ex) existing_dict = None if existing_dict is", "try: # The ismaster command is cheap and does not", "not 'admin': user = User() user.set_dictionary(item) users.append(user) return users def", "# when we went through all posts once we reset", "from passlib.handlers.sha2_crypt import sha256_crypt from pymongo import MongoClient from pymongo.errors", "went through all posts once we reset counter and shuffle", "if post is None: return None social_post = SocialPost() social_post.set_dictionary(post)", "= 0 random.shuffle(self.random_social_post_list) post = self.random_social_post_list[self.reset_counter] self.reset_counter = self.reset_counter +", "users def read_user(self, username): return self.db.socialwall_users.find_one({'username': username}) def write_user(self, user:", "your own connection string self.client = MongoClient(uri) self.db = self.client.socialPosts", "SocialPost() social_post.set_dictionary(post) return social_post # read custom social_post from mongo", "dont repeat the same circle of posts every time self.reset_counter", "from db and shuffle them in random order def update_all_socialposts(self):", "existing_dict = None if existing_dict is None: self.db.socialPosts.insert_one(social_post.__dict__) else: update_identifier", "list # so we dont repeat the same circle of", "None if existing_dict is None: self.db.socialPosts.insert_one(social_post.__dict__) else: update_identifier = {'externalId':", "None db = None random_social_post_list = None reset_counter = None", "== 0: return None else: if self.reset_counter >= len(self.random_social_post_list): #", "0 # read random social_post from list def get_random_social_post(self) ->", "access_token}) if existing_dict is None: identifier = {'access_token': access_token, 'source':", "User() user.set_dictionary(item) users.append(user) return users def read_user(self, username): return self.db.socialwall_users.find_one({'username':", "passlib.handlers.sha2_crypt import sha256_crypt from pymongo import MongoClient from pymongo.errors import", "MongoDBClient.__instance == None: MongoDBClient() client = None db = None", "counter and shuffle list # so we dont repeat the", "the << MONGODB URL >> to reflect your own connection", "def read_access_token(self, source): existing_dict = self.db.storeAccessToken.find_one({'source': source}) return existing_dict def", "self.db.storeAccessToken.replace_one(update_identifier, access_token) return 0 def read_access_token(self, source): existing_dict = self.db.storeAccessToken.find_one({'source':", "random_social_post_list = None reset_counter = None def __init__(self, uri): #", "identifier = {'access_token': access_token, 'source': source} self.db.storeAccessToken.insert_one(identifier) else: update_identifier =", "self.client = MongoClient(uri) self.db = self.client.socialPosts try: # The ismaster", "from mongo def get_custom_social_post(self): doc = list(self.db.socialPosts.aggregate([{'$match': {'source': 'custom post'}}]))", "uri): # connect to MongoDB, change the << MONGODB URL", "MONGODB URL >> to reflect your own connection string self.client", "source} self.db.storeAccessToken.insert_one(identifier) else: update_identifier = {'access_token': access_token, 'source': source} self.db.storeAccessToken.replace_one(update_identifier,", "self.db.socialwall_users.find_one({'username': user.username}) if username_dict is None: self.db.socialwall_users.insert_one(user.__dict__) else: update_identifier =", "read_user(self, username): return self.db.socialwall_users.find_one({'username': username}) def write_user(self, user: User): username_dict", "None social_post_list = [] for post in doc: custom_post_item =", "user.__dict__) return 0 def delete_user(self, user: User): self.db.socialwall_users.delete_one({'username': user['username']}) def", "None reset_counter = None def __init__(self, uri): # connect to", "update_identifier = {'externalId': social_post.externalId, 'source': social_post.source} self.db.socialPosts.replace_one(update_identifier, social_post.__dict__) return 0", "import SocialPost from tarentsocialwall.User import User from tarentsocialwall.Util import Util", "<PASSWORD>(<PASSWORD>) print(\"Admin password is '%s'\" % random_string) user.firstname = 'admin'", "MongoClient from pymongo.errors import ConnectionFailure from tarentsocialwall.SocialPost import SocialPost from", "once we reset counter and shuffle list # so we", "user = User() user.set_dictionary(item) users.append(user) return users def read_user(self, username):", "social_post: SocialPost): existing_dict = None try: existing_dict = self.db.socialPosts.find_one({'externalId': social_post.externalId})", "User() user.username = 'admin' user.password = <PASSWORD>(<PASSWORD>) print(\"Admin password is", "# read random social_post from list def get_random_social_post(self) -> SocialPost:", "username_dict is None: self.db.socialwall_users.insert_one(user.__dict__) else: update_identifier = {'username': user.username} self.db.socialwall_users.replace_one(update_identifier,", "self.reset_counter + 1 print(post) if post is None: return None", "def read_user(self, username): return self.db.socialwall_users.find_one({'username': username}) def write_user(self, user: User):", "raise Exception(\"This class is a singleton!\") else: MongoDBClient.__instance = self", "= [] for post in doc: custom_post_item = SocialPost() custom_post_item.set_dictionary(post)", "access_token) return 0 def read_access_token(self, source): existing_dict = self.db.storeAccessToken.find_one({'source': source})", "import ConnectionFailure from tarentsocialwall.SocialPost import SocialPost from tarentsocialwall.User import User", "cheap and does not require auth. self.client.admin.command('ismaster') except ConnectionFailure: print(\"Server", "user.lastname = 'admin' self.write_user(user) #Get all valid social posts from", "1 print(post) if post is None: return None social_post =", "'source': 'Google calendar'}}, {'$sort': {'start': 1}} ])) if doc is", "list(self.db.socialPosts.aggregate([ {'$match': {'validFrom': {'$lte': timestamp_var}, 'validTo': {'$gte': timestamp_var}, 'source': 'Google", "self.random_social_post_list[self.reset_counter] self.reset_counter = self.reset_counter + 1 print(post) if post is", "None: return None social_post_list = [] for post in doc:", "Exception(\"This class is a singleton!\") else: MongoDBClient.__instance = self self.update_all_socialposts()", "get_users(self): users_db = list(self.db.socialwall_users.find()) if users_db is None: return None", "is None: self.db.socialwall_users.insert_one(user.__dict__) else: update_identifier = {'username': user.username} self.db.socialwall_users.replace_one(update_identifier, user.__dict__)", "print(\"Server not available\") if MongoDBClient.__instance != None: raise Exception(\"This class", "[] for post in doc: custom_post_item = SocialPost() custom_post_item.set_dictionary(post) social_post_list.append(custom_post_item)", "def delete_user(self, user: User): self.db.socialwall_users.delete_one({'username': user['username']}) def init_admin(self): random_string =", "social_post # read custom social_post from mongo def get_custom_social_post(self): doc", "list def get_random_social_post(self) -> SocialPost: if len(self.random_social_post_list) == 0: return", "own connection string self.client = MongoClient(uri) self.db = self.client.socialPosts try:", "existing_dict = None try: existing_dict = self.db.socialPosts.find_one({'externalId': social_post.externalId}) except Exception", "None: return None users = [] for item in users_db:", "user.username} self.db.socialwall_users.replace_one(update_identifier, user.__dict__) return 0 def delete_user(self, user: User): self.db.socialwall_users.delete_one({'username':", "tarentsocialwall.User import User from tarentsocialwall.Util import Util class MongoDBClient: __instance", "all valid social posts from db and shuffle them in", "= None if existing_dict is None: self.db.socialPosts.insert_one(social_post.__dict__) else: update_identifier =", "source}) return existing_dict def get_google_calendar_posts(self): timestamp_var = datetime.utcnow().timestamp() doc =", "users_db = list(self.db.socialwall_users.find()) if users_db is None: return None users", "is None: return None social_post = SocialPost() social_post.set_dictionary(post) return social_post", "social_post_list def delete_post(self, external_id): removed = self.db.socialPosts.delete_one({'externalId': external_id}) print(removed) def", "posts from db and shuffle them in random order def", "# connect to MongoDB, change the << MONGODB URL >>", "= datetime.utcnow().timestamp() self.random_social_post_list = list(self.db.socialPosts.aggregate( [{'$match': {'validFrom': {'$lte': timestamp}, 'validTo':", "except Exception as ex: print(ex) existing_dict = None if existing_dict", "None: MongoDBClient() client = None db = None random_social_post_list =", "change the << MONGODB URL >> to reflect your own", "delete_user(self, user: User): self.db.socialwall_users.delete_one({'username': user['username']}) def init_admin(self): random_string = Util.randomString()", "<filename>tarentsocialwall/MongoDBClient.py import random from datetime import datetime from passlib.handlers.sha2_crypt import", "all posts once we reset counter and shuffle list #", "repeat the same circle of posts every time self.reset_counter =", "{'externalId': social_post.externalId, 'source': social_post.source} self.db.socialPosts.replace_one(update_identifier, social_post.__dict__) return 0 # read", ">> to reflect your own connection string self.client = MongoClient(uri)", "= {'username': user.username} self.db.socialwall_users.replace_one(update_identifier, user.__dict__) return 0 def delete_user(self, user:", "'admin' user.lastname = 'admin' self.write_user(user) #Get all valid social posts", "doc = list(self.db.socialPosts.aggregate([ {'$match': {'validFrom': {'$lte': timestamp_var}, 'validTo': {'$gte': timestamp_var},", "string self.client = MongoClient(uri) self.db = self.client.socialPosts try: # The", "random.shuffle(self.random_social_post_list) post = self.random_social_post_list[self.reset_counter] self.reset_counter = self.reset_counter + 1 print(post)", "try: existing_dict = self.db.socialPosts.find_one({'externalId': social_post.externalId}) except Exception as ex: print(ex)", "{'validFrom': {'$lte': timestamp_var}, 'validTo': {'$gte': timestamp_var}, 'source': 'Google calendar'}}, {'$sort':", "timestamp_var = datetime.utcnow().timestamp() doc = list(self.db.socialPosts.aggregate([ {'$match': {'validFrom': {'$lte': timestamp_var},", "{'$match': {'validFrom': {'$lte': timestamp_var}, 'validTo': {'$gte': timestamp_var}, 'source': 'Google calendar'}},", "social_post.externalId}) except Exception as ex: print(ex) existing_dict = None if", "__instance = None @staticmethod def getInstance(): \"\"\" Static access method.", "get_google_calendar_posts(self): timestamp_var = datetime.utcnow().timestamp() doc = list(self.db.socialPosts.aggregate([ {'$match': {'validFrom': {'$lte':", "None: self.db.socialwall_users.insert_one(user.__dict__) else: update_identifier = {'username': user.username} self.db.socialwall_users.replace_one(update_identifier, user.__dict__) return", "import User from tarentsocialwall.Util import Util class MongoDBClient: __instance =", "= None @staticmethod def getInstance(): \"\"\" Static access method. \"\"\"", "pymongo import MongoClient from pymongo.errors import ConnectionFailure from tarentsocialwall.SocialPost import", "is not 'admin': user = User() user.set_dictionary(item) users.append(user) return users", "= {'access_token': access_token, 'source': source} self.db.storeAccessToken.replace_one(update_identifier, access_token) return 0 def", "= list(self.db.socialPosts.aggregate( [{'$match': {'validFrom': {'$lte': timestamp}, 'validTo': {'$gte': timestamp}}}])) random.shuffle(self.random_social_post_list)", "None def __init__(self, uri): # connect to MongoDB, change the", "list(self.db.socialwall_users.find()) if users_db is None: return None users = []", "if doc is None: return None social_post_list = [] for", "username}) def write_user(self, user: User): username_dict = self.db.socialwall_users.find_one({'username': user.username}) if", "None social_post = SocialPost() social_post.set_dictionary(post) return social_post # read custom", "reflect your own connection string self.client = MongoClient(uri) self.db =", "custom_post_item.set_dictionary(post) social_post_list.append(custom_post_item) return social_post_list def delete_post(self, external_id): removed = self.db.socialPosts.delete_one({'externalId':", "0 def read_access_token(self, source): existing_dict = self.db.storeAccessToken.find_one({'source': source}) return existing_dict", "to MongoDB, change the << MONGODB URL >> to reflect", "existing_dict = self.db.socialPosts.find_one({'externalId': social_post.externalId}) except Exception as ex: print(ex) existing_dict", "{'$lte': timestamp_var}, 'validTo': {'$gte': timestamp_var}, 'source': 'Google calendar'}}, {'$sort': {'start':", "user.firstname = 'admin' user.lastname = 'admin' self.write_user(user) #Get all valid", "{'username': user.username} self.db.socialwall_users.replace_one(update_identifier, user.__dict__) return 0 def delete_user(self, user: User):", "random order def update_all_socialposts(self): timestamp = datetime.utcnow().timestamp() self.random_social_post_list = list(self.db.socialPosts.aggregate(", "doc is None: return None social_post_list = [] for post", "= User() user.set_dictionary(item) users.append(user) return users def read_user(self, username): return", "User from tarentsocialwall.Util import Util class MongoDBClient: __instance = None", "= self.random_social_post_list[self.reset_counter] self.reset_counter = self.reset_counter + 1 print(post) if post", "'source': source} self.db.storeAccessToken.insert_one(identifier) else: update_identifier = {'access_token': access_token, 'source': source}" ]
[ "that the DNS name of the mount target matches exactly", "= url_request_helper(INSTANCE_IAM_URL, iam_role_unsuccessful_resp, iam_role_url_error_msg, retry_with_new_header_token=True) return iam_role_name def credentials_file_helper(file_path, awsprofile):", "# SigV4 Auth ALGORITHM = 'AWS4-HMAC-SHA256' AWS4_REQUEST = 'aws4_request' HTTP_REQUEST_METHOD", "e) return path.strip().decode() def get_system_release_version(): try: with open(SYSTEM_RELEASE_PATH) as f:", "reason is %s' % (url, e.code, e.reason) except URLError as", "multi-threading support in openssl 'database_dir': os.path.join(base_path, mount_name, 'database'), 'certs_dir': os.path.join(base_path,", "= 'http://169.254.169.254/latest/api/token' INSTANCE_METADATA_SERVICE_URL = 'http://169.254.169.254/latest/dynamic/instance-identity/document/' INSTANCE_IAM_URL = 'http://169.254.169.254/latest/meta-data/iam/security-credentials/' SECURITY_CREDS_ECS_URI_HELP_URL =", "raise Exception('Region not found in dns_name_format') def get_aws_ec2_metadata_token(): try: opener", "k in CREDENTIALS_KEYS): return iam_security_dict, 'metadata:' else: return None, None", "credential, formatted_datetime, session_token) + '\\n' request += CANONICAL_HEADERS % fs_id", "awsprofile and use_iam: for file_path in [AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE]: aws_credentials_configs =", "-outform PEM -pubout -out %s' % (private_key, public_key) subprocess_call(cmd, 'Failed", "log stream %s does not exist, %s' % (cloudwatchlog_agent.get('log_group_name'), cloudwatchlog_agent.get('log_stream_name'),", "% (property, instance_identity, e)) except TypeError as e: logging.warning('response %s", "current_time + timedelta(**kwargs) return updated_time.strftime(CERT_DATETIME_FORMAT) def get_utc_now(): \"\"\" Wrapped for", "to the EFS documentation for mounting with DNS names for", "from urllib2 import URLError, HTTPError, build_opener, urlopen, Request, HTTPHandler from", "os.path.join(state_file_dir, temp_tls_state_file[1:])) def get_nfs_mount_options(options): # If you change these options,", "open(os.devnull, 'w') as devnull: subprocess.Popen(['systemctl', 'start', WATCHDOG_SERVICE], stdout=devnull, stderr=devnull, close_fds=True)", "found in config file and metadata service call failed, falling", "'/var/run/efs' PRIVATE_KEY_FILE = '/etc/amazon/efs/privateKey.pem' DATE_ONLY_FORMAT = '%Y%m%d' SIGV4_DATETIME_FORMAT = '%Y%m%dT%H%M%SZ'", "[ local_ca ] database = $dir/database/index.txt serial = $dir/database/serial private_key", "logging.debug('Identified init system: %s', init_system) return init_system def check_network_target(fs_id): with", "Serializes stunnel configuration to a file. Unfortunately this does not", "% (log_group_name, e.response)) return True elif exception == 'LimitExceededException': logging.error('Reached", "mount.log' % (fs_id) else: log_stream_name = 'default - mount.log' return", "options def get_client_info(config): client_info = {} # source key/value pair", "key = key[offset:] sha1 = hashlib.sha1() sha1.update(key) return sha1.hexdigest() def", "mutually exclusive') if 'tlsport' in options: try: int(options['tlsport']) except ValueError:", "elif exception == 'UnrecognizedClientException': logging.debug('The most likely cause is an", "(e.g. for IAM Role for Service Accounts (IRSA) approach on", "cloudwatchlog_agent.get('client').describe_log_streams( logGroupName=cloudwatchlog_agent.get('log_group_name'), logStreamNamePrefix=cloudwatchlog_agent.get('log_stream_name') ) def get_log_stream_next_token(cloudwatchlog_agent): try: response = cloudwatch_describe_log_streams_helper(cloudwatchlog_agent)", "reach %s to retrieve AWS security credentials. See %s for", "try: mode = int(mode_str, 8) except ValueError: logging.warning('Bad state_file_dir_mode \"%s\"", "def get_mount_specific_filename(fs_id, mountpoint, tls_port): return '%s.%s.%d' % (fs_id, os.path.abspath(mountpoint).replace(os.sep, '.').lstrip('.'),", "resp_body if resp_body_type is str else resp_body.decode('utf-8') def parse_options(options): opts", "found in %s', file_path) credentials['AccessKeyId'] = aws_credentials_configs.get(awsprofile, 'aws_access_key_id') credentials['SecretAccessKey'] =", "ECS agent generated if aws_creds_uri: return get_aws_security_credentials_from_ecs(aws_creds_uri, True) # attempt", "p.read(config_file) return p def bootstrap_logging(config, log_dir=LOG_DIR): raw_level = config.get(CONFIG_SECTION, 'logging_level')", "Canonical Request - https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html \"\"\" formatted_datetime = date.strftime(SIGV4_DATETIME_FORMAT) credential =", "request, %s' % error.response) elif exception == 'AccessDeniedException': logging.debug('User is", "'rsize' not in options: options['rsize'] = '1048576' if 'wsize' not", "check_if_cloudwatch_log_enabled(config): if config.has_option(CLOUDWATCH_LOG_SECTION, 'enabled'): return config.getboolean(CLOUDWATCH_LOG_SECTION, 'enabled') return False def", "\"%s\" - check that your file system ID is correct.\\nSee", "%s is malformed' % options['accesspoint']) if 'iam' in options and", "reach the url at %s, reason is %s' % (url,", "openssl ca and req files if they're not present in", "openssl 'database_dir': os.path.join(base_path, mount_name, 'database'), 'certs_dir': os.path.join(base_path, mount_name, 'certs'), 'index':", "return None, None def get_aws_security_credentials_from_webidentity(role_arn, token_file, is_fatal=False): try: with open(token_file,", "return True def cloudwatch_create_log_stream_helper(cloudwatchlog_client, log_group_name, log_stream_name): cloudwatchlog_client.create_log_stream( logGroupName=log_group_name, logStreamName=log_stream_name )", "exist, %s' % (log_group_name, e.response)) return False else: handle_general_botocore_exceptions(e) return", "check_host_supported = is_stunnel_option_supported(stunnel_output, b'checkHost') ocsp_aia_supported = is_stunnel_option_supported(stunnel_output, b'OCSPaia') return check_host_supported,", "def check_and_create_private_key(base_path=STATE_FILE_DIR): # Creating RSA private keys is slow, so", "mounting via \"accesspoint\"') if not AP_ID_RE.match(options['accesspoint']): fatal_error('Access Point ID %s", "octets are the length - \"definite form\" # - the", "+ num_length_octets), and number of unused bits (1) offset =", "os.path.ismount(mountpoint) and is_nfs_mount(mountpoint): sys.stdout.write(\"%s is already mounted, please run 'mount'", "the url at %s: status=%d, reason is %s' % (url,", "%s under named profile [%s]', file_path, awsprofile) if 'aws_session_token' in", "= True t.start() mount_nfs(dns_name, path, mountpoint, options) mount_completed.set() t.join() def", "HTTP_REQUEST_METHOD = 'GET' CANONICAL_URI = '/' CANONICAL_HEADERS_DICT = { 'host':", "fatal_error(unsuccessful_resp, unsuccessful_resp) else: return None, None webidentity_url = STS_ENDPOINT_URL +", "% (str(k), str(v)) nfs_options = [to_nfs_option(k, v) for k, v", "= 'http://169.254.169.254/latest/meta-data/iam/security-credentials/' SECURITY_CREDS_ECS_URI_HELP_URL = 'https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html' SECURITY_CREDS_WEBIDENTITY_HELP_URL = 'https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html' SECURITY_CREDS_IAM_ROLE_HELP_URL =", "(STS_ENDPOINT_URL, SECURITY_CREDS_WEBIDENTITY_HELP_URL) resp = url_request_helper(webidentity_url, unsuccessful_resp, url_error_msg, headers={'Accept': 'application/json'}) if", "in unit tests\"\"\" return PRIVATE_KEY_FILE def check_and_create_private_key(base_path=STATE_FILE_DIR): # Creating RSA", "logging.error('Log group name %s is specified incorrectly, %s' % (log_group_name,", "Key, %s' % e.response) return False elif exception == 'ResourceNotFoundException':", "\"%s\"' % dns_name) return dns_name def tls_paths_dictionary(mount_name, base_path=STATE_FILE_DIR): tls_dict =", "tunnel_proc.returncode is not None: out, err = tunnel_proc.communicate() fatal_error('Failed to", "'noocsp' in options: return False else: return config.getboolean(CONFIG_SECTION, 'stunnel_check_cert_validity') def", "kwargs['sequenceToken'] = token cloudwatchlog_agent.get('client').put_log_events(**kwargs) def publish_cloudwatch_log(cloudwatchlog_agent, message): if not cloudwatchlog_agent", "credentials def get_aws_profile(options, use_iam): awsprofile = options.get('awsprofile') if not awsprofile", "fs_id, mountpoint, options, state_file_dir=STATE_FILE_DIR): tls_port = choose_tls_port(config, options) # override", "error) def main(): parse_arguments_early_exit() assert_root() config = read_config() bootstrap_logging(config) fs_id,", "exit uncleanly with os._exit \"\"\" while not mount_completed.is_set(): try: test_tunnel_process(tunnel_proc,", "this will just re-set tlsport to X. options['tlsport'] = tls_port", "= 'no' stunnel_config = '\\n'.join(serialize_stunnel_config(global_config) + serialize_stunnel_config(efs_config, 'efs')) logging.debug('Writing stunnel", "None def get_aws_security_credentials_from_instance_metadata(iam_role_name): security_creds_lookup_url = INSTANCE_IAM_URL + iam_role_name unsuccessful_resp =", "security_credentials = None client_info = get_client_info(config) if use_iam: aws_creds_uri =", "# # sudo mount /mount_point # # The script will", "as f: f.write(stunnel_config) return stunnel_config_file def write_tls_tunnel_state_file(fs_id, mountpoint, tls_port, tunnel_pid,", "= {} # source key/value pair in config file if", "\"%s\"', mode_str, CONFIG_FILE) except NoOptionError: pass try: os.makedirs(directory, mode) except", "SUSE_RELEASE_NAME] def fatal_error(user_message, log_message=None, exit_code=1): if log_message is None: log_message", "we have to include a locking mechanism to ensure that", "config file if config.has_option(CLIENT_INFO_SECTION, 'source'): client_source = config.get(CLIENT_INFO_SECTION, 'source') if", "WATCHDOG_SERVICE], stdout=devnull, stderr=devnull, close_fds=True) else: logging.debug('%s is already running', WATCHDOG_SERVICE)", "section in current file and return 'default' if so try:", "security_credentials['Token']) if security_credentials else '' efs_client_info_body = efs_client_info_builder(client_info) if client_info", "open_lock_file(): lock_file = os.path.join(base_path, 'efs-utils-lock') f = os.open(lock_file, os.O_CREAT |", "'https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html' DEFAULT_STUNNEL_VERIFY_LEVEL = 2 DEFAULT_STUNNEL_CAFILE = '/etc/amazon/efs/efs-utils.crt' NOT_BEFORE_MINS = 15", "the override is not set if ocsp_enabled: if ocsp_aia_supported: efs_config['OCSPaia']", "-out %s' % \\ (not_before, not_after, certificate_config, certificate_signing_request, certificate) subprocess_call(cmd,", "sock.bind(('localhost', tls_port)) sock.close() return tls_port except socket.error: continue sock.close() if", "prefixed with a '~'. This file needs to be renamed", "name, by adding it # to /etc/fstab. The syntax of", "- %(levelname)s - %(message)s')) logger = logging.getLogger() logger.setLevel(level) logger.addHandler(handler) if", "init_system): if init_system != 'systemd': logging.debug('Not testing network on non-systemd", "= write_stunnel_config_file(config, state_file_dir, fs_id, mountpoint, tls_port, dns_name, verify_level, ocsp_enabled, options,", "mount.log' return log_stream_name def check_if_cloudwatch_log_enabled(config): if config.has_option(CLOUDWATCH_LOG_SECTION, 'enabled'): return config.getboolean(CLOUDWATCH_LOG_SECTION,", "with open(stunnel_config_file, 'w') as f: f.write(stunnel_config) return stunnel_config_file def write_tls_tunnel_state_file(fs_id,", "fs_id): tunnel_proc.poll() if tunnel_proc.returncode is not None: out, err =", "exit_code=0) def check_network_status(fs_id, init_system): if init_system != 'systemd': logging.debug('Not testing", "CLIENT_SOURCE_STR_LEN_LIMIT: client_info['source'] = client_source return client_info def create_certificate(config, mount_name, common_name,", "full_config_body = CA_CONFIG_BODY % (directory, private_key, common_name, ca_extension_body, efs_client_auth_body, efs_client_info_body)", "elif 'start' in status: logging.debug('%s is already running', WATCHDOG_SERVICE) elif", "exited already pass else: return output, err error_message = '%s,", "if not cloudwatchlog_client: return None cloudwatchlog_config = get_cloudwatchlog_config(config, fs_id) log_group_name", "if 'ocsp' in options and 'noocsp' in options: fatal_error('The \"ocsp\"", "e: if errno.EEXIST != e.errno or not os.path.isdir(directory): raise @contextmanager", "return True def cloudwatch_put_retention_policy_helper(cloudwatchlog_client, log_group_name, retention_days): cloudwatchlog_client.put_retention_policy( logGroupName=log_group_name, retentionInDays=retention_days )", "tls_paths['serial'], tls_paths['rand']) private_key = check_and_create_private_key(base_path) if security_credentials: public_key = os.path.join(tls_paths['mount_dir'],", "if args is None: args = sys.argv fsname = None", "[Options] [Dump] [Pass] # # Add an entry like this:", "the DNS name of the mount target matches exactly the", "= {'fs_id': fs_id} expected_replacement_field_ct = 1 if '{region}' in dns_name_format:", "output, err = subprocess_call(cmd, 'Unable to ASN1 parse public key", "main thread, if the tunnel fails, exit uncleanly with os._exit", "= { 'mount_dir': os.path.join(base_path, mount_name), # every mount will have", "Linux release 8' FEDORA_RELEASE_NAME = 'Fedora release' SUSE_RELEASE_NAME = 'openSUSE", "in options: ports_to_try = [int(options['tlsport'])] else: lower_bound, upper_bound = get_tls_port_range(config)", "tunnel_proc.communicate() fatal_error('Failed to initialize TLS tunnel for %s' % fs_id,", "fs_id) except SystemExit as e: os._exit(e.code) mount_completed.wait(.5) def get_init_system(comm_file='/proc/1/comm'): init_system", "byte offset = int(key_line.split(':')[0]) key = key[offset:] num_length_octets = key[1]", "first octet always has the high order bit (8) set", "in their respective directories\"\"\" if not os.path.isfile(index_path): open(index_path, 'w').close() if", "DER encoding TLV (Tag, Length, Value) # - the first", "= 'AWS_CONTAINER_CREDENTIALS_RELATIVE_URI' ECS_TASK_METADATA_API = 'http://169.254.170.2' WEB_IDENTITY_ROLE_ARN_ENV = 'AWS_ROLE_ARN' WEB_IDENTITY_TOKEN_FILE_ENV =", "ecs_uri ecs_url_error_msg = 'Unable to reach %s to retrieve AWS", "= calculate_signature(string_to_sign, date, secret_access_key, region) efs_client_auth_str = '[ efs_client_auth ]'", "as e: if e.errno == errno.EEXIST: logging.info('Failed to take out", "= 'unknown' try: with open(comm_file) as f: init_system = f.read().strip()", "= hashlib.sha256() sha256.update(REQUEST_PAYLOAD.encode()) request += sha256.hexdigest() return request def create_canonical_query_string(public_key_hash,", "are the \"value\" aka content # # For a BIT", "credentials. See %s for more info.' \\ % (ecs_uri, SECURITY_CREDS_ECS_URI_HELP_URL)", "from contextlib import contextmanager from datetime import datetime, timedelta from", "close_fds=True) out, err = proc.communicate() if proc.returncode == 0: message", "NoOptionError: pass try: return get_region_from_instance_metadata() except Exception as e: metadata_exception", "'soft' not in options and 'hard' not in options: options['hard']", "= subprocess.Popen( ['/sbin/status', WATCHDOG_SERVICE], stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) status, _ =", "close_fds=True) proc.wait() _, err = proc.communicate() stunnel_output = err.splitlines() check_host_supported", "role name. See %s for more info.' % \\ (INSTANCE_IAM_URL,", "(str(resp_body), e)) return resp_body if resp_body_type is str else resp_body.decode('utf-8')", "= e.response['Error']['Code'] if exception == 'ResourceNotFoundException': logging.error('Log group %s does", "mountpoint, tls_port, tunnel_proc.pid, tunnel_args, [stunnel_config_file], state_file_dir, cert_details=cert_details) try: yield tunnel_proc", "access key ID or secret Key, %s' % e.response) return", "= aws_credentials_configs.get(awsprofile, 'aws_session_token') credentials['AccessKeyId'] = access_key credentials['SecretAccessKey'] = secret_key credentials['Token']", "get_instance_identity_info_from_instance_metadata('region') if not instance_identity: raise Exception(\"Cannot retrieve region from instance_metadata\")", "False return True def cloudwatch_create_log_stream_helper(cloudwatchlog_client, log_group_name, log_stream_name): cloudwatchlog_client.create_log_stream( logGroupName=log_group_name, logStreamName=log_stream_name", "until after logging is configured level_error = True level =", "tls_port in ports_to_try: try: sock.bind(('localhost', tls_port)) sock.close() return tls_port except", "temp_tls_state_file = write_tls_tunnel_state_file(fs_id, mountpoint, tls_port, tunnel_proc.pid, tunnel_args, [stunnel_config_file], state_file_dir, cert_details=cert_details)", "just re-set tlsport to X. options['tlsport'] = tls_port use_iam =", "'2' if 'noresvport' not in options: options['noresvport'] = None if", "X. options['tlsport'] = tls_port use_iam = 'iam' in options ap_id", "(also create all intermediate directories if they don't exist).\"\"\" if", "the given aws_creds_uri if is_fatal: fatal_error(ecs_unsuccessful_resp, ecs_unsuccessful_resp) else: return None,", "not any(release in system_release_version for release in SKIP_NO_LIBWRAP_RELEASES): efs_config['libwrap'] =", "is used to signify the number of unused bits that", "the specified DNS name is a CNAME record resolving to", "= '%s, error is: %s' % (error_message, err) fatal_error(error_message, error_message)", "format_args['region'] = get_target_region(config) if '{dns_name_suffix}' in dns_name_format: expected_replacement_field_ct += 1", "if 'tls' in options: if 'port' in options: fatal_error('The \"port\"", "stream_creation_completed: return None return { 'client': cloudwatchlog_client, 'log_group_name': log_group_name, 'log_stream_name':", "formatted_datetime, session_token=None): canonical_query_params = { 'Action': 'Connect', # Public key", "'_netdev' option tells the init system that the # 'efs'", "except OSError as e: if errno.EEXIST != e.errno or not", "opts def get_tls_port_range(config): lower_bound = config.getint(CONFIG_SECTION, 'port_range_lower_bound') upper_bound = config.getint(CONFIG_SECTION,", "def parse_arguments_early_exit(args=None): \"\"\"Parse arguments, checking for early exit conditions only\"\"\"", "octet of the value is used to signify the number", "random midpoint, and then try ports in-order from there mid", "as e: if is_fatal: unsuccessful_resp = 'Error reading token file", "fatal_error('The \"ocsp\" and \"noocsp\" options are mutually exclusive') if 'accesspoint'", "client_info): ca_extension_str = '[ v3_ca ]\\nsubjectKeyIdentifier = hash' if ap_id:", "name %s is specified incorrectly, %s' % (log_group_name, log_stream_name, e.response))", "len(ports_to_try) sock = socket.socket() for tls_port in ports_to_try: try: sock.bind(('localhost',", "create one private key and allow mounts to share it.", "init_system, dns_name, path, fs_id, mountpoint, options) else: mount_nfs(dns_name, path, mountpoint,", "%s' % (lower_bound, upper_bound, CONFIG_FILE)) def is_ocsp_enabled(config, options): if 'ocsp'", "for more info.' % \\ (INSTANCE_IAM_URL, SECURITY_CREDS_IAM_ROLE_HELP_URL) iam_role_name = url_request_helper(INSTANCE_IAM_URL,", "with open(index_attr_path, 'w+') as f: f.write('unique_subject = no') if not", "group %s already exist, %s' % (log_group_name, e.response)) return True", "as f: return f.read().strip() except IOError: logging.debug('Unable to read %s',", "options ap_id = options.get('accesspoint') cert_details = {} security_credentials = None", "at %s.' % INSTANCE_IAM_URL iam_role_url_error_msg = 'Unable to reach %s", "= Request(INSTANCE_METADATA_TOKEN_URL, headers=headers, method='PUT') res = urlopen(req) return res.read() def", "be strictly greater than \"port_range_lower_bound\" defined as %d.' % (upper_bound,", "check that the DNS name of the mount target matches", "%s failed, rc=%s, stdout=\"%s\", stderr=\"%s\"' % (cmd, rc, output, err),", "retrieval of AWS security credentials at %s.' % security_creds_lookup_url url_error_msg", "+ num_length_octets + 1 key = key[offset:] sha1 = hashlib.sha1()", "return split_dns_name_format[-3] raise Exception('Region not found in dns_name_format') def get_aws_ec2_metadata_token():", "or from the instance security credentials service' % \\ (AWS_CREDENTIALS_FILE,", "to a non-temporary version following a successful mount. \"\"\" state_file", "UTF8String:' + access_key_id efs_client_auth_str += '\\nsignature = OCTETSTRING:' + signature", "certificate signing request is max 64 characters cert_details['commonName'] = socket.gethostname()[0:64]", "'\\n' string_to_sign += get_credential_scope(date, region) + '\\n' sha256 = hashlib.sha256()", "list: for item in v: lines.append('%s = %s' % (k,", "retrieve EC2 instance metadata.' % INSTANCE_METADATA_SERVICE_URL instance_identity = url_request_helper(INSTANCE_METADATA_SERVICE_URL, ec2_metadata_unsuccessful_resp,", "'hard' not in options: options['hard'] = None if 'timeo' not", "os.path.expanduser(os.path.join('~' + pwd.getpwuid(os.getuid()).pw_name, '.aws', 'config')) CA_CONFIG_BODY = \"\"\"dir = %s", "key def create_certificate_signing_request(config_path, private_key, csr_path): cmd = 'openssl req -new", "'serial': os.path.join(base_path, mount_name, 'database/serial'), 'rand': os.path.join(base_path, mount_name, 'database/.rand') } return", "mount\"\"\" try: remote, path = device.split(':', 1) except ValueError: remote", "dns_name_format: expected_replacement_field_ct += 1 config_section = CONFIG_SECTION region = format_args.get('region')", "credentials_source: cert_details['awsCredentialsMethod'] = credentials_source if ap_id: cert_details['accessPoint'] = ap_id #", "= read_config() bootstrap_logging(config) fs_id, path, mountpoint, options = parse_arguments(config) logging.info('version=%s", "of the parameter to put log events is not valid,", "= True except ImportError: BOTOCORE_PRESENT = False VERSION = '1.28.2'", "f.readlines() lines = lines[1:-1] key = ''.join(lines) key = bytearray(base64.b64decode(key))", "in options and 'hard' not in options: options['hard'] = None", "args = sys.argv if '-h' in args[1:] or '--help' in", "more info.' % \\ (INSTANCE_IAM_URL, SECURITY_CREDS_IAM_ROLE_HELP_URL) iam_role_name = url_request_helper(INSTANCE_IAM_URL, iam_role_unsuccessful_resp,", "options: fatal_error('The \"iam\" option is required when mounting with \"awscredsuri\"')", "logging.warning(warn_message) del options[unsupported_option] def check_options_validity(options): if 'tls' in options: if", "launch the tunnel in a process group so if it", "truncating public key to remove the header and footer '-----(BEGIN|END)", "support \"%s\"', stunnel_option_name) return supported def get_version_specific_stunnel_options(): stunnel_command = [_stunnel_bin(),", "named profile [%s]' % \\ (AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE, awsprofile) fatal_error(log_message) else:", "def get_iam_role_name(): iam_role_unsuccessful_resp = 'Unsuccessful retrieval of IAM role name", "offset = int(key_line.split(':')[0]) key = key[offset:] num_length_octets = key[1] &", "= get_private_key_path() @contextmanager def open_lock_file(): lock_file = os.path.join(base_path, 'efs-utils-lock') f", "logging.debug('The event %s was already logged, %s' % (message, e.response))", "return credentials, credentials_source error_msg = 'AWS Access Key ID and", "%s to retrieve AWS security credentials. See %s for more", "e.errno == errno.EEXIST: logging.info('Failed to take out private key creation", "'connect': '%s:2049', 'sslVersion': 'TLSv1.2', 'renegotiation': 'no', 'TIMEOUTbusy': '20', 'TIMEOUTclose': '0',", "session = botocore.session.get_session() region = get_target_region(config) iam_role_name = get_iam_role_name() if", "\"dns_name_format\" failed') _fatal_error(metadata_exception) def get_region_from_instance_metadata(): instance_identity = get_instance_identity_info_from_instance_metadata('region') if not", "= config.get(CONFIG_SECTION, 'dns_name_format') if '{fs_id}' not in dns_name_format: raise ValueError('DNS", "= aws_credentials_configs.get('default', 'aws_access_key_id') if access_key is not None: return 'default'", "present in their respective directories\"\"\" if not os.path.isfile(index_path): open(index_path, 'w').close()", "from urllib import urlencode except ImportError: from urllib.request import urlopen,", "- 82 - 2 length octets to follow (ignore high", "log_stream_name } def create_default_cloudwatchlog_agent_if_not_exist(config): if not check_if_cloudwatch_log_enabled(config): return None global", "(AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE, awsprofile) fatal_error(log_message) else: return None, None def get_aws_security_credentials_from_ecs(aws_creds_uri,", "tls_ports = list(range(lower_bound, upper_bound)) # Choose a random midpoint, and", "prim: OBJECT :rsaEncryption # 17:d=2 hl=2 l= 0 prim: NULL", "%s' % error.response) elif exception == 'AccessDeniedException': logging.debug('User is not", "= {} security_credentials = None client_info = get_client_info(config) if use_iam:", "system by its short name, by adding it # to", "# # # Copy this script to /sbin/mount.efs and make", "name attached to instance # through IAM role name security", "distinguished_name = req_distinguished_name [ req_distinguished_name ] CN = %s %s", "CNAME record resolving to a valid EFS DNS ' 'name'", "'no', 'foreground': 'yes', 'socket': [ 'l:SO_REUSEADDR=yes', 'a:SO_BINDTODEVICE=lo', ], } STUNNEL_EFS_CONFIG", "sha1 = hashlib.sha1() sha1.update(key) return sha1.hexdigest() def create_canonical_request(public_key_hash, date, access_key,", "ECS_TASK_METADATA_API = 'http://169.254.170.2' WEB_IDENTITY_ROLE_ARN_ENV = 'AWS_ROLE_ARN' WEB_IDENTITY_TOKEN_FILE_ENV = 'AWS_WEB_IDENTITY_TOKEN_FILE' STS_ENDPOINT_URL", "for release in SKIP_NO_LIBWRAP_RELEASES): efs_config['libwrap'] = 'no' stunnel_config = '\\n'.join(serialize_stunnel_config(global_config)", "subprocess.check_output(['which', command]) except subprocess.CalledProcessError as e: fatal_error('Failed to locate %s", "return False def cloudwatch_create_log_group_helper(cloudwatchlog_client, log_group_name): cloudwatchlog_client.create_log_group( logGroupName=log_group_name ) logging.info('Created cloudwatch", "type is a networked file system type. This has been", "in options: fatal_error('The \"port\" and \"tls\" options are mutually exclusive')", "f: json.dump(state, f) return state_file def test_tunnel_process(tunnel_proc, fs_id): tunnel_proc.poll() if", "uses to connect to stunnel. # if the user has", "os.path.join(base_path, mount_name, 'certs'), 'index': os.path.join(base_path, mount_name, 'database/index.txt'), 'index_attr': os.path.join(base_path, mount_name,", "if 'port' in options: fatal_error('The \"port\" and \"tls\" options are", "to resolve \"%s\"' % dns_name) return dns_name def tls_paths_dictionary(mount_name, base_path=STATE_FILE_DIR):", "return with bootstrap_tls(config, init_system, dns_name, fs_id, mountpoint, options) as tunnel_proc:", "config file format, so we have to hand-serialize it. \"\"\"", "%s' % (log_group_name, e.response)) return False else: handle_general_botocore_exceptions(e) return False", "to create the key simultaneously. key = get_private_key_path() @contextmanager def", "%s', comm_file) logging.debug('Identified init system: %s', init_system) return init_system def", "stunnel_config) stunnel_config_file = os.path.join(state_file_dir, 'stunnel-config.%s' % mount_filename) with open(stunnel_config_file, 'w')", "get_region_from_instance_metadata() except Exception as e: metadata_exception = e logging.warning('Region not", "quote_plus(public_key_hash), 'X-Amz-Algorithm': ALGORITHM, 'X-Amz-Credential': credential, 'X-Amz-Date': quote_plus(formatted_datetime), 'X-Amz-Expires': 86400, 'X-Amz-SignedHeaders':", "except NoOptionError: logging.debug('No CA file configured, using default CA file", "fatal_error('Specified port [%s] is unavailable. Try selecting a different port.'", "allow mounts to share it. # This means, however, that", "-selfsign -batch -notext -config %s -in %s -out %s' %", "to handle response error messages\"\"\" retry_times = 3 for retry", "= '[ v3_ca ]\\nsubjectKeyIdentifier = hash' if ap_id: ca_extension_str +=", "expected_replacement_field_ct += 1 format_args['region'] = get_target_region(config) if '{dns_name_suffix}' in dns_name_format:", "] CN = %s %s %s %s \"\"\" # SigV4", "''.join(lines) key = bytearray(base64.b64decode(key)) # Parse the public key to", "= 'Unsuccessful retrieval of IAM role name at %s.' %", "RANDFILE = $dir/database/.rand [ ca ] default_ca = local_ca [", "in config.items(): if type(v) is list: for item in v:", "= '[ efs_client_auth ]' efs_client_auth_str += '\\naccessKeyId = UTF8String:' +", "'publicKey.pem') ca_extension_body = ca_extension_builder(ap_id, security_credentials, fs_id, client_info) efs_client_auth_body = efs_client_auth_builder(public_key_path,", "name of the temporary file containing TLS tunnel state, prefixed", "publish_cloudwatch_log(cloudwatchlog_agent, message): if not cloudwatchlog_agent or not cloudwatchlog_agent.get('client'): return False", "and to handle response error messages\"\"\" retry_times = 3 for", "def get_certificate_timestamp(current_time, **kwargs): updated_time = current_time + timedelta(**kwargs) return updated_time.strftime(CERT_DATETIME_FORMAT)", "% (cloudwatchlog_agent.get('log_group_name'), cloudwatchlog_agent.get('log_stream_name'), e.response)) return False else: logging.debug('Unexpected error: %s'", "tls_ports[:mid] assert len(tls_ports) == len(ports_to_try) sock = socket.socket() for tls_port", "raise ValueError('DNS name format must include {fs_id}') format_args = {'fs_id':", "= os.path.expanduser(os.path.join('~' + pwd.getpwuid(os.getuid()).pw_name, '.aws', 'config')) CA_CONFIG_BODY = \"\"\"dir =", "not exist, %s' % (cloudwatchlog_agent.get('log_group_name'), cloudwatchlog_agent.get('log_stream_name'), e.response)) return False else:", "\"%s\" into json: %s. Returning response body.' % (str(resp_body), e))", "cmd = 'openssl genpkey -algorithm RSA -out %s -pkeyopt rsa_keygen_bits:3072'", "-out %s -pkeyopt rsa_keygen_bits:3072' % key subprocess_call(cmd, 'Failed to create", "%s %s %s %s \"\"\" # SigV4 Auth ALGORITHM =", "1 + num_length_octets + 1 key = key[offset:] sha1 =", "mountpoint, options = parse_arguments(config) logging.info('version=%s options=%s', VERSION, options) global CLOUDWATCHLOG_AGENT", "= cert_details['certificate'] efs_config['key'] = cert_details['privateKey'] check_host_supported, ocsp_aia_supported = get_version_specific_stunnel_options() tls_controls_message", "fs_id start_watchdog(init_system) if not os.path.exists(state_file_dir): create_required_directory(config, state_file_dir) verify_level = int(options.get('verify',", "'rand': os.path.join(base_path, mount_name, 'database/.rand') } return tls_dict def get_public_key_sha1(public_key): #", "_sign(key_date, region).digest() add_service = _sign(add_region, SERVICE).digest() signing_key = _sign(add_service, 'aws4_request').digest()", "= CONFIG_SECTION region = format_args.get('region') if region: region_specific_config_section = '%s.%s'", "% (log_group_name, e.response)) return False elif exception == 'OperationAbortedException': logging.debug('Multiple", "'https://docs.aws.amazon.com/console/efs/mount-dns-name'), 'Failed to resolve \"%s\"' % dns_name) return dns_name def", "exit_code=1): out.write('Usage: mount.efs [--version] [-h|--help] <fsname> <mountpoint> [-o <options>]\\n') sys.exit(exit_code)", "key_line = line.decode('utf-8') if not key_line: err_msg = 'Public key", "def _validate_replacement_field_count(format_str, expected_ct): if format_str.count('{') != expected_ct or format_str.count('}') !=", "system \"%s\"' % (WATCHDOG_SERVICE, init_system) sys.stderr.write('%s\\n' % error_message) logging.warning(error_message) def", "dns_name_format = config.get(CONFIG_SECTION, 'dns_name_format') if '{region}' not in dns_name_format: split_dns_name_format", "03 - BIT STRING tag # - 82 - 2", "name %s is specified incorrectly, %s' % (log_group_name, e.response)) return", "not in dns_name_format: split_dns_name_format = dns_name_format.split('.') if '{dns_name_suffix}' in dns_name_format:", "= 'CentOS Linux release 8' FEDORA_RELEASE_NAME = 'Fedora release' SUSE_RELEASE_NAME", "tls_dict def get_public_key_sha1(public_key): # truncating public key to remove the", "e: os._exit(e.code) mount_completed.wait(.5) def get_init_system(comm_file='/proc/1/comm'): init_system = 'unknown' try: with", "tunnel_pid, 'cmd': command, 'files': files, } if cert_details: state.update(cert_details) with", "# to retrieve metadata, the header should embeded with metadata", "= options['cafile'] else: try: stunnel_cafile = config.get(CONFIG_SECTION, 'stunnel_cafile') except NoOptionError:", "% options['accesspoint']) if 'iam' in options and 'tls' not in", "= '127.0.0.1:%s' % path else: mount_path = '%s:%s' % (dns_name,", "KeyError as e: logging.warning('%s not present in %s: %s' %", "in a process group so if it has any child", "open(os.devnull, 'w') as devnull: rc = subprocess.call(['systemctl', 'status', 'network.target'], stdout=devnull,", "def _sign(key, msg): return hmac.new(key, msg.encode('utf-8'), hashlib.sha256) key_date = _sign(('AWS4'", "in ['AccessKeyId', 'SecretAccessKey', 'SessionToken']): return { 'AccessKeyId': creds['AccessKeyId'], 'SecretAccessKey': creds['SecretAccessKey'],", "raise Exception(\"Cannot retrieve region from instance_metadata\") return instance_identity def get_instance_identity_info_from_instance_metadata(property):", "system: %s', init_system) return init_system def check_network_target(fs_id): with open(os.devnull, 'w')", "log_stream_name = '%s - mount.log' % (fs_id) else: log_stream_name =", "cloudwatchlog_client.create_log_stream( logGroupName=log_group_name, logStreamName=log_stream_name ) logging.info('Created cloudwatch log stream %s in", "if so try: access_key = aws_credentials_configs.get('default', 'aws_access_key_id') if access_key is", "start %s, unrecognized init system \"%s\"' % (WATCHDOG_SERVICE, init_system) sys.stderr.write('%s\\n'", "os.path.exists(database_dir): create_required_directory(config, database_dir) if not os.path.exists(certs_dir): create_required_directory(config, certs_dir) def ca_supporting_files_check(index_path,", "in creds for k in ['AccessKeyId', 'SecretAccessKey', 'SessionToken']): return {", "%s: %s' % (token_file, e) fatal_error(unsuccessful_resp, unsuccessful_resp) else: return None,", "or not mountpoint: usage(out=sys.stderr) fs_id, path = match_device(config, fsname) return", "# # Once there is an entry in fstab, the", "(dns_name, mountpoint) logging.info(message) publish_cloudwatch_log(CLOUDWATCHLOG_AGENT, message) else: message = 'Failed to", "', '') # DER encoding TLV (Tag, Length, Value) #", "efs_config['key'] = cert_details['privateKey'] check_host_supported, ocsp_aia_supported = get_version_specific_stunnel_options() tls_controls_message = 'WARNING:", "= aws_credentials_configs.get(awsprofile, 'aws_access_key_id') credentials['SecretAccessKey'] = aws_credentials_configs.get(awsprofile, 'aws_secret_access_key') except NoSectionError: logging.debug('No", "%s' % e) return False except Exception as e: logging.warning('Unknown", "running', WATCHDOG_SERVICE) elif init_system == 'systemd': rc = subprocess.call(['systemctl', 'is-active',", "['AccessKeyId', 'SecretAccessKey', 'SessionToken']): return { 'AccessKeyId': creds['AccessKeyId'], 'SecretAccessKey': creds['SecretAccessKey'], 'Token':", "efs _netdev 0 0 # # Using the 'efs' type", "at %s.' % ecs_uri ecs_url_error_msg = 'Unable to reach %s", "not found in %s under named profile [%s]', file_path, awsprofile)", "e.response['Error']['Code'] if exception == 'InvalidSequenceTokenException': logging.debug('The sequence token is not", "parse_arguments(config) logging.info('version=%s options=%s', VERSION, options) global CLOUDWATCHLOG_AGENT CLOUDWATCHLOG_AGENT = bootstrap_cloudwatch_logging(config,", "name security credentials lookup uri iam_role_name = get_iam_role_name() if iam_role_name:", "exist in log group %s, %s' % (log_stream_name, log_group_name, e.response))", "= $dir/database/serial private_key = %s cert = $dir/certificate.pem new_certs_dir =", "return string_to_sign def calculate_signature(string_to_sign, date, secret_access_key, region): \"\"\" Calculate the", "+ aws_creds_uri ecs_unsuccessful_resp = 'Unsuccessful retrieval of AWS security credentials", "signing request is max 64 characters cert_details['commonName'] = socket.gethostname()[0:64] cert_details['region']", "CLOUDWATCHLOG_AGENT = bootstrap_cloudwatch_logging(config, fs_id) check_unsupported_options(options) check_options_validity(options) init_system = get_init_system() check_network_status(fs_id,", "= ca_extension_builder(ap_id, security_credentials, fs_id, client_info) efs_client_auth_body = efs_client_auth_builder(public_key_path, security_credentials['AccessKeyId'], security_credentials['SecretAccessKey'],", "elif init_system == 'systemd': rc = subprocess.call(['systemctl', 'is-active', '--quiet', WATCHDOG_SERVICE],", "# - the remaining 127 bits are used to encode", "= list(filter(lambda e: e is not None, [primary] + secondaries))", "fatal_error(ecs_unsuccessful_resp, ecs_unsuccessful_resp) else: return None, None def get_aws_security_credentials_from_webidentity(role_arn, token_file, is_fatal=False):", "from urllib.request import urlopen, Request from urllib.error import URLError, HTTPError", "built-in ' \\ 'trust store.' % unsupported_option sys.stderr.write('WARN: %s\\n' %", "mountpoint, options) else: mount_nfs(dns_name, path, mountpoint, options) if '__main__' ==", "fatal_error('Failed to locate %s in %s - %s' % (command,", "Wrapped for patching purposes in unit tests \"\"\" return datetime.utcnow()", "e.response['Error']['Code'] if exception == 'ResourceNotFoundException': logging.error('Log group %s does not", "def get_system_release_version(): try: with open(SYSTEM_RELEASE_PATH) as f: return f.read().strip() except", "logging.debug('Unexpected error: %s' % e) return False except NoCredentialsError as", "if not provided in fstab. import base64 import errno import", "awsprofile: return get_aws_security_credentials_from_awsprofile(awsprofile, True) # attempt to lookup AWS security", "CANONICAL_URI = '/' CANONICAL_HEADERS_DICT = { 'host': '%s' } CANONICAL_HEADERS", "stderr=\"%s\"' % (cmd, rc, output, err), exc_info=True) try: process.kill() except", "group %s, %s' % (log_stream_name, log_group_name, e.response)) return True elif", "Request(INSTANCE_METADATA_TOKEN_URL, headers=headers, method='PUT') res = urlopen(req) return res.read() def get_aws_security_credentials(use_iam,", "'https://docs.aws.amazon.com/efs/latest/ug/using-amazon-efs-utils.html#upgrading-stunnel') def find_command_path(command, install_method): try: env_path = '/sbin:/usr/sbin:/usr/local/sbin:/root/bin:/usr/local/bin:/usr/bin:/bin' os.putenv('PATH', env_path)", "region, fs_id, security_credentials, ap_id, client_info) create_certificate_signing_request(certificate_config, private_key, certificate_signing_request) not_before =", "supported: logging.warning('stunnel does not support \"%s\"', stunnel_option_name) return supported def", "if 'wsize' not in options: options['wsize'] = '1048576' if 'soft'", "exc_info=True) try: process.kill() except OSError: # Silently fail if the", "ap_id, client_info, base_path=STATE_FILE_DIR): current_time = get_utc_now() tls_paths = tls_paths_dictionary(mount_name, base_path)", "file system ID is correct.\\nSee %s for more detail.' %", "if 'noresvport' not in options: options['noresvport'] = None if 'tls'", "None: out, err = tunnel_proc.communicate() fatal_error('Failed to initialize TLS tunnel", "def bootstrap_logging(config, log_dir=LOG_DIR): raw_level = config.get(CONFIG_SECTION, 'logging_level') levels = {", "of octets that follow # - the following octets encode,", "they're not present in their respective directories\"\"\" if not os.path.isfile(index_path):", "'port' in options: fatal_error('The \"port\" and \"tls\" options are mutually", "= random.randrange(len(tls_ports)) ports_to_try = tls_ports[mid:] + tls_ports[:mid] assert len(tls_ports) ==", "0 0 # # Using the 'efs' type will cause", "@contextmanager def bootstrap_tls(config, init_system, dns_name, fs_id, mountpoint, options, state_file_dir=STATE_FILE_DIR): tls_port", "metadata service call failed, falling back ' 'to legacy \"dns_name_format\"", "role name security credentials lookup uri iam_role_name = get_iam_role_name() if", "with: # # sudo mount /mount_point # # The script", "TLS tunnel state, prefixed with a '~'. This file needs", "'aws_secret_access_key') except NoSectionError: logging.debug('No [%s] section found in config file", "log_stream_name): try: cloudwatch_create_log_stream_helper(cloudwatchlog_client, log_group_name, log_stream_name) except ClientError as e: exception", "e: logging.warning('Credentials are not properly configured, %s' % e) return", "v in sorted(canonical_query_params.items())]) def create_string_to_sign(canonical_request, date, region): \"\"\" Create a", "and metadata calls fail. \"\"\" dns_name_format = config.get(CONFIG_SECTION, 'dns_name_format') if", "cloudwatchlog_agent.get('client').put_log_events(**kwargs) def publish_cloudwatch_log(cloudwatchlog_agent, message): if not cloudwatchlog_agent or not cloudwatchlog_agent.get('client'):", "%s, unrecognized init system \"%s\"' % (WATCHDOG_SERVICE, init_system) sys.stderr.write('%s\\n' %", "+ '\\n' request += SIGNED_HEADERS + '\\n' sha256 = hashlib.sha256()", "have to include a locking mechanism to ensure that the", "not stream_creation_completed: return None return { 'client': cloudwatchlog_client, 'log_group_name': log_group_name,", "%s' % (log_group_name, e.response)) return False elif exception == 'OperationAbortedException':", "fsname) return fs_id, path, mountpoint, options def get_client_info(config): client_info =", "as a number of octets # - the remaining octets", "temp_tls_state_file), os.path.join(state_file_dir, temp_tls_state_file[1:])) def get_nfs_mount_options(options): # If you change these", "logging.error('Failed to import botocore, please install botocore first.') return None", "to reach %s to retrieve IAM role name. See %s", "efsPolicy x509_extensions = v3_ca [ efsPolicy ] CN = supplied", "cert_details['accessPoint'] = ap_id # additional symbol appended to avoid naming", "cons: SEQUENCE # 4:d=1 hl=2 l= 13 cons: SEQUENCE #", "= ['stat', '-f', '-L', '-c', '%T', mountpoint] p = subprocess.Popen(cmd,", "\"\"\"Recreate all supporting openssl ca and req files if they're", "if 'tlsport' in options: fatal_error('Specified port [%s] is unavailable. Try", "EFS mount target. ' 'Please refer to the EFS documentation", "tls_paths_dictionary(mount_name, base_path=STATE_FILE_DIR): tls_dict = { 'mount_dir': os.path.join(base_path, mount_name), # every", "security_credentials else '' efs_client_info_body = efs_client_info_builder(client_info) if client_info else ''", "'trust store.' % unsupported_option sys.stderr.write('WARN: %s\\n' % warn_message) logging.warning(warn_message) del", "build_opener, urlopen, Request, HTTPHandler from urllib import urlencode except ImportError:", "as well at man/mount.efs.8 if 'nfsvers' not in options and", "try: int(options['tlsport']) except ValueError: fatal_error('tlsport option [%s] is not an", "open(index_attr_path, 'w+') as f: f.write('unique_subject = no') if not os.path.isfile(serial_path):", "= args.index('-o') + 1 options = parse_options(args[options_index]) if not fsname", "return PRIVATE_KEY_FILE def check_and_create_private_key(base_path=STATE_FILE_DIR): # Creating RSA private keys is", "compatibility check dns_name_format to obtain the target region. This functionality", "request.add_header('X-aws-ec2-metadata-token-ttl-seconds', 21600) request.get_method = lambda: 'PUT' res = opener.open(request) return", "= json.loads(resp_body.decode(request_resp.headers.get_content_charset() or 'us-ascii')) return resp_dict except ValueError as e:", "into json: %s. Returning response body.' % (str(resp_body), e)) return", "Request from urllib.error import URLError, HTTPError from urllib.parse import urlencode", "state_file_dir) verify_level = int(options.get('verify', DEFAULT_STUNNEL_VERIFY_LEVEL)) ocsp_enabled = is_ocsp_enabled(config, options) stunnel_config_file", "'efs' type is a networked file system type. This has", "in UNSUPPORTED_OPTIONS: if unsupported_option in options: warn_message = 'The \"%s\"", "region, fs_id, session_token) string_to_sign = create_string_to_sign(canonical_request, date, region) signature =", "more info.' % \\ (security_creds_lookup_url, SECURITY_CREDS_IAM_ROLE_HELP_URL) iam_security_dict = url_request_helper(security_creds_lookup_url, unsuccessful_resp,", "ca_extension_str += '\\n1.3.6.1.4.1.4843.7.3 = ASN1:UTF8String:' + fs_id if client_info: ca_extension_str", "if config.getboolean(CONFIG_SECTION, 'stunnel_debug_enabled'): global_config['debug'] = 'debug' if config.has_option(CONFIG_SECTION, 'stunnel_logs_file'): global_config['output']", "lookup AWS security credentials through AWS_CONTAINER_CREDENTIALS_RELATIVE_URI environment variable if ECS_URI_ENV", "by the mount watchdog logging.info('Starting TLS tunnel: \"%s\"', ' '.join(tunnel_args))", "credentials['AccessKeyId'] = access_key credentials['SecretAccessKey'] = secret_key credentials['Token'] = session_token except", "- mount.log' % (fs_id) else: log_stream_name = 'default - mount.log'", "'efs-mount-helper', 'WebIdentityToken': token }) unsuccessful_resp = 'Unsuccessful retrieval of AWS", "mount_nfs(dns_name, path, mountpoint, options): if 'tls' in options: mount_path =", "security credentials not found in %s or %s under named", "close_fds=True) else: logging.debug('%s is already running', WATCHDOG_SERVICE) else: error_message =", "= create_cloudwatch_log_stream(cloudwatchlog_client, log_group_name, log_stream_name) if not stream_creation_completed: return None return", "groups that can be created, %s' % e.response) return False", "created, as mounts occurring in parallel may try to create", "if rc != 0: fatal_error('Failed to mount %s because the", "return fs_id, path, mountpoint, options def get_client_info(config): client_info = {}", "e: if is_fatal: unsuccessful_resp = 'Error reading token file %s:", "tls_port, tunnel_pid, command, files, state_file_dir, cert_details=None): \"\"\" Return the name", "key') def subprocess_call(cmd, error_message): \"\"\"Helper method to run shell openssl", "%s in log group %s' % (log_stream_name, log_group_name)) def create_cloudwatch_log_stream(cloudwatchlog_client,", "lock_file_contents.encode('utf-8')) yield f finally: os.close(f) os.remove(lock_file) def do_with_lock(function): while True:", "in conflict, %s' % (log_group_name, e.response)) return False elif exception", "the LICENSE accompanying this file # for the specific language", "return False elif exception == 'UnrecognizedClientException': logging.debug('The most likely cause", "if is_fatal: fatal_error(ecs_unsuccessful_resp, ecs_unsuccessful_resp) else: return None, None def get_aws_security_credentials_from_webidentity(role_arn,", "in status: logging.debug('%s is already running', WATCHDOG_SERVICE) elif init_system ==", "return False elif exception == 'InvalidParameterException': logging.error('Log group name %s", "get_private_key_path() @contextmanager def open_lock_file(): lock_file = os.path.join(base_path, 'efs-utils-lock') f =", "ec2_metadata_url_error_msg, retry_with_new_header_token=True) if instance_identity: try: return instance_identity[property] except KeyError as", "error will be thrown, # to retrieve metadata, the header", "== 'OperationAbortedException': logging.debug('Multiple requests to update the same log group", "options) if cert_details: efs_config['cert'] = cert_details['certificate'] efs_config['key'] = cert_details['privateKey'] check_host_supported,", "%s' % (private_key, public_key) subprocess_call(cmd, 'Failed to create public key')", "fs_id) log_group_name = cloudwatchlog_config.get('log_group_name') log_stream_name = cloudwatchlog_config.get('log_stream_name') retention_days = cloudwatchlog_config.get('retention_days')", "None def get_iam_role_name(): iam_role_unsuccessful_resp = 'Unsuccessful retrieval of IAM role", "'r') as f: lines = f.readlines() lines = lines[1:-1] key", "%s or %s under named profile [%s]' % \\ (AWS_CREDENTIALS_FILE,", "messages\"\"\" retry_times = 3 for retry in range(retry_times): process =", "' 'https://docs.aws.amazon.com/efs/latest/ug/using-amazon-efs-utils.html#upgrading-stunnel') def find_command_path(command, install_method): try: env_path = '/sbin:/usr/sbin:/usr/local/sbin:/root/bin:/usr/local/bin:/usr/bin:/bin' os.putenv('PATH',", "return tls_port except socket.error: continue sock.close() if 'tlsport' in options:", "v: lines.append('%s = %s' % (k, item)) else: lines.append('%s =", "file containing TLS tunnel state, prefixed with a '~'. This", "options: options['wsize'] = '1048576' if 'soft' not in options and", "IAM role name at %s.' % INSTANCE_IAM_URL iam_role_url_error_msg = 'Unable", "'InvalidSequenceTokenException': logging.debug('The sequence token is not valid, %s' % e.response)", "key ID or secret Key, %s' % e.response) return False", "only be used if region is not present in the", "'70', 'delay': 'yes', } WATCHDOG_SERVICE = 'amazon-efs-mount-watchdog' SYSTEM_RELEASE_PATH = '/etc/system-release'", "= secret_key credentials['Token'] = session_token except NoOptionError as e: if", "%s, %s' % (log_stream_name, log_group_name, e.response)) return True elif exception", "if os.path.isfile(key): return cmd = 'openssl genpkey -algorithm RSA -out", "# attempt to lookup AWS security credentials through AWS_CONTAINER_CREDENTIALS_RELATIVE_URI environment", "return cloudwatchlog_agent.get('client').describe_log_streams( logGroupName=cloudwatchlog_agent.get('log_group_name'), logStreamNamePrefix=cloudwatchlog_agent.get('log_stream_name') ) def get_log_stream_next_token(cloudwatchlog_agent): try: response =", "= e.response['Error']['Code'] if exception == 'InvalidSequenceTokenException': logging.debug('The sequence token is", "(NoSectionError, NoOptionError): continue return awsprofile def url_request_helper(url, unsuccessful_resp, url_error_msg, headers={},", "= True break if not supported: logging.warning('stunnel does not support", "elif exception == 'InvalidParameterException': logging.debug('One of the parameter to put", "%s' % (url, e.reason) if err_msg: logging.debug('%s %s', url_error_msg, err_msg)", "bootstrap_logging(config) fs_id, path, mountpoint, options = parse_arguments(config) logging.info('version=%s options=%s', VERSION,", "upper_bound def choose_tls_port(config, options): if 'tlsport' in options: ports_to_try =", "= 14 # Cloudwatchlog agent dict includes cloudwatchlog botocore client,", "f: for line in f: if 'PRETTY_NAME' in line: return", "to lookup AWS security credentials in AWS credentials file (~/.aws/credentials)", "= hashlib.sha256() sha256.update(canonical_request.encode()) string_to_sign += sha256.hexdigest() return string_to_sign def calculate_signature(string_to_sign,", "dns_name_format: expected_replacement_field_ct += 1 format_args['region'] = get_target_region(config) if '{dns_name_suffix}' in", "NoOptionError): continue return awsprofile def url_request_helper(url, unsuccessful_resp, url_error_msg, headers={}, retry_with_new_header_token=False):", "check_options_validity(options): if 'tls' in options: if 'port' in options: fatal_error('The", "your file system ID is correct.\\nSee %s for more detail.'", "SubjectKeyIdentifier hash, per # https://tools.ietf.org/html/rfc5280#section-4.2.1.2 # # Example: # 0382018f00...<subjectPublicKey>", "'openssl genpkey -algorithm RSA -out %s -pkeyopt rsa_keygen_bits:3072' % key", "value is used to signify the number of unused bits", "Fail if credentials cannot be fetched from the given awsprofile", "0 < len(client_source) <= CLIENT_SOURCE_STR_LEN_LIMIT: client_info['source'] = client_source return client_info", "process.communicate() rc = process.poll() if rc != 0: logging.error('Command %s", "FEDORA_RELEASE_NAME = 'Fedora release' SUSE_RELEASE_NAME = 'openSUSE Leap' SKIP_NO_LIBWRAP_RELEASES =", "does not support \"%s\"', stunnel_option_name) return supported def get_version_specific_stunnel_options(): stunnel_command", "if security_credentials: public_key = os.path.join(tls_paths['mount_dir'], 'publicKey.pem') create_public_key(private_key, public_key) create_ca_conf(certificate_config, common_name,", "as f: f.write('00') if not os.path.isfile(rand_path): open(rand_path, 'w').close() def get_certificate_timestamp(current_time,", "mount %s because the network was not yet available, add", "def get_aws_ec2_metadata_token(): try: opener = build_opener(HTTPHandler) request = Request(INSTANCE_METADATA_TOKEN_URL) request.add_header('X-aws-ec2-metadata-token-ttl-seconds',", "+ fs_id if client_info: ca_extension_str += '\\n1.3.6.1.4.1.4843.7.4 = ASN1:SEQUENCE:efs_client_info' return", "try: lock_file_contents = 'PID: %s' % os.getpid() os.write(f, lock_file_contents.encode('utf-8')) yield", "get_cloudwatch_log_stream_name(fs_id=None): instance_id = get_instance_identity_info_from_instance_metadata('instanceId') if instance_id and fs_id: log_stream_name =", "logging.debug('Set cloudwatch log group retention days to %s' % retention_days)", "def get_cloudwatchlog_config(config, fs_id=None): log_group_name = DEFAULT_CLOUDWATCH_LOG_GROUP if config.has_option(CLOUDWATCH_LOG_SECTION, 'log_group_name'): log_group_name", "open(comm_file) as f: init_system = f.read().strip() except IOError: logging.warning('Unable to", "is: %s' % (error_message, err) fatal_error(error_message, error_message) def ca_dirs_check(config, database_dir,", "share it. # This means, however, that we have to", "logging.warning('stunnel does not support \"%s\"', stunnel_option_name) return supported def get_version_specific_stunnel_options():", "configs file (~/.aws/config) with given awsprofile if awsprofile: return get_aws_security_credentials_from_awsprofile(awsprofile,", "the file system can be mounted with: # # sudo", "session.create_client(service, aws_access_key_id=credentials['AccessKeyId'], aws_secret_access_key=credentials['SecretAccessKey'], aws_session_token=credentials['Token'], region_name=region) return session.create_client(service, region_name=region) def get_cloudwatchlog_config(config,", "from the given awsprofile if is_fatal: log_message = 'AWS security", "credentials, credentials_source = get_aws_security_credentials_from_instance_metadata(iam_role_name) if credentials and credentials_source: return credentials,", "testing network on non-systemd init systems') return check_network_target(fs_id) def start_watchdog(init_system):", "if errno.EEXIST != e.errno or not os.path.isdir(directory): raise @contextmanager def", "hashlib import hmac import json import logging import os import", "of an fstab entry is: # # [Device] [Mount Point]", "err = proc.communicate() if proc.returncode == 0: message = 'Successfully", "when mounting via \"accesspoint\"') if not AP_ID_RE.match(options['accesspoint']): fatal_error('Access Point ID", "\"\"\" formatted_datetime = date.strftime(SIGV4_DATETIME_FORMAT) credential = quote_plus(access_key + '/' +", "format_args.get('dns_name_suffix'), config_section) _validate_replacement_field_count(dns_name_format, expected_replacement_field_ct) dns_name = dns_name_format.format(**format_args) try: socket.gethostbyname(dns_name) except", "stunnel_config = '\\n'.join(serialize_stunnel_config(global_config) + serialize_stunnel_config(efs_config, 'efs')) logging.debug('Writing stunnel configuration:\\n%s', stunnel_config)", "instance_identity: try: return instance_identity[property] except KeyError as e: logging.warning('%s not", "'aws_access_key_id') if access_key is not None: return 'default' except (NoSectionError,", "return key def create_certificate_signing_request(config_path, private_key, csr_path): cmd = 'openssl req", "tunnel_args # launch the tunnel in a process group so", "parsing \"%s\" into json: %s. Returning response body.' % (str(resp_body),", "return False elif exception == 'ResourceNotFoundException': logging.error('Log group %s does", "files, } if cert_details: state.update(cert_details) with open(os.path.join(state_file_dir, state_file), 'w') as", "self-signed client-side certificate') return current_time.strftime(CERT_DATETIME_FORMAT) def get_private_key_path(): \"\"\"Wrapped for mocking", "the parameter to put log events is not valid, %s'", "if cert_details: state.update(cert_details) with open(os.path.join(state_file_dir, state_file), 'w') as f: json.dump(state,", "base_path=STATE_FILE_DIR): current_time = get_utc_now() tls_paths = tls_paths_dictionary(mount_name, base_path) certificate_config =", "cert_details['fsId'] = fs_id start_watchdog(init_system) if not os.path.exists(state_file_dir): create_required_directory(config, state_file_dir) verify_level", "retention_days): cloudwatchlog_client.put_retention_policy( logGroupName=log_group_name, retentionInDays=retention_days ) logging.debug('Set cloudwatch log group retention", "'no' stunnel_config = '\\n'.join(serialize_stunnel_config(global_config) + serialize_stunnel_config(efs_config, 'efs')) logging.debug('Writing stunnel configuration:\\n%s',", "def get_public_key_sha1(public_key): # truncating public key to remove the header", "do_with_lock(function): while True: try: with open_lock_file(): return function() except OSError", "test_tunnel_process(tunnel_proc, fs_id): tunnel_proc.poll() if tunnel_proc.returncode is not None: out, err", "key file, %s, correctly' % public_key) key_line = '' for", "path, mountpoint, options def get_client_info(config): client_info = {} # source", "'tlsport' in options: try: int(options['tlsport']) except ValueError: fatal_error('tlsport option [%s]", "+= date.strftime(SIGV4_DATETIME_FORMAT) + '\\n' string_to_sign += get_credential_scope(date, region) + '\\n'", "= get_dns_name(config, fs_id) if 'tls' in options: mount_tls(config, init_system, dns_name,", "None def get_region_from_legacy_dns_format(config): \"\"\" For backwards compatibility check dns_name_format to", "mountpoint, tls_port, tunnel_pid, command, files, state_file_dir, cert_details=None): \"\"\" Return the", "high order bit (8) set to 1 # - the", "specified tlsport=X at the command line this will just re-set", "return cmd = 'openssl genpkey -algorithm RSA -out %s -pkeyopt", "# # You will be able to mount an EFS", "mountpoint = None options = {} if len(args) > 1:", "date, region) signature = calculate_signature(string_to_sign, date, secret_access_key, region) efs_client_auth_str =", "+ '\\n' request += CANONICAL_URI + '\\n' request += create_canonical_query_string(public_key_hash,", "not mount_completed.is_set(): try: test_tunnel_process(tunnel_proc, fs_id) except SystemExit as e: os._exit(e.code)", "'X-Amz-Algorithm': ALGORITHM, 'X-Amz-Credential': credential, 'X-Amz-Date': quote_plus(formatted_datetime), 'X-Amz-Expires': 86400, 'X-Amz-SignedHeaders': SIGNED_HEADERS,", "config.items(): if type(v) is list: for item in v: lines.append('%s", "return lines def add_stunnel_ca_options(efs_config, config, options): if 'cafile' in options:", "resolve \"%s\"' % dns_name) return dns_name def tls_paths_dictionary(mount_name, base_path=STATE_FILE_DIR): tls_dict", "offset = 1 + 1 + num_length_octets + 1 key", "+ ap_id if security_credentials: ca_extension_str += '\\n1.3.6.1.4.1.4843.7.2 = ASN1:SEQUENCE:efs_client_auth' ca_extension_str", "main(): parse_arguments_early_exit() assert_root() config = read_config() bootstrap_logging(config) fs_id, path, mountpoint,", "global_config['output'] = config.get(CONFIG_SECTION, 'stunnel_logs_file').replace('{fs_id}', fs_id) else: global_config['output'] = os.path.join(log_dir, '%s.stunnel.log'", "subprocess.Popen(stunnel_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) proc.wait() _, err = proc.communicate() stunnel_output", "for mocking purposes in unit tests\"\"\" return PRIVATE_KEY_FILE def check_and_create_private_key(base_path=STATE_FILE_DIR):", "mount since SigV4 signature can change\"\"\" public_key_path = os.path.join(directory, 'publicKey.pem')", "\"iam\"') if 'awsprofile' in options and 'iam' not in options:", "(cloudwatchlog_agent.get('log_group_name'), cloudwatchlog_agent.get('log_stream_name'), e.response)) elif exception == 'ResourceNotFoundException': logging.debug('Either log group", "def usage(out, exit_code=1): out.write('Usage: mount.efs [--version] [-h|--help] <fsname> <mountpoint> [-o", "'awsprofile' in options and 'iam' not in options: fatal_error('The \"iam\"", "'status', 'network.target'], stdout=devnull, stderr=devnull, close_fds=True) if rc != 0: fatal_error('Failed", "= 1 + 1 + num_length_octets + 1 key =", "%s in config section [%s]\", format_args.get('dns_name_suffix'), config_section) _validate_replacement_field_count(dns_name_format, expected_replacement_field_ct) dns_name", "fatal_error('The \"iam\" option is required when mounting with \"awscredsuri\"') if", "# - the following octets encode, as big-endian, the length", ") logging.debug('Set cloudwatch log group retention days to %s' %", "def get_aws_security_credentials(use_iam, awsprofile=None, aws_creds_uri=None): \"\"\" Lookup AWS security credentials (access", "from the given aws_creds_uri if is_fatal: fatal_error(unsuccessful_resp, unsuccessful_resp) else: return", "= ['/sbin/mount.nfs4', mount_path, mountpoint, '-o', get_nfs_mount_options(options)] if 'netns' in options:", "def get_version_specific_stunnel_options(): stunnel_command = [_stunnel_bin(), '-help'] proc = subprocess.Popen(stunnel_command, stdout=subprocess.PIPE,", "region_name=region) def get_cloudwatchlog_config(config, fs_id=None): log_group_name = DEFAULT_CLOUDWATCH_LOG_GROUP if config.has_option(CLOUDWATCH_LOG_SECTION, 'log_group_name'):", "# launch the tunnel in a process group so if", "name at %s.' % INSTANCE_IAM_URL iam_role_url_error_msg = 'Unable to reach", "IAM role name security credentials lookup uri iam_role_name = get_iam_role_name()", "iam_security_dict and all(k in iam_security_dict for k in CREDENTIALS_KEYS): return", "args[:-1]: options_index = args.index('-o') + 1 options = parse_options(args[options_index]) if", "else: create_default_cloudwatchlog_agent_if_not_exist(config) fatal_error('The specified CNAME \"%s\" did not resolve to", "SERVICE = 'elasticfilesystem' CONFIG_FILE = '/etc/amazon/efs/efs-utils.conf' CONFIG_SECTION = 'mount' CLIENT_INFO_SECTION", "os.path.join(log_dir, '%s.stunnel.log' % mount_filename) efs_config = dict(STUNNEL_EFS_CONFIG) efs_config['accept'] = efs_config['accept']", "\"ocsp\" and \"noocsp\" options are mutually exclusive') if 'accesspoint' in", "mechanism to ensure that the private key is # atomically", "'Failed to start TLS tunnel (errno=%d). stdout=\"%s\" stderr=\"%s\"' % (tunnel_proc.returncode,", "None except EndpointConnectionError as e: logging.warning('Could not connect to the", "= '%s - %s - mount.log' % (fs_id, instance_id) elif", "= get_target_region(config) cert_details['certificateCreationTime'] = create_certificate(config, cert_details['mountStateDir'], cert_details['commonName'], cert_details['region'], fs_id, security_credentials,", "integer' % options['tlsport']) if 'ocsp' in options and 'noocsp' in", "p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) output, _ = p.communicate()", "% error) def main(): parse_arguments_early_exit() assert_root() config = read_config() bootstrap_logging(config)", "exist in the last # content byte. Note that this", "return request def create_canonical_query_string(public_key_hash, credential, formatted_datetime, session_token=None): canonical_query_params = {", "from the SubjectKeyIdentifier hash, per # https://tools.ietf.org/html/rfc5280#section-4.2.1.2 # # Example:", "== 401 and retry_with_new_header_token: token = get_aws_ec2_metadata_token() req.add_header('X-aws-ec2-metadata-token', token) request_resp", "options: options['noresvport'] = None if 'tls' in options: options['port'] =", "= credentials_source if ap_id: cert_details['accessPoint'] = ap_id # additional symbol", "get_target_region(config) iam_role_name = get_iam_role_name() if iam_role_name: credentials, _ = get_aws_security_credentials_from_instance_metadata(iam_role_name)", "= RotatingFileHandler(os.path.join(log_dir, LOG_FILE), maxBytes=max_bytes, backupCount=file_count) handler.setFormatter(logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(message)s'))", "NoCredentialsError as e: logging.warning('Credentials are not properly configured, %s' %", "\\ (not_before, not_after, certificate_config, certificate_signing_request, certificate) subprocess_call(cmd, 'Failed to create", "security_credentials, ap_id, client_info, base_path=state_file_dir) cert_details['certificate'] = os.path.join(state_file_dir, cert_details['mountStateDir'], 'certificate.pem') cert_details['privateKey']", "key ID and secret access key). Adapted credentials provider chain", "as e: fatal_error('Failed to locate %s in %s - %s'", "= options.get('awscredsuri') if aws_creds_uri: kwargs = {'aws_creds_uri': aws_creds_uri} else: kwargs", "logging.debug('No [%s] section found in config file %s', awsprofile, file_path)", "'RoleSessionName': 'efs-mount-helper', 'WebIdentityToken': token }) unsuccessful_resp = 'Unsuccessful retrieval of", "[Dump] [Pass] # # Add an entry like this: #", "e.response) return False elif exception == 'InvalidParameterException': logging.debug('One of the", "{}) if all(k in creds for k in ['AccessKeyId', 'SecretAccessKey',", "not found in AWS credentials file (%s), config file (%s),", "dns_name = dns_name_format.format(**format_args) try: socket.gethostbyname(dns_name) except socket.gaierror: fatal_error('Failed to resolve", "If you change these options, update the man page as", "'w') as f: json.dump(state, f) return state_file def test_tunnel_process(tunnel_proc, fs_id):", "sure it is executable. # # You will be able", "quote_plus(formatted_datetime), 'X-Amz-Expires': 86400, 'X-Amz-SignedHeaders': SIGNED_HEADERS, } if session_token: canonical_query_params['X-Amz-Security-Token'] =", "profile [%s]' % \\ (AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE, awsprofile) fatal_error(log_message) else: return", "'nfs' in str(output) def mount_tls(config, init_system, dns_name, path, fs_id, mountpoint,", "ec2_metadata_unsuccessful_resp, ec2_metadata_url_error_msg, retry_with_new_header_token=True) if instance_identity: try: return instance_identity[property] except KeyError", "efs_client_info_body) with open(config_path, 'w') as f: f.write(full_config_body) return full_config_body def", "create_public_key(private_key, public_key): cmd = 'openssl rsa -in %s -outform PEM", "log group %s or log stream %s does not exist,", "security_credentials['SecretAccessKey'], date, region, fs_id, security_credentials['Token']) if security_credentials else '' efs_client_info_body", "or secret Key, %s' % e.response) return False elif exception", "% security_creds_lookup_url url_error_msg = 'Unable to reach %s to retrieve", "efs_config['cert'] = cert_details['certificate'] efs_config['key'] = cert_details['privateKey'] check_host_supported, ocsp_aia_supported = get_version_specific_stunnel_options()", "credentials, credentials_source # attempt to lookup AWS security credentials through", "$dir/certs default_md = sha256 preserve = no policy = efsPolicy", "%s for more info.' % \\ (security_creds_lookup_url, SECURITY_CREDS_IAM_ROLE_HELP_URL) iam_security_dict =", "there mid = random.randrange(len(tls_ports)) ports_to_try = tls_ports[mid:] + tls_ports[:mid] assert", "return output, err error_message = '%s, error is: %s' %", "= 'AWS Access Key ID and Secret Access Key are", "following the instructions at ' 'https://docs.aws.amazon.com/efs/latest/ug/using-amazon-efs-utils.html#upgrading-stunnel') def find_command_path(command, install_method): try:", "os.path.exists(state_file_dir): create_required_directory(config, state_file_dir) verify_level = int(options.get('verify', DEFAULT_STUNNEL_VERIFY_LEVEL)) ocsp_enabled = is_ocsp_enabled(config,", "options and 'awsprofile' in options: fatal_error('The \"awscredsuri\" and \"awsprofile\" options", "None: args = sys.argv fsname = None mountpoint = None", "= os.path.join(tls_paths['mount_dir'], 'request.csr') certificate = os.path.join(tls_paths['mount_dir'], 'certificate.pem') ca_dirs_check(config, tls_paths['database_dir'], tls_paths['certs_dir'])", "database_dir) if not os.path.exists(certs_dir): create_required_directory(config, certs_dir) def ca_supporting_files_check(index_path, index_attr_path, serial_path,", "in config file \"%s\"', mode_str, CONFIG_FILE) except NoOptionError: pass try:", "0o750 try: mode_str = config.get(CONFIG_SECTION, 'state_file_dir_mode') try: mode = int(mode_str,", "fatal_error( 'The specified domain name \"%s\" did not resolve to", "poll the tunnel process health every .5s during the mount", "perform the action, %s' % error.response) else: logging.debug('Unexpected error: %s'", "if config.getboolean(CONFIG_SECTION, 'stunnel_check_cert_hostname'): if check_host_supported: efs_config['checkHost'] = dns_name else: fatal_error(tls_controls_message", "] } if token: kwargs['sequenceToken'] = token cloudwatchlog_agent.get('client').put_log_events(**kwargs) def publish_cloudwatch_log(cloudwatchlog_agent,", "EndpointConnectionError BOTOCORE_PRESENT = True except ImportError: BOTOCORE_PRESENT = False VERSION", "'\\n1.3.6.1.4.1.4843.7.1 = ASN1:UTF8String:' + ap_id if security_credentials: ca_extension_str += '\\n1.3.6.1.4.1.4843.7.2", "if not os.path.isfile(rand_path): open(rand_path, 'w').close() def get_certificate_timestamp(current_time, **kwargs): updated_time =", "Debian 9, and Ubuntu 16.04), and upstart # (Amazon Linux", "mode = 0o750 try: mode_str = config.get(CONFIG_SECTION, 'state_file_dir_mode') try: mode", "'Could not start %s, unrecognized init system \"%s\"' % (WATCHDOG_SERVICE,", "% (dns_name, path) command = ['/sbin/mount.nfs4', mount_path, mountpoint, '-o', get_nfs_mount_options(options)]", "'debug' if config.has_option(CONFIG_SECTION, 'stunnel_logs_file'): global_config['output'] = config.get(CONFIG_SECTION, 'stunnel_logs_file').replace('{fs_id}', fs_id) else:", "= $dir/certificate.pem new_certs_dir = $dir/certs default_md = sha256 preserve =", "system_release_version = get_system_release_version() if not any(release in system_release_version for release", "to be renamed to a non-temporary version following a successful", "% \\ (INSTANCE_IAM_URL, SECURITY_CREDS_IAM_ROLE_HELP_URL) iam_role_name = url_request_helper(INSTANCE_IAM_URL, iam_role_unsuccessful_resp, iam_role_url_error_msg, retry_with_new_header_token=True)", "if 'aws_access_key_id' in str(e) or 'aws_secret_access_key' in str(e): logging.debug('aws_access_key_id or", "all supporting openssl ca and req files if they're not", "stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) output, _ = p.communicate() return output and", "if region: region_specific_config_section = '%s.%s' % (CONFIG_SECTION, region) if config.has_section(region_specific_config_section):", "% e) return False except NoCredentialsError as e: logging.warning('Credentials are", "common name for certificate signing request is max 64 characters", "session_token) + '\\n' request += CANONICAL_HEADERS % fs_id + '\\n'", "not supported: logging.warning('stunnel does not support \"%s\"', stunnel_option_name) return supported", "next octets are the length - \"definite form\" # -", "stunnel. # if the user has specified tlsport=X at the", "correct.\\nSee %s for more detail.' % (dns_name, 'https://docs.aws.amazon.com/console/efs/mount-dns-name'), 'Failed to", "os.path.exists(certs_dir): create_required_directory(config, certs_dir) def ca_supporting_files_check(index_path, index_attr_path, serial_path, rand_path): \"\"\"Recreate all", "complete the request, %s' % error.response) elif exception == 'AccessDeniedException':", "is None: args = sys.argv fsname = None mountpoint =", "retentionInDays=retention_days ) logging.debug('Set cloudwatch log group retention days to %s'", "19:d=1 hl=4 l= 399 prim: BIT STRING cmd = 'openssl", "respective directories\"\"\" if not os.path.isfile(index_path): open(index_path, 'w').close() if not os.path.isfile(index_attr_path):", "mount %s at %s: returncode=%d, stderr=\"%s\"' % (dns_name, mountpoint, proc.returncode,", "-inform PEM -in %s' % public_key output, err = subprocess_call(cmd,", "supported = False for line in stunnel_output: if line.startswith(stunnel_option_name): supported", "The '_netdev' option tells the init system that the #", "to reach the url at %s: status=%d, reason is %s'", "- the first octet always has the high order bit", "publish_cloudwatch_log(CLOUDWATCHLOG_AGENT, message) else: message = 'Failed to mount %s at", "stunnel_option_name) return supported def get_version_specific_stunnel_options(): stunnel_command = [_stunnel_bin(), '-help'] proc", "fatal_error('Access Point ID %s is malformed' % options['accesspoint']) if 'iam'", "'{region}' not in dns_name_format: split_dns_name_format = dns_name_format.split('.') if '{dns_name_suffix}' in", "None return opts def get_tls_port_range(config): lower_bound = config.getint(CONFIG_SECTION, 'port_range_lower_bound') upper_bound", "with open(SYSTEM_RELEASE_PATH) as f: return f.read().strip() except IOError: logging.debug('Unable to", "fs_id, exit_code=0) def check_network_status(fs_id, init_system): if init_system != 'systemd': logging.debug('Not", "session_token: efs_client_auth_str += '\\nsessionToken = EXPLICIT:0,UTF8String:' + session_token return efs_client_auth_str", "'Unsuccessful retrieval of AWS security credentials at %s.' % security_creds_lookup_url", "%(levelname)s - %(message)s')) logger = logging.getLogger() logger.setLevel(level) logger.addHandler(handler) if level_error:", "parameter log group name %s or log stream name %s", "%s' % e.response) return False elif exception == 'OperationAbortedException': logging.debug('Multiple", "os.O_DSYNC | os.O_EXCL | os.O_RDWR) try: lock_file_contents = 'PID: %s'", "more info.' % \\ (STS_ENDPOINT_URL, SECURITY_CREDS_WEBIDENTITY_HELP_URL) resp = url_request_helper(webidentity_url, unsuccessful_resp,", "get_resp_obj(request_resp, url, unsuccessful_resp) err_msg = 'Unable to reach the url", "if '{region}' not in dns_name_format: split_dns_name_format = dns_name_format.split('.') if '{dns_name_suffix}'", "%s at %s: returncode=%d, stderr=\"%s\"' % (dns_name, mountpoint, proc.returncode, err.strip())", "if check_host_supported: efs_config['checkHost'] = dns_name else: fatal_error(tls_controls_message % 'stunnel_check_cert_hostname') #", "= re.compile(r'^(?P<fs_id>fs-[0-9a-f]+)\\.efs\\.(?P<region>[a-z0-9-]+)\\.(?P<dns_name_suffix>[a-z0-9.]+)$') AP_ID_RE = re.compile('^fsap-[0-9a-f]{17}$') CREDENTIALS_KEYS = ['AccessKeyId', 'SecretAccessKey', 'Token']", "%s was already logged, %s' % (message, e.response)) return False", "ecs_security_dict and all(k in ecs_security_dict for k in CREDENTIALS_KEYS): return", "'stunnel_cafile') except NoOptionError: logging.debug('No CA file configured, using default CA", "e.code, e.reason) except URLError as e: err_msg = 'Unable to", "LICENSE accompanying this file # for the specific language governing", "None cloudwatchlog_client = get_botocore_client(config, 'logs') if not cloudwatchlog_client: return None", "iam_role_name: credentials, _ = get_aws_security_credentials_from_instance_metadata(iam_role_name) if credentials: return session.create_client(service, aws_access_key_id=credentials['AccessKeyId'],", "of the value is used to signify the number of", "try: cloudwatch_put_log_events_helper(cloudwatchlog_agent, message, token) except ClientError as e: exception =", "of IAM role name at %s.' % INSTANCE_IAM_URL iam_role_url_error_msg =", "'network.target'], stdout=devnull, stderr=devnull, close_fds=True) if rc != 0: fatal_error('Failed to", "1 if '{region}' in dns_name_format: expected_replacement_field_ct += 1 format_args['region'] =", "'tls' in options: mount_path = '127.0.0.1:%s' % path else: mount_path", "(cmd, rc, output, err), exc_info=True) try: process.kill() except OSError: #", "AWS_CREDENTIALS_FILE = os.path.expanduser(os.path.join('~' + pwd.getpwuid(os.getuid()).pw_name, '.aws', 'credentials')) AWS_CONFIG_FILE = os.path.expanduser(os.path.join('~'", "'port_range_upper_bound') if lower_bound >= upper_bound: fatal_error('Configuration option \"port_range_upper_bound\" defined as", "agent generated if aws_creds_uri: return get_aws_security_credentials_from_ecs(aws_creds_uri, True) # attempt to", "metadata at %s.' % INSTANCE_METADATA_SERVICE_URL ec2_metadata_url_error_msg = 'Unable to reach", "yet available, add \"_netdev\" to your mount options' % fs_id,", "hours=NOT_AFTER_HOURS) cmd = 'openssl ca -startdate %s -enddate %s -selfsign", "+ ' %s: ResponseCode=%d', url, request_resp.getcode()) return None resp_body =", "get_aws_security_credentials_from_awsprofile(awsprofile, True) # attempt to lookup AWS security credentials through", "os._exit(e.code) mount_completed.wait(.5) def get_init_system(comm_file='/proc/1/comm'): init_system = 'unknown' try: with open(comm_file)", "'certs'), 'index': os.path.join(base_path, mount_name, 'database/index.txt'), 'index_attr': os.path.join(base_path, mount_name, 'database/index.txt.attr'), 'serial':", "%s' % (log_group_name, retention_days, e.response)) return False else: handle_general_botocore_exceptions(e) return", "mountpoint, '-o', get_nfs_mount_options(options)] if 'netns' in options: command = ['nsenter',", "'accept': '127.0.0.1:%s', 'connect': '%s:2049', 'sslVersion': 'TLSv1.2', 'renegotiation': 'no', 'TIMEOUTbusy': '20',", "and if not, create directories (also create all intermediate directories", "= get_mount_specific_filename(fs_id, mountpoint, tls_port) + '+' # common name for", "get_iam_role_name() if iam_role_name: credentials, credentials_source = get_aws_security_credentials_from_instance_metadata(iam_role_name) if credentials and", "with open(comm_file) as f: init_system = f.read().strip() except IOError: logging.warning('Unable", "os.environ and WEB_IDENTITY_TOKEN_FILE_ENV in os.environ: credentials, credentials_source = get_aws_security_credentials_from_webidentity( os.environ[WEB_IDENTITY_ROLE_ARN_ENV],", "so if it has any child processes, they can be", "with open(config_path, 'w') as f: f.write(full_config_body) return full_config_body def ca_extension_builder(ap_id,", "Value) # - the first octet (byte) is the tag", "_sign(('AWS4' + secret_access_key).encode('utf-8'), date.strftime(DATE_ONLY_FORMAT)).digest() add_region = _sign(key_date, region).digest() add_service =", "cannot be fetched from the given awsprofile if is_fatal: log_message", "group name %s or log stream name %s is specified", "CENTOS8_RELEASE_NAME, FEDORA_RELEASE_NAME, SUSE_RELEASE_NAME] def fatal_error(user_message, log_message=None, exit_code=1): if log_message is", "e) return False return True def cloudwatch_describe_log_streams_helper(cloudwatchlog_agent): return cloudwatchlog_agent.get('client').describe_log_streams( logGroupName=cloudwatchlog_agent.get('log_group_name'),", "to if hostname == expected_dns_name: return fs_id, path else: create_default_cloudwatchlog_agent_if_not_exist(config)", "retention_days) except ClientError as e: exception = e.response['Error']['Code'] if exception", "credentials_source = get_aws_security_credentials_from_instance_metadata(iam_role_name) if credentials and credentials_source: return credentials, credentials_source", "+ get_credential_scope(date, region)) request = HTTP_REQUEST_METHOD + '\\n' request +=", "proc.returncode, err.strip()) fatal_error(err.strip(), message, proc.returncode) def usage(out, exit_code=1): out.write('Usage: mount.efs", "if they're not present in their respective directories\"\"\" if not", "tls_port) global_config = dict(STUNNEL_GLOBAL_CONFIG) if config.getboolean(CONFIG_SECTION, 'stunnel_debug_enabled'): global_config['debug'] = 'debug'", "status: with open(os.devnull, 'w') as devnull: subprocess.Popen(['/sbin/start', WATCHDOG_SERVICE], stdout=devnull, stderr=devnull,", "is specified incorrectly, %s' % (log_group_name, log_stream_name, e.response)) return False", "mountpoint, tls_port, dns_name, verify_level, ocsp_enabled, options, log_dir=LOG_DIR, cert_details=None): \"\"\" Serializes", "config_section) _validate_replacement_field_count(dns_name_format, expected_replacement_field_ct) dns_name = dns_name_format.format(**format_args) try: socket.gethostbyname(dns_name) except socket.gaierror:", ".5s during the mount attempt to fail fast if the", "awsprofile = options.get('awsprofile') if not awsprofile and use_iam: for file_path", "urllib import urlencode except ImportError: from urllib.request import urlopen, Request", "target matches exactly the DNS name the CNAME resolves to", "from configparser import ConfigParser, NoOptionError, NoSectionError try: from urllib.parse import", "'efs-utils-lock') f = os.open(lock_file, os.O_CREAT | os.O_DSYNC | os.O_EXCL |", "security credentials. See %s for more info.' \\ % (ecs_uri,", "# Copy this script to /sbin/mount.efs and make sure it", "read_only_mode) do_with_lock(generate_key) return key def create_certificate_signing_request(config_path, private_key, csr_path): cmd =", "an integer' % options['tlsport']) if 'ocsp' in options and 'noocsp'", "credentials['Token'] = session_token except NoOptionError as e: if 'aws_access_key_id' in", "try: cloudwatch_create_log_group_helper(cloudwatchlog_client, log_group_name) except ClientError as e: exception = e.response['Error']['Code']", "so we have to hand-serialize it. \"\"\" mount_filename = get_mount_specific_filename(fs_id,", "subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) out, err = proc.communicate() if proc.returncode", "if '--version' in args[1:]: sys.stdout.write('%s Version: %s\\n' % (args[0], VERSION))", "+ '?' + urlencode({ 'Version': '2011-06-15', 'Action': 'AssumeRoleWithWebIdentity', 'RoleArn': role_arn,", "json: %s. Returning response body.' % (str(resp_body), e)) return resp_body", "+ secondaries)) except socket.gaierror: create_default_cloudwatchlog_agent_if_not_exist(config) fatal_error( 'Failed to resolve \"%s\"", "e) return None try: log_stream = response['logStreams'][0] return log_stream.get('uploadSequenceToken') except", "options) global CLOUDWATCHLOG_AGENT CLOUDWATCHLOG_AGENT = bootstrap_cloudwatch_logging(config, fs_id) check_unsupported_options(options) check_options_validity(options) init_system", "get_region_from_instance_metadata(): instance_identity = get_instance_identity_info_from_instance_metadata('region') if not instance_identity: raise Exception(\"Cannot retrieve", "exception == 'ServiceUnavailableException': logging.debug('The service cannot complete the request, %s'", "as e: logging.warning('%s not present in %s: %s' % (property,", "name the CNAME resolves to if hostname == expected_dns_name: return", "+= '\\n1.3.6.1.4.1.4843.7.3 = ASN1:UTF8String:' + fs_id if client_info: ca_extension_str +=", "target' % remote ) for hostname in hostnames: efs_fqdn_match =", "is_nfs_mount(mountpoint): sys.stdout.write(\"%s is already mounted, please run 'mount' command to", "if header: lines.append('[%s]' % header) for k, v in config.items():", "os.O_EXCL | os.O_RDWR) try: lock_file_contents = 'PID: %s' % os.getpid()", "credentials file (~/.aws/credentials) # and configs file (~/.aws/config) with given", "proc = subprocess.Popen( ['/sbin/status', WATCHDOG_SERVICE], stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) status, _", "verify_level > 0: add_stunnel_ca_options(efs_config, config, options) if cert_details: efs_config['cert'] =", "efs_config['checkHost'] = dns_name else: fatal_error(tls_controls_message % 'stunnel_check_cert_hostname') # Only use", "bits (1) offset = 1 + 1 + num_length_octets +", "client_source return client_info def create_certificate(config, mount_name, common_name, region, fs_id, security_credentials,", "token) except ClientError as e: exception = e.response['Error']['Code'] if exception", "get_client_info(config): client_info = {} # source key/value pair in config", "% (private_key, public_key) subprocess_call(cmd, 'Failed to create public key') def", "state_file_dir=STATE_FILE_DIR): tls_port = choose_tls_port(config, options) # override the tlsport option", "as e: logging.warning('Could not connect to the endpoint, %s' %", "credentials service' % \\ (AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE) fatal_error(error_msg, error_msg) def get_aws_security_credentials_from_awsprofile(awsprofile,", "out private key creation lock, sleeping 50 ms') time.sleep(0.05) else:", "instance_metadata\") return instance_identity def get_instance_identity_info_from_instance_metadata(property): ec2_metadata_unsuccessful_resp = 'Unsuccessful retrieval of", "'dns_name_suffix') logging.debug(\"Using dns_name_suffix %s in config section [%s]\", format_args.get('dns_name_suffix'), config_section)", "'config.conf') certificate_signing_request = os.path.join(tls_paths['mount_dir'], 'request.csr') certificate = os.path.join(tls_paths['mount_dir'], 'certificate.pem') ca_dirs_check(config,", "return False except EndpointConnectionError as e: logging.warning('Could not connect to", "request is max 64 characters cert_details['commonName'] = socket.gethostname()[0:64] cert_details['region'] =", "fs_id, 'Failed to start TLS tunnel (errno=%d). stdout=\"%s\" stderr=\"%s\"' %", "state_file_dir, fs_id, mountpoint, tls_port, dns_name, verify_level, ocsp_enabled, options, cert_details=cert_details) tunnel_args", "% INSTANCE_METADATA_SERVICE_URL instance_identity = url_request_helper(INSTANCE_METADATA_SERVICE_URL, ec2_metadata_unsuccessful_resp, ec2_metadata_url_error_msg, retry_with_new_header_token=True) if instance_identity:", "for the specific language governing permissions and limitations under #", "when mounting with \"awscredsuri\"') if 'awscredsuri' in options and 'awsprofile'", "hl=4 l= 418 cons: SEQUENCE # 4:d=1 hl=2 l= 13", "= token cloudwatchlog_agent.get('client').put_log_events(**kwargs) def publish_cloudwatch_log(cloudwatchlog_agent, message): if not cloudwatchlog_agent or", "os.makedirs(directory, mode) except OSError as e: if errno.EEXIST != e.errno", "instructions at ' 'https://docs.aws.amazon.com/efs/latest/ug/using-amazon-efs-utils.html#upgrading-stunnel') def find_command_path(command, install_method): try: env_path =", "parameter in the efs-utils configuration file.', message) metadata_exception = 'Unknown", "'2011-06-15', 'Action': 'AssumeRoleWithWebIdentity', 'RoleArn': role_arn, 'RoleSessionName': 'efs-mount-helper', 'WebIdentityToken': token })", "log group name %s or retention in days %s is", "logging.debug('Log group %s already exist, %s' % (log_group_name, e.response)) return", "mode_str = config.get(CONFIG_SECTION, 'state_file_dir_mode') try: mode = int(mode_str, 8) except", "msg.encode('utf-8'), hashlib.sha256) key_date = _sign(('AWS4' + secret_access_key).encode('utf-8'), date.strftime(DATE_ONLY_FORMAT)).digest() add_region =", "EndpointConnectionError as e: logging.warning('Could not connect to the endpoint, %s'", "to create private key') read_only_mode = 0o400 os.chmod(key, read_only_mode) do_with_lock(generate_key)", "SigV4 Auth ALGORITHM = 'AWS4-HMAC-SHA256' AWS4_REQUEST = 'aws4_request' HTTP_REQUEST_METHOD =", "for key, value in client_info.items(): efs_client_info_str += '\\n%s = UTF8String:%s'", "% options['tlsport']) if 'ocsp' in options and 'noocsp' in options:", "at man/mount.efs.8 if 'nfsvers' not in options and 'vers' not", "'X-Amz-Credential': credential, 'X-Amz-Date': quote_plus(formatted_datetime), 'X-Amz-Expires': 86400, 'X-Amz-SignedHeaders': SIGNED_HEADERS, } if", "parse_arguments_early_exit() assert_root() config = read_config() bootstrap_logging(config) fs_id, path, mountpoint, options", "calculate_signature(string_to_sign, date, secret_access_key, region): \"\"\" Calculate the Signature - https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html", "\"value\" aka content # # For a BIT STRING, the", "to create public key') def subprocess_call(cmd, error_message): \"\"\"Helper method to", "accompanying this file # for the specific language governing permissions", "resp_dict except ValueError as e: logging.info('ValueError parsing \"%s\" into json:", "configuration file.', message) metadata_exception = 'Unknown error' try: return config.get(CONFIG_SECTION,", "due to lack of multi-threading support in openssl 'database_dir': os.path.join(base_path,", "read %s', SYSTEM_RELEASE_PATH) try: with open(OS_RELEASE_PATH) as f: for line", "= device.split(':', 1) except ValueError: remote = device path =", "[] if header: lines.append('[%s]' % header) for k, v in", "to_nfs_option(k, v): if v is None: return k return '%s=%s'", "json.loads(resp_body.decode(request_resp.headers.get_content_charset() or 'us-ascii')) return resp_dict except ValueError as e: logging.info('ValueError", "at every mount since SigV4 signature can change\"\"\" public_key_path =", "if it has any child processes, they can be killed", "must include {fs_id}') format_args = {'fs_id': fs_id} expected_replacement_field_ct = 1", "% error.response) else: logging.debug('Unexpected error: %s' % error) def main():", "e.response)) elif exception == 'ResourceNotFoundException': logging.debug('Either log group %s or", "retrieving region. Please set the \"region\" parameter in the efs-utils", "= os.path.join(state_file_dir, 'stunnel-config.%s' % mount_filename) with open(stunnel_config_file, 'w') as f:", "path to mount\"\"\" try: remote, path = device.split(':', 1) except", "security_credentials, ap_id, client_info, base_path=STATE_FILE_DIR): current_time = get_utc_now() tls_paths = tls_paths_dictionary(mount_name,", "= { 'Action': 'Connect', # Public key hash is included", "[primary] + secondaries)) except socket.gaierror: create_default_cloudwatchlog_agent_if_not_exist(config) fatal_error( 'Failed to resolve", "split_dns_name_format = dns_name_format.split('.') if '{dns_name_suffix}' in dns_name_format: return split_dns_name_format[-2] elif", "the init system that the # 'efs' type is a", "= efs_fqdn_match.group('fs_id') expected_dns_name = get_dns_name(config, fs_id) # check that the", "the \"region\" ' 'parameter in the efs-utils configuration file.') return", "k, v in headers.items(): req.add_header(k, v) request_resp = urlopen(req, timeout=1)", "the \"value\" aka content # # For a BIT STRING,", "yield f finally: os.close(f) os.remove(lock_file) def do_with_lock(function): while True: try:", "user_message) logging.error(log_message) publish_cloudwatch_log(CLOUDWATCHLOG_AGENT, 'Mount failed, %s' % log_message) sys.exit(exit_code) def", "- length of 399 # - 00 - no unused", "= 3 EFS_ONLY_OPTIONS = [ 'accesspoint', 'awscredsuri', 'awsprofile', 'cafile', 'iam',", "if not os.path.exists(database_dir): create_required_directory(config, database_dir) if not os.path.exists(certs_dir): create_required_directory(config, certs_dir)", "as e: exception = e.response['Error']['Code'] if exception == 'ResourceAlreadyExistsException': logging.debug('Log", "== 'InvalidParameterException': logging.error('Log group name %s is specified incorrectly, %s'", "* 1000)), 'message': message } ] } if token: kwargs['sequenceToken']", "the instance security credentials service' % \\ (AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE) fatal_error(error_msg,", "if args is None: args = sys.argv if '-h' in", "if line.startswith(stunnel_option_name): supported = True break if not supported: logging.warning('stunnel", "= STS_ENDPOINT_URL + '?' + urlencode({ 'Version': '2011-06-15', 'Action': 'AssumeRoleWithWebIdentity',", "= '/etc/amazon/efs/efs-utils.crt' NOT_BEFORE_MINS = 15 NOT_AFTER_HOURS = 3 EFS_ONLY_OPTIONS =", "for more info.' \\ % (ecs_uri, SECURITY_CREDS_ECS_URI_HELP_URL) ecs_security_dict = url_request_helper(ecs_uri,", "1 key = key[offset:] sha1 = hashlib.sha1() sha1.update(key) return sha1.hexdigest()", "Linux 2, CentOS 7, RHEL 7, Debian 9, and Ubuntu", "metadata calls fail. \"\"\" dns_name_format = config.get(CONFIG_SECTION, 'dns_name_format') if '{region}'", "LOG_DIR = '/var/log/amazon/efs' LOG_FILE = 'mount.log' STATE_FILE_DIR = '/var/run/efs' PRIVATE_KEY_FILE", "stunnel_config_file def write_tls_tunnel_state_file(fs_id, mountpoint, tls_port, tunnel_pid, command, files, state_file_dir, cert_details=None):", "have its own ca mode assets due to lack of", "excluded from the SubjectKeyIdentifier hash, per # https://tools.ietf.org/html/rfc5280#section-4.2.1.2 # #", "v in headers.items(): req.add_header(k, v) request_resp = urlopen(req, timeout=1) return", "= get_cloudwatch_log_stream_name(fs_id) return { 'log_group_name': log_group_name, 'retention_days': int(retention_days), 'log_stream_name': log_stream_name", "EFS_FQDN_RE = re.compile(r'^(?P<fs_id>fs-[0-9a-f]+)\\.efs\\.(?P<region>[a-z0-9-]+)\\.(?P<dns_name_suffix>[a-z0-9.]+)$') AP_ID_RE = re.compile('^fsap-[0-9a-f]{17}$') CREDENTIALS_KEYS = ['AccessKeyId', 'SecretAccessKey',", "= efs_client_auth_builder(public_key_path, security_credentials['AccessKeyId'], security_credentials['SecretAccessKey'], date, region, fs_id, security_credentials['Token']) if security_credentials", "the man page as well at man/mount.efs.8 if 'nfsvers' not", "region, SERVICE, AWS4_REQUEST]) def match_device(config, device): \"\"\"Return the EFS id", "check_network_status(fs_id, init_system): if init_system != 'systemd': logging.debug('Not testing network on", "role name attached to instance # through IAM role name", "(security_creds_lookup_url, SECURITY_CREDS_IAM_ROLE_HELP_URL) iam_security_dict = url_request_helper(security_creds_lookup_url, unsuccessful_resp, url_error_msg, retry_with_new_header_token=True) if iam_security_dict", "verify_level, ocsp_enabled, options, cert_details=cert_details) tunnel_args = [_stunnel_bin(), stunnel_config_file] if 'netns'", "common_name, ca_extension_body, efs_client_auth_body, efs_client_info_body) with open(config_path, 'w') as f: f.write(full_config_body)", "for this file system. The '_netdev' option tells the init", "def get_region_from_legacy_dns_format(config): \"\"\" For backwards compatibility check dns_name_format to obtain", "INSTANCE_METADATA_TOKEN_URL = 'http://169.254.169.254/latest/api/token' INSTANCE_METADATA_SERVICE_URL = 'http://169.254.169.254/latest/dynamic/instance-identity/document/' INSTANCE_IAM_URL = 'http://169.254.169.254/latest/meta-data/iam/security-credentials/' SECURITY_CREDS_ECS_URI_HELP_URL", "# Only use the config setting if the override is", "# check if aws access key id is found under", "directories if they don't exist).\"\"\" if not os.path.exists(database_dir): create_required_directory(config, database_dir)", "has specified tlsport=X at the command line this will just", "error_message = '%s, error is: %s' % (error_message, err) fatal_error(error_message,", "awsprofile def url_request_helper(url, unsuccessful_resp, url_error_msg, headers={}, retry_with_new_header_token=False): try: req =", "else: handle_general_botocore_exceptions(e) return None except NoCredentialsError as e: logging.warning('Credentials are", "get_log_stream_next_token(cloudwatchlog_agent): try: response = cloudwatch_describe_log_streams_helper(cloudwatchlog_agent) except ClientError as e: exception", "not os.path.isfile(serial_path): with open(serial_path, 'w+') as f: f.write('00') if not", "= efs_config['accept'] % tls_port efs_config['connect'] = efs_config['connect'] % dns_name efs_config['verify']", "instance security credentials service' % \\ (AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE) fatal_error(error_msg, error_msg)", "line.decode('utf-8') if not key_line: err_msg = 'Public key file, %s,", "IMDSv2, Unauthorized 401 error will be thrown, # to retrieve", "# attempt to lookup AWS security credentials with IAM role", "upper_bound = get_tls_port_range(config) tls_ports = list(range(lower_bound, upper_bound)) # Choose a", "found in config file %s', awsprofile, file_path) return credentials def", "else: mount_path = '%s:%s' % (dns_name, path) command = ['/sbin/mount.nfs4',", "STRING' in line.decode('utf-8'): key_line = line.decode('utf-8') if not key_line: err_msg", "options_index = args.index('-o') + 1 options = parse_options(args[options_index]) if not", "resp_body_type is str else resp_body.decode('utf-8') def parse_options(options): opts = {}", "= get_mount_specific_filename(fs_id, mountpoint, tls_port) global_config = dict(STUNNEL_GLOBAL_CONFIG) if config.getboolean(CONFIG_SECTION, 'stunnel_debug_enabled'):", "fs_id) check_unsupported_options(options) check_options_validity(options) init_system = get_init_system() check_network_status(fs_id, init_system) dns_name =", "+= '\\nsigv4DateTime = UTCTIME:' + date.strftime(CERT_DATETIME_FORMAT) if session_token: efs_client_auth_str +=", "config file \"%s\"', mode_str, CONFIG_FILE) except NoOptionError: pass try: os.makedirs(directory,", "- check that your file system ID is correct.\\nSee %s", "exception == 'ResourceNotFoundException': logging.error('Either log group %s or log stream", "can change\"\"\" public_key_path = os.path.join(directory, 'publicKey.pem') ca_extension_body = ca_extension_builder(ap_id, security_credentials,", "config_section = CONFIG_SECTION region = format_args.get('region') if region: region_specific_config_section =", "stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) proc.wait() _, err = proc.communicate() stunnel_output =", "return None return { 'client': cloudwatchlog_client, 'log_group_name': log_group_name, 'log_stream_name': log_stream_name", "url_request_helper(webidentity_url, unsuccessful_resp, url_error_msg, headers={'Accept': 'application/json'}) if resp: creds = resp", "private keys is slow, so we will create one private", "tls_port efs_config['connect'] = efs_config['connect'] % dns_name efs_config['verify'] = verify_level if", "retention_days = DEFAULT_RETENTION_DAYS if config.has_option(CLOUDWATCH_LOG_SECTION, 'retention_in_days'): retention_days = config.get(CLOUDWATCH_LOG_SECTION, 'retention_in_days')", "def put_cloudwatch_log_retention_policy(cloudwatchlog_client, log_group_name, retention_days): try: cloudwatch_put_retention_policy_helper(cloudwatchlog_client, log_group_name, retention_days) except ClientError", "+ timedelta(**kwargs) return updated_time.strftime(CERT_DATETIME_FORMAT) def get_utc_now(): \"\"\" Wrapped for patching", "url, request_resp.getcode()) return None resp_body = request_resp.read() resp_body_type = type(resp_body)", "This functionality should only be used if region is not", "check_network_status(fs_id, init_system) dns_name = get_dns_name(config, fs_id) if 'tls' in options:", "fatal_error('Failed to initialize TLS tunnel for %s' % fs_id, 'Failed", "high order bit) # - 018f - length of 399", "as f: f.write(full_config_body) return full_config_body def ca_extension_builder(ap_id, security_credentials, fs_id, client_info):", "a number of octets # - the remaining octets are", "create_canonical_request(public_key_hash, date, access_key_id, region, fs_id, session_token) string_to_sign = create_string_to_sign(canonical_request, date,", "= [_stunnel_bin(), '-help'] proc = subprocess.Popen(stunnel_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) proc.wait()", "as devnull: subprocess.Popen(['/sbin/start', WATCHDOG_SERVICE], stdout=devnull, stderr=devnull, close_fds=True) elif 'start' in", "to /etc/fstab. The syntax of an fstab entry is: #", "None session = botocore.session.get_session() region = get_target_region(config) iam_role_name = get_iam_role_name()", "OS_RELEASE_PATH = '/etc/os-release' RHEL8_RELEASE_NAME = 'Red Hat Enterprise Linux release", "= 'client-info' CLIENT_SOURCE_STR_LEN_LIMIT = 100 CLOUDWATCH_LOG_SECTION = 'cloudwatch-log' DEFAULT_CLOUDWATCH_LOG_GROUP =", "subprocess import sys import threading import time from contextlib import", "rand_path): \"\"\"Recreate all supporting openssl ca and req files if", "stderr=\"%s\"' % (tunnel_proc.returncode, out.strip(), err.strip())) def poll_tunnel_process(tunnel_proc, fs_id, mount_completed): \"\"\"", "'=' in o: k, v = o.split('=') opts[k] = v", "= get_utc_now() tls_paths = tls_paths_dictionary(mount_name, base_path) certificate_config = os.path.join(tls_paths['mount_dir'], 'config.conf')", "the same log group %s were in conflict, %s' %", "in sorted(canonical_query_params.items())]) def create_string_to_sign(canonical_request, date, region): \"\"\" Create a String", "e: err_msg = 'Unable to reach the url at %s,", "mount_completed)) t.daemon = True t.start() mount_nfs(dns_name, path, mountpoint, options) mount_completed.set()", "change\"\"\" public_key_path = os.path.join(directory, 'publicKey.pem') ca_extension_body = ca_extension_builder(ap_id, security_credentials, fs_id,", "header=None): lines = [] if header: lines.append('[%s]' % header) for", "['/sbin/status', WATCHDOG_SERVICE], stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) status, _ = proc.communicate() if", "None try: log_stream = response['logStreams'][0] return log_stream.get('uploadSequenceToken') except (IndexError, TypeError,", "command line this will just re-set tlsport to X. options['tlsport']", "else: mount_nfs(dns_name, path, mountpoint, options) if '__main__' == __name__: main()", "uri iam_role_name = get_iam_role_name() if iam_role_name: credentials, credentials_source = get_aws_security_credentials_from_instance_metadata(iam_role_name)", "'database/serial'), 'rand': os.path.join(base_path, mount_name, 'database/.rand') } return tls_dict def get_public_key_sha1(public_key):", "= 'https://sts.amazonaws.com/' INSTANCE_METADATA_TOKEN_URL = 'http://169.254.169.254/latest/api/token' INSTANCE_METADATA_SERVICE_URL = 'http://169.254.169.254/latest/dynamic/instance-identity/document/' INSTANCE_IAM_URL =", "attempt to lookup AWS security credentials in AWS credentials file", "= os.path.join(tls_paths['mount_dir'], 'publicKey.pem') create_public_key(private_key, public_key) create_ca_conf(certificate_config, common_name, tls_paths['mount_dir'], private_key, current_time,", "= Request(INSTANCE_METADATA_TOKEN_URL) request.add_header('X-aws-ec2-metadata-token-ttl-seconds', 21600) request.get_method = lambda: 'PUT' res =", "import NoOptionError, NoSectionError except ImportError: from configparser import ConfigParser, NoOptionError,", "log_message) sys.exit(exit_code) def get_target_region(config): def _fatal_error(message): fatal_error('Error retrieving region. Please", ">= upper_bound: fatal_error('Configuration option \"port_range_upper_bound\" defined as %d ' 'must", "setting logging level to %s', raw_level, level) def get_dns_name(config, fs_id):", "' \\ 'or disable \"%%s\" in %s.\\nSee %s for more", "(fs_id) else: log_stream_name = 'default - mount.log' return log_stream_name def", "err) fatal_error(error_message, error_message) def ca_dirs_check(config, database_dir, certs_dir): \"\"\"Check if mount's", "and https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html \"\"\" if not use_iam: return None, None #", "efs_client_auth_str def efs_client_info_builder(client_info): efs_client_info_str = '[ efs_client_info ]' for key,", "credentials_source: return credentials, credentials_source error_msg = 'AWS Access Key ID", "\"\"\" dns_name_format = config.get(CONFIG_SECTION, 'dns_name_format') if '{region}' not in dns_name_format:", "os.environ[WEB_IDENTITY_TOKEN_FILE_ENV], False ) if credentials and credentials_source: return credentials, credentials_source", "'retrans' not in options: options['retrans'] = '2' if 'noresvport' not", "cloudwatch_create_log_group_helper(cloudwatchlog_client, log_group_name) except ClientError as e: exception = e.response['Error']['Code'] if", "config.get(CONFIG_SECTION, 'dns_name_format') if '{region}' not in dns_name_format: split_dns_name_format = dns_name_format.split('.')", "files, state_file_dir, cert_details=None): \"\"\" Return the name of the temporary", "e) return False except Exception as e: logging.warning('Unknown error, %s.'", "tls_port) state = { 'pid': tunnel_pid, 'cmd': command, 'files': files,", "exception == 'DataAlreadyAcceptedException': logging.debug('The event %s was already logged, %s'", "token is not valid, %s' % e.response) return False elif", "in str(e): logging.debug('aws_session_token not found in %s', file_path) credentials['AccessKeyId'] =", "= subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) output, _ = p.communicate() return", "= DEFAULT_STUNNEL_CAFILE if not os.path.exists(stunnel_cafile): fatal_error('Failed to find certificate authority", "a BIT STRING, the first octet of the value is", "region = format_args.get('region') if region: region_specific_config_section = '%s.%s' % (CONFIG_SECTION,", "[ 'l:SO_REUSEADDR=yes', 'a:SO_BINDTODEVICE=lo', ], } STUNNEL_EFS_CONFIG = { 'client': 'yes',", "fs_id, security_credentials, ap_id, client_info, base_path=STATE_FILE_DIR): current_time = get_utc_now() tls_paths =", "= '%s - mount.log' % (instance_id) elif fs_id: log_stream_name =", "a String to Sign - https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html \"\"\" string_to_sign = ALGORITHM", "command = ['/sbin/mount.nfs4', mount_path, mountpoint, '-o', get_nfs_mount_options(options)] if 'netns' in", "fs_id=None): if not check_if_cloudwatch_log_enabled(config): return None cloudwatchlog_client = get_botocore_client(config, 'logs')", "\"iam\" option is required when mounting with \"awscredsuri\"') if 'awscredsuri'", "option \"port_range_upper_bound\" defined as %d ' 'must be strictly greater", "opts[k] = v else: opts[o] = None return opts def", "str(e): logging.debug('aws_access_key_id or aws_secret_access_key not found in %s under named", "aws_creds_uri: kwargs = {'aws_creds_uri': aws_creds_uri} else: kwargs = {'awsprofile': get_aws_profile(options,", "command = ['nsenter', '--net=' + options['netns']] + command logging.info('Executing: \"%s\"',", "get_nfs_mount_options(options): # If you change these options, update the man", "ca and req files if they're not present in their", "tls_paths['mount_dir'], private_key, current_time, region, fs_id, security_credentials, ap_id, client_info) create_certificate_signing_request(certificate_config, private_key,", "# the License. # # # Copy this script to", "True) # attempt to lookup AWS security credentials in AWS", "hl=4 l= 399 prim: BIT STRING cmd = 'openssl asn1parse", "with open(os.devnull, 'w') as devnull: subprocess.Popen(['systemctl', 'start', WATCHDOG_SERVICE], stdout=devnull, stderr=devnull,", "as %d.' % (upper_bound, lower_bound)) return lower_bound, upper_bound def choose_tls_port(config,", "(%s), config file (%s), ' \\ 'from ECS credentials relative", "# for the specific language governing permissions and limitations under", "None: args = sys.argv if '-h' in args[1:] or '--help'", "Version: %s\\n' % (args[0], VERSION)) sys.exit(0) def parse_arguments(config, args=None): \"\"\"Parse", "[ ca ] default_ca = local_ca [ local_ca ] database", "\\ .get('AssumeRoleWithWebIdentityResult', {}) \\ .get('Credentials', {}) if all(k in creds", "headers=headers, method='PUT') res = urlopen(req) return res.read() def get_aws_security_credentials(use_iam, awsprofile=None,", "region_name=region) return session.create_client(service, region_name=region) def get_cloudwatchlog_config(config, fs_id=None): log_group_name = DEFAULT_CLOUDWATCH_LOG_GROUP", "and upstart # (Amazon Linux 2017.09). # # Once there", "config.getboolean(CONFIG_SECTION, 'stunnel_check_cert_validity') def get_mount_specific_filename(fs_id, mountpoint, tls_port): return '%s.%s.%d' % (fs_id,", "DNS ' 'name' % remote, 'Failed to resolve \"%s\"' %", "be able to mount an EFS file system by its", "except NoOptionError: pass try: os.makedirs(directory, mode) except OSError as e:", "format, so we have to hand-serialize it. \"\"\" mount_filename =", "we have to hand-serialize it. \"\"\" mount_filename = get_mount_specific_filename(fs_id, mountpoint,", "logGroupName=log_group_name, logStreamName=log_stream_name ) logging.info('Created cloudwatch log stream %s in log", "%s to retrieve EC2 instance metadata.' % INSTANCE_METADATA_SERVICE_URL instance_identity =", "= session_token except NoOptionError as e: if 'aws_access_key_id' in str(e)", "return False elif exception == 'InvalidParameterException': logging.debug('One of the parameter", "the number of unused bits that exist in the last", "'PUT' res = opener.open(request) return res.read() except NameError: headers =", "a different port range in %s' % (lower_bound, upper_bound, CONFIG_FILE))", "ConfigParser from ConfigParser import NoOptionError, NoSectionError except ImportError: from configparser", "= f.read() except Exception as e: if is_fatal: unsuccessful_resp =", "[_stunnel_bin(), '-help'] proc = subprocess.Popen(stunnel_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) proc.wait() _,", "False return True def cloudwatch_describe_log_streams_helper(cloudwatchlog_agent): return cloudwatchlog_agent.get('client').describe_log_streams( logGroupName=cloudwatchlog_agent.get('log_group_name'), logStreamNamePrefix=cloudwatchlog_agent.get('log_stream_name') )", "'delay': 'yes', } WATCHDOG_SERVICE = 'amazon-efs-mount-watchdog' SYSTEM_RELEASE_PATH = '/etc/system-release' OS_RELEASE_PATH", "+ pwd.getpwuid(os.getuid()).pw_name, '.aws', 'config')) CA_CONFIG_BODY = \"\"\"dir = %s RANDFILE", "in options: command = ['nsenter', '--net=' + options['netns']] + command", "Copyright 2017-2018 Amazon.com, Inc. and its affiliates. All Rights Reserved.", "in o: k, v = o.split('=') opts[k] = v else:", "os.chmod(key, read_only_mode) do_with_lock(generate_key) return key def create_certificate_signing_request(config_path, private_key, csr_path): cmd", "config.getboolean(CONFIG_SECTION, 'stunnel_debug_enabled'): global_config['debug'] = 'debug' if config.has_option(CONFIG_SECTION, 'stunnel_logs_file'): global_config['output'] =", "'efs' type will cause '/sbin/mount.efs' to be called by 'mount", "= 'openSUSE Leap' SKIP_NO_LIBWRAP_RELEASES = [RHEL8_RELEASE_NAME, CENTOS8_RELEASE_NAME, FEDORA_RELEASE_NAME, SUSE_RELEASE_NAME] def", "def get_aws_security_credentials_from_webidentity(role_arn, token_file, is_fatal=False): try: with open(token_file, 'r') as f:", "= ['AccessKeyId', 'SecretAccessKey', 'Token'] ECS_URI_ENV = 'AWS_CONTAINER_CREDENTIALS_RELATIVE_URI' ECS_TASK_METADATA_API = 'http://169.254.170.2'", "error messages\"\"\" retry_times = 3 for retry in range(retry_times): process", "in \"dns_name_format\" failed') _fatal_error(metadata_exception) def get_region_from_instance_metadata(): instance_identity = get_instance_identity_info_from_instance_metadata('region') if", "\"\"\" Calculate the Signature - https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html \"\"\" def _sign(key, msg):", "open(SYSTEM_RELEASE_PATH) as f: return f.read().strip() except IOError: logging.debug('Unable to read", "the signature to a specific key pair to avoid replay", "please run 'mount' command to verify\\n\" % mountpoint) logging.warning(\"%s is", "and 'awsprofile' in options: fatal_error('The \"awscredsuri\" and \"awsprofile\" options are", "def assert_root(): if os.geteuid() != 0: sys.stderr.write('only root can run", "get_region_from_legacy_dns_format(config) sys.stdout.write('Warning: region obtained from \"dns_name_format\" field. Please set the", "%s, correctly' % public_key) key_line = '' for line in", "system_release_version for release in SKIP_NO_LIBWRAP_RELEASES): efs_config['libwrap'] = 'no' stunnel_config =", "elif exception == 'DataAlreadyAcceptedException': logging.debug('The event %s was already logged,", "'GET' CANONICAL_URI = '/' CANONICAL_HEADERS_DICT = { 'host': '%s' }", "} def get_cloudwatch_log_stream_name(fs_id=None): instance_id = get_instance_identity_info_from_instance_metadata('instanceId') if instance_id and fs_id:", "urlopen(req, timeout=1) return get_resp_obj(request_resp, url, unsuccessful_resp) except HTTPError as e:", "'Token': None} try: access_key = aws_credentials_configs.get(awsprofile, 'aws_access_key_id') secret_key = aws_credentials_configs.get(awsprofile,", "key/value pair in config file if config.has_option(CLIENT_INFO_SECTION, 'source'): client_source =", "public_key_hash = get_public_key_sha1(public_key_path) canonical_request = create_canonical_request(public_key_hash, date, access_key_id, region, fs_id,", "process group so if it has any child processes, they", "the MIT License. See the LICENSE accompanying this file #", "@contextmanager def open_lock_file(): lock_file = os.path.join(base_path, 'efs-utils-lock') f = os.open(lock_file,", "however, that we have to include a locking mechanism to", "= json.loads(resp_body) else: resp_dict = json.loads(resp_body.decode(request_resp.headers.get_content_charset() or 'us-ascii')) return resp_dict", "remote path to mount\"\"\" try: remote, path = device.split(':', 1)", "level to %s', raw_level, level) def get_dns_name(config, fs_id): def _validate_replacement_field_count(format_str,", "level_error = False if not level: # delay logging error", "an fstab entry is: # # [Device] [Mount Point] [File", "% mountpoint) return with bootstrap_tls(config, init_system, dns_name, fs_id, mountpoint, options)", "} def create_default_cloudwatchlog_agent_if_not_exist(config): if not check_if_cloudwatch_log_enabled(config): return None global CLOUDWATCHLOG_AGENT", "STATE_FILE_DIR = '/var/run/efs' PRIVATE_KEY_FILE = '/etc/amazon/efs/privateKey.pem' DATE_ONLY_FORMAT = '%Y%m%d' SIGV4_DATETIME_FORMAT", "not in options: options['noresvport'] = None if 'tls' in options:", "%s.\\nSee %s for more detail.' % (CONFIG_FILE, 'https://docs.aws.amazon.com/console/efs/troubleshooting-tls') if config.getboolean(CONFIG_SECTION,", "options=%s', VERSION, options) global CLOUDWATCHLOG_AGENT CLOUDWATCHLOG_AGENT = bootstrap_cloudwatch_logging(config, fs_id) check_unsupported_options(options)", "os.close(f) os.remove(lock_file) def do_with_lock(function): while True: try: with open_lock_file(): return", "key[1] & 0b01111111 # Exclude the tag (1), length (1", "system ID is correct.\\nSee %s for more detail.' % (dns_name,", "+ '\\n' string_to_sign += date.strftime(SIGV4_DATETIME_FORMAT) + '\\n' string_to_sign += get_credential_scope(date,", "\"_netdev\" to your mount options' % fs_id, exit_code=0) def check_network_status(fs_id,", "False def cloudwatch_create_log_group_helper(cloudwatchlog_client, log_group_name): cloudwatchlog_client.create_log_group( logGroupName=log_group_name ) logging.info('Created cloudwatch log", "'aws_access_key_id' in str(e) or 'aws_secret_access_key' in str(e): logging.debug('aws_access_key_id or aws_secret_access_key", "'awsprofile', 'cafile', 'iam', 'netns', 'noocsp', 'ocsp', 'tls', 'tlsport', 'verify' ]", "ports_to_try = tls_ports[mid:] + tls_ports[:mid] assert len(tls_ports) == len(ports_to_try) sock", "may be 0) as a number of octets # -", "every .5s during the mount attempt to fail fast if", "return False except Exception as e: logging.warning('Unknown error, %s.' %", "if resp_body_type is str: resp_dict = json.loads(resp_body) else: resp_dict =", "in the range [%d, %d], try specifying a different port", "headers.items(): req.add_header(k, v) request_resp = urlopen(req, timeout=1) return get_resp_obj(request_resp, url,", "option so that we can later override the port the", "b'OCSPaia') return check_host_supported, ocsp_aia_supported def _stunnel_bin(): return find_command_path('stunnel', 'Please install", "%s' % os.getpid() os.write(f, lock_file_contents.encode('utf-8')) yield f finally: os.close(f) os.remove(lock_file)", "v in options.items() if k not in EFS_ONLY_OPTIONS] return ','.join(nfs_options)", "instance_id) elif instance_id: log_stream_name = '%s - mount.log' % (instance_id)", "get_mount_specific_filename(fs_id, mountpoint, tls_port): return '%s.%s.%d' % (fs_id, os.path.abspath(mountpoint).replace(os.sep, '.').lstrip('.'), tls_port)", "= config.getint(CONFIG_SECTION, 'logging_max_bytes') file_count = config.getint(CONFIG_SECTION, 'logging_file_count') handler = RotatingFileHandler(os.path.join(log_dir,", "region: region_specific_config_section = '%s.%s' % (CONFIG_SECTION, region) if config.has_section(region_specific_config_section): config_section", "exist, %s' % (cloudwatchlog_agent.get('log_group_name'), cloudwatchlog_agent.get('log_stream_name'), e.response)) else: handle_general_botocore_exceptions(e) return None", "CENTOS8_RELEASE_NAME = 'CentOS Linux release 8' FEDORA_RELEASE_NAME = 'Fedora release'", "None if 'tls' in options: options['port'] = options['tlsport'] def to_nfs_option(k,", "os.rename(os.path.join(state_file_dir, temp_tls_state_file), os.path.join(state_file_dir, temp_tls_state_file[1:])) def get_nfs_mount_options(options): # If you change", "= get_system_release_version() if not any(release in system_release_version for release in", "= 2 DEFAULT_STUNNEL_CAFILE = '/etc/amazon/efs/efs-utils.crt' NOT_BEFORE_MINS = 15 NOT_AFTER_HOURS =", "= 'https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html' SECURITY_CREDS_WEBIDENTITY_HELP_URL = 'https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html' SECURITY_CREDS_IAM_ROLE_HELP_URL = 'https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html' DEFAULT_STUNNEL_VERIFY_LEVEL =", "req ] prompt = no distinguished_name = req_distinguished_name [ req_distinguished_name", "0: sys.stderr.write('only root can run mount.efs\\n') sys.exit(1) def read_config(config_file=CONFIG_FILE): try:", "'InvalidParameterException': logging.error('Either parameter log group name %s or log stream", "to find certificate authority file for verification', 'Failed to find", "lines = lines[1:-1] key = ''.join(lines) key = bytearray(base64.b64decode(key)) #", "prim: NULL # 19:d=1 hl=4 l= 399 prim: BIT STRING", "client uses to connect to stunnel. # if the user", "== 'UnrecognizedClientException': logging.debug('The most likely cause is an invalid AWS", "= get_tls_port_range(config) tls_ports = list(range(lower_bound, upper_bound)) # Choose a random", "mount_completed.set() t.join() def check_unsupported_options(options): for unsupported_option in UNSUPPORTED_OPTIONS: if unsupported_option", "\"\"\" Create a String to Sign - https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html \"\"\" string_to_sign", "if proc.returncode == 0: message = 'Successfully mounted %s at", "'start' in status: logging.debug('%s is already running', WATCHDOG_SERVICE) elif init_system", "info.' % \\ (STS_ENDPOINT_URL, SECURITY_CREDS_WEBIDENTITY_HELP_URL) resp = url_request_helper(webidentity_url, unsuccessful_resp, url_error_msg,", "True elif exception == 'InvalidParameterException': logging.error('Either parameter log group name", "tunnel_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, preexec_fn=os.setsid, close_fds=True) logging.info('Started TLS tunnel, pid: %d',", "fatal_error('Error retrieving region. Please set the \"region\" parameter in the", "if credentials and credentials_source: return credentials, credentials_source # attempt to", "+ get_mount_specific_filename(fs_id, mountpoint, tls_port) state = { 'pid': tunnel_pid, 'cmd':", "global_config = dict(STUNNEL_GLOBAL_CONFIG) if config.getboolean(CONFIG_SECTION, 'stunnel_debug_enabled'): global_config['debug'] = 'debug' if", "fs_id, mountpoint, tls_port, dns_name, verify_level, ocsp_enabled, options, cert_details=cert_details) tunnel_args =", "record resolving to a valid EFS DNS ' 'name' %", "%s' % (instance_identity, e)) return None def get_region_from_legacy_dns_format(config): \"\"\" For", "-batch -notext -config %s -in %s -out %s' % \\", "not in options: options['wsize'] = '1048576' if 'soft' not in", "create_required_directory(config, directory): mode = 0o750 try: mode_str = config.get(CONFIG_SECTION, 'state_file_dir_mode')", "credentials, _ = get_aws_security_credentials_from_instance_metadata(iam_role_name) if credentials: return session.create_client(service, aws_access_key_id=credentials['AccessKeyId'], aws_secret_access_key=credentials['SecretAccessKey'],", "'-o' in args[:-1]: options_index = args.index('-o') + 1 options =", "check_options_validity(options) init_system = get_init_system() check_network_status(fs_id, init_system) dns_name = get_dns_name(config, fs_id)", "'netns' in options: tunnel_args = ['nsenter', '--net=' + options['netns']] +", "dns_name, verify_level, ocsp_enabled, options, log_dir=LOG_DIR, cert_details=None): \"\"\" Serializes stunnel configuration", "signify the number of unused bits that exist in the", "0b01111111 # Exclude the tag (1), length (1 + num_length_octets),", "= $dir/database/.rand [ ca ] default_ca = local_ca [ local_ca", "tls_port) def serialize_stunnel_config(config, header=None): lines = [] if header: lines.append('[%s]'", "import quote_plus try: from urllib2 import URLError, HTTPError, build_opener, urlopen,", "= ''.join(lines) key = bytearray(base64.b64decode(key)) # Parse the public key", "return instance_identity[property] except KeyError as e: logging.warning('%s not present in", "tag # - 82 - 2 length octets to follow", "try: with open(token_file, 'r') as f: token = f.read() except", "= tls_port use_iam = 'iam' in options ap_id = options.get('accesspoint')", "[Device] [Mount Point] [File System Type] [Options] [Dump] [Pass] #", "= key[offset:] sha1 = hashlib.sha1() sha1.update(key) return sha1.hexdigest() def create_canonical_request(public_key_hash,", "%s' % (property, instance_identity, e)) except TypeError as e: logging.warning('response", "connect to stunnel. # if the user has specified tlsport=X", "key and allow mounts to share it. # This means,", "unrecognized init system \"%s\"' % (WATCHDOG_SERVICE, init_system) sys.stderr.write('%s\\n' % error_message)", "True def cloudwatch_put_log_events_helper(cloudwatchlog_agent, message, token=None): kwargs = { 'logGroupName': cloudwatchlog_agent.get('log_group_name'),", "/mount_point # # The script will add recommended mount options,", "%s' % (command, env_path, install_method), e) return path.strip().decode() def get_system_release_version():", "proc.communicate() stunnel_output = err.splitlines() check_host_supported = is_stunnel_option_supported(stunnel_output, b'checkHost') ocsp_aia_supported =", "exception == 'InvalidParameterException': logging.debug('One of the parameter to put log", "kwargs = {'awsprofile': get_aws_profile(options, use_iam)} security_credentials, credentials_source = get_aws_security_credentials(use_iam, **kwargs)", "'AWS4-HMAC-SHA256' AWS4_REQUEST = 'aws4_request' HTTP_REQUEST_METHOD = 'GET' CANONICAL_URI = '/'", "IOError: logging.debug('Unable to read %s', SYSTEM_RELEASE_PATH) try: with open(OS_RELEASE_PATH) as", "config.get(CONFIG_SECTION, 'stunnel_cafile') except NoOptionError: logging.debug('No CA file configured, using default", "incorrectly, %s' % (log_group_name, log_stream_name, e.response)) return False elif exception", "not authorized to perform the action, %s' % error.response) else:", "os.path.join(state_file_dir, cert_details['mountStateDir'], 'certificate.pem') cert_details['privateKey'] = get_private_key_path() cert_details['fsId'] = fs_id start_watchdog(init_system)", "logging level to %s', raw_level, level) def get_dns_name(config, fs_id): def", "midpoint, and then try ports in-order from there mid =", "stunnel_cafile = DEFAULT_STUNNEL_CAFILE if not os.path.exists(stunnel_cafile): fatal_error('Failed to find certificate", "options: fatal_error('The \"tls\" option is required when mounting via \"accesspoint\"')", "in line: return line.split('=')[1].strip() except IOError: logging.debug('Unable to read %s',", "an EFS file system by its short name, by adding", "the %s's return '&'.join(['%s=%s' % (k, v) for k, v", "% remote, 'Failed to resolve \"%s\"' % remote ) if", "aws_session_token=credentials['Token'], region_name=region) return session.create_client(service, region_name=region) def get_cloudwatchlog_config(config, fs_id=None): log_group_name =", "= UTF8String:' + access_key_id efs_client_auth_str += '\\nsignature = OCTETSTRING:' +", "% os.getpid() os.write(f, lock_file_contents.encode('utf-8')) yield f finally: os.close(f) os.remove(lock_file) def", "All Rights Reserved. # # Licensed under the MIT License.", "and then try ports in-order from there mid = random.randrange(len(tls_ports))", "in options: warn_message = 'The \"%s\" option is not supported", "'/var/log/amazon/efs' LOG_FILE = 'mount.log' STATE_FILE_DIR = '/var/run/efs' PRIVATE_KEY_FILE = '/etc/amazon/efs/privateKey.pem'", "client_info else '' full_config_body = CA_CONFIG_BODY % (directory, private_key, common_name,", "ap_id, client_info): \"\"\"Populate ca/req configuration file with fresh configurations at", "= config.getint(CONFIG_SECTION, 'port_range_upper_bound') if lower_bound >= upper_bound: fatal_error('Configuration option \"port_range_upper_bound\"", "= no') if not os.path.isfile(serial_path): with open(serial_path, 'w+') as f:", "efsPolicy ] CN = supplied [ req ] prompt =", "date, region, fs_id, session_token=None): public_key_hash = get_public_key_sha1(public_key_path) canonical_request = create_canonical_request(public_key_hash,", "store.' % unsupported_option sys.stderr.write('WARN: %s\\n' % warn_message) logging.warning(warn_message) del options[unsupported_option]", "and make sure it is executable. # # You will", "if not instance_identity: raise Exception(\"Cannot retrieve region from instance_metadata\") return", "'stunnel_check_cert_validity') def get_mount_specific_filename(fs_id, mountpoint, tls_port): return '%s.%s.%d' % (fs_id, os.path.abspath(mountpoint).replace(os.sep,", "and secret access key). Adapted credentials provider chain from: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html", "update the man page as well at man/mount.efs.8 if 'nfsvers'", "\"awscredsuri\" and \"awsprofile\" options are mutually exclusive') def bootstrap_cloudwatch_logging(config, fs_id=None):", "request to tie the signature to a specific key pair", "def ca_dirs_check(config, database_dir, certs_dir): \"\"\"Check if mount's database and certs", "thrown, # to retrieve metadata, the header should embeded with", "if 'tls' not in options: fatal_error('The \"tls\" option is required", "in options: return False else: return config.getboolean(CONFIG_SECTION, 'stunnel_check_cert_validity') def get_mount_specific_filename(fs_id,", "'accesspoint', 'awscredsuri', 'awsprofile', 'cafile', 'iam', 'netns', 'noocsp', 'ocsp', 'tls', 'tlsport',", "if is_fatal: log_message = 'AWS security credentials not found in", "ConfigParser, NoOptionError, NoSectionError try: from urllib.parse import quote_plus except ImportError:", "log_stream_name) if not stream_creation_completed: return None return { 'client': cloudwatchlog_client,", "'Please install it following the instructions at ' 'https://docs.aws.amazon.com/efs/latest/ug/using-amazon-efs-utils.html#upgrading-stunnel') def", "ConfigParser() p.read(config_file) return p def bootstrap_logging(config, log_dir=LOG_DIR): raw_level = config.get(CONFIG_SECTION,", "to avoid naming collisions cert_details['mountStateDir'] = get_mount_specific_filename(fs_id, mountpoint, tls_port) +", "fatal_error(log_message) else: return None, None def get_aws_security_credentials_from_ecs(aws_creds_uri, is_fatal=False): ecs_uri =", "Exclude the tag (1), length (1 + num_length_octets), and number", "in options: fatal_error('Specified port [%s] is unavailable. Try selecting a", "config.has_option(CLOUDWATCH_LOG_SECTION, 'retention_in_days'): retention_days = config.get(CLOUDWATCH_LOG_SECTION, 'retention_in_days') log_stream_name = get_cloudwatch_log_stream_name(fs_id) return", "time from contextlib import contextmanager from datetime import datetime, timedelta", "if not any(release in system_release_version for release in SKIP_NO_LIBWRAP_RELEASES): efs_config['libwrap']", "for item in v: lines.append('%s = %s' % (k, item))", "tunnel, pid: %d', tunnel_proc.pid) temp_tls_state_file = write_tls_tunnel_state_file(fs_id, mountpoint, tls_port, tunnel_proc.pid,", "if rc != 0: logging.error('Command %s failed, rc=%s, stdout=\"%s\", stderr=\"%s\"'", "string_to_sign += date.strftime(SIGV4_DATETIME_FORMAT) + '\\n' string_to_sign += get_credential_scope(date, region) +", "since this is not called from the main thread, if", "request = Request(INSTANCE_METADATA_TOKEN_URL) request.add_header('X-aws-ec2-metadata-token-ttl-seconds', 21600) request.get_method = lambda: 'PUT' res", "config file (%s), ' \\ 'from ECS credentials relative uri,", "= 'WARNING: Your client lacks sufficient controls to properly enforce", "exception == 'ResourceAlreadyExistsException': logging.debug('Log group %s already exist, %s' %", "serialize_stunnel_config(config, header=None): lines = [] if header: lines.append('[%s]' % header)", "not found in %s or %s under named profile [%s]'", "that your file system ID is correct.\\nSee %s for more", "with os._exit \"\"\" while not mount_completed.is_set(): try: test_tunnel_process(tunnel_proc, fs_id) except", "return None def get_resp_obj(request_resp, url, unsuccessful_resp): if request_resp.getcode() != 200:", "approach on EKS) if WEB_IDENTITY_ROLE_ARN_ENV in os.environ and WEB_IDENTITY_TOKEN_FILE_ENV in", "this file # for the specific language governing permissions and", "\"%s\"', ' '.join(tunnel_args)) tunnel_proc = subprocess.Popen( tunnel_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, preexec_fn=os.setsid,", "return True def cloudwatch_put_log_events_helper(cloudwatchlog_agent, message, token=None): kwargs = { 'logGroupName':", "'Unsuccessful retrieval of AWS security credentials at %s.' % STS_ENDPOINT_URL", "file (%s), config file (%s), ' \\ 'from ECS credentials", "config setting if the override is not set if ocsp_enabled:", "upstart # (Amazon Linux 2017.09). # # Once there is", "credentials through the credentials URI the ECS agent generated if", "'vers' not in options: options['nfsvers'] = '4.1' if 'rsize' not", "public key file, %s, correctly' % public_key) key_line = ''", "command logging.info('Executing: \"%s\"', ' '.join(command)) proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,", "are mutually exclusive') def bootstrap_cloudwatch_logging(config, fs_id=None): if not check_if_cloudwatch_log_enabled(config): return", "CERT_DATETIME_FORMAT = '%y%m%d%H%M%SZ' AWS_CREDENTIALS_FILE = os.path.expanduser(os.path.join('~' + pwd.getpwuid(os.getuid()).pw_name, '.aws', 'credentials'))", "return line.split('=')[1].strip() except IOError: logging.debug('Unable to read %s', OS_RELEASE_PATH) return", "e: e is not None, [primary] + secondaries)) except socket.gaierror:", "0382018f00...<subjectPublicKey> # - 03 - BIT STRING tag # -", "cert = $dir/certificate.pem new_certs_dir = $dir/certs default_md = sha256 preserve", "cert_details['mountStateDir'], 'certificate.pem') cert_details['privateKey'] = get_private_key_path() cert_details['fsId'] = fs_id start_watchdog(init_system) if", "$dir/database/.rand [ ca ] default_ca = local_ca [ local_ca ]", "if all(k in creds for k in ['AccessKeyId', 'SecretAccessKey', 'SessionToken']):", "in options: if 'tls' not in options: fatal_error('The \"tls\" option", "get_botocore_client(config, 'logs') if not cloudwatchlog_client: return None cloudwatchlog_config = get_cloudwatchlog_config(config,", "'WARNING: Your client lacks sufficient controls to properly enforce TLS.", "DEFAULT_STUNNEL_CAFILE if not os.path.exists(stunnel_cafile): fatal_error('Failed to find certificate authority file", "logging.error('Command %s failed, rc=%s, stdout=\"%s\", stderr=\"%s\"' % (cmd, rc, output,", "if not os.path.exists(stunnel_cafile): fatal_error('Failed to find certificate authority file for", "lookup AWS security credentials through AssumeRoleWithWebIdentity # (e.g. for IAM", "'Mount failed, %s' % log_message) sys.exit(exit_code) def get_target_region(config): def _fatal_error(message):", "ocsp_aia_supported def _stunnel_bin(): return find_command_path('stunnel', 'Please install it following the", "random import re import socket import subprocess import sys import", "% error_message) logging.warning(error_message) def create_required_directory(config, directory): mode = 0o750 try:", "= '/' CANONICAL_HEADERS_DICT = { 'host': '%s' } CANONICAL_HEADERS =", "unsuccessful_resp) except HTTPError as e: # For instance enable with", "process health every .5s during the mount attempt to fail", "source key/value pair in config file if config.has_option(CLIENT_INFO_SECTION, 'source'): client_source", "given awsprofile if awsprofile: return get_aws_security_credentials_from_awsprofile(awsprofile, True) # attempt to", "return config.getboolean(CONFIG_SECTION, 'stunnel_check_cert_validity') def get_mount_specific_filename(fs_id, mountpoint, tls_port): return '%s.%s.%d' %", "\"dns_name_format\" check') try: region = get_region_from_legacy_dns_format(config) sys.stdout.write('Warning: region obtained from", "ValueError as e: logging.info('ValueError parsing \"%s\" into json: %s. Returning", "import ConfigParser, NoOptionError, NoSectionError try: from urllib.parse import quote_plus except", "urllib.error import URLError, HTTPError from urllib.parse import urlencode try: import", "in status: with open(os.devnull, 'w') as devnull: subprocess.Popen(['/sbin/start', WATCHDOG_SERVICE], stdout=devnull,", "warn_message) logging.warning(warn_message) del options[unsupported_option] def check_options_validity(options): if 'tls' in options:", "= 0o750 try: mode_str = config.get(CONFIG_SECTION, 'state_file_dir_mode') try: mode =", "except OSError: # Silently fail if the subprocess has exited", "because the network was not yet available, add \"_netdev\" to", "logger.setLevel(level) logger.addHandler(handler) if level_error: logging.error('Malformed logging level \"%s\", setting logging", "% e) return None except Exception as e: logging.warning('Unknown error,", "return datetime.utcnow() def assert_root(): if os.geteuid() != 0: sys.stderr.write('only root", "keys is slow, so we will create one private key", "metadata_exception = 'Unknown error' try: return config.get(CONFIG_SECTION, 'region') except NoOptionError:", "%s: returncode=%d, stderr=\"%s\"' % (dns_name, mountpoint, proc.returncode, err.strip()) fatal_error(err.strip(), message,", "the instructions at ' 'https://docs.aws.amazon.com/efs/latest/ug/using-amazon-efs-utils.html#upgrading-stunnel') def find_command_path(command, install_method): try: env_path", "'.').lstrip('.'), tls_port) def serialize_stunnel_config(config, header=None): lines = [] if header:", "supporting openssl ca and req files if they're not present", "client_info: ca_extension_str += '\\n1.3.6.1.4.1.4843.7.4 = ASN1:SEQUENCE:efs_client_info' return ca_extension_str def efs_client_auth_builder(public_key_path,", "'%T', mountpoint] p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) output, _", "the actual key material by looking for the key BIT", "credentials, os.path.basename(file_path) + ':' + awsprofile # Fail if credentials", "metadata, the header should embeded with metadata token if e.code", "number of octets that follow # - the following octets", "AWS security credentials at %s.' % ecs_uri ecs_url_error_msg = 'Unable", "failed, falling back ' 'to legacy \"dns_name_format\" check') try: region", "for line in f: if 'PRETTY_NAME' in line: return line.split('=')[1].strip()", "def calculate_signature(string_to_sign, date, secret_access_key, region): \"\"\" Calculate the Signature -", "# Public key hash is included in canonical request to", "cloudwatch_create_log_stream_helper(cloudwatchlog_client, log_group_name, log_stream_name) except ClientError as e: exception = e.response['Error']['Code']", "verification', 'Failed to find CAfile \"%s\"' % stunnel_cafile) efs_config['CAfile'] =", "init systems') return check_network_target(fs_id) def start_watchdog(init_system): if init_system == 'init':", "for k, v in sorted(CANONICAL_HEADERS_DICT.items())]) SIGNED_HEADERS = ';'.join(CANONICAL_HEADERS_DICT.keys()) REQUEST_PAYLOAD =", "botocore, please install botocore first.') return None session = botocore.session.get_session()", "sleeping 50 ms') time.sleep(0.05) else: raise def generate_key(): if os.path.isfile(key):", "name for an EFS mount target. ' 'Please refer to", "is not None: out, err = tunnel_proc.communicate() fatal_error('Failed to initialize", "%s -enddate %s -selfsign -batch -notext -config %s -in %s", "%s -selfsign -batch -notext -config %s -in %s -out %s'", "% (args[0], VERSION)) sys.exit(0) def parse_arguments(config, args=None): \"\"\"Parse arguments, return", "# Once there is an entry in fstab, the file", "in fstab. import base64 import errno import hashlib import hmac", "= %s RANDFILE = $dir/database/.rand [ ca ] default_ca =", "efs_fqdn_match.group('fs_id') expected_dns_name = get_dns_name(config, fs_id) # check that the DNS", "% (config_path, private_key, csr_path) subprocess_call(cmd, 'Failed to create certificate signing", "'~' + get_mount_specific_filename(fs_id, mountpoint, tls_port) state = { 'pid': tunnel_pid,", "not_after = get_certificate_timestamp(current_time, hours=NOT_AFTER_HOURS) cmd = 'openssl ca -startdate %s", "= get_region_from_legacy_dns_format(config) sys.stdout.write('Warning: region obtained from \"dns_name_format\" field. Please set", "mount options, if not provided in fstab. import base64 import", "'stunnel_logs_file'): global_config['output'] = config.get(CONFIG_SECTION, 'stunnel_logs_file').replace('{fs_id}', fs_id) else: global_config['output'] = os.path.join(log_dir,", "string_to_sign = ALGORITHM + '\\n' string_to_sign += date.strftime(SIGV4_DATETIME_FORMAT) + '\\n'", "in options: tunnel_args = ['nsenter', '--net=' + options['netns']] + tunnel_args", "# You will be able to mount an EFS file", "config.get(CONFIG_SECTION, 'region') except NoOptionError: pass try: return get_region_from_instance_metadata() except Exception", "named profile option, \"awsprofile\"') if 'awscredsuri' in options and 'iam'", "For instance enable with IMDSv2, Unauthorized 401 error will be", "cloudwatch log group %s' % log_group_name) def create_cloudwatch_log_group(cloudwatchlog_client, log_group_name): try:", "'unknown' def write_stunnel_config_file(config, state_file_dir, fs_id, mountpoint, tls_port, dns_name, verify_level, ocsp_enabled,", "unsupported_option in options: warn_message = 'The \"%s\" option is not", "!= 0: fatal_error('Failed to mount %s because the network was", "options): if 'cafile' in options: stunnel_cafile = options['cafile'] else: try:", "security_credentials: public_key = os.path.join(tls_paths['mount_dir'], 'publicKey.pem') create_public_key(private_key, public_key) create_ca_conf(certificate_config, common_name, tls_paths['mount_dir'],", "if not awsprofile and use_iam: for file_path in [AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE]:", "handler = RotatingFileHandler(os.path.join(log_dir, LOG_FILE), maxBytes=max_bytes, backupCount=file_count) handler.setFormatter(logging.Formatter(fmt='%(asctime)s - %(levelname)s -", "output.splitlines(): if 'BIT STRING' in line.decode('utf-8'): key_line = line.decode('utf-8') if", "t.start() mount_nfs(dns_name, path, mountpoint, options) mount_completed.set() t.join() def check_unsupported_options(options): for", "stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) out, err = proc.communicate() if proc.returncode ==", "get_aws_security_credentials(use_iam, awsprofile=None, aws_creds_uri=None): \"\"\" Lookup AWS security credentials (access key", "(instance_identity, e)) return None def get_region_from_legacy_dns_format(config): \"\"\" For backwards compatibility", "lines.append('%s = %s' % (k, v)) return lines def add_stunnel_ca_options(efs_config,", "tls_port use_iam = 'iam' in options ap_id = options.get('accesspoint') cert_details", "- the following octets encode, as big-endian, the length (which", "in args[:-1]: options_index = args.index('-o') + 1 options = parse_options(args[options_index])", "'.aws', 'config')) CA_CONFIG_BODY = \"\"\"dir = %s RANDFILE = $dir/database/.rand", "instance_identity def get_instance_identity_info_from_instance_metadata(property): ec2_metadata_unsuccessful_resp = 'Unsuccessful retrieval of EC2 metadata", "man/mount.efs.8 if 'nfsvers' not in options and 'vers' not in", "'mount' CLIENT_INFO_SECTION = 'client-info' CLIENT_SOURCE_STR_LEN_LIMIT = 100 CLOUDWATCH_LOG_SECTION = 'cloudwatch-log'", "path, fs_id, mountpoint, options): if os.path.ismount(mountpoint) and is_nfs_mount(mountpoint): sys.stdout.write(\"%s is", "cert_details['awsCredentialsMethod'] = credentials_source if ap_id: cert_details['accessPoint'] = ap_id # additional", "= parse_options(args[options_index]) if not fsname or not mountpoint: usage(out=sys.stderr) fs_id,", "e.errno or not os.path.isdir(directory): raise @contextmanager def bootstrap_tls(config, init_system, dns_name,", "get_tls_port_range(config): lower_bound = config.getint(CONFIG_SECTION, 'port_range_lower_bound') upper_bound = config.getint(CONFIG_SECTION, 'port_range_upper_bound') if", "== len(ports_to_try) sock = socket.socket() for tls_port in ports_to_try: try:", "cloudwatchlog_agent.get('log_group_name'), 'logStreamName': cloudwatchlog_agent.get('log_stream_name'), 'logEvents': [ { 'timestamp': int(round(time.time() * 1000)),", "RotatingFileHandler(os.path.join(log_dir, LOG_FILE), maxBytes=max_bytes, backupCount=file_count) handler.setFormatter(logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(message)s')) logger", "'w').close() def get_certificate_timestamp(current_time, **kwargs): updated_time = current_time + timedelta(**kwargs) return", "common_name, tls_paths['mount_dir'], private_key, current_time, region, fs_id, security_credentials, ap_id, client_info) create_certificate_signing_request(certificate_config,", "logging is configured level_error = True level = logging.INFO max_bytes", "+ options['netns']] + tunnel_args # launch the tunnel in a", "hostnames = list(filter(lambda e: e is not None, [primary] +", "security_creds_lookup_url = INSTANCE_IAM_URL + iam_role_name unsuccessful_resp = 'Unsuccessful retrieval of", "events is not valid, %s' % e.response) return False elif", "'TIMEOUTidle': '70', 'delay': 'yes', } WATCHDOG_SERVICE = 'amazon-efs-mount-watchdog' SYSTEM_RELEASE_PATH =", "== expected_dns_name: return fs_id, path else: create_default_cloudwatchlog_agent_if_not_exist(config) fatal_error('The specified CNAME", "resp = url_request_helper(webidentity_url, unsuccessful_resp, url_error_msg, headers={'Accept': 'application/json'}) if resp: creds", "config.getint(CONFIG_SECTION, 'logging_max_bytes') file_count = config.getint(CONFIG_SECTION, 'logging_file_count') handler = RotatingFileHandler(os.path.join(log_dir, LOG_FILE),", "access_key credentials['SecretAccessKey'] = secret_key credentials['Token'] = session_token except NoOptionError as", "+= '\\nsignature = OCTETSTRING:' + signature efs_client_auth_str += '\\nsigv4DateTime =", "iam_role_name = get_iam_role_name() if iam_role_name: credentials, _ = get_aws_security_credentials_from_instance_metadata(iam_role_name) if", "access_key = aws_credentials_configs.get(awsprofile, 'aws_access_key_id') secret_key = aws_credentials_configs.get(awsprofile, 'aws_secret_access_key') session_token =", "credentials not found in %s or %s under named profile", "%s for more info.' \\ % (ecs_uri, SECURITY_CREDS_ECS_URI_HELP_URL) ecs_security_dict =", "- 03 - BIT STRING tag # - 82 -", "else: logging.debug('Unexpected error: %s' % e) return False except NoCredentialsError", "when mounting via \"iam\"') if 'awsprofile' in options and 'iam'", "import socket import subprocess import sys import threading import time", "get_aws_ec2_metadata_token(): try: opener = build_opener(HTTPHandler) request = Request(INSTANCE_METADATA_TOKEN_URL) request.add_header('X-aws-ec2-metadata-token-ttl-seconds', 21600)", "security_credentials, ap_id, client_info) create_certificate_signing_request(certificate_config, private_key, certificate_signing_request) not_before = get_certificate_timestamp(current_time, minutes=-NOT_BEFORE_MINS)", "credential, 'X-Amz-Date': quote_plus(formatted_datetime), 'X-Amz-Expires': 86400, 'X-Amz-SignedHeaders': SIGNED_HEADERS, } if session_token:", "permissions and limitations under # the License. # # #", "use_iam: return None, None # attempt to lookup AWS security", "relies on a built-in ' \\ 'trust store.' % unsupported_option", "there is an entry in fstab, the file system can", "(1 + num_length_octets), and number of unused bits (1) offset", "= args[2] if len(args) > 4 and '-o' in args[:-1]:", "'127.0.0.1:%s', 'connect': '%s:2049', 'sslVersion': 'TLSv1.2', 'renegotiation': 'no', 'TIMEOUTbusy': '20', 'TIMEOUTclose':", "if not AP_ID_RE.match(options['accesspoint']): fatal_error('Access Point ID %s is malformed' %", "efs_client_info_str += '\\n%s = UTF8String:%s' % (key, value) return efs_client_info_str", "% dns_name) return dns_name def tls_paths_dictionary(mount_name, base_path=STATE_FILE_DIR): tls_dict = {", "chain from: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html and https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html \"\"\" if not use_iam: return", "k in ['AccessKeyId', 'SecretAccessKey', 'SessionToken']): return { 'AccessKeyId': creds['AccessKeyId'], 'SecretAccessKey':", "ap_id = options.get('accesspoint') cert_details = {} security_credentials = None client_info", "urllib import quote_plus try: from urllib2 import URLError, HTTPError, build_opener,", "False elif exception == 'DataAlreadyAcceptedException': logging.debug('The event %s was already", "= subprocess.Popen(stunnel_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) proc.wait() _, err = proc.communicate()", "%s.' % e) return False return True def cloudwatch_describe_log_streams_helper(cloudwatchlog_agent): return", "'Unable to reach %s to retrieve AWS security credentials. See", "out, err = tunnel_proc.communicate() fatal_error('Failed to initialize TLS tunnel for", "= current_time + timedelta(**kwargs) return updated_time.strftime(CERT_DATETIME_FORMAT) def get_utc_now(): \"\"\" Wrapped", "} ] } if token: kwargs['sequenceToken'] = token cloudwatchlog_agent.get('client').put_log_events(**kwargs) def", "return False else: return config.getboolean(CONFIG_SECTION, 'stunnel_check_cert_validity') def get_mount_specific_filename(fs_id, mountpoint, tls_port):", "characters cert_details['commonName'] = socket.gethostname()[0:64] cert_details['region'] = get_target_region(config) cert_details['certificateCreationTime'] = create_certificate(config,", "cloudwatchlog_client = get_botocore_client(config, 'logs') if not cloudwatchlog_client: return None cloudwatchlog_config", "proc = subprocess.Popen(stunnel_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) proc.wait() _, err =", "DEFAULT_STUNNEL_CAFILE = '/etc/amazon/efs/efs-utils.crt' NOT_BEFORE_MINS = 15 NOT_AFTER_HOURS = 3 EFS_ONLY_OPTIONS", "get_aws_security_credentials_from_ecs(aws_creds_uri, is_fatal=False): ecs_uri = ECS_TASK_METADATA_API + aws_creds_uri ecs_unsuccessful_resp = 'Unsuccessful", "= int(mode_str, 8) except ValueError: logging.warning('Bad state_file_dir_mode \"%s\" in config", "get_certificate_timestamp(current_time, **kwargs): updated_time = current_time + timedelta(**kwargs) return updated_time.strftime(CERT_DATETIME_FORMAT) def", "path, fs_id, mountpoint, options) else: mount_nfs(dns_name, path, mountpoint, options) if", "the header and footer '-----(BEGIN|END) PUBLIC KEY-----' with open(public_key, 'r')", "is_fatal=False): ecs_uri = ECS_TASK_METADATA_API + aws_creds_uri ecs_unsuccessful_resp = 'Unsuccessful retrieval", "properly configured, %s' % e) return False except EndpointConnectionError as", "bootstrap_tls(config, init_system, dns_name, fs_id, mountpoint, options) as tunnel_proc: mount_completed =", "if efs_fqdn_match: fs_id = efs_fqdn_match.group('fs_id') expected_dns_name = get_dns_name(config, fs_id) #", "if ECS_URI_ENV in os.environ: credentials, credentials_source = get_aws_security_credentials_from_ecs(os.environ[ECS_URI_ENV], False) if", "to properly enforce TLS. Please upgrade stunnel, ' \\ 'or", "None put_retention_policy_completed = put_cloudwatch_log_retention_policy(cloudwatchlog_client, log_group_name, retention_days) if not put_retention_policy_completed: return", "try ports in-order from there mid = random.randrange(len(tls_ports)) ports_to_try =", "fs_id): def _validate_replacement_field_count(format_str, expected_ct): if format_str.count('{') != expected_ct or format_str.count('}')", "CA file %s', DEFAULT_STUNNEL_CAFILE) stunnel_cafile = DEFAULT_STUNNEL_CAFILE if not os.path.exists(stunnel_cafile):", "%s' % e) return None try: log_stream = response['logStreams'][0] return", "{} if len(args) > 1: fsname = args[1] if len(args)", "means, however, that we have to include a locking mechanism", "% 'stunnel_check_cert_hostname') # Only use the config setting if the", "find certificate authority file for verification', 'Failed to find CAfile", "token_file]) # Fail if credentials cannot be fetched from the", "\"\"\" Lookup AWS security credentials (access key ID and secret", "format_args.get('region') if region: region_specific_config_section = '%s.%s' % (CONFIG_SECTION, region) if", "OS_RELEASE_PATH) return 'unknown' def write_stunnel_config_file(config, state_file_dir, fs_id, mountpoint, tls_port, dns_name,", "-a' # for this file system. The '_netdev' option tells", "See the LICENSE accompanying this file # for the specific", "is the tag (type) # - the next octets are", "not in options and 'hard' not in options: options['hard'] =", "these options, update the man page as well at man/mount.efs.8", "Auth ALGORITHM = 'AWS4-HMAC-SHA256' AWS4_REQUEST = 'aws4_request' HTTP_REQUEST_METHOD = 'GET'", "p = ConfigParser.SafeConfigParser() except AttributeError: p = ConfigParser() p.read(config_file) return", "config.getint(CONFIG_SECTION, 'port_range_lower_bound') upper_bound = config.getint(CONFIG_SECTION, 'port_range_upper_bound') if lower_bound >= upper_bound:", "+ '+' # common name for certificate signing request is", "key). Adapted credentials provider chain from: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html and https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html \"\"\"", "'Token': creds['SessionToken'] }, 'webidentity:' + ','.join([role_arn, token_file]) # Fail if", "exclusive') if 'accesspoint' in options: if 'tls' not in options:", "if exception == 'ServiceUnavailableException': logging.debug('The service cannot complete the request,", "% (token_file, e) fatal_error(unsuccessful_resp, unsuccessful_resp) else: return None, None webidentity_url", "date, access_key_id, region, fs_id, session_token) string_to_sign = create_string_to_sign(canonical_request, date, region)", "at %s, reason is %s' % (url, e.reason) if err_msg:", "= %s' % (k, item)) else: lines.append('%s = %s' %", "AWS_CONFIG_FILE) fatal_error(error_msg, error_msg) def get_aws_security_credentials_from_awsprofile(awsprofile, is_fatal=False): for file_path in [AWS_CREDENTIALS_FILE,", "AWS security credentials. See %s for more info.' \\ %", "+ serialize_stunnel_config(efs_config, 'efs')) logging.debug('Writing stunnel configuration:\\n%s', stunnel_config) stunnel_config_file = os.path.join(state_file_dir,", "= '600' if 'retrans' not in options: options['retrans'] = '2'", "hash, per # https://tools.ietf.org/html/rfc5280#section-4.2.1.2 # # Example: # 0382018f00...<subjectPublicKey> #", "= read_config(file_path) credentials = {'AccessKeyId': None, 'SecretAccessKey': None, 'Token': None}", "'{fs_id}' not in dns_name_format: raise ValueError('DNS name format must include", "% mountpoint) logging.warning(\"%s is already mounted, mount aborted\" % mountpoint)", "subprocess_call(cmd, 'Failed to create public key') def subprocess_call(cmd, error_message): \"\"\"Helper", "'logGroupName': cloudwatchlog_agent.get('log_group_name'), 'logStreamName': cloudwatchlog_agent.get('log_stream_name'), 'logEvents': [ { 'timestamp': int(round(time.time() *", "tunnel_pid, command, files, state_file_dir, cert_details=None): \"\"\" Return the name of", "to X. options['tlsport'] = tls_port use_iam = 'iam' in options", "if init_system == 'init': proc = subprocess.Popen( ['/sbin/status', WATCHDOG_SERVICE], stdout=subprocess.PIPE,", "try: sock.bind(('localhost', tls_port)) sock.close() return tls_port except socket.error: continue sock.close()", "def check_network_target(fs_id): with open(os.devnull, 'w') as devnull: rc = subprocess.call(['systemctl',", "the last content byte offset = int(key_line.split(':')[0]) key = key[offset:]", "def get_client_info(config): client_info = {} # source key/value pair in", "does not exist, %s' % (cloudwatchlog_agent.get('log_group_name'), cloudwatchlog_agent.get('log_stream_name'), e.response)) else: handle_general_botocore_exceptions(e)", "'RoleArn': role_arn, 'RoleSessionName': 'efs-mount-helper', 'WebIdentityToken': token }) unsuccessful_resp = 'Unsuccessful", "Enterprise Linux release 8' CENTOS8_RELEASE_NAME = 'CentOS Linux release 8'", "STS_ENDPOINT_URL + '?' + urlencode({ 'Version': '2011-06-15', 'Action': 'AssumeRoleWithWebIdentity', 'RoleArn':", "%s - mount.log' % (fs_id, instance_id) elif instance_id: log_stream_name =", "WEB_IDENTITY_ROLE_ARN_ENV = 'AWS_ROLE_ARN' WEB_IDENTITY_TOKEN_FILE_ENV = 'AWS_WEB_IDENTITY_TOKEN_FILE' STS_ENDPOINT_URL = 'https://sts.amazonaws.com/' INSTANCE_METADATA_TOKEN_URL", "{} # source key/value pair in config file if config.has_option(CLIENT_INFO_SECTION,", "50 ms') time.sleep(0.05) else: raise def generate_key(): if os.path.isfile(key): return", "log_stream_name = '%s - %s - mount.log' % (fs_id, instance_id)", "% e) return False return True def cloudwatch_put_retention_policy_helper(cloudwatchlog_client, log_group_name, retention_days):", "k, v in sorted(CANONICAL_HEADERS_DICT.items())]) SIGNED_HEADERS = ';'.join(CANONICAL_HEADERS_DICT.keys()) REQUEST_PAYLOAD = ''", "start_watchdog(init_system) if not os.path.exists(state_file_dir): create_required_directory(config, state_file_dir) verify_level = int(options.get('verify', DEFAULT_STUNNEL_VERIFY_LEVEL))", "options, update the man page as well at man/mount.efs.8 if", "in unit tests \"\"\" return datetime.utcnow() def assert_root(): if os.geteuid()", "res.read() def get_aws_security_credentials(use_iam, awsprofile=None, aws_creds_uri=None): \"\"\" Lookup AWS security credentials", "None, None # attempt to lookup AWS security credentials through", "port in the range [%d, %d], try specifying a different", "retry in range(retry_times): process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) (output,", "tunnel_args = ['nsenter', '--net=' + options['netns']] + tunnel_args # launch", "their respective directories\"\"\" if not os.path.isfile(index_path): open(index_path, 'w').close() if not", "== 'InvalidSequenceTokenException': logging.debug('The sequence token is not valid, %s' %", "request += CANONICAL_URI + '\\n' request += create_canonical_query_string(public_key_hash, credential, formatted_datetime,", "get_public_key_sha1(public_key): # truncating public key to remove the header and", "'retention_in_days') log_stream_name = get_cloudwatch_log_stream_name(fs_id) return { 'log_group_name': log_group_name, 'retention_days': int(retention_days),", "logging.warning('%s not present in %s: %s' % (property, instance_identity, e))", "config.getboolean(CLOUDWATCH_LOG_SECTION, 'enabled') return False def cloudwatch_create_log_group_helper(cloudwatchlog_client, log_group_name): cloudwatchlog_client.create_log_group( logGroupName=log_group_name )", "init_system, dns_name, path, fs_id, mountpoint, options): if os.path.ismount(mountpoint) and is_nfs_mount(mountpoint):", "if FS_ID_RE.match(remote): return remote, path try: primary, secondaries, _ =", "e)) except TypeError as e: logging.warning('response %s is not a", "read %s', OS_RELEASE_PATH) return 'unknown' def write_stunnel_config_file(config, state_file_dir, fs_id, mountpoint,", "tunnel for %s' % fs_id, 'Failed to start TLS tunnel", "port [%s] is unavailable. Try selecting a different port.' %", "group %s' % log_group_name) def create_cloudwatch_log_group(cloudwatchlog_client, log_group_name): try: cloudwatch_create_log_group_helper(cloudwatchlog_client, log_group_name)", "verify_level = int(options.get('verify', DEFAULT_STUNNEL_VERIFY_LEVEL)) ocsp_enabled = is_ocsp_enabled(config, options) stunnel_config_file =", "} return tls_dict def get_public_key_sha1(public_key): # truncating public key to", "if exception == 'InvalidParameterException': logging.debug('Either parameter log group name %s", "for verification', 'Failed to find CAfile \"%s\"' % stunnel_cafile) efs_config['CAfile']", "in str(e): logging.debug('aws_access_key_id or aws_secret_access_key not found in %s under", "maximum number of log groups that can be created, %s'", "def create_cloudwatch_log_group(cloudwatchlog_client, log_group_name): try: cloudwatch_create_log_group_helper(cloudwatchlog_client, log_group_name) except ClientError as e:", "of octets # - the remaining octets are the \"value\"", "2, CentOS 7, RHEL 7, Debian 9, and Ubuntu 16.04),", "to %s' % retention_days) def put_cloudwatch_log_retention_policy(cloudwatchlog_client, log_group_name, retention_days): try: cloudwatch_put_retention_policy_helper(cloudwatchlog_client,", "subprocess.Popen(['systemctl', 'start', WATCHDOG_SERVICE], stdout=devnull, stderr=devnull, close_fds=True) else: logging.debug('%s is already", "' \\ 'trust store.' % unsupported_option sys.stderr.write('WARN: %s\\n' % warn_message)", "'cloudwatch-log' DEFAULT_CLOUDWATCH_LOG_GROUP = '/aws/efs/utils' DEFAULT_RETENTION_DAYS = 14 # Cloudwatchlog agent", "return instance_identity def get_instance_identity_info_from_instance_metadata(property): ec2_metadata_unsuccessful_resp = 'Unsuccessful retrieval of EC2", "this does not conform to Python's config file format, so", "stream %s in log group %s' % (log_stream_name, log_group_name)) def", "% stunnel_cafile) efs_config['CAfile'] = stunnel_cafile def is_stunnel_option_supported(stunnel_output, stunnel_option_name): supported =", ":rsaEncryption # 17:d=2 hl=2 l= 0 prim: NULL # 19:d=1", "= f.readlines() lines = lines[1:-1] key = ''.join(lines) key =", "not set if ocsp_enabled: if ocsp_aia_supported: efs_config['OCSPaia'] = 'yes' else:", "expected_dns_name: return fs_id, path else: create_default_cloudwatchlog_agent_if_not_exist(config) fatal_error('The specified CNAME \"%s\"", "# This means, however, that we have to include a", "len(args) > 4 and '-o' in args[:-1]: options_index = args.index('-o')", "if log_message is None: log_message = user_message sys.stderr.write('%s\\n' % user_message)", "in %s or %s under named profile [%s]' % \\", "hashlib.sha256) key_date = _sign(('AWS4' + secret_access_key).encode('utf-8'), date.strftime(DATE_ONLY_FORMAT)).digest() add_region = _sign(key_date,", "(str(k), str(v)) nfs_options = [to_nfs_option(k, v) for k, v in", "%d.' % (upper_bound, lower_bound)) return lower_bound, upper_bound def choose_tls_port(config, options):", "credentials, credentials_source = get_aws_security_credentials_from_webidentity( os.environ[WEB_IDENTITY_ROLE_ARN_ENV], os.environ[WEB_IDENTITY_TOKEN_FILE_ENV], False ) if credentials", "configured, using default CA file %s', DEFAULT_STUNNEL_CAFILE) stunnel_cafile = DEFAULT_STUNNEL_CAFILE", "logging.warning('Legacy check for region in \"dns_name_format\" failed') _fatal_error(metadata_exception) def get_region_from_instance_metadata():", "mount watchdog logging.info('Starting TLS tunnel: \"%s\"', ' '.join(tunnel_args)) tunnel_proc =", "elif exception == 'InvalidParameterException': logging.error('Log group name %s is specified", "SECURITY_CREDS_IAM_ROLE_HELP_URL) iam_role_name = url_request_helper(INSTANCE_IAM_URL, iam_role_unsuccessful_resp, iam_role_url_error_msg, retry_with_new_header_token=True) return iam_role_name def", "f: f.write('00') if not os.path.isfile(rand_path): open(rand_path, 'w').close() def get_certificate_timestamp(current_time, **kwargs):", "8' FEDORA_RELEASE_NAME = 'Fedora release' SUSE_RELEASE_NAME = 'openSUSE Leap' SKIP_NO_LIBWRAP_RELEASES", "%s -in %s -out %s' % \\ (not_before, not_after, certificate_config,", "awsprofile) if 'aws_session_token' in str(e): logging.debug('aws_session_token not found in %s',", "[%s]\", format_args.get('dns_name_suffix'), config_section) _validate_replacement_field_count(dns_name_format, expected_replacement_field_ct) dns_name = dns_name_format.format(**format_args) try: socket.gethostbyname(dns_name)", "+ 1 key = key[offset:] sha1 = hashlib.sha1() sha1.update(key) return", "'AssumeRoleWithWebIdentity', 'RoleArn': role_arn, 'RoleSessionName': 'efs-mount-helper', 'WebIdentityToken': token }) unsuccessful_resp =", "except ValueError as e: logging.info('ValueError parsing \"%s\" into json: %s.", "options are mutually exclusive') if 'accesspoint' in options: if 'tls'", "security credentials. See %s for more info.' % \\ (security_creds_lookup_url,", "return True elif exception == 'LimitExceededException': logging.error('Reached the maximum number", "a '~'. This file needs to be renamed to a", "logging.debug('%s is already running', WATCHDOG_SERVICE) else: error_message = 'Could not", "syntax of an fstab entry is: # # [Device] [Mount", "client_info, base_path=STATE_FILE_DIR): current_time = get_utc_now() tls_paths = tls_paths_dictionary(mount_name, base_path) certificate_config", "URLError, HTTPError, build_opener, urlopen, Request, HTTPHandler from urllib import urlencode", "is_fatal: fatal_error(ecs_unsuccessful_resp, ecs_unsuccessful_resp) else: return None, None def get_aws_security_credentials_from_webidentity(role_arn, token_file,", "configuration file.') return region except Exception: logging.warning('Legacy check for region", "mount_name, 'database'), 'certs_dir': os.path.join(base_path, mount_name, 'certs'), 'index': os.path.join(base_path, mount_name, 'database/index.txt'),", "200: logging.debug(unsuccessful_resp + ' %s: ResponseCode=%d', url, request_resp.getcode()) return None", "on non-systemd init systems') return check_network_target(fs_id) def start_watchdog(init_system): if init_system", "handle_general_botocore_exceptions(error): exception = error.response['Error']['Code'] if exception == 'ServiceUnavailableException': logging.debug('The service", "def mount_tls(config, init_system, dns_name, path, fs_id, mountpoint, options): if os.path.ismount(mountpoint)", "%s' % e) return False except EndpointConnectionError as e: logging.warning('Could", "args[2] if len(args) > 4 and '-o' in args[:-1]: options_index", "(IndexError, TypeError, KeyError): pass return None def handle_general_botocore_exceptions(error): exception =", "errno import hashlib import hmac import json import logging import", "in EFS_ONLY_OPTIONS] return ','.join(nfs_options) def mount_nfs(dns_name, path, mountpoint, options): if", "tls_paths['rand']) private_key = check_and_create_private_key(base_path) if security_credentials: public_key = os.path.join(tls_paths['mount_dir'], 'publicKey.pem')", "with a '~'. This file needs to be renamed to", "with named profile option, \"awsprofile\"') if 'awscredsuri' in options and", "create_default_cloudwatchlog_agent_if_not_exist(config) fatal_error('The specified CNAME \"%s\" did not resolve to a", "e.response)) return False else: logging.debug('Unexpected error: %s' % e) return", "the action, %s' % error.response) else: logging.debug('Unexpected error: %s' %", "o: k, v = o.split('=') opts[k] = v else: opts[o]", "the given awsprofile if is_fatal: log_message = 'AWS security credentials", "fs_id, security_credentials, ap_id, client_info): \"\"\"Populate ca/req configuration file with fresh", "% (cloudwatchlog_agent.get('log_group_name'), cloudwatchlog_agent.get('log_stream_name'), e.response)) else: handle_general_botocore_exceptions(e) return None except NoCredentialsError", "in options: fatal_error('The \"ocsp\" and \"noocsp\" options are mutually exclusive')", "log_stream.get('uploadSequenceToken') except (IndexError, TypeError, KeyError): pass return None def handle_general_botocore_exceptions(error):", "the name of the temporary file containing TLS tunnel state,", "+= CANONICAL_HEADERS % fs_id + '\\n' request += SIGNED_HEADERS +", "mount_path, mountpoint, '-o', get_nfs_mount_options(options)] if 'netns' in options: command =", "options): if 'tls' in options: mount_path = '127.0.0.1:%s' % path", "security credentials service' % \\ (AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE) fatal_error(error_msg, error_msg) def", "is specified incorrectly, %s' % (cloudwatchlog_agent.get('log_group_name'), cloudwatchlog_agent.get('log_stream_name'), e.response)) elif exception", "line: return line.split('=')[1].strip() except IOError: logging.debug('Unable to read %s', OS_RELEASE_PATH)", "def find_command_path(command, install_method): try: env_path = '/sbin:/usr/sbin:/usr/local/sbin:/root/bin:/usr/local/bin:/usr/bin:/bin' os.putenv('PATH', env_path) path", "cert_details['region'] = get_target_region(config) cert_details['certificateCreationTime'] = create_certificate(config, cert_details['mountStateDir'], cert_details['commonName'], cert_details['region'], fs_id,", "INSTANCE_IAM_URL = 'http://169.254.169.254/latest/meta-data/iam/security-credentials/' SECURITY_CREDS_ECS_URI_HELP_URL = 'https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html' SECURITY_CREDS_WEBIDENTITY_HELP_URL = 'https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html' SECURITY_CREDS_IAM_ROLE_HELP_URL", "to 1 # - the remaining 127 bits are used", "ca_dirs_check(config, tls_paths['database_dir'], tls_paths['certs_dir']) ca_supporting_files_check(tls_paths['index'], tls_paths['index_attr'], tls_paths['serial'], tls_paths['rand']) private_key = check_and_create_private_key(base_path)", "try: remote, path = device.split(':', 1) except ValueError: remote =", "a built-in ' \\ 'trust store.' % unsupported_option sys.stderr.write('WARN: %s\\n'", "region. This functionality should only be used if region is", "WATCHDOG_SERVICE], stdout=devnull, stderr=devnull, close_fds=True) elif 'start' in status: logging.debug('%s is", "logging.ERROR, 'critical': logging.CRITICAL } level = levels.get(raw_level.lower()) level_error = False", "'logging_max_bytes') file_count = config.getint(CONFIG_SECTION, 'logging_file_count') handler = RotatingFileHandler(os.path.join(log_dir, LOG_FILE), maxBytes=max_bytes,", "(key, value) return efs_client_info_str def create_public_key(private_key, public_key): cmd = 'openssl", "None except NoCredentialsError as e: logging.warning('Credentials are not properly configured,", "EFS documentation for mounting with DNS names for examples: %s'", "at %s.' % security_creds_lookup_url url_error_msg = 'Unable to reach %s", "command, 'files': files, } if cert_details: state.update(cert_details) with open(os.path.join(state_file_dir, state_file),", "- the remaining octets are the \"value\" aka content #", "]' for key, value in client_info.items(): efs_client_info_str += '\\n%s =", "material by looking for the key BIT STRING # Example:", "in options and 'tls' not in options: fatal_error('The \"tls\" option", "key to remove the header and footer '-----(BEGIN|END) PUBLIC KEY-----'", "aws_creds_uri # Fail if credentials cannot be fetched from the", "release 8' CENTOS8_RELEASE_NAME = 'CentOS Linux release 8' FEDORA_RELEASE_NAME =", "parse_arguments(config, args=None): \"\"\"Parse arguments, return (fsid, path, mountpoint, options)\"\"\" if", "= 'default - mount.log' return log_stream_name def check_if_cloudwatch_log_enabled(config): if config.has_option(CLOUDWATCH_LOG_SECTION,", "9 prim: OBJECT :rsaEncryption # 17:d=2 hl=2 l= 0 prim:", "the config setting if the override is not set if", "add_service = _sign(add_region, SERVICE).digest() signing_key = _sign(add_service, 'aws4_request').digest() return _sign(signing_key,", "if not check_if_cloudwatch_log_enabled(config): return None global CLOUDWATCHLOG_AGENT if not CLOUDWATCHLOG_AGENT:", "return { 'log_group_name': log_group_name, 'retention_days': int(retention_days), 'log_stream_name': log_stream_name } def", "be created, %s' % e.response) return False elif exception ==", "configurations at every mount since SigV4 signature can change\"\"\" public_key_path", "set the \"region\" ' 'parameter in the efs-utils configuration file.')", "options: options['nfsvers'] = '4.1' if 'rsize' not in options: options['rsize']", "== 'ServiceUnavailableException': logging.debug('The service cannot complete the request, %s' %", "tls_port except socket.error: continue sock.close() if 'tlsport' in options: fatal_error('Specified", "k return '%s=%s' % (str(k), str(v)) nfs_options = [to_nfs_option(k, v)", "except ImportError: from urllib import quote_plus try: from urllib2 import", "updated_time = current_time + timedelta(**kwargs) return updated_time.strftime(CERT_DATETIME_FORMAT) def get_utc_now(): \"\"\"", "'/'.join([date.strftime(DATE_ONLY_FORMAT), region, SERVICE, AWS4_REQUEST]) def match_device(config, device): \"\"\"Return the EFS", "if is_fatal: fatal_error(unsuccessful_resp, unsuccessful_resp) else: return None, None def get_aws_security_credentials_from_instance_metadata(iam_role_name):", "'Failed to find CAfile \"%s\"' % stunnel_cafile) efs_config['CAfile'] = stunnel_cafile", "False elif exception == 'UnrecognizedClientException': logging.debug('The most likely cause is", "'Unable to reach the url at %s, reason is %s'", "# Parse the public key to pull out the actual", "mount_completed): \"\"\" poll the tunnel process health every .5s during", "reason is %s' % (url, e.reason) if err_msg: logging.debug('%s %s',", "'index': os.path.join(base_path, mount_name, 'database/index.txt'), 'index_attr': os.path.join(base_path, mount_name, 'database/index.txt.attr'), 'serial': os.path.join(base_path,", "cause '/sbin/mount.efs' to be called by 'mount -a' # for", "private_key = check_and_create_private_key(base_path) if security_credentials: public_key = os.path.join(tls_paths['mount_dir'], 'publicKey.pem') create_public_key(private_key,", "options.get('awsprofile') if not awsprofile and use_iam: for file_path in [AWS_CREDENTIALS_FILE,", "efs_client_auth_str += '\\naccessKeyId = UTF8String:' + access_key_id efs_client_auth_str += '\\nsignature", "credentials_source # attempt to lookup AWS security credentials with IAM", "% warn_message) logging.warning(warn_message) del options[unsupported_option] def check_options_validity(options): if 'tls' in", "serial = $dir/database/serial private_key = %s cert = $dir/certificate.pem new_certs_dir", "except (IndexError, TypeError, KeyError): pass return None def handle_general_botocore_exceptions(error): exception", "else: return output, err error_message = '%s, error is: %s'", "remote = device path = '/' if FS_ID_RE.match(remote): return remote,", "'init': proc = subprocess.Popen( ['/sbin/status', WATCHDOG_SERVICE], stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) status,", "(k, v)) return lines def add_stunnel_ca_options(efs_config, config, options): if 'cafile'", "rsa_keygen_bits:3072' % key subprocess_call(cmd, 'Failed to create private key') read_only_mode", "security_credentials: ca_extension_str += '\\n1.3.6.1.4.1.4843.7.2 = ASN1:SEQUENCE:efs_client_auth' ca_extension_str += '\\n1.3.6.1.4.1.4843.7.3 =", "have to hand-serialize it. \"\"\" mount_filename = get_mount_specific_filename(fs_id, mountpoint, tls_port)", "\\ (INSTANCE_IAM_URL, SECURITY_CREDS_IAM_ROLE_HELP_URL) iam_role_name = url_request_helper(INSTANCE_IAM_URL, iam_role_unsuccessful_resp, iam_role_url_error_msg, retry_with_new_header_token=True) return", "'log_stream_name': log_stream_name } def create_default_cloudwatchlog_agent_if_not_exist(config): if not check_if_cloudwatch_log_enabled(config): return None", "the efs-utils configuration file.', message) metadata_exception = 'Unknown error' try:", "credentials, credentials_source = get_aws_security_credentials_from_ecs(os.environ[ECS_URI_ENV], False) if credentials and credentials_source: return", "'-help'] proc = subprocess.Popen(stunnel_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) proc.wait() _, err", "file.', message) metadata_exception = 'Unknown error' try: return config.get(CONFIG_SECTION, 'region')", "error.response) elif exception == 'AccessDeniedException': logging.debug('User is not authorized to", "# https://tools.ietf.org/html/rfc5280#section-4.2.1.2 # # Example: # 0382018f00...<subjectPublicKey> # - 03", "as f: token = f.read() except Exception as e: if", "get_aws_security_credentials_from_webidentity(role_arn, token_file, is_fatal=False): try: with open(token_file, 'r') as f: token", "= config.get(CLIENT_INFO_SECTION, 'source') if 0 < len(client_source) <= CLIENT_SOURCE_STR_LEN_LIMIT: client_info['source']", "region): \"\"\" Create a String to Sign - https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html \"\"\"", "is_stunnel_option_supported(stunnel_output, b'checkHost') ocsp_aia_supported = is_stunnel_option_supported(stunnel_output, b'OCSPaia') return check_host_supported, ocsp_aia_supported def", "'' FS_ID_RE = re.compile('^(?P<fs_id>fs-[0-9a-f]+)$') EFS_FQDN_RE = re.compile(r'^(?P<fs_id>fs-[0-9a-f]+)\\.efs\\.(?P<region>[a-z0-9-]+)\\.(?P<dns_name_suffix>[a-z0-9.]+)$') AP_ID_RE = re.compile('^fsap-[0-9a-f]{17}$')", "signing request (csr)') def create_ca_conf(config_path, common_name, directory, private_key, date, region,", "is explicitly excluded from the SubjectKeyIdentifier hash, per # https://tools.ietf.org/html/rfc5280#section-4.2.1.2", "cloudwatchlog_config.get('retention_days') group_creation_completed = create_cloudwatch_log_group(cloudwatchlog_client, log_group_name) if not group_creation_completed: return None", "already logged, %s' % (message, e.response)) return False elif exception", "(byte) is the tag (type) # - the next octets", "if not os.path.isfile(index_path): open(index_path, 'w').close() if not os.path.isfile(index_attr_path): with open(index_attr_path,", "'' efs_client_info_body = efs_client_info_builder(client_info) if client_info else '' full_config_body =", "refer to the EFS documentation for mounting with DNS names", "through AssumeRoleWithWebIdentity # (e.g. for IAM Role for Service Accounts", "return get_resp_obj(request_resp, url, unsuccessful_resp) err_msg = 'Unable to reach the", "Point ID %s is malformed' % options['accesspoint']) if 'iam' in", "import errno import hashlib import hmac import json import logging", "or '--help' in args[1:]: usage(out=sys.stdout, exit_code=0) if '--version' in args[1:]:", "0: logging.error('Command %s failed, rc=%s, stdout=\"%s\", stderr=\"%s\"' % (cmd, rc,", "mount /mount_point # # The script will add recommended mount", "> 0: add_stunnel_ca_options(efs_config, config, options) if cert_details: efs_config['cert'] = cert_details['certificate']", "'tls', 'tlsport', 'verify' ] UNSUPPORTED_OPTIONS = [ 'capath' ] STUNNEL_GLOBAL_CONFIG", "security_credentials['AccessKeyId'], security_credentials['SecretAccessKey'], date, region, fs_id, security_credentials['Token']) if security_credentials else ''", "log_group_name = cloudwatchlog_config.get('log_group_name') log_stream_name = cloudwatchlog_config.get('log_stream_name') retention_days = cloudwatchlog_config.get('retention_days') group_creation_completed", "url, unsuccessful_resp) except HTTPError as e: # For instance enable", "fatal_error('The \"iam\" option is required when mounting with named profile", "TLS tunnel: \"%s\"', ' '.join(tunnel_args)) tunnel_proc = subprocess.Popen( tunnel_args, stdout=subprocess.PIPE,", "VERSION = '1.28.2' SERVICE = 'elasticfilesystem' CONFIG_FILE = '/etc/amazon/efs/efs-utils.conf' CONFIG_SECTION", "'r') as f: token = f.read() except Exception as e:", "sys.argv if '-h' in args[1:] or '--help' in args[1:]: usage(out=sys.stdout,", "certs directories exist and if not, create directories (also create", "% e.response) return False elif exception == 'OperationAbortedException': logging.debug('Multiple requests", "'ResourceNotFoundException': logging.error('Either log group %s or log stream %s does", "except NoOptionError: pass try: return get_region_from_instance_metadata() except Exception as e:", "%s is specified incorrectly, %s' % (cloudwatchlog_agent.get('log_group_name'), cloudwatchlog_agent.get('log_stream_name'), e.response)) elif", "16.04), and upstart # (Amazon Linux 2017.09). # # Once", "== 'InvalidParameterException': logging.error('Either parameter log group name %s or retention", "\"%s\"' % remote ) if not hostnames: create_default_cloudwatchlog_agent_if_not_exist(config) fatal_error( 'The", "Public key hash is included in canonical request to tie", "timedelta from logging.handlers import RotatingFileHandler try: import ConfigParser from ConfigParser", "file \"%s\"', mode_str, CONFIG_FILE) except NoOptionError: pass try: os.makedirs(directory, mode)", "'\\n' request += CANONICAL_HEADERS % fs_id + '\\n' request +=", "kwargs = {'aws_creds_uri': aws_creds_uri} else: kwargs = {'awsprofile': get_aws_profile(options, use_iam)}", "options) mount_completed.set() t.join() def check_unsupported_options(options): for unsupported_option in UNSUPPORTED_OPTIONS: if", "resp_body.decode('utf-8') def parse_options(options): opts = {} for o in options.split(','):", "client_info) efs_client_auth_body = efs_client_auth_builder(public_key_path, security_credentials['AccessKeyId'], security_credentials['SecretAccessKey'], date, region, fs_id, security_credentials['Token'])", "f = os.open(lock_file, os.O_CREAT | os.O_DSYNC | os.O_EXCL | os.O_RDWR)", "AWS_CONFIG_FILE]: if os.path.exists(file_path): credentials = credentials_file_helper(file_path, awsprofile) if credentials['AccessKeyId']: return", "def get_resp_obj(request_resp, url, unsuccessful_resp): if request_resp.getcode() != 200: logging.debug(unsuccessful_resp +", "'\\n1.3.6.1.4.1.4843.7.4 = ASN1:SEQUENCE:efs_client_info' return ca_extension_str def efs_client_auth_builder(public_key_path, access_key_id, secret_access_key, date,", "private key and allow mounts to share it. # This", "authorized to perform the action, %s' % error.response) else: logging.debug('Unexpected", "= socket.gethostbyname_ex(remote) hostnames = list(filter(lambda e: e is not None,", "f: init_system = f.read().strip() except IOError: logging.warning('Unable to read %s',", "the ECS agent generated if aws_creds_uri: return get_aws_security_credentials_from_ecs(aws_creds_uri, True) #", "'SecretAccessKey', 'Token'] ECS_URI_ENV = 'AWS_CONTAINER_CREDENTIALS_RELATIVE_URI' ECS_TASK_METADATA_API = 'http://169.254.170.2' WEB_IDENTITY_ROLE_ARN_ENV =", "[ { 'timestamp': int(round(time.time() * 1000)), 'message': message } ]", "options: mount_tls(config, init_system, dns_name, path, fs_id, mountpoint, options) else: mount_nfs(dns_name,", "= UTCTIME:' + date.strftime(CERT_DATETIME_FORMAT) if session_token: efs_client_auth_str += '\\nsessionToken =", "SKIP_NO_LIBWRAP_RELEASES = [RHEL8_RELEASE_NAME, CENTOS8_RELEASE_NAME, FEDORA_RELEASE_NAME, SUSE_RELEASE_NAME] def fatal_error(user_message, log_message=None, exit_code=1):", "to read %s', comm_file) logging.debug('Identified init system: %s', init_system) return", "= 'iam' in options ap_id = options.get('accesspoint') cert_details = {}", "not found in dns_name_format') def get_aws_ec2_metadata_token(): try: opener = build_opener(HTTPHandler)", "of log groups that can be created, %s' % e.response)", "Fail if credentials cannot be fetched from the given aws_creds_uri", "return stunnel_config_file def write_tls_tunnel_state_file(fs_id, mountpoint, tls_port, tunnel_pid, command, files, state_file_dir,", "for k, v in headers.items(): req.add_header(k, v) request_resp = urlopen(req,", "unused bits that exist in the last # content byte.", "String to Sign - https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html \"\"\" string_to_sign = ALGORITHM +", "stream name %s is specified incorrectly, %s' % (log_group_name, log_stream_name,", "'tls' in options: if 'port' in options: fatal_error('The \"port\" and", "EFS_ONLY_OPTIONS] return ','.join(nfs_options) def mount_nfs(dns_name, path, mountpoint, options): if 'tls'", "format_str.count('}') != expected_ct: raise ValueError('DNS name format has an incorrect", "EFS file system by its short name, by adding it", "def publish_cloudwatch_log(cloudwatchlog_agent, message): if not cloudwatchlog_agent or not cloudwatchlog_agent.get('client'): return", "# Cannot use urllib.urlencode because it replaces the %s's return", "read_config(file_path) # check if aws access key id is found", "is %s' % (url, e.reason) if err_msg: logging.debug('%s %s', url_error_msg,", "public_key fatal_error(err_msg, err_msg) key_line = key_line.replace(' ', '') # DER", "message) else: message = 'Failed to mount %s at %s:", "every mount since SigV4 signature can change\"\"\" public_key_path = os.path.join(directory,", "'\\n' request += CANONICAL_URI + '\\n' request += create_canonical_query_string(public_key_hash, credential,", "= '%Y%m%dT%H%M%SZ' CERT_DATETIME_FORMAT = '%y%m%d%H%M%SZ' AWS_CREDENTIALS_FILE = os.path.expanduser(os.path.join('~' + pwd.getpwuid(os.getuid()).pw_name,", "# additional symbol appended to avoid naming collisions cert_details['mountStateDir'] =", "python # # Copyright 2017-2018 Amazon.com, Inc. and its affiliates.", "if 'awsprofile' in options and 'iam' not in options: fatal_error('The", "e.response)) return False elif exception == 'InvalidParameterException': logging.error('Either parameter log", "# - the next octets are the length - \"definite", "credentials. See %s for more info.' % \\ (STS_ENDPOINT_URL, SECURITY_CREDS_WEBIDENTITY_HELP_URL)", "exception == 'InvalidSequenceTokenException': logging.debug('The sequence token is not valid, %s'", "= '' FS_ID_RE = re.compile('^(?P<fs_id>fs-[0-9a-f]+)$') EFS_FQDN_RE = re.compile(r'^(?P<fs_id>fs-[0-9a-f]+)\\.efs\\.(?P<region>[a-z0-9-]+)\\.(?P<dns_name_suffix>[a-z0-9.]+)$') AP_ID_RE =", "= bootstrap_cloudwatch_logging(config, fs_id) check_unsupported_options(options) check_options_validity(options) init_system = get_init_system() check_network_status(fs_id, init_system)", "[Pass] # # Add an entry like this: # #", "to lookup AWS security credentials through AWS_CONTAINER_CREDENTIALS_RELATIVE_URI environment variable if", "%s for more detail.' % (CONFIG_FILE, 'https://docs.aws.amazon.com/console/efs/troubleshooting-tls') if config.getboolean(CONFIG_SECTION, 'stunnel_check_cert_hostname'):", "has exited already pass else: return output, err error_message =", "'Failed to resolve \"%s\"' % dns_name) return dns_name def tls_paths_dictionary(mount_name,", "as e: logging.warning('Unknown error, %s.' % e) return False return", "error, %s.' % e) return False return True def cloudwatch_create_log_stream_helper(cloudwatchlog_client,", "ConfigParser.SafeConfigParser() except AttributeError: p = ConfigParser() p.read(config_file) return p def", "\"port\" and \"tls\" options are mutually exclusive') if 'tlsport' in", "= EFS_FQDN_RE.match(hostname) if efs_fqdn_match: fs_id = efs_fqdn_match.group('fs_id') expected_dns_name = get_dns_name(config,", "try: p = ConfigParser.SafeConfigParser() except AttributeError: p = ConfigParser() p.read(config_file)", "Lookup AWS security credentials (access key ID and secret access", "# # Copy this script to /sbin/mount.efs and make sure", "logging.error('Log group %s does not exist, %s' % (log_group_name, e.response))", "and req files if they're not present in their respective", "AWS_CONFIG_FILE = os.path.expanduser(os.path.join('~' + pwd.getpwuid(os.getuid()).pw_name, '.aws', 'config')) CA_CONFIG_BODY = \"\"\"dir", "replaces the %s's return '&'.join(['%s=%s' % (k, v) for k,", "!= 200: logging.debug(unsuccessful_resp + ' %s: ResponseCode=%d', url, request_resp.getcode()) return", "% (instance_identity, e)) return None def get_region_from_legacy_dns_format(config): \"\"\" For backwards", "stderr=subprocess.PIPE, close_fds=True) status, _ = proc.communicate() if 'stop' in status:", "for o in options.split(','): if '=' in o: k, v", "log level until after logging is configured level_error = True", "unsuccessful_resp): if request_resp.getcode() != 200: logging.debug(unsuccessful_resp + ' %s: ResponseCode=%d',", "{ 'timestamp': int(round(time.time() * 1000)), 'message': message } ] }", "= device path = '/' if FS_ID_RE.match(remote): return remote, path", "https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html \"\"\" if not use_iam: return None, None # attempt", "already running', WATCHDOG_SERVICE) else: error_message = 'Could not start %s,", "% public_key) key_line = '' for line in output.splitlines(): if", "dns_name_format: split_dns_name_format = dns_name_format.split('.') if '{dns_name_suffix}' in dns_name_format: return split_dns_name_format[-2]", "creds['SecretAccessKey'], 'Token': creds['SessionToken'] }, 'webidentity:' + ','.join([role_arn, token_file]) # Fail", "init_system = f.read().strip() except IOError: logging.warning('Unable to read %s', comm_file)", "get_mount_specific_filename(fs_id, mountpoint, tls_port) + '+' # common name for certificate", "footer '-----(BEGIN|END) PUBLIC KEY-----' with open(public_key, 'r') as f: lines", "== 'ResourceAlreadyExistsException': logging.debug('Log group %s already exist, %s' % (log_group_name,", "= '/sbin:/usr/sbin:/usr/local/sbin:/root/bin:/usr/local/bin:/usr/bin:/bin' os.putenv('PATH', env_path) path = subprocess.check_output(['which', command]) except subprocess.CalledProcessError", "import json import logging import os import pwd import random", "# # For a BIT STRING, the first octet of", "def write_tls_tunnel_state_file(fs_id, mountpoint, tls_port, tunnel_pid, command, files, state_file_dir, cert_details=None): \"\"\"", "the length - \"definite form\" # - the first octet", "= get_iam_role_name() if iam_role_name: credentials, _ = get_aws_security_credentials_from_instance_metadata(iam_role_name) if credentials:", "%s is not a json object: %s' % (instance_identity, e))", "the remaining octets are the \"value\" aka content # #", "entry is: # # [Device] [Mount Point] [File System Type]", "\"dns_name_format\" field. Please set the \"region\" ' 'parameter in the", "Once there is an entry in fstab, the file system", "# 4:d=1 hl=2 l= 13 cons: SEQUENCE # 6:d=2 hl=2", "except OSError as e: if e.errno == errno.EEXIST: logging.info('Failed to", "'mount -a' # for this file system. The '_netdev' option", "res = opener.open(request) return res.read() except NameError: headers = {'X-aws-ec2-metadata-token-ttl-seconds':", "CLOUDWATCHLOG_AGENT CLOUDWATCHLOG_AGENT = bootstrap_cloudwatch_logging(config, fs_id) check_unsupported_options(options) check_options_validity(options) init_system = get_init_system()", "canonical request to tie the signature to a specific key", "is not authorized to perform the action, %s' % error.response)", "install it following the instructions at ' 'https://docs.aws.amazon.com/efs/latest/ug/using-amazon-efs-utils.html#upgrading-stunnel') def find_command_path(command,", "level = levels.get(raw_level.lower()) level_error = False if not level: #", "sys.exit(1) def read_config(config_file=CONFIG_FILE): try: p = ConfigParser.SafeConfigParser() except AttributeError: p", "# - 82 - 2 length octets to follow (ignore", "fatal_error(err_msg, err_msg) key_line = key_line.replace(' ', '') # DER encoding", "'systemd': logging.debug('Not testing network on non-systemd init systems') return check_network_target(fs_id)", "e.response) return False elif exception == 'DataAlreadyAcceptedException': logging.debug('The event %s", "resp_dict = json.loads(resp_body) else: resp_dict = json.loads(resp_body.decode(request_resp.headers.get_content_charset() or 'us-ascii')) return", "[int(options['tlsport'])] else: lower_bound, upper_bound = get_tls_port_range(config) tls_ports = list(range(lower_bound, upper_bound))", "%s', awsprofile, file_path) return credentials def get_aws_profile(options, use_iam): awsprofile =", "command and to handle response error messages\"\"\" retry_times = 3", "to ASN1 parse public key file, %s, correctly' % public_key)", "% (cmd, rc, output, err), exc_info=True) try: process.kill() except OSError:", "close_fds=True) output, _ = p.communicate() return output and 'nfs' in", "} level = levels.get(raw_level.lower()) level_error = False if not level:", "found in %s under named profile [%s]', file_path, awsprofile) if", "level: # delay logging error about malformed log level until", "STUNNEL_EFS_CONFIG = { 'client': 'yes', 'accept': '127.0.0.1:%s', 'connect': '%s:2049', 'sslVersion':", "'ocsp' in options and 'noocsp' in options: fatal_error('The \"ocsp\" and", "'InvalidParameterException': logging.error('Log group name %s is specified incorrectly, %s' %", "date, secret_access_key, region) efs_client_auth_str = '[ efs_client_auth ]' efs_client_auth_str +=", "v) request_resp = urlopen(req, timeout=1) return get_resp_obj(request_resp, url, unsuccessful_resp) except", "options: return False else: return config.getboolean(CONFIG_SECTION, 'stunnel_check_cert_validity') def get_mount_specific_filename(fs_id, mountpoint,", "'timestamp': int(round(time.time() * 1000)), 'message': message } ] } if", "'%s.stunnel.log' % mount_filename) efs_config = dict(STUNNEL_EFS_CONFIG) efs_config['accept'] = efs_config['accept'] %", "to Sign - https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html \"\"\" string_to_sign = ALGORITHM + '\\n'", "return 'default' except (NoSectionError, NoOptionError): continue return awsprofile def url_request_helper(url,", "= True level = logging.INFO max_bytes = config.getint(CONFIG_SECTION, 'logging_max_bytes') file_count", "Linux 2017.09). # # Once there is an entry in", "instance_identity = url_request_helper(INSTANCE_METADATA_SERVICE_URL, ec2_metadata_unsuccessful_resp, ec2_metadata_url_error_msg, retry_with_new_header_token=True) if instance_identity: try: return", "_sign(signing_key, string_to_sign).hexdigest() def get_credential_scope(date, region): return '/'.join([date.strftime(DATE_ONLY_FORMAT), region, SERVICE, AWS4_REQUEST])", "override is not set if ocsp_enabled: if ocsp_aia_supported: efs_config['OCSPaia'] =", "(fsid, path, mountpoint, options)\"\"\" if args is None: args =", "ID and secret access key). Adapted credentials provider chain from:", "from urllib.error import URLError, HTTPError from urllib.parse import urlencode try:", "message, token) except ClientError as e: exception = e.response['Error']['Code'] if", "os.getpid() os.write(f, lock_file_contents.encode('utf-8')) yield f finally: os.close(f) os.remove(lock_file) def do_with_lock(function):", "if '{fs_id}' not in dns_name_format: raise ValueError('DNS name format must", "= get_target_region(config) if '{dns_name_suffix}' in dns_name_format: expected_replacement_field_ct += 1 config_section", "return full_config_body def ca_extension_builder(ap_id, security_credentials, fs_id, client_info): ca_extension_str = '[", "%s.' % e) return False return True def cloudwatch_put_log_events_helper(cloudwatchlog_agent, message,", "[default] section in current file and return 'default' if so", "as e: logging.warning('response %s is not a json object: %s'", "l= 418 cons: SEQUENCE # 4:d=1 hl=2 l= 13 cons:", "not connect to the endpoint, %s' % e) return False", "given aws_creds_uri if is_fatal: fatal_error(ecs_unsuccessful_resp, ecs_unsuccessful_resp) else: return None, None", "= 'Successfully mounted %s at %s' % (dns_name, mountpoint) logging.info(message)", "logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL }", "your mount options' % fs_id, exit_code=0) def check_network_status(fs_id, init_system): if", "create the key simultaneously. key = get_private_key_path() @contextmanager def open_lock_file():", "= '1048576' if 'wsize' not in options: options['wsize'] = '1048576'", "= 'mount' CLIENT_INFO_SECTION = 'client-info' CLIENT_SOURCE_STR_LEN_LIMIT = 100 CLOUDWATCH_LOG_SECTION =", "v) for k, v in sorted(CANONICAL_HEADERS_DICT.items())]) SIGNED_HEADERS = ';'.join(CANONICAL_HEADERS_DICT.keys()) REQUEST_PAYLOAD", "cloudwatch_create_log_group_helper(cloudwatchlog_client, log_group_name): cloudwatchlog_client.create_log_group( logGroupName=log_group_name ) logging.info('Created cloudwatch log group %s'", "formatted' % public_key fatal_error(err_msg, err_msg) key_line = key_line.replace(' ', '')", "ocsp_aia_supported = get_version_specific_stunnel_options() tls_controls_message = 'WARNING: Your client lacks sufficient", "= tunnel_proc.communicate() fatal_error('Failed to initialize TLS tunnel for %s' %", "_fatal_error(metadata_exception) def get_region_from_instance_metadata(): instance_identity = get_instance_identity_info_from_instance_metadata('region') if not instance_identity: raise", "reading token file %s: %s' % (token_file, e) fatal_error(unsuccessful_resp, unsuccessful_resp)", "os.path.basename(file_path) + ':' + awsprofile # Fail if credentials cannot", "= UTF8String:%s' % (key, value) return efs_client_info_str def create_public_key(private_key, public_key):", "== 'ResourceNotFoundException': logging.error('Either log group %s or log stream %s", "does not exist, %s' % (cloudwatchlog_agent.get('log_group_name'), cloudwatchlog_agent.get('log_stream_name'), e.response)) return False", "mountpoint, options) as tunnel_proc: mount_completed = threading.Event() t = threading.Thread(target=poll_tunnel_process,", "def fatal_error(user_message, log_message=None, exit_code=1): if log_message is None: log_message =", "dns_name, path, fs_id, mountpoint, options) else: mount_nfs(dns_name, path, mountpoint, options)", "file system. The '_netdev' option tells the init system that", "21600} req = Request(INSTANCE_METADATA_TOKEN_URL, headers=headers, method='PUT') res = urlopen(req) return", "create public key') def subprocess_call(cmd, error_message): \"\"\"Helper method to run", "%s: status=%d, reason is %s' % (url, e.code, e.reason) except", "return False return True def cloudwatch_put_log_events_helper(cloudwatchlog_agent, message, token=None): kwargs =", "limitations under # the License. # # # Copy this", "%d], try specifying a different port range in %s' %", "be fetched from the given awsprofile if is_fatal: log_message =", "open(public_key, 'r') as f: lines = f.readlines() lines = lines[1:-1]", "subprocess.Popen( ['/sbin/status', WATCHDOG_SERVICE], stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) status, _ = proc.communicate()", "<mountpoint> [-o <options>]\\n') sys.exit(exit_code) def parse_arguments_early_exit(args=None): \"\"\"Parse arguments, checking for", "KEY-----' with open(public_key, 'r') as f: lines = f.readlines() lines", "'database'), 'certs_dir': os.path.join(base_path, mount_name, 'certs'), 'index': os.path.join(base_path, mount_name, 'database/index.txt'), 'index_attr':", "format_args = {'fs_id': fs_id} expected_replacement_field_ct = 1 if '{region}' in", "+= '\\naccessKeyId = UTF8String:' + access_key_id efs_client_auth_str += '\\nsignature =", "7, Debian 9, and Ubuntu 16.04), and upstart # (Amazon", "% (dns_name, mountpoint, proc.returncode, err.strip()) fatal_error(err.strip(), message, proc.returncode) def usage(out,", "import re import socket import subprocess import sys import threading", "None cloudwatchlog_config = get_cloudwatchlog_config(config, fs_id) log_group_name = cloudwatchlog_config.get('log_group_name') log_stream_name =", "SECURITY_CREDS_WEBIDENTITY_HELP_URL = 'https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html' SECURITY_CREDS_IAM_ROLE_HELP_URL = 'https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html' DEFAULT_STUNNEL_VERIFY_LEVEL = 2 DEFAULT_STUNNEL_CAFILE", "= '/etc/os-release' RHEL8_RELEASE_NAME = 'Red Hat Enterprise Linux release 8'", "in f: if 'PRETTY_NAME' in line: return line.split('=')[1].strip() except IOError:", "HTTPError as e: # For instance enable with IMDSv2, Unauthorized", "and the remote path to mount\"\"\" try: remote, path =", "that can be created, %s' % e.response) return False elif", "not os.path.exists(state_file_dir): create_required_directory(config, state_file_dir) verify_level = int(options.get('verify', DEFAULT_STUNNEL_VERIFY_LEVEL)) ocsp_enabled =", "init_system) sys.stderr.write('%s\\n' % error_message) logging.warning(error_message) def create_required_directory(config, directory): mode =", "to hand-serialize it. \"\"\" mount_filename = get_mount_specific_filename(fs_id, mountpoint, tls_port) global_config", "credentials through AssumeRoleWithWebIdentity # (e.g. for IAM Role for Service", "TLV (Tag, Length, Value) # - the first octet (byte)", "logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL } level =", "options['tlsport']) else: fatal_error('Failed to locate an available port in the", "endpoint, %s' % e) return False except Exception as e:", "with DNS names for examples: %s' % (remote, 'https://docs.aws.amazon.com/efs/latest/ug/mounting-fs-mount-cmd-dns-name.html')) def", "state_file_dir, cert_details=cert_details) try: yield tunnel_proc finally: os.rename(os.path.join(state_file_dir, temp_tls_state_file), os.path.join(state_file_dir, temp_tls_state_file[1:]))", "if exception == 'ResourceNotFoundException': logging.error('Log group %s does not exist,", "via \"iam\"') if 'awsprofile' in options and 'iam' not in", "split_dns_name_format[-2] elif 'amazonaws.com' in dns_name_format: return split_dns_name_format[-3] raise Exception('Region not", "AWS security credentials (access key ID and secret access key).", "CNAME \"%s\" did not resolve to a valid DNS name", "= efs_client_info_builder(client_info) if client_info else '' full_config_body = CA_CONFIG_BODY %", "if hostname == expected_dns_name: return fs_id, path else: create_default_cloudwatchlog_agent_if_not_exist(config) fatal_error('The", "= OCTETSTRING:' + signature efs_client_auth_str += '\\nsigv4DateTime = UTCTIME:' +", "def get_target_region(config): def _fatal_error(message): fatal_error('Error retrieving region. Please set the", "as big-endian, the length (which may be 0) as a", "and 'nfs' in str(output) def mount_tls(config, init_system, dns_name, path, fs_id,", "'Unable to reach the url at %s: status=%d, reason is", "v)) return lines def add_stunnel_ca_options(efs_config, config, options): if 'cafile' in", "global_config['debug'] = 'debug' if config.has_option(CONFIG_SECTION, 'stunnel_logs_file'): global_config['output'] = config.get(CONFIG_SECTION, 'stunnel_logs_file').replace('{fs_id}',", "# - the first octet (byte) is the tag (type)", "'client': cloudwatchlog_client, 'log_group_name': log_group_name, 'log_stream_name': log_stream_name } def create_default_cloudwatchlog_agent_if_not_exist(config): if", "return None except NoCredentialsError as e: logging.warning('Credentials are not properly", "the config file and metadata calls fail. \"\"\" dns_name_format =", "different port range in %s' % (lower_bound, upper_bound, CONFIG_FILE)) def", "socket.gaierror: create_default_cloudwatchlog_agent_if_not_exist(config) fatal_error( 'Failed to resolve \"%s\" - check that", "'awscredsuri' in options and 'iam' not in options: fatal_error('The \"iam\"", "= process.communicate() rc = process.poll() if rc != 0: logging.error('Command", "open(token_file, 'r') as f: token = f.read() except Exception as", "options: options['hard'] = None if 'timeo' not in options: options['timeo']", "BIT STRING tag # - 82 - 2 length octets", "signing_key = _sign(add_service, 'aws4_request').digest() return _sign(signing_key, string_to_sign).hexdigest() def get_credential_scope(date, region):", "+= '\\nsessionToken = EXPLICIT:0,UTF8String:' + session_token return efs_client_auth_str def efs_client_info_builder(client_info):", "SEQUENCE # 4:d=1 hl=2 l= 13 cons: SEQUENCE # 6:d=2", "and \"awsprofile\" options are mutually exclusive') def bootstrap_cloudwatch_logging(config, fs_id=None): if", "{ 'client': cloudwatchlog_client, 'log_group_name': log_group_name, 'log_stream_name': log_stream_name } def create_default_cloudwatchlog_agent_if_not_exist(config):", "url_request_helper(INSTANCE_METADATA_SERVICE_URL, ec2_metadata_unsuccessful_resp, ec2_metadata_url_error_msg, retry_with_new_header_token=True) if instance_identity: try: return instance_identity[property] except", "error.response) else: logging.debug('Unexpected error: %s' % error) def main(): parse_arguments_early_exit()", "= get_certificate_timestamp(current_time, hours=NOT_AFTER_HOURS) cmd = 'openssl ca -startdate %s -enddate", "cloudwatch_put_retention_policy_helper(cloudwatchlog_client, log_group_name, retention_days): cloudwatchlog_client.put_retention_policy( logGroupName=log_group_name, retentionInDays=retention_days ) logging.debug('Set cloudwatch log", "try: with open(OS_RELEASE_PATH) as f: for line in f: if", "in options: options['port'] = options['tlsport'] def to_nfs_option(k, v): if v", "'w') as f: f.write(full_config_body) return full_config_body def ca_extension_builder(ap_id, security_credentials, fs_id,", "at %s.' % STS_ENDPOINT_URL url_error_msg = 'Unable to reach %s", "not cloudwatchlog_client: return None cloudwatchlog_config = get_cloudwatchlog_config(config, fs_id) log_group_name =", "req = Request(url) for k, v in headers.items(): req.add_header(k, v)", "e: # For instance enable with IMDSv2, Unauthorized 401 error", "logging.info('Failed to take out private key creation lock, sleeping 50", "(Amazon Linux 2017.09). # # Once there is an entry", "'yes' else: fatal_error(tls_controls_message % 'stunnel_check_cert_validity') system_release_version = get_system_release_version() if not", "ca/req configuration file with fresh configurations at every mount since", "fail. \"\"\" dns_name_format = config.get(CONFIG_SECTION, 'dns_name_format') if '{region}' not in", "aws_creds_uri} else: kwargs = {'awsprofile': get_aws_profile(options, use_iam)} security_credentials, credentials_source =", "RHEL 7, Debian 9, and Ubuntu 16.04), and upstart #", "logGroupName=cloudwatchlog_agent.get('log_group_name'), logStreamNamePrefix=cloudwatchlog_agent.get('log_stream_name') ) def get_log_stream_next_token(cloudwatchlog_agent): try: response = cloudwatch_describe_log_streams_helper(cloudwatchlog_agent) except", "no policy = efsPolicy x509_extensions = v3_ca [ efsPolicy ]", "in config file %s', awsprofile, file_path) return credentials def get_aws_profile(options,", "exception == 'AccessDeniedException': logging.debug('User is not authorized to perform the", "region_specific_config_section format_args['dns_name_suffix'] = config.get(config_section, 'dns_name_suffix') logging.debug(\"Using dns_name_suffix %s in config", "401 and retry_with_new_header_token: token = get_aws_ec2_metadata_token() req.add_header('X-aws-ec2-metadata-token', token) request_resp =", "options['timeo'] = '600' if 'retrans' not in options: options['retrans'] =", "re.compile('^(?P<fs_id>fs-[0-9a-f]+)$') EFS_FQDN_RE = re.compile(r'^(?P<fs_id>fs-[0-9a-f]+)\\.efs\\.(?P<region>[a-z0-9-]+)\\.(?P<dns_name_suffix>[a-z0-9.]+)$') AP_ID_RE = re.compile('^fsap-[0-9a-f]{17}$') CREDENTIALS_KEYS = ['AccessKeyId',", "= get_public_key_sha1(public_key_path) canonical_request = create_canonical_request(public_key_hash, date, access_key_id, region, fs_id, session_token)", "stdout=devnull, stderr=devnull, close_fds=True) if rc != 0: fatal_error('Failed to mount", "0o400 os.chmod(key, read_only_mode) do_with_lock(generate_key) return key def create_certificate_signing_request(config_path, private_key, csr_path):", "%s %s %s \"\"\" # SigV4 Auth ALGORITHM = 'AWS4-HMAC-SHA256'", "'pid': tunnel_pid, 'cmd': command, 'files': files, } if cert_details: state.update(cert_details)", "service call failed, falling back ' 'to legacy \"dns_name_format\" check')", "log_stream = response['logStreams'][0] return log_stream.get('uploadSequenceToken') except (IndexError, TypeError, KeyError): pass", "tls_ports[mid:] + tls_ports[:mid] assert len(tls_ports) == len(ports_to_try) sock = socket.socket()", "sys.exit(0) def parse_arguments(config, args=None): \"\"\"Parse arguments, return (fsid, path, mountpoint,", "supported def get_version_specific_stunnel_options(): stunnel_command = [_stunnel_bin(), '-help'] proc = subprocess.Popen(stunnel_command,", "get_iam_role_name(): iam_role_unsuccessful_resp = 'Unsuccessful retrieval of IAM role name at", "[%s]', file_path, awsprofile) if 'aws_session_token' in str(e): logging.debug('aws_session_token not found", "def to_nfs_option(k, v): if v is None: return k return", "else: kwargs = {'awsprofile': get_aws_profile(options, use_iam)} security_credentials, credentials_source = get_aws_security_credentials(use_iam,", "the tunnel fails, exit uncleanly with os._exit \"\"\" while not", "int(mode_str, 8) except ValueError: logging.warning('Bad state_file_dir_mode \"%s\" in config file", "True t.start() mount_nfs(dns_name, path, mountpoint, options) mount_completed.set() t.join() def check_unsupported_options(options):", "to connect to stunnel. # if the user has specified", "if config.has_option(CLOUDWATCH_LOG_SECTION, 'enabled'): return config.getboolean(CLOUDWATCH_LOG_SECTION, 'enabled') return False def cloudwatch_create_log_group_helper(cloudwatchlog_client,", "and configs file (~/.aws/config) with given awsprofile if awsprofile: return", "controls to properly enforce TLS. Please upgrade stunnel, ' \\", "e) return False except EndpointConnectionError as e: logging.warning('Could not connect", "the tag (type) # - the next octets are the", "its affiliates. All Rights Reserved. # # Licensed under the", "to reach the url at %s, reason is %s' %", "logging.info('Starting TLS tunnel: \"%s\"', ' '.join(tunnel_args)) tunnel_proc = subprocess.Popen( tunnel_args,", "not in options: options['retrans'] = '2' if 'noresvport' not in", "'https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html' SECURITY_CREDS_WEBIDENTITY_HELP_URL = 'https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html' SECURITY_CREDS_IAM_ROLE_HELP_URL = 'https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html' DEFAULT_STUNNEL_VERIFY_LEVEL = 2", "return path.strip().decode() def get_system_release_version(): try: with open(SYSTEM_RELEASE_PATH) as f: return", "You will be able to mount an EFS file system", "\"\"\" poll the tunnel process health every .5s during the", "= {} if len(args) > 1: fsname = args[1] if", "in %s' % (lower_bound, upper_bound, CONFIG_FILE)) def is_ocsp_enabled(config, options): if", "tunnel: \"%s\"', ' '.join(tunnel_args)) tunnel_proc = subprocess.Popen( tunnel_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE,", "cert_details['mountStateDir'] = get_mount_specific_filename(fs_id, mountpoint, tls_port) + '+' # common name", "else: return None, None webidentity_url = STS_ENDPOINT_URL + '?' +", "stunnel configuration:\\n%s', stunnel_config) stunnel_config_file = os.path.join(state_file_dir, 'stunnel-config.%s' % mount_filename) with", "def create_cloudwatch_log_stream(cloudwatchlog_client, log_group_name, log_stream_name): try: cloudwatch_create_log_stream_helper(cloudwatchlog_client, log_group_name, log_stream_name) except ClientError", "= get_dns_name(config, fs_id) # check that the DNS name of", "= error.response['Error']['Code'] if exception == 'ServiceUnavailableException': logging.debug('The service cannot complete", "(Amazon Linux 2, CentOS 7, RHEL 7, Debian 9, and", "in %s.\\nSee %s for more detail.' % (CONFIG_FILE, 'https://docs.aws.amazon.com/console/efs/troubleshooting-tls') if", "log_group_name) if not group_creation_completed: return None put_retention_policy_completed = put_cloudwatch_log_retention_policy(cloudwatchlog_client, log_group_name,", "be thrown, # to retrieve metadata, the header should embeded", "'1.28.2' SERVICE = 'elasticfilesystem' CONFIG_FILE = '/etc/amazon/efs/efs-utils.conf' CONFIG_SECTION = 'mount'", "+= '\\n1.3.6.1.4.1.4843.7.1 = ASN1:UTF8String:' + ap_id if security_credentials: ca_extension_str +=", "p def bootstrap_logging(config, log_dir=LOG_DIR): raw_level = config.get(CONFIG_SECTION, 'logging_level') levels =", "log group name %s or log stream name %s is", "str(output) def mount_tls(config, init_system, dns_name, path, fs_id, mountpoint, options): if", "SECURITY_CREDS_ECS_URI_HELP_URL) ecs_security_dict = url_request_helper(ecs_uri, ecs_unsuccessful_resp, ecs_url_error_msg) if ecs_security_dict and all(k", "'host': '%s' } CANONICAL_HEADERS = '\\n'.join(['%s:%s' % (k, v) for", "'&'.join(['%s=%s' % (k, v) for k, v in sorted(canonical_query_params.items())]) def", "been ignored, as amazon-efs-utils relies on a built-in ' \\", "This has been tested with systemd # (Amazon Linux 2,", "WEB_IDENTITY_ROLE_ARN_ENV in os.environ and WEB_IDENTITY_TOKEN_FILE_ENV in os.environ: credentials, credentials_source =", "+ secret_access_key).encode('utf-8'), date.strftime(DATE_ONLY_FORMAT)).digest() add_region = _sign(key_date, region).digest() add_service = _sign(add_region,", "logging.warning('Credentials are not properly configured, %s' % e) return False", "mounted with: # # sudo mount /mount_point # # The", "def bootstrap_cloudwatch_logging(config, fs_id=None): if not check_if_cloudwatch_log_enabled(config): return None cloudwatchlog_client =", "try: access_key = aws_credentials_configs.get(awsprofile, 'aws_access_key_id') secret_key = aws_credentials_configs.get(awsprofile, 'aws_secret_access_key') session_token", "= err.splitlines() check_host_supported = is_stunnel_option_supported(stunnel_output, b'checkHost') ocsp_aia_supported = is_stunnel_option_supported(stunnel_output, b'OCSPaia')", "that this is explicitly excluded from the SubjectKeyIdentifier hash, per", "\\ 'from ECS credentials relative uri, or from the instance", "bits are used to encode the number of octets that", "True: try: with open_lock_file(): return function() except OSError as e:", "\"%s\" in config file \"%s\"', mode_str, CONFIG_FILE) except NoOptionError: pass", "message, token=None): kwargs = { 'logGroupName': cloudwatchlog_agent.get('log_group_name'), 'logStreamName': cloudwatchlog_agent.get('log_stream_name'), 'logEvents':", "False ) if credentials and credentials_source: return credentials, credentials_source #", "return True elif 'noocsp' in options: return False else: return", "an invalid AWS access key ID or secret Key, %s'", "if session_token: efs_client_auth_str += '\\nsessionToken = EXPLICIT:0,UTF8String:' + session_token return", "'log_group_name'): log_group_name = config.get(CLOUDWATCH_LOG_SECTION, 'log_group_name') retention_days = DEFAULT_RETENTION_DAYS if config.has_option(CLOUDWATCH_LOG_SECTION,", "Please set the \"region\" parameter in the efs-utils configuration file.',", "'renegotiation': 'no', 'TIMEOUTbusy': '20', 'TIMEOUTclose': '0', 'TIMEOUTidle': '70', 'delay': 'yes',", "appended to avoid naming collisions cert_details['mountStateDir'] = get_mount_specific_filename(fs_id, mountpoint, tls_port)", "unsuccessful_resp, url_error_msg, retry_with_new_header_token=True) if iam_security_dict and all(k in iam_security_dict for", "re.compile(r'^(?P<fs_id>fs-[0-9a-f]+)\\.efs\\.(?P<region>[a-z0-9-]+)\\.(?P<dns_name_suffix>[a-z0-9.]+)$') AP_ID_RE = re.compile('^fsap-[0-9a-f]{17}$') CREDENTIALS_KEYS = ['AccessKeyId', 'SecretAccessKey', 'Token'] ECS_URI_ENV", "to create certificate signing request (csr)') def create_ca_conf(config_path, common_name, directory,", "= ConfigParser.SafeConfigParser() except AttributeError: p = ConfigParser() p.read(config_file) return p", "1 options = parse_options(args[options_index]) if not fsname or not mountpoint:", "check_network_target(fs_id): with open(os.devnull, 'w') as devnull: rc = subprocess.call(['systemctl', 'status',", "random.randrange(len(tls_ports)) ports_to_try = tls_ports[mid:] + tls_ports[:mid] assert len(tls_ports) == len(ports_to_try)", "= { 'client': 'yes', 'accept': '127.0.0.1:%s', 'connect': '%s:2049', 'sslVersion': 'TLSv1.2',", "Request - https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html \"\"\" formatted_datetime = date.strftime(SIGV4_DATETIME_FORMAT) credential = quote_plus(access_key", "get_aws_security_credentials_from_instance_metadata(iam_role_name) if credentials: return session.create_client(service, aws_access_key_id=credentials['AccessKeyId'], aws_secret_access_key=credentials['SecretAccessKey'], aws_session_token=credentials['Token'], region_name=region) return", "e: exception = e.response['Error']['Code'] if exception == 'InvalidParameterException': logging.debug('Either parameter", "session_token return efs_client_auth_str def efs_client_info_builder(client_info): efs_client_info_str = '[ efs_client_info ]'", "cert_details = {} security_credentials = None client_info = get_client_info(config) if", "def write_stunnel_config_file(config, state_file_dir, fs_id, mountpoint, tls_port, dns_name, verify_level, ocsp_enabled, options,", "% (log_group_name, log_stream_name, e.response)) return False elif exception == 'ResourceNotFoundException':", "if e.code == 401 and retry_with_new_header_token: token = get_aws_ec2_metadata_token() req.add_header('X-aws-ec2-metadata-token',", "-startdate %s -enddate %s -selfsign -batch -notext -config %s -in", "create private key') read_only_mode = 0o400 os.chmod(key, read_only_mode) do_with_lock(generate_key) return", "an entry in fstab, the file system can be mounted", "try: primary, secondaries, _ = socket.gethostbyname_ex(remote) hostnames = list(filter(lambda e:", "% mount_filename) efs_config = dict(STUNNEL_EFS_CONFIG) efs_config['accept'] = efs_config['accept'] % tls_port", "'to legacy \"dns_name_format\" check') try: region = get_region_from_legacy_dns_format(config) sys.stdout.write('Warning: region", "Access Key are not found in AWS credentials file (%s),", "{ 'pid': tunnel_pid, 'cmd': command, 'files': files, } if cert_details:", "for certificate signing request is max 64 characters cert_details['commonName'] =", "if config.has_section(region_specific_config_section): config_section = region_specific_config_section format_args['dns_name_suffix'] = config.get(config_section, 'dns_name_suffix') logging.debug(\"Using", "mount_path = '127.0.0.1:%s' % path else: mount_path = '%s:%s' %", "open(serial_path, 'w+') as f: f.write('00') if not os.path.isfile(rand_path): open(rand_path, 'w').close()", "%s for more info.' % \\ (STS_ENDPOINT_URL, SECURITY_CREDS_WEBIDENTITY_HELP_URL) resp =", "handle_general_botocore_exceptions(e) return None except NoCredentialsError as e: logging.warning('Credentials are not", "options)\"\"\" if args is None: args = sys.argv fsname =", "locate %s in %s - %s' % (command, env_path, install_method),", "args.index('-o') + 1 options = parse_options(args[options_index]) if not fsname or", "is already running', WATCHDOG_SERVICE) else: error_message = 'Could not start", "'%Y%m%dT%H%M%SZ' CERT_DATETIME_FORMAT = '%y%m%d%H%M%SZ' AWS_CREDENTIALS_FILE = os.path.expanduser(os.path.join('~' + pwd.getpwuid(os.getuid()).pw_name, '.aws',", "'--version' in args[1:]: sys.stdout.write('%s Version: %s\\n' % (args[0], VERSION)) sys.exit(0)", "with open(token_file, 'r') as f: token = f.read() except Exception", "= None mountpoint = None options = {} if len(args)", "(CONFIG_FILE, 'https://docs.aws.amazon.com/console/efs/troubleshooting-tls') if config.getboolean(CONFIG_SECTION, 'stunnel_check_cert_hostname'): if check_host_supported: efs_config['checkHost'] = dns_name", "config.has_option(CLOUDWATCH_LOG_SECTION, 'log_group_name'): log_group_name = config.get(CLOUDWATCH_LOG_SECTION, 'log_group_name') retention_days = DEFAULT_RETENTION_DAYS if", "# Add an entry like this: # # fs-deadbeef /mount_point", "install_method), e) return path.strip().decode() def get_system_release_version(): try: with open(SYSTEM_RELEASE_PATH) as", "the tunnel dies - since this is not called from", "'http://169.254.169.254/latest/api/token' INSTANCE_METADATA_SERVICE_URL = 'http://169.254.169.254/latest/dynamic/instance-identity/document/' INSTANCE_IAM_URL = 'http://169.254.169.254/latest/meta-data/iam/security-credentials/' SECURITY_CREDS_ECS_URI_HELP_URL = 'https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html'", "config = read_config() bootstrap_logging(config) fs_id, path, mountpoint, options = parse_arguments(config)", "e)) return None def get_region_from_legacy_dns_format(config): \"\"\" For backwards compatibility check", "private_key, certificate_signing_request) not_before = get_certificate_timestamp(current_time, minutes=-NOT_BEFORE_MINS) not_after = get_certificate_timestamp(current_time, hours=NOT_AFTER_HOURS)", "fatal_error('Failed to resolve \"%s\" - check that your file system", "certificate_signing_request) not_before = get_certificate_timestamp(current_time, minutes=-NOT_BEFORE_MINS) not_after = get_certificate_timestamp(current_time, hours=NOT_AFTER_HOURS) cmd", "so we will create one private key and allow mounts", "likely cause is an invalid AWS access key ID or", "script to /sbin/mount.efs and make sure it is executable. #", "root can run mount.efs\\n') sys.exit(1) def read_config(config_file=CONFIG_FILE): try: p =", "2017-2018 Amazon.com, Inc. and its affiliates. All Rights Reserved. #", "for more info.' % \\ (security_creds_lookup_url, SECURITY_CREDS_IAM_ROLE_HELP_URL) iam_security_dict = url_request_helper(security_creds_lookup_url,", "def get_init_system(comm_file='/proc/1/comm'): init_system = 'unknown' try: with open(comm_file) as f:", "signature = calculate_signature(string_to_sign, date, secret_access_key, region) efs_client_auth_str = '[ efs_client_auth", "def start_watchdog(init_system): if init_system == 'init': proc = subprocess.Popen( ['/sbin/status',", "'mount.log' STATE_FILE_DIR = '/var/run/efs' PRIVATE_KEY_FILE = '/etc/amazon/efs/privateKey.pem' DATE_ONLY_FORMAT = '%Y%m%d'", "'openSUSE Leap' SKIP_NO_LIBWRAP_RELEASES = [RHEL8_RELEASE_NAME, CENTOS8_RELEASE_NAME, FEDORA_RELEASE_NAME, SUSE_RELEASE_NAME] def fatal_error(user_message,", "tls_paths['index_attr'], tls_paths['serial'], tls_paths['rand']) private_key = check_and_create_private_key(base_path) if security_credentials: public_key =", "resolve to an EFS mount target' % remote ) for", "region, fs_id, security_credentials, ap_id, client_info, base_path=STATE_FILE_DIR): current_time = get_utc_now() tls_paths", "not None, [primary] + secondaries)) except socket.gaierror: create_default_cloudwatchlog_agent_if_not_exist(config) fatal_error( 'Failed", "not found in config file and metadata service call failed,", "OSError as e: if e.errno == errno.EEXIST: logging.info('Failed to take", "mount aborted\" % mountpoint) return with bootstrap_tls(config, init_system, dns_name, fs_id,", "json.loads(resp_body) else: resp_dict = json.loads(resp_body.decode(request_resp.headers.get_content_charset() or 'us-ascii')) return resp_dict except", "stunnel_output = err.splitlines() check_host_supported = is_stunnel_option_supported(stunnel_output, b'checkHost') ocsp_aia_supported = is_stunnel_option_supported(stunnel_output,", "-algorithm RSA -out %s -pkeyopt rsa_keygen_bits:3072' % key subprocess_call(cmd, 'Failed", "status: logging.debug('%s is already running', WATCHDOG_SERVICE) elif init_system == 'systemd':", "the remaining 127 bits are used to encode the number", "if format_str.count('{') != expected_ct or format_str.count('}') != expected_ct: raise ValueError('DNS", "expected_ct or format_str.count('}') != expected_ct: raise ValueError('DNS name format has", "%s' % (message, e.response)) return False elif exception == 'UnrecognizedClientException':", "the efs-utils configuration file.') return region except Exception: logging.warning('Legacy check", "url_request_helper(INSTANCE_IAM_URL, iam_role_unsuccessful_resp, iam_role_url_error_msg, retry_with_new_header_token=True) return iam_role_name def credentials_file_helper(file_path, awsprofile): aws_credentials_configs", "get_public_key_sha1(public_key_path) canonical_request = create_canonical_request(public_key_hash, date, access_key_id, region, fs_id, session_token) string_to_sign", "(log_group_name, e.response)) return False elif exception == 'OperationAbortedException': logging.debug('Multiple requests", "is an invalid AWS access key ID or secret Key,", "public key to pull out the actual key material by", "= process.poll() if rc != 0: logging.error('Command %s failed, rc=%s,", "req_distinguished_name ] CN = %s %s %s %s \"\"\" #", "fatal_error('Failed to find certificate authority file for verification', 'Failed to", "EFS mount target' % remote ) for hostname in hostnames:", "line in f: if 'PRETTY_NAME' in line: return line.split('=')[1].strip() except", "re.compile('^fsap-[0-9a-f]{17}$') CREDENTIALS_KEYS = ['AccessKeyId', 'SecretAccessKey', 'Token'] ECS_URI_ENV = 'AWS_CONTAINER_CREDENTIALS_RELATIVE_URI' ECS_TASK_METADATA_API", "a non-temporary version following a successful mount. \"\"\" state_file =", "token=None): kwargs = { 'logGroupName': cloudwatchlog_agent.get('log_group_name'), 'logStreamName': cloudwatchlog_agent.get('log_stream_name'), 'logEvents': [", "\"awsprofile\"') if 'awscredsuri' in options and 'iam' not in options:", "\"\"\" Serializes stunnel configuration to a file. Unfortunately this does", "as e: os._exit(e.code) mount_completed.wait(.5) def get_init_system(comm_file='/proc/1/comm'): init_system = 'unknown' try:", "\"%s\" - check that the specified DNS name is a", "None webidentity_url = STS_ENDPOINT_URL + '?' + urlencode({ 'Version': '2011-06-15',", "are not properly configured, %s' % e) return False except", "role_arn, 'RoleSessionName': 'efs-mount-helper', 'WebIdentityToken': token }) unsuccessful_resp = 'Unsuccessful retrieval", "elif instance_id: log_stream_name = '%s - mount.log' % (instance_id) elif", "not present in the config file and metadata calls fail.", "configured, %s' % e) return False except EndpointConnectionError as e:", "intermediate directories if they don't exist).\"\"\" if not os.path.exists(database_dir): create_required_directory(config,", "and 'noocsp' in options: fatal_error('The \"ocsp\" and \"noocsp\" options are", "log group retention days to %s' % retention_days) def put_cloudwatch_log_retention_policy(cloudwatchlog_client,", "date.strftime(DATE_ONLY_FORMAT)).digest() add_region = _sign(key_date, region).digest() add_service = _sign(add_region, SERVICE).digest() signing_key", "# attempt to lookup AWS security credentials in AWS credentials", "url_error_msg, headers={}, retry_with_new_header_token=False): try: req = Request(url) for k, v", "security_credentials, credentials_source = get_aws_security_credentials(use_iam, **kwargs) if credentials_source: cert_details['awsCredentialsMethod'] = credentials_source", "aws_creds_uri: return get_aws_security_credentials_from_ecs(aws_creds_uri, True) # attempt to lookup AWS security", "credentials['AccessKeyId'] = aws_credentials_configs.get(awsprofile, 'aws_access_key_id') credentials['SecretAccessKey'] = aws_credentials_configs.get(awsprofile, 'aws_secret_access_key') except NoSectionError:", "options: fatal_error('The \"awscredsuri\" and \"awsprofile\" options are mutually exclusive') def", "AWS_CONFIG_FILE, awsprofile) fatal_error(log_message) else: return None, None def get_aws_security_credentials_from_ecs(aws_creds_uri, is_fatal=False):", "it is executable. # # You will be able to", "hand-serialize it. \"\"\" mount_filename = get_mount_specific_filename(fs_id, mountpoint, tls_port) global_config =", "int(options.get('verify', DEFAULT_STUNNEL_VERIFY_LEVEL)) ocsp_enabled = is_ocsp_enabled(config, options) stunnel_config_file = write_stunnel_config_file(config, state_file_dir,", "file_path) return credentials def get_aws_profile(options, use_iam): awsprofile = options.get('awsprofile') if", "create_default_cloudwatchlog_agent_if_not_exist(config): if not check_if_cloudwatch_log_enabled(config): return None global CLOUDWATCHLOG_AGENT if not", "config, options): if 'cafile' in options: stunnel_cafile = options['cafile'] else:", "DEFAULT_STUNNEL_VERIFY_LEVEL)) ocsp_enabled = is_ocsp_enabled(config, options) stunnel_config_file = write_stunnel_config_file(config, state_file_dir, fs_id,", "connect to the endpoint, %s' % e) return False except", "ports_to_try: try: sock.bind(('localhost', tls_port)) sock.close() return tls_port except socket.error: continue", "security credentials through the credentials URI the ECS agent generated", "%s' % (k, item)) else: lines.append('%s = %s' % (k,", "so that we can later override the port the NFS", "f: if 'PRETTY_NAME' in line: return line.split('=')[1].strip() except IOError: logging.debug('Unable", "import time from contextlib import contextmanager from datetime import datetime,", "target region. This functionality should only be used if region", "is a networked file system type. This has been tested", "os.path.join(base_path, mount_name, 'database/.rand') } return tls_dict def get_public_key_sha1(public_key): # truncating", "mount_tls(config, init_system, dns_name, path, fs_id, mountpoint, options): if os.path.ismount(mountpoint) and", "to verify\\n\" % mountpoint) logging.warning(\"%s is already mounted, mount aborted\"", "%s' % (cloudwatchlog_agent.get('log_group_name'), cloudwatchlog_agent.get('log_stream_name'), e.response)) else: handle_general_botocore_exceptions(e) return None except", "'publicKey.pem') create_public_key(private_key, public_key) create_ca_conf(certificate_config, common_name, tls_paths['mount_dir'], private_key, current_time, region, fs_id,", "key pair to avoid replay attacks 'PublicKeyHash': quote_plus(public_key_hash), 'X-Amz-Algorithm': ALGORITHM,", "%s.' % STS_ENDPOINT_URL url_error_msg = 'Unable to reach %s to", "'default' if so try: access_key = aws_credentials_configs.get('default', 'aws_access_key_id') if access_key", "CONFIG_FILE)) def is_ocsp_enabled(config, options): if 'ocsp' in options: return True", "'port_range_lower_bound') upper_bound = config.getint(CONFIG_SECTION, 'port_range_upper_bound') if lower_bound >= upper_bound: fatal_error('Configuration", "public_key): cmd = 'openssl rsa -in %s -outform PEM -pubout", "octet always has the high order bit (8) set to", "fs_id, client_info) efs_client_auth_body = efs_client_auth_builder(public_key_path, security_credentials['AccessKeyId'], security_credentials['SecretAccessKey'], date, region, fs_id,", "config.getint(CONFIG_SECTION, 'logging_file_count') handler = RotatingFileHandler(os.path.join(log_dir, LOG_FILE), maxBytes=max_bytes, backupCount=file_count) handler.setFormatter(logging.Formatter(fmt='%(asctime)s -", "level_error: logging.error('Malformed logging level \"%s\", setting logging level to %s',", "= is_stunnel_option_supported(stunnel_output, b'OCSPaia') return check_host_supported, ocsp_aia_supported def _stunnel_bin(): return find_command_path('stunnel',", "run shell openssl command and to handle response error messages\"\"\"", "logging.error('Malformed logging level \"%s\", setting logging level to %s', raw_level,", "def cloudwatch_put_retention_policy_helper(cloudwatchlog_client, log_group_name, retention_days): cloudwatchlog_client.put_retention_policy( logGroupName=log_group_name, retentionInDays=retention_days ) logging.debug('Set cloudwatch", "aws access key id is found under [default] section in", "continue sock.close() if 'tlsport' in options: fatal_error('Specified port [%s] is", "efs_client_auth_str += '\\nsigv4DateTime = UTCTIME:' + date.strftime(CERT_DATETIME_FORMAT) if session_token: efs_client_auth_str", "not os.path.exists(stunnel_cafile): fatal_error('Failed to find certificate authority file for verification',", "poll_tunnel_process(tunnel_proc, fs_id, mount_completed): \"\"\" poll the tunnel process health every", "time.sleep(0.05) else: raise def generate_key(): if os.path.isfile(key): return cmd =", "ASN1:SEQUENCE:efs_client_auth' ca_extension_str += '\\n1.3.6.1.4.1.4843.7.3 = ASN1:UTF8String:' + fs_id if client_info:", "False except Exception as e: logging.warning('Unknown error, %s.' % e)", "health every .5s during the mount attempt to fail fast", "or format_str.count('}') != expected_ct: raise ValueError('DNS name format has an", "please install botocore first.') return None session = botocore.session.get_session() region", "'Unknown error' try: return config.get(CONFIG_SECTION, 'region') except NoOptionError: pass try:", "number of octets # - the remaining octets are the", "options and 'tls' not in options: fatal_error('The \"tls\" option is", "if config.has_option(CLOUDWATCH_LOG_SECTION, 'retention_in_days'): retention_days = config.get(CLOUDWATCH_LOG_SECTION, 'retention_in_days') log_stream_name = get_cloudwatch_log_stream_name(fs_id)", "its short name, by adding it # to /etc/fstab. The", "if exception == 'ResourceAlreadyExistsException': logging.debug('Log stream %s already exist in", "'X-Amz-Expires': 86400, 'X-Amz-SignedHeaders': SIGNED_HEADERS, } if session_token: canonical_query_params['X-Amz-Security-Token'] = quote_plus(session_token)", "for k, v in config.items(): if type(v) is list: for", "to a valid EFS DNS ' 'name' % remote, 'Failed", "'start', WATCHDOG_SERVICE], stdout=devnull, stderr=devnull, close_fds=True) else: logging.debug('%s is already running',", "did not resolve to a valid DNS name for an", "and credentials_source: return credentials, credentials_source # attempt to lookup AWS", "include {fs_id}') format_args = {'fs_id': fs_id} expected_replacement_field_ct = 1 if", "parameter log group name %s or retention in days %s", "= v3_ca [ efsPolicy ] CN = supplied [ req", "'aws_access_key_id') credentials['SecretAccessKey'] = aws_credentials_configs.get(awsprofile, 'aws_secret_access_key') except NoSectionError: logging.debug('No [%s] section", "= { 'fips': 'no', 'foreground': 'yes', 'socket': [ 'l:SO_REUSEADDR=yes', 'a:SO_BINDTODEVICE=lo',", "AWS security credentials in AWS credentials file (~/.aws/credentials) # and", "obtain the target region. This functionality should only be used", "raise def generate_key(): if os.path.isfile(key): return cmd = 'openssl genpkey", "= efs_config['connect'] % dns_name efs_config['verify'] = verify_level if verify_level >", "options are mutually exclusive') def bootstrap_cloudwatch_logging(config, fs_id=None): if not check_if_cloudwatch_log_enabled(config):", "stunnel configuration to a file. Unfortunately this does not conform", "get_tls_port_range(config) tls_ports = list(range(lower_bound, upper_bound)) # Choose a random midpoint,", "= config.get(CONFIG_SECTION, 'dns_name_format') if '{region}' not in dns_name_format: split_dns_name_format =", "is_fatal: fatal_error(unsuccessful_resp, unsuccessful_resp) else: return None, None def get_aws_security_credentials_from_instance_metadata(iam_role_name): security_creds_lookup_url", "hostnames: efs_fqdn_match = EFS_FQDN_RE.match(hostname) if efs_fqdn_match: fs_id = efs_fqdn_match.group('fs_id') expected_dns_name", "file and metadata calls fail. \"\"\" dns_name_format = config.get(CONFIG_SECTION, 'dns_name_format')", "number of replacement fields') dns_name_format = config.get(CONFIG_SECTION, 'dns_name_format') if '{fs_id}'", "== 'systemd': rc = subprocess.call(['systemctl', 'is-active', '--quiet', WATCHDOG_SERVICE], close_fds=True) if", "file, %s, correctly' % public_key) key_line = '' for line", "efs_client_info_builder(client_info): efs_client_info_str = '[ efs_client_info ]' for key, value in", "'logging_level') levels = { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING,", "> 2: mountpoint = args[2] if len(args) > 4 and", "(private_key, public_key) subprocess_call(cmd, 'Failed to create public key') def subprocess_call(cmd,", "current_time.strftime(CERT_DATETIME_FORMAT) def get_private_key_path(): \"\"\"Wrapped for mocking purposes in unit tests\"\"\"", "def parse_arguments(config, args=None): \"\"\"Parse arguments, return (fsid, path, mountpoint, options)\"\"\"", "logGroupName=log_group_name, retentionInDays=retention_days ) logging.debug('Set cloudwatch log group retention days to", "os.environ: credentials, credentials_source = get_aws_security_credentials_from_ecs(os.environ[ECS_URI_ENV], False) if credentials and credentials_source:", "= 'openssl asn1parse -inform PEM -in %s' % public_key output,", "args is None: args = sys.argv if '-h' in args[1:]", "Service Accounts (IRSA) approach on EKS) if WEB_IDENTITY_ROLE_ARN_ENV in os.environ", "IAM role name. See %s for more info.' % \\", "try: test_tunnel_process(tunnel_proc, fs_id) except SystemExit as e: os._exit(e.code) mount_completed.wait(.5) def", "and credentials_source: return credentials, credentials_source error_msg = 'AWS Access Key", "datetime.utcnow() def assert_root(): if os.geteuid() != 0: sys.stderr.write('only root can", "log groups that can be created, %s' % e.response) return", "OBJECT :rsaEncryption # 17:d=2 hl=2 l= 0 prim: NULL #", "'PublicKeyHash': quote_plus(public_key_hash), 'X-Amz-Algorithm': ALGORITHM, 'X-Amz-Credential': credential, 'X-Amz-Date': quote_plus(formatted_datetime), 'X-Amz-Expires': 86400,", "DEFAULT_CLOUDWATCH_LOG_GROUP = '/aws/efs/utils' DEFAULT_RETENTION_DAYS = 14 # Cloudwatchlog agent dict", "elif exception == 'ResourceNotFoundException': logging.error('Log group %s does not exist,", "log_group_name, log_stream_name) except ClientError as e: exception = e.response['Error']['Code'] if", "efs_fqdn_match: fs_id = efs_fqdn_match.group('fs_id') expected_dns_name = get_dns_name(config, fs_id) # check", "logging.info('Started TLS tunnel, pid: %d', tunnel_proc.pid) temp_tls_state_file = write_tls_tunnel_state_file(fs_id, mountpoint,", "def get_aws_security_credentials_from_ecs(aws_creds_uri, is_fatal=False): ecs_uri = ECS_TASK_METADATA_API + aws_creds_uri ecs_unsuccessful_resp =", "log_stream_name } def get_cloudwatch_log_stream_name(fs_id=None): instance_id = get_instance_identity_info_from_instance_metadata('instanceId') if instance_id and", "- since this is not called from the main thread,", "errno.EEXIST: logging.info('Failed to take out private key creation lock, sleeping", "e.response)) return False elif exception == 'ResourceNotFoundException': logging.error('Log group %s", "for examples: %s' % (remote, 'https://docs.aws.amazon.com/efs/latest/ug/mounting-fs-mount-cmd-dns-name.html')) def is_nfs_mount(mountpoint): cmd =", "%s already exist, %s' % (log_group_name, e.response)) return True elif", "log group %s were in conflict, %s' % (log_group_name, e.response))", "to signify the number of unused bits that exist in", "options.get('accesspoint') cert_details = {} security_credentials = None client_info = get_client_info(config)", "all intermediate directories if they don't exist).\"\"\" if not os.path.exists(database_dir):", "and metadata service call failed, falling back ' 'to legacy", "ClientError as e: exception = e.response['Error']['Code'] if exception == 'ResourceNotFoundException':", "= '1.28.2' SERVICE = 'elasticfilesystem' CONFIG_FILE = '/etc/amazon/efs/efs-utils.conf' CONFIG_SECTION =", "from: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html and https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html \"\"\" if not use_iam: return None,", "recommended mount options, if not provided in fstab. import base64", "break if not supported: logging.warning('stunnel does not support \"%s\"', stunnel_option_name)", "fatal_error('Failed to locate an available port in the range [%d,", "environment variable if ECS_URI_ENV in os.environ: credentials, credentials_source = get_aws_security_credentials_from_ecs(os.environ[ECS_URI_ENV],", "reach the url at %s: status=%d, reason is %s' %", "the length (which may be 0) as a number of", "session.create_client(service, region_name=region) def get_cloudwatchlog_config(config, fs_id=None): log_group_name = DEFAULT_CLOUDWATCH_LOG_GROUP if config.has_option(CLOUDWATCH_LOG_SECTION,", "log stream %s in log group %s' % (log_stream_name, log_group_name))", "def cloudwatch_describe_log_streams_helper(cloudwatchlog_agent): return cloudwatchlog_agent.get('client').describe_log_streams( logGroupName=cloudwatchlog_agent.get('log_group_name'), logStreamNamePrefix=cloudwatchlog_agent.get('log_stream_name') ) def get_log_stream_next_token(cloudwatchlog_agent): try:", "if v is None: return k return '%s=%s' % (str(k),", "do_with_lock(generate_key) return key def create_certificate_signing_request(config_path, private_key, csr_path): cmd = 'openssl", "in [AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE]: aws_credentials_configs = read_config(file_path) # check if aws", "= key[offset:] num_length_octets = key[1] & 0b01111111 # Exclude the", "URI the ECS agent generated if aws_creds_uri: return get_aws_security_credentials_from_ecs(aws_creds_uri, True)", "fs_id, security_credentials, ap_id, client_info) create_certificate_signing_request(certificate_config, private_key, certificate_signing_request) not_before = get_certificate_timestamp(current_time,", "options: fatal_error('The \"iam\" option is required when mounting with named", "collisions cert_details['mountStateDir'] = get_mount_specific_filename(fs_id, mountpoint, tls_port) + '+' # common", "if verify_level > 0: add_stunnel_ca_options(efs_config, config, options) if cert_details: efs_config['cert']", "%s at %s' % (dns_name, mountpoint) logging.info(message) publish_cloudwatch_log(CLOUDWATCHLOG_AGENT, message) else:", "def tls_paths_dictionary(mount_name, base_path=STATE_FILE_DIR): tls_dict = { 'mount_dir': os.path.join(base_path, mount_name), #", "= 'Unable to reach %s to retrieve AWS security credentials.", "be called by 'mount -a' # for this file system.", "'http://169.254.170.2' WEB_IDENTITY_ROLE_ARN_ENV = 'AWS_ROLE_ARN' WEB_IDENTITY_TOKEN_FILE_ENV = 'AWS_WEB_IDENTITY_TOKEN_FILE' STS_ENDPOINT_URL = 'https://sts.amazonaws.com/'", "fatal_error('Configuration option \"port_range_upper_bound\" defined as %d ' 'must be strictly", "mount's database and certs directories exist and if not, create", "ValueError('DNS name format has an incorrect number of replacement fields')", "not in options: options['timeo'] = '600' if 'retrans' not in", "= 'GET' CANONICAL_URI = '/' CANONICAL_HEADERS_DICT = { 'host': '%s'", "KeyError): pass return None def handle_general_botocore_exceptions(error): exception = error.response['Error']['Code'] if", "ensure that the private key is # atomically created, as", "if 'cafile' in options: stunnel_cafile = options['cafile'] else: try: stunnel_cafile", "arguments, return (fsid, path, mountpoint, options)\"\"\" if args is None:", "read_only_mode = 0o400 os.chmod(key, read_only_mode) do_with_lock(generate_key) return key def create_certificate_signing_request(config_path,", "} STUNNEL_EFS_CONFIG = { 'client': 'yes', 'accept': '127.0.0.1:%s', 'connect': '%s:2049',", "= verify_level if verify_level > 0: add_stunnel_ca_options(efs_config, config, options) if", "False for line in stunnel_output: if line.startswith(stunnel_option_name): supported = True", "to Python's config file format, so we have to hand-serialize", "elif exception == 'ResourceNotFoundException': logging.debug('Either log group %s or log", "session_token = aws_credentials_configs.get(awsprofile, 'aws_session_token') credentials['AccessKeyId'] = access_key credentials['SecretAccessKey'] = secret_key", "config.getint(CONFIG_SECTION, 'port_range_upper_bound') if lower_bound >= upper_bound: fatal_error('Configuration option \"port_range_upper_bound\" defined", "proc.returncode == 0: message = 'Successfully mounted %s at %s'", "'retention_days': int(retention_days), 'log_stream_name': log_stream_name } def get_cloudwatch_log_stream_name(fs_id=None): instance_id = get_instance_identity_info_from_instance_metadata('instanceId')", "' 'parameter in the efs-utils configuration file.') return region except", "0: message = 'Successfully mounted %s at %s' % (dns_name,", "stderr=devnull, close_fds=True) else: logging.debug('%s is already running', WATCHDOG_SERVICE) else: error_message", "the number of octets that follow # - the following", "name, cloudwatchlog stream name CLOUDWATCHLOG_AGENT = None LOG_DIR = '/var/log/amazon/efs'", "CN = supplied [ req ] prompt = no distinguished_name", "in options: return True elif 'noocsp' in options: return False", "lookup AWS security credentials in AWS credentials file (~/.aws/credentials) #", "octets to follow (ignore high order bit) # - 018f", "def get_log_stream_next_token(cloudwatchlog_agent): try: response = cloudwatch_describe_log_streams_helper(cloudwatchlog_agent) except ClientError as e:", "device path = '/' if FS_ID_RE.match(remote): return remote, path try:", "= options['tlsport'] def to_nfs_option(k, v): if v is None: return", "string_to_sign += sha256.hexdigest() return string_to_sign def calculate_signature(string_to_sign, date, secret_access_key, region):", "iam_security_dict for k in CREDENTIALS_KEYS): return iam_security_dict, 'metadata:' else: return", "stderr=devnull, close_fds=True) if rc != 0: fatal_error('Failed to mount %s", "return find_command_path('stunnel', 'Please install it following the instructions at '", "creds['SessionToken'] }, 'webidentity:' + ','.join([role_arn, token_file]) # Fail if credentials", "[Mount Point] [File System Type] [Options] [Dump] [Pass] # #", "not an integer' % options['tlsport']) if 'ocsp' in options and", "not exist, %s' % (cloudwatchlog_agent.get('log_group_name'), cloudwatchlog_agent.get('log_stream_name'), e.response)) else: handle_general_botocore_exceptions(e) return", "names for examples: %s' % (remote, 'https://docs.aws.amazon.com/efs/latest/ug/mounting-fs-mount-cmd-dns-name.html')) def is_nfs_mount(mountpoint): cmd", "log_group_name): cloudwatchlog_client.create_log_group( logGroupName=log_group_name ) logging.info('Created cloudwatch log group %s' %", "UNSUPPORTED_OPTIONS = [ 'capath' ] STUNNEL_GLOBAL_CONFIG = { 'fips': 'no',", "% (command, env_path, install_method), e) return path.strip().decode() def get_system_release_version(): try:", "%s' % fs_id, 'Failed to start TLS tunnel (errno=%d). stdout=\"%s\"", "= 'openssl genpkey -algorithm RSA -out %s -pkeyopt rsa_keygen_bits:3072' %", "logging.warning('Could not connect to the endpoint, %s' % e) return", "+ tls_ports[:mid] assert len(tls_ports) == len(ports_to_try) sock = socket.socket() for", "import pwd import random import re import socket import subprocess", "if err_msg: logging.debug('%s %s', url_error_msg, err_msg) return None def get_resp_obj(request_resp,", "%s to retrieve IAM role name. See %s for more", "conflict, %s' % (log_group_name, e.response)) return False elif exception ==", "= list(range(lower_bound, upper_bound)) # Choose a random midpoint, and then", "def generate_key(): if os.path.isfile(key): return cmd = 'openssl genpkey -algorithm", "return None global CLOUDWATCHLOG_AGENT if not CLOUDWATCHLOG_AGENT: CLOUDWATCHLOG_AGENT = bootstrap_cloudwatch_logging(config)", "options: tunnel_args = ['nsenter', '--net=' + options['netns']] + tunnel_args #", "to mount an EFS file system by its short name,", "tunnel_proc.pid, tunnel_args, [stunnel_config_file], state_file_dir, cert_details=cert_details) try: yield tunnel_proc finally: os.rename(os.path.join(state_file_dir,", "except ClientError as e: exception = e.response['Error']['Code'] if exception ==", "mount_completed = threading.Event() t = threading.Thread(target=poll_tunnel_process, args=(tunnel_proc, fs_id, mount_completed)) t.daemon", "def _fatal_error(message): fatal_error('Error retrieving region. Please set the \"region\" parameter", "return False elif exception == 'ResourceNotFoundException': logging.error('Either log group %s", "devnull: subprocess.Popen(['/sbin/start', WATCHDOG_SERVICE], stdout=devnull, stderr=devnull, close_fds=True) elif 'start' in status:", "in options: options['wsize'] = '1048576' if 'soft' not in options", "will be able to mount an EFS file system by", "except AttributeError: p = ConfigParser() p.read(config_file) return p def bootstrap_logging(config,", "ecs_unsuccessful_resp) else: return None, None def get_aws_security_credentials_from_webidentity(role_arn, token_file, is_fatal=False): try:", "retry_times = 3 for retry in range(retry_times): process = subprocess.Popen(cmd.split(),", "bytearray(base64.b64decode(key)) # Parse the public key to pull out the", "INSTANCE_METADATA_SERVICE_URL instance_identity = url_request_helper(INSTANCE_METADATA_SERVICE_URL, ec2_metadata_unsuccessful_resp, ec2_metadata_url_error_msg, retry_with_new_header_token=True) if instance_identity: try:", "= ALGORITHM + '\\n' string_to_sign += date.strftime(SIGV4_DATETIME_FORMAT) + '\\n' string_to_sign", "response body.' % (str(resp_body), e)) return resp_body if resp_body_type is", "f.write(stunnel_config) return stunnel_config_file def write_tls_tunnel_state_file(fs_id, mountpoint, tls_port, tunnel_pid, command, files,", "= f.read().strip() except IOError: logging.warning('Unable to read %s', comm_file) logging.debug('Identified", "not_after, certificate_config, certificate_signing_request, certificate) subprocess_call(cmd, 'Failed to create self-signed client-side", "if iam_security_dict and all(k in iam_security_dict for k in CREDENTIALS_KEYS):", "return output and 'nfs' in str(output) def mount_tls(config, init_system, dns_name,", "% (CONFIG_FILE, 'https://docs.aws.amazon.com/console/efs/troubleshooting-tls') if config.getboolean(CONFIG_SECTION, 'stunnel_check_cert_hostname'): if check_host_supported: efs_config['checkHost'] =", "= e.response['Error']['Code'] if exception == 'InvalidParameterException': logging.debug('Either parameter log group", "if len(args) > 4 and '-o' in args[:-1]: options_index =", "e.response['Error']['Code'] if exception == 'InvalidParameterException': logging.debug('Either parameter log group name", "close_fds=True) logging.info('Started TLS tunnel, pid: %d', tunnel_proc.pid) temp_tls_state_file = write_tls_tunnel_state_file(fs_id,", "required when mounting with named profile option, \"awsprofile\"') if 'awscredsuri'", "retrieve metadata, the header should embeded with metadata token if", "of the temporary file containing TLS tunnel state, prefixed with", "logging.debug('%s is already running', WATCHDOG_SERVICE) elif init_system == 'systemd': rc", "request = HTTP_REQUEST_METHOD + '\\n' request += CANONICAL_URI + '\\n'", "ID or secret Key, %s' % e.response) return False elif", "defined as %d ' 'must be strictly greater than \"port_range_lower_bound\"", "from urllib.parse import quote_plus except ImportError: from urllib import quote_plus", "return dns_name def tls_paths_dictionary(mount_name, base_path=STATE_FILE_DIR): tls_dict = { 'mount_dir': os.path.join(base_path,", "config.has_option(CLIENT_INFO_SECTION, 'source'): client_source = config.get(CLIENT_INFO_SECTION, 'source') if 0 < len(client_source)", "elif exception == 'LimitExceededException': logging.error('Reached the maximum number of log", "stdout=\"%s\" stderr=\"%s\"' % (tunnel_proc.returncode, out.strip(), err.strip())) def poll_tunnel_process(tunnel_proc, fs_id, mount_completed):", "stunnel_cafile def is_stunnel_option_supported(stunnel_output, stunnel_option_name): supported = False for line in", "[to_nfs_option(k, v) for k, v in options.items() if k not", "cons: SEQUENCE # 6:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption", "try: req = Request(url) for k, v in headers.items(): req.add_header(k,", "request (csr)') def create_ca_conf(config_path, common_name, directory, private_key, date, region, fs_id,", "stunnel_cafile) efs_config['CAfile'] = stunnel_cafile def is_stunnel_option_supported(stunnel_output, stunnel_option_name): supported = False", "if 'tlsport' in options: ports_to_try = [int(options['tlsport'])] else: lower_bound, upper_bound", "request_resp = urlopen(req, timeout=1) return get_resp_obj(request_resp, url, unsuccessful_resp) except HTTPError", "= get_instance_identity_info_from_instance_metadata('region') if not instance_identity: raise Exception(\"Cannot retrieve region from", "The script will add recommended mount options, if not provided", "return updated_time.strftime(CERT_DATETIME_FORMAT) def get_utc_now(): \"\"\" Wrapped for patching purposes in", "err_msg) return None def get_resp_obj(request_resp, url, unsuccessful_resp): if request_resp.getcode() !=", "= dict(STUNNEL_EFS_CONFIG) efs_config['accept'] = efs_config['accept'] % tls_port efs_config['connect'] = efs_config['connect']", "security credentials lookup uri iam_role_name = get_iam_role_name() if iam_role_name: credentials,", "logGroupName=log_group_name ) logging.info('Created cloudwatch log group %s' % log_group_name) def", "import botocore.session from botocore.exceptions import ClientError, NoCredentialsError, EndpointConnectionError BOTOCORE_PRESENT =", "fetched from the given awsprofile if is_fatal: log_message = 'AWS", "Exception: logging.warning('Legacy check for region in \"dns_name_format\" failed') _fatal_error(metadata_exception) def", "url_error_msg, retry_with_new_header_token=True) if iam_security_dict and all(k in iam_security_dict for k", "% public_key output, err = subprocess_call(cmd, 'Unable to ASN1 parse", "None options = {} if len(args) > 1: fsname =", "match_device(config, device): \"\"\"Return the EFS id and the remote path", "logging.debug('Log stream %s already exist in log group %s, %s'", "re import socket import subprocess import sys import threading import", "and Secret Access Key are not found in AWS credentials", "region, fs_id, session_token=None): \"\"\" Create a Canonical Request - https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html", "name \"%s\" did not resolve to an EFS mount target'", "to retrieve AWS security credentials. See %s for more info.'", "canonical_query_params['X-Amz-Security-Token'] = quote_plus(session_token) # Cannot use urllib.urlencode because it replaces", "be used if region is not present in the config", "STRING, the first octet of the value is used to", "through AWS_CONTAINER_CREDENTIALS_RELATIVE_URI environment variable if ECS_URI_ENV in os.environ: credentials, credentials_source", "the tunnel in a process group so if it has", "(dns_name, path) command = ['/sbin/mount.nfs4', mount_path, mountpoint, '-o', get_nfs_mount_options(options)] if", "# override the tlsport option so that we can later", "lambda: 'PUT' res = opener.open(request) return res.read() except NameError: headers", "else resp_body.decode('utf-8') def parse_options(options): opts = {} for o in", "create_certificate_signing_request(certificate_config, private_key, certificate_signing_request) not_before = get_certificate_timestamp(current_time, minutes=-NOT_BEFORE_MINS) not_after = get_certificate_timestamp(current_time,", "= create_certificate(config, cert_details['mountStateDir'], cert_details['commonName'], cert_details['region'], fs_id, security_credentials, ap_id, client_info, base_path=state_file_dir)", "'\\naccessKeyId = UTF8String:' + access_key_id efs_client_auth_str += '\\nsignature = OCTETSTRING:'", "# atomically created, as mounts occurring in parallel may try", "user has specified tlsport=X at the command line this will", "get_region_from_legacy_dns_format(config): \"\"\" For backwards compatibility check dns_name_format to obtain the", "dies - since this is not called from the main", "credentials. See %s for more info.' % \\ (security_creds_lookup_url, SECURITY_CREDS_IAM_ROLE_HELP_URL)", "== 'AccessDeniedException': logging.debug('User is not authorized to perform the action,", "def get_private_key_path(): \"\"\"Wrapped for mocking purposes in unit tests\"\"\" return", "[ efsPolicy ] CN = supplied [ req ] prompt", "Exception as e: logging.warning('Unknown error, %s.' % e) return False", "'aws_secret_access_key' in str(e): logging.debug('aws_access_key_id or aws_secret_access_key not found in %s", "to import botocore, please install botocore first.') return None session", "CREDENTIALS_KEYS = ['AccessKeyId', 'SecretAccessKey', 'Token'] ECS_URI_ENV = 'AWS_CONTAINER_CREDENTIALS_RELATIVE_URI' ECS_TASK_METADATA_API =", "credentials at %s.' % security_creds_lookup_url url_error_msg = 'Unable to reach", "options['cafile'] else: try: stunnel_cafile = config.get(CONFIG_SECTION, 'stunnel_cafile') except NoOptionError: logging.debug('No", "'stunnel_check_cert_validity') system_release_version = get_system_release_version() if not any(release in system_release_version for", "+ date.strftime(CERT_DATETIME_FORMAT) if session_token: efs_client_auth_str += '\\nsessionToken = EXPLICIT:0,UTF8String:' +", "try: access_key = aws_credentials_configs.get('default', 'aws_access_key_id') if access_key is not None:", "exception == 'InvalidParameterException': logging.debug('Either parameter log group name %s or", "{} for o in options.split(','): if '=' in o: k,", "security_creds_lookup_url url_error_msg = 'Unable to reach %s to retrieve AWS", "provider chain from: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html and https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html \"\"\" if not use_iam:", "state.update(cert_details) with open(os.path.join(state_file_dir, state_file), 'w') as f: json.dump(state, f) return", "cloudwatchlog_agent.get('client'): return False token = get_log_stream_next_token(cloudwatchlog_agent) try: cloudwatch_put_log_events_helper(cloudwatchlog_agent, message, token)", "# check that the DNS name of the mount target", "mountpoint, proc.returncode, err.strip()) fatal_error(err.strip(), message, proc.returncode) def usage(out, exit_code=1): out.write('Usage:", "'Unable to ASN1 parse public key file, %s, correctly' %", "check') try: region = get_region_from_legacy_dns_format(config) sys.stdout.write('Warning: region obtained from \"dns_name_format\"", "except ValueError: logging.warning('Bad state_file_dir_mode \"%s\" in config file \"%s\"', mode_str,", "if os.path.ismount(mountpoint) and is_nfs_mount(mountpoint): sys.stdout.write(\"%s is already mounted, please run", "to fail fast if the tunnel dies - since this", "is list: for item in v: lines.append('%s = %s' %", "is_stunnel_option_supported(stunnel_output, b'OCSPaia') return check_host_supported, ocsp_aia_supported def _stunnel_bin(): return find_command_path('stunnel', 'Please", "child processes, they can be killed easily by the mount", "init_system = get_init_system() check_network_status(fs_id, init_system) dns_name = get_dns_name(config, fs_id) if", "'database/index.txt'), 'index_attr': os.path.join(base_path, mount_name, 'database/index.txt.attr'), 'serial': os.path.join(base_path, mount_name, 'database/serial'), 'rand':", "'Action': 'AssumeRoleWithWebIdentity', 'RoleArn': role_arn, 'RoleSessionName': 'efs-mount-helper', 'WebIdentityToken': token }) unsuccessful_resp", "arguments, checking for early exit conditions only\"\"\" if args is", "error, %s' % e) return None try: log_stream = response['logStreams'][0]", "except subprocess.CalledProcessError as e: fatal_error('Failed to locate %s in %s", "sha1.update(key) return sha1.hexdigest() def create_canonical_request(public_key_hash, date, access_key, region, fs_id, session_token=None):", "return '%s.%s.%d' % (fs_id, os.path.abspath(mountpoint).replace(os.sep, '.').lstrip('.'), tls_port) def serialize_stunnel_config(config, header=None):", "os.path.isfile(serial_path): with open(serial_path, 'w+') as f: f.write('00') if not os.path.isfile(rand_path):", "URLError, HTTPError from urllib.parse import urlencode try: import botocore.session from", "default CA file %s', DEFAULT_STUNNEL_CAFILE) stunnel_cafile = DEFAULT_STUNNEL_CAFILE if not", "= 'openssl req -new -config %s -key %s -out %s'", "ca_extension_builder(ap_id, security_credentials, fs_id, client_info) efs_client_auth_body = efs_client_auth_builder(public_key_path, security_credentials['AccessKeyId'], security_credentials['SecretAccessKey'], date,", "file (~/.aws/config) with given awsprofile if awsprofile: return get_aws_security_credentials_from_awsprofile(awsprofile, True)", "'TLSv1.2', 'renegotiation': 'no', 'TIMEOUTbusy': '20', 'TIMEOUTclose': '0', 'TIMEOUTidle': '70', 'delay':", "uri, or from the instance security credentials service' % \\", "num_length_octets + 1 key = key[offset:] sha1 = hashlib.sha1() sha1.update(key)", "url at %s: status=%d, reason is %s' % (url, e.code,", "= dns_name_format.format(**format_args) try: socket.gethostbyname(dns_name) except socket.gaierror: fatal_error('Failed to resolve \"%s\"", "header) for k, v in config.items(): if type(v) is list:", "aws_creds_uri if is_fatal: fatal_error(ecs_unsuccessful_resp, ecs_unsuccessful_resp) else: return None, None def", "'\\nsignature = OCTETSTRING:' + signature efs_client_auth_str += '\\nsigv4DateTime = UTCTIME:'", "yield tunnel_proc finally: os.rename(os.path.join(state_file_dir, temp_tls_state_file), os.path.join(state_file_dir, temp_tls_state_file[1:])) def get_nfs_mount_options(options): #", "re-set tlsport to X. options['tlsport'] = tls_port use_iam = 'iam'", "'Unsuccessful retrieval of IAM role name at %s.' % INSTANCE_IAM_URL", "'stunnel-config.%s' % mount_filename) with open(stunnel_config_file, 'w') as f: f.write(stunnel_config) return", "e) return False except NoCredentialsError as e: logging.warning('Credentials are not", "v is None: return k return '%s=%s' % (str(k), str(v))", "mount_name), # every mount will have its own ca mode", "content byte offset = int(key_line.split(':')[0]) key = key[offset:] num_length_octets =", "[--version] [-h|--help] <fsname> <mountpoint> [-o <options>]\\n') sys.exit(exit_code) def parse_arguments_early_exit(args=None): \"\"\"Parse", "l= 0 prim: NULL # 19:d=1 hl=4 l= 399 prim:", "return log_stream.get('uploadSequenceToken') except (IndexError, TypeError, KeyError): pass return None def", "sock = socket.socket() for tls_port in ports_to_try: try: sock.bind(('localhost', tls_port))", "CREDENTIALS_KEYS): return ecs_security_dict, 'ecs:' + aws_creds_uri # Fail if credentials", "mount will have its own ca mode assets due to", "_, err = proc.communicate() stunnel_output = err.splitlines() check_host_supported = is_stunnel_option_supported(stunnel_output,", "in CREDENTIALS_KEYS): return ecs_security_dict, 'ecs:' + aws_creds_uri # Fail if", "dns_name_format: raise ValueError('DNS name format must include {fs_id}') format_args =", "# # fs-deadbeef /mount_point efs _netdev 0 0 # #", "= 'Public key file, %s, is incorrectly formatted' % public_key", "public_key = os.path.join(tls_paths['mount_dir'], 'publicKey.pem') create_public_key(private_key, public_key) create_ca_conf(certificate_config, common_name, tls_paths['mount_dir'], private_key,", "as f: lines = f.readlines() lines = lines[1:-1] key =", "kwargs = { 'logGroupName': cloudwatchlog_agent.get('log_group_name'), 'logStreamName': cloudwatchlog_agent.get('log_stream_name'), 'logEvents': [ {", "return config.get(CONFIG_SECTION, 'region') except NoOptionError: pass try: return get_region_from_instance_metadata() except", "warn_message = 'The \"%s\" option is not supported and has", "stunnel_config_file] if 'netns' in options: tunnel_args = ['nsenter', '--net=' +", "item)) else: lines.append('%s = %s' % (k, v)) return lines", "(url, e.reason) if err_msg: logging.debug('%s %s', url_error_msg, err_msg) return None", "e.response)) return False elif exception == 'InvalidParameterException': logging.error('Log group name", "import ClientError, NoCredentialsError, EndpointConnectionError BOTOCORE_PRESENT = True except ImportError: BOTOCORE_PRESENT", "e)) return resp_body if resp_body_type is str else resp_body.decode('utf-8') def", "bootstrap_cloudwatch_logging(config, fs_id) check_unsupported_options(options) check_options_validity(options) init_system = get_init_system() check_network_status(fs_id, init_system) dns_name", "| os.O_EXCL | os.O_RDWR) try: lock_file_contents = 'PID: %s' %", "PEM -pubout -out %s' % (private_key, public_key) subprocess_call(cmd, 'Failed to", "= 'The \"%s\" option is not supported and has been", "request_resp.read() resp_body_type = type(resp_body) try: if resp_body_type is str: resp_dict", "line.decode('utf-8'): key_line = line.decode('utf-8') if not key_line: err_msg = 'Public", "(csr)') def create_ca_conf(config_path, common_name, directory, private_key, date, region, fs_id, security_credentials,", "if not put_retention_policy_completed: return None stream_creation_completed = create_cloudwatch_log_stream(cloudwatchlog_client, log_group_name, log_stream_name)", "the tag (1), length (1 + num_length_octets), and number of", "int(options['tlsport']) except ValueError: fatal_error('tlsport option [%s] is not an integer'", "simultaneously. key = get_private_key_path() @contextmanager def open_lock_file(): lock_file = os.path.join(base_path,", "except NoCredentialsError as e: logging.warning('Credentials are not properly configured, %s'", "def get_utc_now(): \"\"\" Wrapped for patching purposes in unit tests", "options: fatal_error('The \"port\" and \"tls\" options are mutually exclusive') if", "not_before = get_certificate_timestamp(current_time, minutes=-NOT_BEFORE_MINS) not_after = get_certificate_timestamp(current_time, hours=NOT_AFTER_HOURS) cmd =", "get_version_specific_stunnel_options(): stunnel_command = [_stunnel_bin(), '-help'] proc = subprocess.Popen(stunnel_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,", "int(round(time.time() * 1000)), 'message': message } ] } if token:", "import urlencode except ImportError: from urllib.request import urlopen, Request from", "t.join() def check_unsupported_options(options): for unsupported_option in UNSUPPORTED_OPTIONS: if unsupported_option in", "to lack of multi-threading support in openssl 'database_dir': os.path.join(base_path, mount_name,", "= get_aws_security_credentials_from_instance_metadata(iam_role_name) if credentials and credentials_source: return credentials, credentials_source error_msg", "request def create_canonical_query_string(public_key_hash, credential, formatted_datetime, session_token=None): canonical_query_params = { 'Action':", "fs_id, path, mountpoint, options = parse_arguments(config) logging.info('version=%s options=%s', VERSION, options)", "(tunnel_proc.returncode, out.strip(), err.strip())) def poll_tunnel_process(tunnel_proc, fs_id, mount_completed): \"\"\" poll the", "except Exception as e: logging.warning('Unknown error, %s' % e) return", "easily by the mount watchdog logging.info('Starting TLS tunnel: \"%s\"', '", "function() except OSError as e: if e.errno == errno.EEXIST: logging.info('Failed", "= '\\n'.join(serialize_stunnel_config(global_config) + serialize_stunnel_config(efs_config, 'efs')) logging.debug('Writing stunnel configuration:\\n%s', stunnel_config) stunnel_config_file", "= 'aws4_request' HTTP_REQUEST_METHOD = 'GET' CANONICAL_URI = '/' CANONICAL_HEADERS_DICT =", "= 'Unsuccessful retrieval of EC2 metadata at %s.' % INSTANCE_METADATA_SERVICE_URL", "functionality should only be used if region is not present", "mount_filename) efs_config = dict(STUNNEL_EFS_CONFIG) efs_config['accept'] = efs_config['accept'] % tls_port efs_config['connect']", "range in %s' % (lower_bound, upper_bound, CONFIG_FILE)) def is_ocsp_enabled(config, options):", "init_system, dns_name, fs_id, mountpoint, options) as tunnel_proc: mount_completed = threading.Event()", "mount_name, 'database/serial'), 'rand': os.path.join(base_path, mount_name, 'database/.rand') } return tls_dict def", "= INSTANCE_IAM_URL + iam_role_name unsuccessful_resp = 'Unsuccessful retrieval of AWS", "ap_id if security_credentials: ca_extension_str += '\\n1.3.6.1.4.1.4843.7.2 = ASN1:SEQUENCE:efs_client_auth' ca_extension_str +=", "ocsp_aia_supported = is_stunnel_option_supported(stunnel_output, b'OCSPaia') return check_host_supported, ocsp_aia_supported def _stunnel_bin(): return", "[ req ] prompt = no distinguished_name = req_distinguished_name [", "exist).\"\"\" if not os.path.exists(database_dir): create_required_directory(config, database_dir) if not os.path.exists(certs_dir): create_required_directory(config,", "of 399 # - 00 - no unused bits in", "try: if resp_body_type is str: resp_dict = json.loads(resp_body) else: resp_dict", "fs_id=None): log_group_name = DEFAULT_CLOUDWATCH_LOG_GROUP if config.has_option(CLOUDWATCH_LOG_SECTION, 'log_group_name'): log_group_name = config.get(CLOUDWATCH_LOG_SECTION,", "\"definite form\" # - the first octet always has the", "MIT License. See the LICENSE accompanying this file # for", "url_request_helper(ecs_uri, ecs_unsuccessful_resp, ecs_url_error_msg) if ecs_security_dict and all(k in ecs_security_dict for", "with IMDSv2, Unauthorized 401 error will be thrown, # to", "(args[0], VERSION)) sys.exit(0) def parse_arguments(config, args=None): \"\"\"Parse arguments, return (fsid,", "'%y%m%d%H%M%SZ' AWS_CREDENTIALS_FILE = os.path.expanduser(os.path.join('~' + pwd.getpwuid(os.getuid()).pw_name, '.aws', 'credentials')) AWS_CONFIG_FILE =", "retention_days, e.response)) return False else: handle_general_botocore_exceptions(e) return False except NoCredentialsError", "region)) request = HTTP_REQUEST_METHOD + '\\n' request += CANONICAL_URI +", "+= create_canonical_query_string(public_key_hash, credential, formatted_datetime, session_token) + '\\n' request += CANONICAL_HEADERS", "stunnel_option_name): supported = False for line in stunnel_output: if line.startswith(stunnel_option_name):", "stdout=\"%s\", stderr=\"%s\"' % (cmd, rc, output, err), exc_info=True) try: process.kill()", "ca ] default_ca = local_ca [ local_ca ] database =", "configuration to a file. Unfortunately this does not conform to", "from datetime import datetime, timedelta from logging.handlers import RotatingFileHandler try:", "logging.warning('Unable to read %s', comm_file) logging.debug('Identified init system: %s', init_system)", "'Failed to create public key') def subprocess_call(cmd, error_message): \"\"\"Helper method", "group retention days to %s' % retention_days) def put_cloudwatch_log_retention_policy(cloudwatchlog_client, log_group_name,", "unit tests\"\"\" return PRIVATE_KEY_FILE def check_and_create_private_key(base_path=STATE_FILE_DIR): # Creating RSA private", "command]) except subprocess.CalledProcessError as e: fatal_error('Failed to locate %s in", "and is_nfs_mount(mountpoint): sys.stdout.write(\"%s is already mounted, please run 'mount' command", "subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) output, _ = p.communicate() return output", "%s' % (config_path, private_key, csr_path) subprocess_call(cmd, 'Failed to create certificate", "credentials['SecretAccessKey'] = secret_key credentials['Token'] = session_token except NoOptionError as e:", "client, cloudwatchlog group name, cloudwatchlog stream name CLOUDWATCHLOG_AGENT = None", "% fs_id, exit_code=0) def check_network_status(fs_id, init_system): if init_system != 'systemd':", "ID is correct.\\nSee %s for more detail.' % (dns_name, 'https://docs.aws.amazon.com/console/efs/mount-dns-name'),", "option is required when mounting via \"accesspoint\"') if not AP_ID_RE.match(options['accesspoint']):", "'--help' in args[1:]: usage(out=sys.stdout, exit_code=0) if '--version' in args[1:]: sys.stdout.write('%s", "in options: fatal_error('The \"iam\" option is required when mounting with", "options and 'vers' not in options: options['nfsvers'] = '4.1' if", "2 DEFAULT_STUNNEL_CAFILE = '/etc/amazon/efs/efs-utils.crt' NOT_BEFORE_MINS = 15 NOT_AFTER_HOURS = 3", "in dns_name_format: return split_dns_name_format[-2] elif 'amazonaws.com' in dns_name_format: return split_dns_name_format[-3]", "instance_identity: raise Exception(\"Cannot retrieve region from instance_metadata\") return instance_identity def", "# common name for certificate signing request is max 64", "dns_name_format.format(**format_args) try: socket.gethostbyname(dns_name) except socket.gaierror: fatal_error('Failed to resolve \"%s\" -", "is required when mounting with named profile option, \"awsprofile\"') if", "fatal_error( 'Failed to resolve \"%s\" - check that the specified", "choose_tls_port(config, options): if 'tlsport' in options: ports_to_try = [int(options['tlsport'])] else:", "as e: if 'aws_access_key_id' in str(e) or 'aws_secret_access_key' in str(e):", "in options: mount_tls(config, init_system, dns_name, path, fs_id, mountpoint, options) else:", "order bit (8) set to 1 # - the remaining", "CONFIG_FILE = '/etc/amazon/efs/efs-utils.conf' CONFIG_SECTION = 'mount' CLIENT_INFO_SECTION = 'client-info' CLIENT_SOURCE_STR_LEN_LIMIT", "public_key) subprocess_call(cmd, 'Failed to create public key') def subprocess_call(cmd, error_message):", "key = key[offset:] num_length_octets = key[1] & 0b01111111 # Exclude", "%s' % error) def main(): parse_arguments_early_exit() assert_root() config = read_config()", "'region') except NoOptionError: pass try: return get_region_from_instance_metadata() except Exception as", "attempt to lookup AWS security credentials through AssumeRoleWithWebIdentity # (e.g.", "name format has an incorrect number of replacement fields') dns_name_format", "cloudwatchlog_config.get('log_stream_name') retention_days = cloudwatchlog_config.get('retention_days') group_creation_completed = create_cloudwatch_log_group(cloudwatchlog_client, log_group_name) if not", "string_to_sign).hexdigest() def get_credential_scope(date, region): return '/'.join([date.strftime(DATE_ONLY_FORMAT), region, SERVICE, AWS4_REQUEST]) def", "= aws_credentials_configs.get(awsprofile, 'aws_secret_access_key') session_token = aws_credentials_configs.get(awsprofile, 'aws_session_token') credentials['AccessKeyId'] = access_key", "e: logging.warning('Unknown error, %s.' % e) return False return True", "'%Y%m%d' SIGV4_DATETIME_FORMAT = '%Y%m%dT%H%M%SZ' CERT_DATETIME_FORMAT = '%y%m%d%H%M%SZ' AWS_CREDENTIALS_FILE = os.path.expanduser(os.path.join('~'", "def poll_tunnel_process(tunnel_proc, fs_id, mount_completed): \"\"\" poll the tunnel process health", "= url_request_helper(security_creds_lookup_url, unsuccessful_resp, url_error_msg, retry_with_new_header_token=True) if iam_security_dict and all(k in", "not in options and 'vers' not in options: options['nfsvers'] =", "exception = e.response['Error']['Code'] if exception == 'ResourceAlreadyExistsException': logging.debug('Log stream %s", "the main thread, if the tunnel fails, exit uncleanly with", "return efs_client_info_str def create_public_key(private_key, public_key): cmd = 'openssl rsa -in", "= ['nsenter', '--net=' + options['netns']] + command logging.info('Executing: \"%s\"', '", "\"\"\"Return the EFS id and the remote path to mount\"\"\"", "error' try: return config.get(CONFIG_SECTION, 'region') except NoOptionError: pass try: return", "if not os.path.isfile(index_attr_path): with open(index_attr_path, 'w+') as f: f.write('unique_subject =", "False return True def cloudwatch_put_log_events_helper(cloudwatchlog_agent, message, token=None): kwargs = {", "= url_request_helper(ecs_uri, ecs_unsuccessful_resp, ecs_url_error_msg) if ecs_security_dict and all(k in ecs_security_dict", "to /sbin/mount.efs and make sure it is executable. # #", "to encode the number of octets that follow # -", "e: exception = e.response['Error']['Code'] if exception == 'ResourceAlreadyExistsException': logging.debug('Log group", "False if not level: # delay logging error about malformed", "= get_target_region(config) iam_role_name = get_iam_role_name() if iam_role_name: credentials, _ =", "INSTANCE_IAM_URL iam_role_url_error_msg = 'Unable to reach %s to retrieve IAM", "get_resp_obj(request_resp, url, unsuccessful_resp): if request_resp.getcode() != 200: logging.debug(unsuccessful_resp + '", "p.communicate() return output and 'nfs' in str(output) def mount_tls(config, init_system,", "_fatal_error(message): fatal_error('Error retrieving region. Please set the \"region\" parameter in", "file needs to be renamed to a non-temporary version following", "+= CANONICAL_URI + '\\n' request += create_canonical_query_string(public_key_hash, credential, formatted_datetime, session_token)", "ASN1:UTF8String:' + fs_id if client_info: ca_extension_str += '\\n1.3.6.1.4.1.4843.7.4 = ASN1:SEQUENCE:efs_client_info'", "# if the user has specified tlsport=X at the command", "'\\n' sha256 = hashlib.sha256() sha256.update(canonical_request.encode()) string_to_sign += sha256.hexdigest() return string_to_sign", "options, cert_details=cert_details) tunnel_args = [_stunnel_bin(), stunnel_config_file] if 'netns' in options:", "token_file, is_fatal=False): try: with open(token_file, 'r') as f: token =", "127 bits are used to encode the number of octets", "elif fs_id: log_stream_name = '%s - mount.log' % (fs_id) else:", "ValueError('DNS name format must include {fs_id}') format_args = {'fs_id': fs_id}", "specified DNS name is a CNAME record resolving to a", "error.response['Error']['Code'] if exception == 'ServiceUnavailableException': logging.debug('The service cannot complete the", "% fs_id + '\\n' request += SIGNED_HEADERS + '\\n' sha256", "pair in config file if config.has_option(CLIENT_INFO_SECTION, 'source'): client_source = config.get(CLIENT_INFO_SECTION,", "= resp \\ .get('AssumeRoleWithWebIdentityResponse', {}) \\ .get('AssumeRoleWithWebIdentityResult', {}) \\ .get('Credentials',", "dict(STUNNEL_GLOBAL_CONFIG) if config.getboolean(CONFIG_SECTION, 'stunnel_debug_enabled'): global_config['debug'] = 'debug' if config.has_option(CONFIG_SECTION, 'stunnel_logs_file'):", "system type. This has been tested with systemd # (Amazon", "set to 1 # - the remaining 127 bits are", "{ 'host': '%s' } CANONICAL_HEADERS = '\\n'.join(['%s:%s' % (k, v)", "signature efs_client_auth_str += '\\nsigv4DateTime = UTCTIME:' + date.strftime(CERT_DATETIME_FORMAT) if session_token:", "'log_group_name': log_group_name, 'retention_days': int(retention_days), 'log_stream_name': log_stream_name } def get_cloudwatch_log_stream_name(fs_id=None): instance_id", "use urllib.urlencode because it replaces the %s's return '&'.join(['%s=%s' %", "put_cloudwatch_log_retention_policy(cloudwatchlog_client, log_group_name, retention_days) if not put_retention_policy_completed: return None stream_creation_completed =", "%s' % e) return None except Exception as e: logging.warning('Unknown", "return '&'.join(['%s=%s' % (k, v) for k, v in sorted(canonical_query_params.items())])", "config file and metadata calls fail. \"\"\" dns_name_format = config.get(CONFIG_SECTION,", "bootstrap_cloudwatch_logging(config) def get_botocore_client(config, service): if not BOTOCORE_PRESENT: logging.error('Failed to import", "not resolve to a valid DNS name for an EFS", "%d ' 'must be strictly greater than \"port_range_lower_bound\" defined as", "else: logging.debug('Unexpected error: %s' % error) def main(): parse_arguments_early_exit() assert_root()", "in-order from there mid = random.randrange(len(tls_ports)) ports_to_try = tls_ports[mid:] +", "the tunnel process health every .5s during the mount attempt", "info.' % \\ (security_creds_lookup_url, SECURITY_CREDS_IAM_ROLE_HELP_URL) iam_security_dict = url_request_helper(security_creds_lookup_url, unsuccessful_resp, url_error_msg,", "options['tlsport'] = tls_port use_iam = 'iam' in options ap_id =", "See %s for more info.' % \\ (security_creds_lookup_url, SECURITY_CREDS_IAM_ROLE_HELP_URL) iam_security_dict", "and number of unused bits (1) offset = 1 +", "cert_details=None): \"\"\" Serializes stunnel configuration to a file. Unfortunately this", "resolve \"%s\"' % remote ) if not hostnames: create_default_cloudwatchlog_agent_if_not_exist(config) fatal_error(", "logging.debug('Unexpected error: %s' % error) def main(): parse_arguments_early_exit() assert_root() config", "subprocess_call(cmd, 'Unable to ASN1 parse public key file, %s, correctly'", "fs_id, security_credentials, ap_id, client_info, base_path=state_file_dir) cert_details['certificate'] = os.path.join(state_file_dir, cert_details['mountStateDir'], 'certificate.pem')", "%s' % (log_group_name, log_stream_name, e.response)) return False elif exception ==", "check_network_target(fs_id) def start_watchdog(init_system): if init_system == 'init': proc = subprocess.Popen(", "mountpoint) return with bootstrap_tls(config, init_system, dns_name, fs_id, mountpoint, options) as", "retention in days %s is specified incorrectly, %s' % (log_group_name,", "e is not None, [primary] + secondaries)) except socket.gaierror: create_default_cloudwatchlog_agent_if_not_exist(config)", "dns_name, fs_id, mountpoint, options, state_file_dir=STATE_FILE_DIR): tls_port = choose_tls_port(config, options) #", "2 length octets to follow (ignore high order bit) #", "try: with open(comm_file) as f: init_system = f.read().strip() except IOError:", "credentials relative uri, or from the instance security credentials service'", "if 'nfsvers' not in options and 'vers' not in options:", "':' + awsprofile # Fail if credentials cannot be fetched", "resp: creds = resp \\ .get('AssumeRoleWithWebIdentityResponse', {}) \\ .get('AssumeRoleWithWebIdentityResult', {})", "only\"\"\" if args is None: args = sys.argv if '-h'", "attempt to lookup AWS security credentials through the credentials URI", "def open_lock_file(): lock_file = os.path.join(base_path, 'efs-utils-lock') f = os.open(lock_file, os.O_CREAT", "(k, item)) else: lines.append('%s = %s' % (k, v)) return", "'name' % remote, 'Failed to resolve \"%s\"' % remote )", "as e: exception = e.response['Error']['Code'] if exception == 'InvalidParameterException': logging.debug('Either", "from the instance security credentials service' % \\ (AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE)", "path) command = ['/sbin/mount.nfs4', mount_path, mountpoint, '-o', get_nfs_mount_options(options)] if 'netns'", "if ocsp_aia_supported: efs_config['OCSPaia'] = 'yes' else: fatal_error(tls_controls_message % 'stunnel_check_cert_validity') system_release_version", "= create_cloudwatch_log_group(cloudwatchlog_client, log_group_name) if not group_creation_completed: return None put_retention_policy_completed =", "security credentials at %s.' % security_creds_lookup_url url_error_msg = 'Unable to", "= '%s:%s' % (dns_name, path) command = ['/sbin/mount.nfs4', mount_path, mountpoint,", "= _sign(add_service, 'aws4_request').digest() return _sign(signing_key, string_to_sign).hexdigest() def get_credential_scope(date, region): return", "security credentials at %s.' % ecs_uri ecs_url_error_msg = 'Unable to", "= put_cloudwatch_log_retention_policy(cloudwatchlog_client, log_group_name, retention_days) if not put_retention_policy_completed: return None stream_creation_completed", "or 'aws_secret_access_key' in str(e): logging.debug('aws_access_key_id or aws_secret_access_key not found in", "this: # # fs-deadbeef /mount_point efs _netdev 0 0 #", "page as well at man/mount.efs.8 if 'nfsvers' not in options", "may try to create the key simultaneously. key = get_private_key_path()", "secret_access_key, region): \"\"\" Calculate the Signature - https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html \"\"\" def", "that the private key is # atomically created, as mounts", "= write_tls_tunnel_state_file(fs_id, mountpoint, tls_port, tunnel_proc.pid, tunnel_args, [stunnel_config_file], state_file_dir, cert_details=cert_details) try:", "public key to remove the header and footer '-----(BEGIN|END) PUBLIC", "and its affiliates. All Rights Reserved. # # Licensed under", "or aws_secret_access_key not found in %s under named profile [%s]',", "f finally: os.close(f) os.remove(lock_file) def do_with_lock(function): while True: try: with", "DNS name is a CNAME record resolving to a valid", "for k, v in sorted(canonical_query_params.items())]) def create_string_to_sign(canonical_request, date, region): \"\"\"", "while not mount_completed.is_set(): try: test_tunnel_process(tunnel_proc, fs_id) except SystemExit as e:", "try: mode_str = config.get(CONFIG_SECTION, 'state_file_dir_mode') try: mode = int(mode_str, 8)", "sha1.hexdigest() def create_canonical_request(public_key_hash, date, access_key, region, fs_id, session_token=None): \"\"\" Create", "override the port the NFS client uses to connect to", "except IOError: logging.debug('Unable to read %s', OS_RELEASE_PATH) return 'unknown' def", "OCTETSTRING:' + signature efs_client_auth_str += '\\nsigv4DateTime = UTCTIME:' + date.strftime(CERT_DATETIME_FORMAT)", "current_time, region, fs_id, security_credentials, ap_id, client_info) create_certificate_signing_request(certificate_config, private_key, certificate_signing_request) not_before", "token) request_resp = urlopen(req, timeout=1) return get_resp_obj(request_resp, url, unsuccessful_resp) err_msg", "get_init_system(comm_file='/proc/1/comm'): init_system = 'unknown' try: with open(comm_file) as f: init_system", "support in openssl 'database_dir': os.path.join(base_path, mount_name, 'database'), 'certs_dir': os.path.join(base_path, mount_name,", "unsupported_option in UNSUPPORTED_OPTIONS: if unsupported_option in options: warn_message = 'The", "= '' for line in output.splitlines(): if 'BIT STRING' in", "'%s:2049', 'sslVersion': 'TLSv1.2', 'renegotiation': 'no', 'TIMEOUTbusy': '20', 'TIMEOUTclose': '0', 'TIMEOUTidle':", "None def get_aws_security_credentials_from_webidentity(role_arn, token_file, is_fatal=False): try: with open(token_file, 'r') as", "not in dns_name_format: raise ValueError('DNS name format must include {fs_id}')", "= \"\"\"dir = %s RANDFILE = $dir/database/.rand [ ca ]", "# Licensed under the MIT License. See the LICENSE accompanying", "e.response['Error']['Code'] if exception == 'ResourceAlreadyExistsException': logging.debug('Log group %s already exist,", "be renamed to a non-temporary version following a successful mount.", "log_group_name, retention_days) except ClientError as e: exception = e.response['Error']['Code'] if", "stream name CLOUDWATCHLOG_AGENT = None LOG_DIR = '/var/log/amazon/efs' LOG_FILE =", "tls_controls_message = 'WARNING: Your client lacks sufficient controls to properly", "group %s or log stream %s does not exist, %s'", "]' efs_client_auth_str += '\\naccessKeyId = UTF8String:' + access_key_id efs_client_auth_str +=", "import urlopen, Request from urllib.error import URLError, HTTPError from urllib.parse", "%s -key %s -out %s' % (config_path, private_key, csr_path) subprocess_call(cmd,", "retrieve AWS security credentials. See %s for more info.' %", "= None return opts def get_tls_port_range(config): lower_bound = config.getint(CONFIG_SECTION, 'port_range_lower_bound')", "list(range(lower_bound, upper_bound)) # Choose a random midpoint, and then try", "stderr=subprocess.PIPE, close_fds=True) out, err = proc.communicate() if proc.returncode == 0:", "ResponseCode=%d', url, request_resp.getcode()) return None resp_body = request_resp.read() resp_body_type =", "key hash is included in canonical request to tie the", "a json object: %s' % (instance_identity, e)) return None def", "configured, %s' % e) return None except EndpointConnectionError as e:", "is None: args = sys.argv if '-h' in args[1:] or", "base_path=state_file_dir) cert_details['certificate'] = os.path.join(state_file_dir, cert_details['mountStateDir'], 'certificate.pem') cert_details['privateKey'] = get_private_key_path() cert_details['fsId']", "if access_key is not None: return 'default' except (NoSectionError, NoOptionError):", "= get_certificate_timestamp(current_time, minutes=-NOT_BEFORE_MINS) not_after = get_certificate_timestamp(current_time, hours=NOT_AFTER_HOURS) cmd = 'openssl", "request_resp.getcode()) return None resp_body = request_resp.read() resp_body_type = type(resp_body) try:", "%d', tunnel_proc.pid) temp_tls_state_file = write_tls_tunnel_state_file(fs_id, mountpoint, tls_port, tunnel_proc.pid, tunnel_args, [stunnel_config_file],", "tie the signature to a specific key pair to avoid", "pwd.getpwuid(os.getuid()).pw_name, '.aws', 'config')) CA_CONFIG_BODY = \"\"\"dir = %s RANDFILE =", "in iam_security_dict for k in CREDENTIALS_KEYS): return iam_security_dict, 'metadata:' else:", "VERSION)) sys.exit(0) def parse_arguments(config, args=None): \"\"\"Parse arguments, return (fsid, path,", "REQUEST_PAYLOAD = '' FS_ID_RE = re.compile('^(?P<fs_id>fs-[0-9a-f]+)$') EFS_FQDN_RE = re.compile(r'^(?P<fs_id>fs-[0-9a-f]+)\\.efs\\.(?P<region>[a-z0-9-]+)\\.(?P<dns_name_suffix>[a-z0-9.]+)$') AP_ID_RE", "logging.error('Either log group %s or log stream %s does not", "add \"_netdev\" to your mount options' % fs_id, exit_code=0) def", "dns_name_format: return split_dns_name_format[-2] elif 'amazonaws.com' in dns_name_format: return split_dns_name_format[-3] raise", "number of unused bits that exist in the last #", "bit (8) set to 1 # - the remaining 127", "be mounted with: # # sudo mount /mount_point # #", "fsname or not mountpoint: usage(out=sys.stderr) fs_id, path = match_device(config, fsname)", "(log_group_name, retention_days, e.response)) return False else: handle_general_botocore_exceptions(e) return False except", "except KeyError as e: logging.warning('%s not present in %s: %s'", "tunnel in a process group so if it has any", "AWS security credentials. See %s for more info.' % \\", "IAM role name attached to instance # through IAM role", "= 15 NOT_AFTER_HOURS = 3 EFS_ONLY_OPTIONS = [ 'accesspoint', 'awscredsuri',", "selecting a different port.' % options['tlsport']) else: fatal_error('Failed to locate", "in config section [%s]\", format_args.get('dns_name_suffix'), config_section) _validate_replacement_field_count(dns_name_format, expected_replacement_field_ct) dns_name =", "key material by looking for the key BIT STRING #", "awsprofile, file_path) return credentials def get_aws_profile(options, use_iam): awsprofile = options.get('awsprofile')", "create_public_key(private_key, public_key) create_ca_conf(certificate_config, common_name, tls_paths['mount_dir'], private_key, current_time, region, fs_id, security_credentials,", "bootstrap_logging(config, log_dir=LOG_DIR): raw_level = config.get(CONFIG_SECTION, 'logging_level') levels = { 'debug':", "_ = socket.gethostbyname_ex(remote) hostnames = list(filter(lambda e: e is not", "in headers.items(): req.add_header(k, v) request_resp = urlopen(req, timeout=1) return get_resp_obj(request_resp,", "certificate = os.path.join(tls_paths['mount_dir'], 'certificate.pem') ca_dirs_check(config, tls_paths['database_dir'], tls_paths['certs_dir']) ca_supporting_files_check(tls_paths['index'], tls_paths['index_attr'], tls_paths['serial'],", "not CLOUDWATCHLOG_AGENT: CLOUDWATCHLOG_AGENT = bootstrap_cloudwatch_logging(config) def get_botocore_client(config, service): if not", "['nsenter', '--net=' + options['netns']] + command logging.info('Executing: \"%s\"', ' '.join(command))", "except ValueError: fatal_error('tlsport option [%s] is not an integer' %", "= 'cloudwatch-log' DEFAULT_CLOUDWATCH_LOG_GROUP = '/aws/efs/utils' DEFAULT_RETENTION_DAYS = 14 # Cloudwatchlog", "= proc.communicate() if proc.returncode == 0: message = 'Successfully mounted", "= lambda: 'PUT' res = opener.open(request) return res.read() except NameError:", "file %s', awsprofile, file_path) return credentials def get_aws_profile(options, use_iam): awsprofile", "to resolve \"%s\"' % remote ) if not hostnames: create_default_cloudwatchlog_agent_if_not_exist(config)", "os.path.isfile(index_attr_path): with open(index_attr_path, 'w+') as f: f.write('unique_subject = no') if", "fs_id if client_info: ca_extension_str += '\\n1.3.6.1.4.1.4843.7.4 = ASN1:SEQUENCE:efs_client_info' return ca_extension_str", "e.response) return False elif exception == 'ResourceNotFoundException': logging.error('Either log group", "= None LOG_DIR = '/var/log/amazon/efs' LOG_FILE = 'mount.log' STATE_FILE_DIR =", "key') read_only_mode = 0o400 os.chmod(key, read_only_mode) do_with_lock(generate_key) return key def", "group_creation_completed = create_cloudwatch_log_group(cloudwatchlog_client, log_group_name) if not group_creation_completed: return None put_retention_policy_completed", "script will add recommended mount options, if not provided in", "'Unsuccessful retrieval of EC2 metadata at %s.' % INSTANCE_METADATA_SERVICE_URL ec2_metadata_url_error_msg", "is required when mounting via \"accesspoint\"') if not AP_ID_RE.match(options['accesspoint']): fatal_error('Access", "Copy this script to /sbin/mount.efs and make sure it is", "ASN1:UTF8String:' + ap_id if security_credentials: ca_extension_str += '\\n1.3.6.1.4.1.4843.7.2 = ASN1:SEQUENCE:efs_client_auth'", "import hmac import json import logging import os import pwd", "return k return '%s=%s' % (str(k), str(v)) nfs_options = [to_nfs_option(k,", "is # atomically created, as mounts occurring in parallel may", "efs_client_auth_builder(public_key_path, security_credentials['AccessKeyId'], security_credentials['SecretAccessKey'], date, region, fs_id, security_credentials['Token']) if security_credentials else", "url, unsuccessful_resp) err_msg = 'Unable to reach the url at", "'client-info' CLIENT_SOURCE_STR_LEN_LIMIT = 100 CLOUDWATCH_LOG_SECTION = 'cloudwatch-log' DEFAULT_CLOUDWATCH_LOG_GROUP = '/aws/efs/utils'", "STRING tag # - 82 - 2 length octets to", "because it replaces the %s's return '&'.join(['%s=%s' % (k, v)", "try: import botocore.session from botocore.exceptions import ClientError, NoCredentialsError, EndpointConnectionError BOTOCORE_PRESENT", "creds for k in ['AccessKeyId', 'SecretAccessKey', 'SessionToken']): return { 'AccessKeyId':", "given awsprofile if is_fatal: log_message = 'AWS security credentials not", "get_iam_role_name() if iam_role_name: credentials, _ = get_aws_security_credentials_from_instance_metadata(iam_role_name) if credentials: return", "group name %s or retention in days %s is specified", "get_target_region(config) cert_details['certificateCreationTime'] = create_certificate(config, cert_details['mountStateDir'], cert_details['commonName'], cert_details['region'], fs_id, security_credentials, ap_id,", "options): if os.path.ismount(mountpoint) and is_nfs_mount(mountpoint): sys.stdout.write(\"%s is already mounted, please", "included in canonical request to tie the signature to a", "SIGV4_DATETIME_FORMAT = '%Y%m%dT%H%M%SZ' CERT_DATETIME_FORMAT = '%y%m%d%H%M%SZ' AWS_CREDENTIALS_FILE = os.path.expanduser(os.path.join('~' +", "'AccessDeniedException': logging.debug('User is not authorized to perform the action, %s'", "\\ (security_creds_lookup_url, SECURITY_CREDS_IAM_ROLE_HELP_URL) iam_security_dict = url_request_helper(security_creds_lookup_url, unsuccessful_resp, url_error_msg, retry_with_new_header_token=True) if", "create_string_to_sign(canonical_request, date, region) signature = calculate_signature(string_to_sign, date, secret_access_key, region) efs_client_auth_str", "CLOUDWATCHLOG_AGENT if not CLOUDWATCHLOG_AGENT: CLOUDWATCHLOG_AGENT = bootstrap_cloudwatch_logging(config) def get_botocore_client(config, service):", "ImportError: from urllib.request import urlopen, Request from urllib.error import URLError,", "as f: init_system = f.read().strip() except IOError: logging.warning('Unable to read", "is specified incorrectly, %s' % (log_group_name, retention_days, e.response)) return False", "a different port.' % options['tlsport']) else: fatal_error('Failed to locate an", "unsuccessful_resp, url_error_msg, headers={'Accept': 'application/json'}) if resp: creds = resp \\", "(url, e.code, e.reason) except URLError as e: err_msg = 'Unable", "found in dns_name_format') def get_aws_ec2_metadata_token(): try: opener = build_opener(HTTPHandler) request", "for IAM Role for Service Accounts (IRSA) approach on EKS)", "logStreamNamePrefix=cloudwatchlog_agent.get('log_stream_name') ) def get_log_stream_next_token(cloudwatchlog_agent): try: response = cloudwatch_describe_log_streams_helper(cloudwatchlog_agent) except ClientError", "AttributeError: p = ConfigParser() p.read(config_file) return p def bootstrap_logging(config, log_dir=LOG_DIR):", "network was not yet available, add \"_netdev\" to your mount", "% \\ (STS_ENDPOINT_URL, SECURITY_CREDS_WEBIDENTITY_HELP_URL) resp = url_request_helper(webidentity_url, unsuccessful_resp, url_error_msg, headers={'Accept':", "' '.join(tunnel_args)) tunnel_proc = subprocess.Popen( tunnel_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, preexec_fn=os.setsid, close_fds=True)", "lookup AWS security credentials with IAM role name attached to", "the NFS client uses to connect to stunnel. # if", "key subprocess_call(cmd, 'Failed to create private key') read_only_mode = 0o400", "not present in their respective directories\"\"\" if not os.path.isfile(index_path): open(index_path,", "the url at %s, reason is %s' % (url, e.reason)", "except socket.error: continue sock.close() if 'tlsport' in options: fatal_error('Specified port", "available port in the range [%d, %d], try specifying a", "attempt to fail fast if the tunnel dies - since", "timedelta(**kwargs) return updated_time.strftime(CERT_DATETIME_FORMAT) def get_utc_now(): \"\"\" Wrapped for patching purposes", "unavailable. Try selecting a different port.' % options['tlsport']) else: fatal_error('Failed", "'\\nsessionToken = EXPLICIT:0,UTF8String:' + session_token return efs_client_auth_str def efs_client_info_builder(client_info): efs_client_info_str", "split_dns_name_format[-3] raise Exception('Region not found in dns_name_format') def get_aws_ec2_metadata_token(): try:", "region, fs_id, security_credentials['Token']) if security_credentials else '' efs_client_info_body = efs_client_info_builder(client_info)", "in parallel may try to create the key simultaneously. key", "f: lines = f.readlines() lines = lines[1:-1] key = ''.join(lines)", "in dns_name_format: expected_replacement_field_ct += 1 format_args['region'] = get_target_region(config) if '{dns_name_suffix}'", "'AWS Access Key ID and Secret Access Key are not", "octets that follow # - the following octets encode, as", "fs_id, session_token=None): \"\"\" Create a Canonical Request - https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html \"\"\"", "the endpoint, %s' % e) return None except Exception as", "(log_group_name, e.response)) return True elif exception == 'LimitExceededException': logging.error('Reached the", "not exist, %s' % (log_group_name, e.response)) return False elif exception", "certificate_config = os.path.join(tls_paths['mount_dir'], 'config.conf') certificate_signing_request = os.path.join(tls_paths['mount_dir'], 'request.csr') certificate =", "return None, None webidentity_url = STS_ENDPOINT_URL + '?' + urlencode({", "= os.path.join(base_path, 'efs-utils-lock') f = os.open(lock_file, os.O_CREAT | os.O_DSYNC |", "% (error_message, err) fatal_error(error_message, error_message) def ca_dirs_check(config, database_dir, certs_dir): \"\"\"Check", "can run mount.efs\\n') sys.exit(1) def read_config(config_file=CONFIG_FILE): try: p = ConfigParser.SafeConfigParser()", "options: fatal_error('The \"tls\" option is required when mounting via \"iam\"')", "you change these options, update the man page as well", "sys.stderr.write('WARN: %s\\n' % warn_message) logging.warning(warn_message) del options[unsupported_option] def check_options_validity(options): if", "like this: # # fs-deadbeef /mount_point efs _netdev 0 0", "tunnel_proc finally: os.rename(os.path.join(state_file_dir, temp_tls_state_file), os.path.join(state_file_dir, temp_tls_state_file[1:])) def get_nfs_mount_options(options): # If", "{}) \\ .get('AssumeRoleWithWebIdentityResult', {}) \\ .get('Credentials', {}) if all(k in", "create_ca_conf(config_path, common_name, directory, private_key, date, region, fs_id, security_credentials, ap_id, client_info):", "credentials_source = get_aws_security_credentials_from_webidentity( os.environ[WEB_IDENTITY_ROLE_ARN_ENV], os.environ[WEB_IDENTITY_TOKEN_FILE_ENV], False ) if credentials and", "{'AccessKeyId': None, 'SecretAccessKey': None, 'Token': None} try: access_key = aws_credentials_configs.get(awsprofile,", "find_command_path(command, install_method): try: env_path = '/sbin:/usr/sbin:/usr/local/sbin:/root/bin:/usr/local/bin:/usr/bin:/bin' os.putenv('PATH', env_path) path =", "AWS security credentials through AssumeRoleWithWebIdentity # (e.g. for IAM Role", "out, err = proc.communicate() if proc.returncode == 0: message =", "key file, %s, is incorrectly formatted' % public_key fatal_error(err_msg, err_msg)", "'' for line in output.splitlines(): if 'BIT STRING' in line.decode('utf-8'):", "octet (byte) is the tag (type) # - the next", "check that the specified DNS name is a CNAME record", "% remote ) for hostname in hostnames: efs_fqdn_match = EFS_FQDN_RE.match(hostname)", "if session_token: canonical_query_params['X-Amz-Security-Token'] = quote_plus(session_token) # Cannot use urllib.urlencode because", "= re.compile('^fsap-[0-9a-f]{17}$') CREDENTIALS_KEYS = ['AccessKeyId', 'SecretAccessKey', 'Token'] ECS_URI_ENV = 'AWS_CONTAINER_CREDENTIALS_RELATIVE_URI'", "includes cloudwatchlog botocore client, cloudwatchlog group name, cloudwatchlog stream name", "public_key output, err = subprocess_call(cmd, 'Unable to ASN1 parse public", "stunnel, ' \\ 'or disable \"%%s\" in %s.\\nSee %s for", "ecs_security_dict = url_request_helper(ecs_uri, ecs_unsuccessful_resp, ecs_url_error_msg) if ecs_security_dict and all(k in", "% (k, v) for k, v in sorted(CANONICAL_HEADERS_DICT.items())]) SIGNED_HEADERS =", "This means, however, that we have to include a locking", "= False for line in stunnel_output: if line.startswith(stunnel_option_name): supported =", "+= '\\n1.3.6.1.4.1.4843.7.2 = ASN1:SEQUENCE:efs_client_auth' ca_extension_str += '\\n1.3.6.1.4.1.4843.7.3 = ASN1:UTF8String:' +", "options, log_dir=LOG_DIR, cert_details=None): \"\"\" Serializes stunnel configuration to a file.", "security credentials (access key ID and secret access key). Adapted", "raise @contextmanager def bootstrap_tls(config, init_system, dns_name, fs_id, mountpoint, options, state_file_dir=STATE_FILE_DIR):", "region).digest() add_service = _sign(add_region, SERVICE).digest() signing_key = _sign(add_service, 'aws4_request').digest() return", "ASN1 parse public key file, %s, correctly' % public_key) key_line", "try: from urllib.parse import quote_plus except ImportError: from urllib import", "WATCHDOG_SERVICE) else: error_message = 'Could not start %s, unrecognized init", "'%s.%s' % (CONFIG_SECTION, region) if config.has_section(region_specific_config_section): config_section = region_specific_config_section format_args['dns_name_suffix']", "%s's return '&'.join(['%s=%s' % (k, v) for k, v in", "+= sha256.hexdigest() return string_to_sign def calculate_signature(string_to_sign, date, secret_access_key, region): \"\"\"", "to include a locking mechanism to ensure that the private", "k, v in sorted(canonical_query_params.items())]) def create_string_to_sign(canonical_request, date, region): \"\"\" Create", "exception == 'OperationAbortedException': logging.debug('Multiple requests to update the same log", "'\\n' string_to_sign += date.strftime(SIGV4_DATETIME_FORMAT) + '\\n' string_to_sign += get_credential_scope(date, region)", "\\ .get('Credentials', {}) if all(k in creds for k in", "mutually exclusive') def bootstrap_cloudwatch_logging(config, fs_id=None): if not check_if_cloudwatch_log_enabled(config): return None", "mountpoint, options def get_client_info(config): client_info = {} # source key/value", "shell openssl command and to handle response error messages\"\"\" retry_times", "%s' % \\ (not_before, not_after, certificate_config, certificate_signing_request, certificate) subprocess_call(cmd, 'Failed", "def is_stunnel_option_supported(stunnel_output, stunnel_option_name): supported = False for line in stunnel_output:", "err = proc.communicate() stunnel_output = err.splitlines() check_host_supported = is_stunnel_option_supported(stunnel_output, b'checkHost')", "session_token=None): canonical_query_params = { 'Action': 'Connect', # Public key hash", "os.path.join(base_path, 'efs-utils-lock') f = os.open(lock_file, os.O_CREAT | os.O_DSYNC | os.O_EXCL", "for file_path in [AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE]: aws_credentials_configs = read_config(file_path) # check", "as amazon-efs-utils relies on a built-in ' \\ 'trust store.'", "$dir/certificate.pem new_certs_dir = $dir/certs default_md = sha256 preserve = no", "certs_dir) def ca_supporting_files_check(index_path, index_attr_path, serial_path, rand_path): \"\"\"Recreate all supporting openssl", "= cloudwatchlog_config.get('log_group_name') log_stream_name = cloudwatchlog_config.get('log_stream_name') retention_days = cloudwatchlog_config.get('retention_days') group_creation_completed =", "% e) return False return True def cloudwatch_put_log_events_helper(cloudwatchlog_agent, message, token=None):", "group %s were in conflict, %s' % (log_group_name, e.response)) return", "retention days to %s' % retention_days) def put_cloudwatch_log_retention_policy(cloudwatchlog_client, log_group_name, retention_days):", "ports_to_try = [int(options['tlsport'])] else: lower_bound, upper_bound = get_tls_port_range(config) tls_ports =", "comm_file) logging.debug('Identified init system: %s', init_system) return init_system def check_network_target(fs_id):", "'must be strictly greater than \"port_range_lower_bound\" defined as %d.' %", "NULL # 19:d=1 hl=4 l= 399 prim: BIT STRING cmd", "as e: exception = e.response['Error']['Code'] if exception == 'ResourceNotFoundException': logging.error('Log", "were in conflict, %s' % (log_group_name, e.response)) return False elif", "lack of multi-threading support in openssl 'database_dir': os.path.join(base_path, mount_name, 'database'),", "7, RHEL 7, Debian 9, and Ubuntu 16.04), and upstart", "'openssl asn1parse -inform PEM -in %s' % public_key output, err", "% (lower_bound, upper_bound, CONFIG_FILE)) def is_ocsp_enabled(config, options): if 'ocsp' in", "for line in stunnel_output: if line.startswith(stunnel_option_name): supported = True break", "sock.close() if 'tlsport' in options: fatal_error('Specified port [%s] is unavailable.", "% (k, v)) return lines def add_stunnel_ca_options(efs_config, config, options): if", "'us-ascii')) return resp_dict except ValueError as e: logging.info('ValueError parsing \"%s\"", "= client_source return client_info def create_certificate(config, mount_name, common_name, region, fs_id,", "delay logging error about malformed log level until after logging", "'l:SO_REUSEADDR=yes', 'a:SO_BINDTODEVICE=lo', ], } STUNNEL_EFS_CONFIG = { 'client': 'yes', 'accept':", "+ urlencode({ 'Version': '2011-06-15', 'Action': 'AssumeRoleWithWebIdentity', 'RoleArn': role_arn, 'RoleSessionName': 'efs-mount-helper',", "mounting with \"awscredsuri\"') if 'awscredsuri' in options and 'awsprofile' in", "ClientError as e: exception = e.response['Error']['Code'] if exception == 'InvalidParameterException':", "logger = logging.getLogger() logger.setLevel(level) logger.addHandler(handler) if level_error: logging.error('Malformed logging level", "def get_tls_port_range(config): lower_bound = config.getint(CONFIG_SECTION, 'port_range_lower_bound') upper_bound = config.getint(CONFIG_SECTION, 'port_range_upper_bound')", "client_info def create_certificate(config, mount_name, common_name, region, fs_id, security_credentials, ap_id, client_info,", "'awscredsuri', 'awsprofile', 'cafile', 'iam', 'netns', 'noocsp', 'ocsp', 'tls', 'tlsport', 'verify'", "= get_client_info(config) if use_iam: aws_creds_uri = options.get('awscredsuri') if aws_creds_uri: kwargs", "= user_message sys.stderr.write('%s\\n' % user_message) logging.error(log_message) publish_cloudwatch_log(CLOUDWATCHLOG_AGENT, 'Mount failed, %s'", "temporary file containing TLS tunnel state, prefixed with a '~'.", "str else resp_body.decode('utf-8') def parse_options(options): opts = {} for o", "(INSTANCE_IAM_URL, SECURITY_CREDS_IAM_ROLE_HELP_URL) iam_role_name = url_request_helper(INSTANCE_IAM_URL, iam_role_unsuccessful_resp, iam_role_url_error_msg, retry_with_new_header_token=True) return iam_role_name", "%s because the network was not yet available, add \"_netdev\"", "create_canonical_query_string(public_key_hash, credential, formatted_datetime, session_token=None): canonical_query_params = { 'Action': 'Connect', #", "lines = [] if header: lines.append('[%s]' % header) for k,", "efs_client_info_str def create_public_key(private_key, public_key): cmd = 'openssl rsa -in %s", "= create_string_to_sign(canonical_request, date, region) signature = calculate_signature(string_to_sign, date, secret_access_key, region)", "efs_client_auth_body, efs_client_info_body) with open(config_path, 'w') as f: f.write(full_config_body) return full_config_body", "9, and Ubuntu 16.04), and upstart # (Amazon Linux 2017.09).", "credentials_file_helper(file_path, awsprofile) if credentials['AccessKeyId']: return credentials, os.path.basename(file_path) + ':' +", "'/etc/amazon/efs/privateKey.pem' DATE_ONLY_FORMAT = '%Y%m%d' SIGV4_DATETIME_FORMAT = '%Y%m%dT%H%M%SZ' CERT_DATETIME_FORMAT = '%y%m%d%H%M%SZ'", "mount target matches exactly the DNS name the CNAME resolves", "= get_aws_security_credentials_from_ecs(os.environ[ECS_URI_ENV], False) if credentials and credentials_source: return credentials, credentials_source", "'Fedora release' SUSE_RELEASE_NAME = 'openSUSE Leap' SKIP_NO_LIBWRAP_RELEASES = [RHEL8_RELEASE_NAME, CENTOS8_RELEASE_NAME,", "SECURITY_CREDS_IAM_ROLE_HELP_URL) iam_security_dict = url_request_helper(security_creds_lookup_url, unsuccessful_resp, url_error_msg, retry_with_new_header_token=True) if iam_security_dict and", "creds['AccessKeyId'], 'SecretAccessKey': creds['SecretAccessKey'], 'Token': creds['SessionToken'] }, 'webidentity:' + ','.join([role_arn, token_file])", "to update the same log group %s were in conflict,", "= key_line.replace(' ', '') # DER encoding TLV (Tag, Length,", "preserve = no policy = efsPolicy x509_extensions = v3_ca [", "in %s under named profile [%s]', file_path, awsprofile) if 'aws_session_token'", "CANONICAL_HEADERS % fs_id + '\\n' request += SIGNED_HEADERS + '\\n'", "named profile [%s]', file_path, awsprofile) if 'aws_session_token' in str(e): logging.debug('aws_session_token", "global CLOUDWATCHLOG_AGENT CLOUDWATCHLOG_AGENT = bootstrap_cloudwatch_logging(config, fs_id) check_unsupported_options(options) check_options_validity(options) init_system =", "locate an available port in the range [%d, %d], try", "any(release in system_release_version for release in SKIP_NO_LIBWRAP_RELEASES): efs_config['libwrap'] = 'no'", "replay attacks 'PublicKeyHash': quote_plus(public_key_hash), 'X-Amz-Algorithm': ALGORITHM, 'X-Amz-Credential': credential, 'X-Amz-Date': quote_plus(formatted_datetime),", "default_ca = local_ca [ local_ca ] database = $dir/database/index.txt serial", "number of log groups that can be created, %s' %", "None: return k return '%s=%s' % (str(k), str(v)) nfs_options =", "certs_dir): \"\"\"Check if mount's database and certs directories exist and", "instance_id = get_instance_identity_info_from_instance_metadata('instanceId') if instance_id and fs_id: log_stream_name = '%s", "else: error_message = 'Could not start %s, unrecognized init system", "logging.debug('%s %s', url_error_msg, err_msg) return None def get_resp_obj(request_resp, url, unsuccessful_resp):", "= config.get(config_section, 'dns_name_suffix') logging.debug(\"Using dns_name_suffix %s in config section [%s]\",", "if 'timeo' not in options: options['timeo'] = '600' if 'retrans'", "'SecretAccessKey': creds['SecretAccessKey'], 'Token': creds['SessionToken'] }, 'webidentity:' + ','.join([role_arn, token_file]) #", "(fs_id, os.path.abspath(mountpoint).replace(os.sep, '.').lstrip('.'), tls_port) def serialize_stunnel_config(config, header=None): lines = []", "-pubout -out %s' % (private_key, public_key) subprocess_call(cmd, 'Failed to create", "'\\n' sha256 = hashlib.sha256() sha256.update(REQUEST_PAYLOAD.encode()) request += sha256.hexdigest() return request", "mount.efs [--version] [-h|--help] <fsname> <mountpoint> [-o <options>]\\n') sys.exit(exit_code) def parse_arguments_early_exit(args=None):", "if request_resp.getcode() != 200: logging.debug(unsuccessful_resp + ' %s: ResponseCode=%d', url,", "value) return efs_client_info_str def create_public_key(private_key, public_key): cmd = 'openssl rsa", "mount_filename) with open(stunnel_config_file, 'w') as f: f.write(stunnel_config) return stunnel_config_file def", "%s or retention in days %s is specified incorrectly, %s'", "os.path.join(state_file_dir, 'stunnel-config.%s' % mount_filename) with open(stunnel_config_file, 'w') as f: f.write(stunnel_config)", "and WEB_IDENTITY_TOKEN_FILE_ENV in os.environ: credentials, credentials_source = get_aws_security_credentials_from_webidentity( os.environ[WEB_IDENTITY_ROLE_ARN_ENV], os.environ[WEB_IDENTITY_TOKEN_FILE_ENV],", "atomically created, as mounts occurring in parallel may try to", "'[ efs_client_auth ]' efs_client_auth_str += '\\naccessKeyId = UTF8String:' + access_key_id", "rc = subprocess.call(['systemctl', 'status', 'network.target'], stdout=devnull, stderr=devnull, close_fds=True) if rc", "%s', file_path) credentials['AccessKeyId'] = aws_credentials_configs.get(awsprofile, 'aws_access_key_id') credentials['SecretAccessKey'] = aws_credentials_configs.get(awsprofile, 'aws_secret_access_key')", "sha256.update(REQUEST_PAYLOAD.encode()) request += sha256.hexdigest() return request def create_canonical_query_string(public_key_hash, credential, formatted_datetime,", "del options[unsupported_option] def check_options_validity(options): if 'tls' in options: if 'port'", "key_line: err_msg = 'Public key file, %s, is incorrectly formatted'", "= None if 'tls' in options: options['port'] = options['tlsport'] def", "the command line this will just re-set tlsport to X.", "lines def add_stunnel_ca_options(efs_config, config, options): if 'cafile' in options: stunnel_cafile", "Note that this is explicitly excluded from the SubjectKeyIdentifier hash,", "secret Key, %s' % e.response) return False elif exception ==", "AWS credentials file (~/.aws/credentials) # and configs file (~/.aws/config) with", "RSA private keys is slow, so we will create one", "(which may be 0) as a number of octets #", "(upper_bound, lower_bound)) return lower_bound, upper_bound def choose_tls_port(config, options): if 'tlsport'", "def check_network_status(fs_id, init_system): if init_system != 'systemd': logging.debug('Not testing network", "_netdev 0 0 # # Using the 'efs' type will", "not a json object: %s' % (instance_identity, e)) return None", "= read_config(file_path) # check if aws access key id is", "log_message = 'AWS security credentials not found in %s or", "ECS_TASK_METADATA_API + aws_creds_uri ecs_unsuccessful_resp = 'Unsuccessful retrieval of AWS security", "-new -config %s -key %s -out %s' % (config_path, private_key,", "fs_id) # check that the DNS name of the mount", "under the MIT License. See the LICENSE accompanying this file", "log_message is None: log_message = user_message sys.stderr.write('%s\\n' % user_message) logging.error(log_message)", "req.add_header('X-aws-ec2-metadata-token', token) request_resp = urlopen(req, timeout=1) return get_resp_obj(request_resp, url, unsuccessful_resp)", "if cert_details: efs_config['cert'] = cert_details['certificate'] efs_config['key'] = cert_details['privateKey'] check_host_supported, ocsp_aia_supported", "tls_port)) sock.close() return tls_port except socket.error: continue sock.close() if 'tlsport'", "- BIT STRING tag # - 82 - 2 length", "= {'aws_creds_uri': aws_creds_uri} else: kwargs = {'awsprofile': get_aws_profile(options, use_iam)} security_credentials,", "'iam' in options and 'tls' not in options: fatal_error('The \"tls\"", "= lines[1:-1] key = ''.join(lines) key = bytearray(base64.b64decode(key)) # Parse", "unused bits (1) offset = 1 + 1 + num_length_octets", "- https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html \"\"\" string_to_sign = ALGORITHM + '\\n' string_to_sign +=", "tls_port) + '+' # common name for certificate signing request", "options[unsupported_option] def check_options_validity(options): if 'tls' in options: if 'port' in", "temp_tls_state_file[1:])) def get_nfs_mount_options(options): # If you change these options, update", "will just re-set tlsport to X. options['tlsport'] = tls_port use_iam", "not found in %s', file_path) credentials['AccessKeyId'] = aws_credentials_configs.get(awsprofile, 'aws_access_key_id') credentials['SecretAccessKey']", "} WATCHDOG_SERVICE = 'amazon-efs-mount-watchdog' SYSTEM_RELEASE_PATH = '/etc/system-release' OS_RELEASE_PATH = '/etc/os-release'", "create directories (also create all intermediate directories if they don't", "= '~' + get_mount_specific_filename(fs_id, mountpoint, tls_port) state = { 'pid':", "<options>]\\n') sys.exit(exit_code) def parse_arguments_early_exit(args=None): \"\"\"Parse arguments, checking for early exit", "return None except EndpointConnectionError as e: logging.warning('Could not connect to", "return False return True def cloudwatch_put_retention_policy_helper(cloudwatchlog_client, log_group_name, retention_days): cloudwatchlog_client.put_retention_policy( logGroupName=log_group_name,", "access_key_id, secret_access_key, date, region, fs_id, session_token=None): public_key_hash = get_public_key_sha1(public_key_path) canonical_request", "Exception as e: if is_fatal: unsuccessful_resp = 'Error reading token", "Please set the \"region\" ' 'parameter in the efs-utils configuration", "efs_client_auth_body = efs_client_auth_builder(public_key_path, security_credentials['AccessKeyId'], security_credentials['SecretAccessKey'], date, region, fs_id, security_credentials['Token']) if", "tunnel process health every .5s during the mount attempt to", "close_fds=True) if rc != 0: with open(os.devnull, 'w') as devnull:", "[RHEL8_RELEASE_NAME, CENTOS8_RELEASE_NAME, FEDORA_RELEASE_NAME, SUSE_RELEASE_NAME] def fatal_error(user_message, log_message=None, exit_code=1): if log_message", "% e) return False except EndpointConnectionError as e: logging.warning('Could not", "expected_ct): if format_str.count('{') != expected_ct or format_str.count('}') != expected_ct: raise", "list(filter(lambda e: e is not None, [primary] + secondaries)) except", "region in \"dns_name_format\" failed') _fatal_error(metadata_exception) def get_region_from_instance_metadata(): instance_identity = get_instance_identity_info_from_instance_metadata('region')", "unit tests \"\"\" return datetime.utcnow() def assert_root(): if os.geteuid() !=", "secondaries, _ = socket.gethostbyname_ex(remote) hostnames = list(filter(lambda e: e is", "database_dir, certs_dir): \"\"\"Check if mount's database and certs directories exist", "8) except ValueError: logging.warning('Bad state_file_dir_mode \"%s\" in config file \"%s\"',", "Inc. and its affiliates. All Rights Reserved. # # Licensed", "logging.debug('Writing stunnel configuration:\\n%s', stunnel_config) stunnel_config_file = os.path.join(state_file_dir, 'stunnel-config.%s' % mount_filename)", "security_credentials, fs_id, client_info) efs_client_auth_body = efs_client_auth_builder(public_key_path, security_credentials['AccessKeyId'], security_credentials['SecretAccessKey'], date, region,", "embeded with metadata token if e.code == 401 and retry_with_new_header_token:", "to reach %s to retrieve AWS security credentials. See %s", "already exist, %s' % (log_group_name, e.response)) return True elif exception", "expected_ct: raise ValueError('DNS name format has an incorrect number of", "if security_credentials else '' efs_client_info_body = efs_client_info_builder(client_info) if client_info else", "additional symbol appended to avoid naming collisions cert_details['mountStateDir'] = get_mount_specific_filename(fs_id,", "'Failed to create private key') read_only_mode = 0o400 os.chmod(key, read_only_mode)", "'yes', 'socket': [ 'l:SO_REUSEADDR=yes', 'a:SO_BINDTODEVICE=lo', ], } STUNNEL_EFS_CONFIG = {", "mountpoint) logging.warning(\"%s is already mounted, mount aborted\" % mountpoint) return", "urlopen, Request, HTTPHandler from urllib import urlencode except ImportError: from", "return False else: logging.debug('Unexpected error: %s' % e) return False", "if 'tls' in options: options['port'] = options['tlsport'] def to_nfs_option(k, v):", "= 'AWS security credentials not found in %s or %s", "signature to a specific key pair to avoid replay attacks", "to run shell openssl command and to handle response error", "'/etc/os-release' RHEL8_RELEASE_NAME = 'Red Hat Enterprise Linux release 8' CENTOS8_RELEASE_NAME", "= _sign(add_region, SERVICE).digest() signing_key = _sign(add_service, 'aws4_request').digest() return _sign(signing_key, string_to_sign).hexdigest()", "= aws_credentials_configs.get(awsprofile, 'aws_secret_access_key') except NoSectionError: logging.debug('No [%s] section found in", "def get_nfs_mount_options(options): # If you change these options, update the", "if credentials: return session.create_client(service, aws_access_key_id=credentials['AccessKeyId'], aws_secret_access_key=credentials['SecretAccessKey'], aws_session_token=credentials['Token'], region_name=region) return session.create_client(service,", "logging.warning(error_message) def create_required_directory(config, directory): mode = 0o750 try: mode_str =", "# For a BIT STRING, the first octet of the", "= '%s - mount.log' % (fs_id) else: log_stream_name = 'default", "get_dns_name(config, fs_id) # check that the DNS name of the", "'SessionToken']): return { 'AccessKeyId': creds['AccessKeyId'], 'SecretAccessKey': creds['SecretAccessKey'], 'Token': creds['SessionToken'] },", "% e) return False return True def cloudwatch_create_log_stream_helper(cloudwatchlog_client, log_group_name, log_stream_name):", "'log_stream_name': log_stream_name } def get_cloudwatch_log_stream_name(fs_id=None): instance_id = get_instance_identity_info_from_instance_metadata('instanceId') if instance_id", "def get_aws_security_credentials_from_awsprofile(awsprofile, is_fatal=False): for file_path in [AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE]: if os.path.exists(file_path):", "SERVICE).digest() signing_key = _sign(add_service, 'aws4_request').digest() return _sign(signing_key, string_to_sign).hexdigest() def get_credential_scope(date,", "if iam_role_name: credentials, credentials_source = get_aws_security_credentials_from_instance_metadata(iam_role_name) if credentials and credentials_source:", "return get_aws_security_credentials_from_ecs(aws_creds_uri, True) # attempt to lookup AWS security credentials", "# 0382018f00...<subjectPublicKey> # - 03 - BIT STRING tag #", "to resolve \"%s\" - check that your file system ID", "'/aws/efs/utils' DEFAULT_RETENTION_DAYS = 14 # Cloudwatchlog agent dict includes cloudwatchlog", "# sudo mount /mount_point # # The script will add", "csr_path): cmd = 'openssl req -new -config %s -key %s", "file_path) credentials['AccessKeyId'] = aws_credentials_configs.get(awsprofile, 'aws_access_key_id') credentials['SecretAccessKey'] = aws_credentials_configs.get(awsprofile, 'aws_secret_access_key') except", "= url_request_helper(webidentity_url, unsuccessful_resp, url_error_msg, headers={'Accept': 'application/json'}) if resp: creds =", "else: global_config['output'] = os.path.join(log_dir, '%s.stunnel.log' % mount_filename) efs_config = dict(STUNNEL_EFS_CONFIG)", "date, access_key, region, fs_id, session_token=None): \"\"\" Create a Canonical Request", "and \"noocsp\" options are mutually exclusive') if 'accesspoint' in options:", "sys.argv fsname = None mountpoint = None options = {}", "properly configured, %s' % e) return None except EndpointConnectionError as", "CONFIG_FILE) except NoOptionError: pass try: os.makedirs(directory, mode) except OSError as", "looking for the key BIT STRING # Example: # 0:d=0", "primary, secondaries, _ = socket.gethostbyname_ex(remote) hostnames = list(filter(lambda e: e", "BOTOCORE_PRESENT: logging.error('Failed to import botocore, please install botocore first.') return", "with given awsprofile if awsprofile: return get_aws_security_credentials_from_awsprofile(awsprofile, True) # attempt", "private_key, current_time, region, fs_id, security_credentials, ap_id, client_info) create_certificate_signing_request(certificate_config, private_key, certificate_signing_request)", "get_cloudwatchlog_config(config, fs_id=None): log_group_name = DEFAULT_CLOUDWATCH_LOG_GROUP if config.has_option(CLOUDWATCH_LOG_SECTION, 'log_group_name'): log_group_name =", "- the first octet (byte) is the tag (type) #", "to perform the action, %s' % error.response) else: logging.debug('Unexpected error:", "% \\ (AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE) fatal_error(error_msg, error_msg) def get_aws_security_credentials_from_awsprofile(awsprofile, is_fatal=False): for", "+ ','.join([role_arn, token_file]) # Fail if credentials cannot be fetched", "Role for Service Accounts (IRSA) approach on EKS) if WEB_IDENTITY_ROLE_ARN_ENV", "mountpoint, tls_port) + '+' # common name for certificate signing", "governing permissions and limitations under # the License. # #", "len(args) > 2: mountpoint = args[2] if len(args) > 4", "mount_name, common_name, region, fs_id, security_credentials, ap_id, client_info, base_path=STATE_FILE_DIR): current_time =", "Exception(\"Cannot retrieve region from instance_metadata\") return instance_identity def get_instance_identity_info_from_instance_metadata(property): ec2_metadata_unsuccessful_resp", "if 'retrans' not in options: options['retrans'] = '2' if 'noresvport'", "return log_stream_name def check_if_cloudwatch_log_enabled(config): if config.has_option(CLOUDWATCH_LOG_SECTION, 'enabled'): return config.getboolean(CLOUDWATCH_LOG_SECTION, 'enabled')", "be 0) as a number of octets # - the", "stunnel_output: if line.startswith(stunnel_option_name): supported = True break if not supported:", "add_stunnel_ca_options(efs_config, config, options) if cert_details: efs_config['cert'] = cert_details['certificate'] efs_config['key'] =", "try: with open(SYSTEM_RELEASE_PATH) as f: return f.read().strip() except IOError: logging.debug('Unable", "'application/json'}) if resp: creds = resp \\ .get('AssumeRoleWithWebIdentityResponse', {}) \\", "not None: return 'default' except (NoSectionError, NoOptionError): continue return awsprofile", "None # attempt to lookup AWS security credentials through the", "in args[1:] or '--help' in args[1:]: usage(out=sys.stdout, exit_code=0) if '--version'", "credentials_source = get_aws_security_credentials_from_ecs(os.environ[ECS_URI_ENV], False) if credentials and credentials_source: return credentials,", "url_error_msg = 'Unable to reach %s to retrieve AWS security", "get_credential_scope(date, region): return '/'.join([date.strftime(DATE_ONLY_FORMAT), region, SERVICE, AWS4_REQUEST]) def match_device(config, device):", "build_opener(HTTPHandler) request = Request(INSTANCE_METADATA_TOKEN_URL) request.add_header('X-aws-ec2-metadata-token-ttl-seconds', 21600) request.get_method = lambda: 'PUT'", "will add recommended mount options, if not provided in fstab.", "= req_distinguished_name [ req_distinguished_name ] CN = %s %s %s", "return opts def get_tls_port_range(config): lower_bound = config.getint(CONFIG_SECTION, 'port_range_lower_bound') upper_bound =", "usage(out, exit_code=1): out.write('Usage: mount.efs [--version] [-h|--help] <fsname> <mountpoint> [-o <options>]\\n')", "err error_message = '%s, error is: %s' % (error_message, err)", "'w+') as f: f.write('00') if not os.path.isfile(rand_path): open(rand_path, 'w').close() def", "def parse_options(options): opts = {} for o in options.split(','): if", "to mount\"\"\" try: remote, path = device.split(':', 1) except ValueError:", "= bootstrap_cloudwatch_logging(config) def get_botocore_client(config, service): if not BOTOCORE_PRESENT: logging.error('Failed to", "return False elif exception == 'OperationAbortedException': logging.debug('Multiple requests to update", "def create_default_cloudwatchlog_agent_if_not_exist(config): if not check_if_cloudwatch_log_enabled(config): return None global CLOUDWATCHLOG_AGENT if", "logging.debug('Either parameter log group name %s or log stream name", "fs_id, session_token=None): public_key_hash = get_public_key_sha1(public_key_path) canonical_request = create_canonical_request(public_key_hash, date, access_key_id,", "_ = proc.communicate() if 'stop' in status: with open(os.devnull, 'w')", "in options and 'vers' not in options: options['nfsvers'] = '4.1'", "= _sign(('AWS4' + secret_access_key).encode('utf-8'), date.strftime(DATE_ONLY_FORMAT)).digest() add_region = _sign(key_date, region).digest() add_service", "credentials file (%s), config file (%s), ' \\ 'from ECS", "mountpoint, options): if os.path.ismount(mountpoint) and is_nfs_mount(mountpoint): sys.stdout.write(\"%s is already mounted,", "\"\"\" string_to_sign = ALGORITHM + '\\n' string_to_sign += date.strftime(SIGV4_DATETIME_FORMAT) +", "options) as tunnel_proc: mount_completed = threading.Event() t = threading.Thread(target=poll_tunnel_process, args=(tunnel_proc,", "else: resp_dict = json.loads(resp_body.decode(request_resp.headers.get_content_charset() or 'us-ascii')) return resp_dict except ValueError", "name %s or log stream name %s is specified incorrectly,", "logging.debug('The service cannot complete the request, %s' % error.response) elif", "= url_request_helper(INSTANCE_METADATA_SERVICE_URL, ec2_metadata_unsuccessful_resp, ec2_metadata_url_error_msg, retry_with_new_header_token=True) if instance_identity: try: return instance_identity[property]", "def get_region_from_instance_metadata(): instance_identity = get_instance_identity_info_from_instance_metadata('region') if not instance_identity: raise Exception(\"Cannot", "create certificate signing request (csr)') def create_ca_conf(config_path, common_name, directory, private_key,", "system. The '_netdev' option tells the init system that the", "= supplied [ req ] prompt = no distinguished_name =", "[ 'capath' ] STUNNEL_GLOBAL_CONFIG = { 'fips': 'no', 'foreground': 'yes',", "STRING cmd = 'openssl asn1parse -inform PEM -in %s' %", "'The specified domain name \"%s\" did not resolve to an", "required when mounting via \"accesspoint\"') if not AP_ID_RE.match(options['accesspoint']): fatal_error('Access Point", "of AWS security credentials at %s.' % STS_ENDPOINT_URL url_error_msg =", "Unauthorized 401 error will be thrown, # to retrieve metadata,", "def check_options_validity(options): if 'tls' in options: if 'port' in options:", "','.join(nfs_options) def mount_nfs(dns_name, path, mountpoint, options): if 'tls' in options:", "try: region = get_region_from_legacy_dns_format(config) sys.stdout.write('Warning: region obtained from \"dns_name_format\" field.", "def create_canonical_request(public_key_hash, date, access_key, region, fs_id, session_token=None): \"\"\" Create a", "per # https://tools.ietf.org/html/rfc5280#section-4.2.1.2 # # Example: # 0382018f00...<subjectPublicKey> # -", "'\\n'.join(serialize_stunnel_config(global_config) + serialize_stunnel_config(efs_config, 'efs')) logging.debug('Writing stunnel configuration:\\n%s', stunnel_config) stunnel_config_file =", "remaining octets are the \"value\" aka content # # For", "[%d, %d], try specifying a different port range in %s'", "range [%d, %d], try specifying a different port range in", "exit_code=0) if '--version' in args[1:]: sys.stdout.write('%s Version: %s\\n' % (args[0],", "= hash' if ap_id: ca_extension_str += '\\n1.3.6.1.4.1.4843.7.1 = ASN1:UTF8String:' +", "unused bits in the last content byte offset = int(key_line.split(':')[0])", "= 'https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html' DEFAULT_STUNNEL_VERIFY_LEVEL = 2 DEFAULT_STUNNEL_CAFILE = '/etc/amazon/efs/efs-utils.crt' NOT_BEFORE_MINS =", "if is_fatal: unsuccessful_resp = 'Error reading token file %s: %s'", "to mount %s because the network was not yet available,", "open(os.devnull, 'w') as devnull: subprocess.Popen(['/sbin/start', WATCHDOG_SERVICE], stdout=devnull, stderr=devnull, close_fds=True) elif", "BOTOCORE_PRESENT = True except ImportError: BOTOCORE_PRESENT = False VERSION =", "lock_file = os.path.join(base_path, 'efs-utils-lock') f = os.open(lock_file, os.O_CREAT | os.O_DSYNC", "= $dir/database/index.txt serial = $dir/database/serial private_key = %s cert =", "= get_aws_security_credentials_from_webidentity( os.environ[WEB_IDENTITY_ROLE_ARN_ENV], os.environ[WEB_IDENTITY_TOKEN_FILE_ENV], False ) if credentials and credentials_source:", "# 0:d=0 hl=4 l= 418 cons: SEQUENCE # 4:d=1 hl=2", "in options.split(','): if '=' in o: k, v = o.split('=')", "documentation for mounting with DNS names for examples: %s' %", "= [int(options['tlsport'])] else: lower_bound, upper_bound = get_tls_port_range(config) tls_ports = list(range(lower_bound,", "path = device.split(':', 1) except ValueError: remote = device path", "log_stream_name = '%s - mount.log' % (instance_id) elif fs_id: log_stream_name", "elif exception == 'AccessDeniedException': logging.debug('User is not authorized to perform", "get_log_stream_next_token(cloudwatchlog_agent) try: cloudwatch_put_log_events_helper(cloudwatchlog_agent, message, token) except ClientError as e: exception", "_validate_replacement_field_count(format_str, expected_ct): if format_str.count('{') != expected_ct or format_str.count('}') != expected_ct:", "session_token) string_to_sign = create_string_to_sign(canonical_request, date, region) signature = calculate_signature(string_to_sign, date,", "\"\"\"Check if mount's database and certs directories exist and if", "(~/.aws/credentials) # and configs file (~/.aws/config) with given awsprofile if", "global CLOUDWATCHLOG_AGENT if not CLOUDWATCHLOG_AGENT: CLOUDWATCHLOG_AGENT = bootstrap_cloudwatch_logging(config) def get_botocore_client(config,", "1000)), 'message': message } ] } if token: kwargs['sequenceToken'] =", "region obtained from \"dns_name_format\" field. Please set the \"region\" '", "iam_role_unsuccessful_resp, iam_role_url_error_msg, retry_with_new_header_token=True) return iam_role_name def credentials_file_helper(file_path, awsprofile): aws_credentials_configs =", "def subprocess_call(cmd, error_message): \"\"\"Helper method to run shell openssl command", "if level_error: logging.error('Malformed logging level \"%s\", setting logging level to", "not put_retention_policy_completed: return None stream_creation_completed = create_cloudwatch_log_stream(cloudwatchlog_client, log_group_name, log_stream_name) if", "not os.path.exists(database_dir): create_required_directory(config, database_dir) if not os.path.exists(certs_dir): create_required_directory(config, certs_dir) def", "url_error_msg, err_msg) return None def get_resp_obj(request_resp, url, unsuccessful_resp): if request_resp.getcode()", "else: fatal_error(tls_controls_message % 'stunnel_check_cert_validity') system_release_version = get_system_release_version() if not any(release", "length octets to follow (ignore high order bit) # -", "is None: log_message = user_message sys.stderr.write('%s\\n' % user_message) logging.error(log_message) publish_cloudwatch_log(CLOUDWATCHLOG_AGENT,", "= key[1] & 0b01111111 # Exclude the tag (1), length", "= '2' if 'noresvport' not in options: options['noresvport'] = None", "%s -out %s' % \\ (not_before, not_after, certificate_config, certificate_signing_request, certificate)", "cloudwatchlog_client.create_log_group( logGroupName=log_group_name ) logging.info('Created cloudwatch log group %s' % log_group_name)", "as e: exception = e.response['Error']['Code'] if exception == 'InvalidSequenceTokenException': logging.debug('The", "import base64 import errno import hashlib import hmac import json", "stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) (output, err) = process.communicate() rc = process.poll()", "has been tested with systemd # (Amazon Linux 2, CentOS", "3 for retry in range(retry_times): process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE,", "'default' except (NoSectionError, NoOptionError): continue return awsprofile def url_request_helper(url, unsuccessful_resp,", "ClientError as e: exception = e.response['Error']['Code'] if exception == 'ResourceAlreadyExistsException':", "err = subprocess_call(cmd, 'Unable to ASN1 parse public key file,", "aws_credentials_configs.get(awsprofile, 'aws_session_token') credentials['AccessKeyId'] = access_key credentials['SecretAccessKey'] = secret_key credentials['Token'] =", "aws_creds_uri = options.get('awscredsuri') if aws_creds_uri: kwargs = {'aws_creds_uri': aws_creds_uri} else:", "mount_path = '%s:%s' % (dns_name, path) command = ['/sbin/mount.nfs4', mount_path,", "TLS tunnel for %s' % fs_id, 'Failed to start TLS", "serial_path, rand_path): \"\"\"Recreate all supporting openssl ca and req files", "'tls' in options: options['port'] = options['tlsport'] def to_nfs_option(k, v): if", "ap_id, client_info, base_path=state_file_dir) cert_details['certificate'] = os.path.join(state_file_dir, cert_details['mountStateDir'], 'certificate.pem') cert_details['privateKey'] =", "specified incorrectly, %s' % (cloudwatchlog_agent.get('log_group_name'), cloudwatchlog_agent.get('log_stream_name'), e.response)) elif exception ==", "put_retention_policy_completed: return None stream_creation_completed = create_cloudwatch_log_stream(cloudwatchlog_client, log_group_name, log_stream_name) if not", "if len(args) > 1: fsname = args[1] if len(args) >", "options) stunnel_config_file = write_stunnel_config_file(config, state_file_dir, fs_id, mountpoint, tls_port, dns_name, verify_level,", "if client_info: ca_extension_str += '\\n1.3.6.1.4.1.4843.7.4 = ASN1:SEQUENCE:efs_client_info' return ca_extension_str def", "'ResourceAlreadyExistsException': logging.debug('Log stream %s already exist in log group %s,", "= 'Failed to mount %s at %s: returncode=%d, stderr=\"%s\"' %", "specified CNAME \"%s\" did not resolve to a valid DNS", "l= 13 cons: SEQUENCE # 6:d=2 hl=2 l= 9 prim:", "used if region is not present in the config file", "tls_dict = { 'mount_dir': os.path.join(base_path, mount_name), # every mount will", "'wsize' not in options: options['wsize'] = '1048576' if 'soft' not", "['stat', '-f', '-L', '-c', '%T', mountpoint] p = subprocess.Popen(cmd, stdout=subprocess.PIPE,", "agent dict includes cloudwatchlog botocore client, cloudwatchlog group name, cloudwatchlog", "'%s' } CANONICAL_HEADERS = '\\n'.join(['%s:%s' % (k, v) for k,", "17:d=2 hl=2 l= 0 prim: NULL # 19:d=1 hl=4 l=", "(cloudwatchlog_agent.get('log_group_name'), cloudwatchlog_agent.get('log_stream_name'), e.response)) return False else: logging.debug('Unexpected error: %s' %", "if the override is not set if ocsp_enabled: if ocsp_aia_supported:", "get_aws_security_credentials_from_ecs(os.environ[ECS_URI_ENV], False) if credentials and credentials_source: return credentials, credentials_source #", "under named profile [%s]' % \\ (AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE, awsprofile) fatal_error(log_message)", "from the given aws_creds_uri if is_fatal: fatal_error(ecs_unsuccessful_resp, ecs_unsuccessful_resp) else: return", "from the main thread, if the tunnel fails, exit uncleanly", "AWS_CONFIG_FILE]: aws_credentials_configs = read_config(file_path) # check if aws access key", "len(args) > 1: fsname = args[1] if len(args) > 2:", "are the length - \"definite form\" # - the first", "not present in %s: %s' % (property, instance_identity, e)) except", "the given aws_creds_uri if is_fatal: fatal_error(unsuccessful_resp, unsuccessful_resp) else: return None,", "try: stunnel_cafile = config.get(CONFIG_SECTION, 'stunnel_cafile') except NoOptionError: logging.debug('No CA file", "this is not called from the main thread, if the", "def is_nfs_mount(mountpoint): cmd = ['stat', '-f', '-L', '-c', '%T', mountpoint]", "= $dir/certs default_md = sha256 preserve = no policy =", "nfs_options = [to_nfs_option(k, v) for k, v in options.items() if", "'critical': logging.CRITICAL } level = levels.get(raw_level.lower()) level_error = False if", "%s.' % e) return False return True def cloudwatch_create_log_stream_helper(cloudwatchlog_client, log_group_name,", "version following a successful mount. \"\"\" state_file = '~' +", "is included in canonical request to tie the signature to", "pass else: return output, err error_message = '%s, error is:", "elif exception == 'ResourceNotFoundException': logging.error('Either log group %s or log", "req_distinguished_name [ req_distinguished_name ] CN = %s %s %s %s", "AWS security credentials through AWS_CONTAINER_CREDENTIALS_RELATIVE_URI environment variable if ECS_URI_ENV in", "configured level_error = True level = logging.INFO max_bytes = config.getint(CONFIG_SECTION,", "'iam' not in options: fatal_error('The \"iam\" option is required when", "'retention_in_days'): retention_days = config.get(CLOUDWATCH_LOG_SECTION, 'retention_in_days') log_stream_name = get_cloudwatch_log_stream_name(fs_id) return {", "return None, None def get_aws_security_credentials_from_ecs(aws_creds_uri, is_fatal=False): ecs_uri = ECS_TASK_METADATA_API +", "'socket': [ 'l:SO_REUSEADDR=yes', 'a:SO_BINDTODEVICE=lo', ], } STUNNEL_EFS_CONFIG = { 'client':", "# Using the 'efs' type will cause '/sbin/mount.efs' to be", "None def get_aws_security_credentials_from_ecs(aws_creds_uri, is_fatal=False): ecs_uri = ECS_TASK_METADATA_API + aws_creds_uri ecs_unsuccessful_resp", "UNSUPPORTED_OPTIONS: if unsupported_option in options: warn_message = 'The \"%s\" option", "with open(public_key, 'r') as f: lines = f.readlines() lines =", "stream_creation_completed = create_cloudwatch_log_stream(cloudwatchlog_client, log_group_name, log_stream_name) if not stream_creation_completed: return None", "= ap_id # additional symbol appended to avoid naming collisions", "it has any child processes, they can be killed easily", "= sys.argv if '-h' in args[1:] or '--help' in args[1:]:", "mode = int(mode_str, 8) except ValueError: logging.warning('Bad state_file_dir_mode \"%s\" in", "for tls_port in ports_to_try: try: sock.bind(('localhost', tls_port)) sock.close() return tls_port", "remote, path = device.split(':', 1) except ValueError: remote = device", "ap_id # additional symbol appended to avoid naming collisions cert_details['mountStateDir']", "STUNNEL_GLOBAL_CONFIG = { 'fips': 'no', 'foreground': 'yes', 'socket': [ 'l:SO_REUSEADDR=yes',", "'tls' not in options: fatal_error('The \"tls\" option is required when", "not fsname or not mountpoint: usage(out=sys.stderr) fs_id, path = match_device(config,", "first.') return None session = botocore.session.get_session() region = get_target_region(config) iam_role_name", "64 characters cert_details['commonName'] = socket.gethostname()[0:64] cert_details['region'] = get_target_region(config) cert_details['certificateCreationTime'] =", "and 'vers' not in options: options['nfsvers'] = '4.1' if 'rsize'", "if '{dns_name_suffix}' in dns_name_format: expected_replacement_field_ct += 1 config_section = CONFIG_SECTION", "info.' % \\ (INSTANCE_IAM_URL, SECURITY_CREDS_IAM_ROLE_HELP_URL) iam_role_name = url_request_helper(INSTANCE_IAM_URL, iam_role_unsuccessful_resp, iam_role_url_error_msg,", "Please upgrade stunnel, ' \\ 'or disable \"%%s\" in %s.\\nSee", "preexec_fn=os.setsid, close_fds=True) logging.info('Started TLS tunnel, pid: %d', tunnel_proc.pid) temp_tls_state_file =", "token cloudwatchlog_agent.get('client').put_log_events(**kwargs) def publish_cloudwatch_log(cloudwatchlog_agent, message): if not cloudwatchlog_agent or not", "naming collisions cert_details['mountStateDir'] = get_mount_specific_filename(fs_id, mountpoint, tls_port) + '+' #", "found under [default] section in current file and return 'default'", "options['nfsvers'] = '4.1' if 'rsize' not in options: options['rsize'] =", "import subprocess import sys import threading import time from contextlib", "retention_days = config.get(CLOUDWATCH_LOG_SECTION, 'retention_in_days') log_stream_name = get_cloudwatch_log_stream_name(fs_id) return { 'log_group_name':", "EXPLICIT:0,UTF8String:' + session_token return efs_client_auth_str def efs_client_info_builder(client_info): efs_client_info_str = '[", "% e) return False except Exception as e: logging.warning('Unknown error,", "'\\nsigv4DateTime = UTCTIME:' + date.strftime(CERT_DATETIME_FORMAT) if session_token: efs_client_auth_str += '\\nsessionToken", "database = $dir/database/index.txt serial = $dir/database/serial private_key = %s cert", "fs_id: log_stream_name = '%s - mount.log' % (fs_id) else: log_stream_name", "from \"dns_name_format\" field. Please set the \"region\" ' 'parameter in", "\"%s\"' % stunnel_cafile) efs_config['CAfile'] = stunnel_cafile def is_stunnel_option_supported(stunnel_output, stunnel_option_name): supported", "running', WATCHDOG_SERVICE) else: error_message = 'Could not start %s, unrecognized", "%s is specified incorrectly, %s' % (log_group_name, e.response)) return False", "v3_ca ]\\nsubjectKeyIdentifier = hash' if ap_id: ca_extension_str += '\\n1.3.6.1.4.1.4843.7.1 =", "efs_config['CAfile'] = stunnel_cafile def is_stunnel_option_supported(stunnel_output, stunnel_option_name): supported = False for", "of EC2 metadata at %s.' % INSTANCE_METADATA_SERVICE_URL ec2_metadata_url_error_msg = 'Unable", "e: exception = e.response['Error']['Code'] if exception == 'ResourceNotFoundException': logging.error('Log group", "encoding TLV (Tag, Length, Value) # - the first octet", "'aws_session_token') credentials['AccessKeyId'] = access_key credentials['SecretAccessKey'] = secret_key credentials['Token'] = session_token", "'The \"%s\" option is not supported and has been ignored,", "'config')) CA_CONFIG_BODY = \"\"\"dir = %s RANDFILE = $dir/database/.rand [", "& 0b01111111 # Exclude the tag (1), length (1 +", "(log_group_name, e.response)) return False elif exception == 'InvalidParameterException': logging.error('Either parameter", "max_bytes = config.getint(CONFIG_SECTION, 'logging_max_bytes') file_count = config.getint(CONFIG_SECTION, 'logging_file_count') handler =", "config.get(config_section, 'dns_name_suffix') logging.debug(\"Using dns_name_suffix %s in config section [%s]\", format_args.get('dns_name_suffix'),", "is already running', WATCHDOG_SERVICE) elif init_system == 'systemd': rc =", "= '/var/run/efs' PRIVATE_KEY_FILE = '/etc/amazon/efs/privateKey.pem' DATE_ONLY_FORMAT = '%Y%m%d' SIGV4_DATETIME_FORMAT =", "'Failed to create certificate signing request (csr)') def create_ca_conf(config_path, common_name,", "options['port'] = options['tlsport'] def to_nfs_option(k, v): if v is None:", "- \"definite form\" # - the first octet always has", "= [ 'capath' ] STUNNEL_GLOBAL_CONFIG = { 'fips': 'no', 'foreground':", "not in options: options['nfsvers'] = '4.1' if 'rsize' not in", "options, if not provided in fstab. import base64 import errno", "AssumeRoleWithWebIdentity # (e.g. for IAM Role for Service Accounts (IRSA)", "# For instance enable with IMDSv2, Unauthorized 401 error will", "= config.get(CLOUDWATCH_LOG_SECTION, 'log_group_name') retention_days = DEFAULT_RETENTION_DAYS if config.has_option(CLOUDWATCH_LOG_SECTION, 'retention_in_days'): retention_days", "399 # - 00 - no unused bits in the", "in options: fatal_error('The \"tls\" option is required when mounting via", "'ResourceNotFoundException': logging.error('Log group %s does not exist, %s' % (log_group_name,", "cloudwatchlog_client, 'log_group_name': log_group_name, 'log_stream_name': log_stream_name } def create_default_cloudwatchlog_agent_if_not_exist(config): if not", "FS_ID_RE = re.compile('^(?P<fs_id>fs-[0-9a-f]+)$') EFS_FQDN_RE = re.compile(r'^(?P<fs_id>fs-[0-9a-f]+)\\.efs\\.(?P<region>[a-z0-9-]+)\\.(?P<dns_name_suffix>[a-z0-9.]+)$') AP_ID_RE = re.compile('^fsap-[0-9a-f]{17}$') CREDENTIALS_KEYS", "return (fsid, path, mountpoint, options)\"\"\" if args is None: args", "%s already exist in log group %s, %s' % (log_stream_name,", "elif exception == 'InvalidParameterException': logging.error('Either parameter log group name %s", "f.write(full_config_body) return full_config_body def ca_extension_builder(ap_id, security_credentials, fs_id, client_info): ca_extension_str =", "legacy \"dns_name_format\" check') try: region = get_region_from_legacy_dns_format(config) sys.stdout.write('Warning: region obtained", "error_msg) def get_aws_security_credentials_from_awsprofile(awsprofile, is_fatal=False): for file_path in [AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE]: if", "def get_instance_identity_info_from_instance_metadata(property): ec2_metadata_unsuccessful_resp = 'Unsuccessful retrieval of EC2 metadata at", "INSTANCE_METADATA_SERVICE_URL ec2_metadata_url_error_msg = 'Unable to reach %s to retrieve EC2", "os.path.join(base_path, mount_name, 'database/index.txt.attr'), 'serial': os.path.join(base_path, mount_name, 'database/serial'), 'rand': os.path.join(base_path, mount_name,", "if 'awscredsuri' in options and 'awsprofile' in options: fatal_error('The \"awscredsuri\"", "during the mount attempt to fail fast if the tunnel", "-key %s -out %s' % (config_path, private_key, csr_path) subprocess_call(cmd, 'Failed", "# Example: # 0:d=0 hl=4 l= 418 cons: SEQUENCE #", "in the last content byte offset = int(key_line.split(':')[0]) key =", "field. Please set the \"region\" ' 'parameter in the efs-utils", "TLS tunnel (errno=%d). stdout=\"%s\" stderr=\"%s\"' % (tunnel_proc.returncode, out.strip(), err.strip())) def", "in SKIP_NO_LIBWRAP_RELEASES): efs_config['libwrap'] = 'no' stunnel_config = '\\n'.join(serialize_stunnel_config(global_config) + serialize_stunnel_config(efs_config,", "tls_port): return '%s.%s.%d' % (fs_id, os.path.abspath(mountpoint).replace(os.sep, '.').lstrip('.'), tls_port) def serialize_stunnel_config(config,", "region is not present in the config file and metadata", "close_fds=True) elif 'start' in status: logging.debug('%s is already running', WATCHDOG_SERVICE)", "os.path.expanduser(os.path.join('~' + pwd.getpwuid(os.getuid()).pw_name, '.aws', 'credentials')) AWS_CONFIG_FILE = os.path.expanduser(os.path.join('~' + pwd.getpwuid(os.getuid()).pw_name,", "file if config.has_option(CLIENT_INFO_SECTION, 'source'): client_source = config.get(CLIENT_INFO_SECTION, 'source') if 0", "e: logging.warning('Unknown error, %s' % e) return None try: log_stream", "region) signature = calculate_signature(string_to_sign, date, secret_access_key, region) efs_client_auth_str = '[", "different port.' % options['tlsport']) else: fatal_error('Failed to locate an available", "DATE_ONLY_FORMAT = '%Y%m%d' SIGV4_DATETIME_FORMAT = '%Y%m%dT%H%M%SZ' CERT_DATETIME_FORMAT = '%y%m%d%H%M%SZ' AWS_CREDENTIALS_FILE", "proc.wait() _, err = proc.communicate() stunnel_output = err.splitlines() check_host_supported =", "False token = get_log_stream_next_token(cloudwatchlog_agent) try: cloudwatch_put_log_events_helper(cloudwatchlog_agent, message, token) except ClientError", "line this will just re-set tlsport to X. options['tlsport'] =", "%s' % log_group_name) def create_cloudwatch_log_group(cloudwatchlog_client, log_group_name): try: cloudwatch_create_log_group_helper(cloudwatchlog_client, log_group_name) except", "'Token'] ECS_URI_ENV = 'AWS_CONTAINER_CREDENTIALS_RELATIVE_URI' ECS_TASK_METADATA_API = 'http://169.254.170.2' WEB_IDENTITY_ROLE_ARN_ENV = 'AWS_ROLE_ARN'", "efs-utils configuration file.') return region except Exception: logging.warning('Legacy check for", "% (message, e.response)) return False elif exception == 'UnrecognizedClientException': logging.debug('The", "= ';'.join(CANONICAL_HEADERS_DICT.keys()) REQUEST_PAYLOAD = '' FS_ID_RE = re.compile('^(?P<fs_id>fs-[0-9a-f]+)$') EFS_FQDN_RE =", "supported = True break if not supported: logging.warning('stunnel does not", "return ca_extension_str def efs_client_auth_builder(public_key_path, access_key_id, secret_access_key, date, region, fs_id, session_token=None):", "a locking mechanism to ensure that the private key is", "fstab, the file system can be mounted with: # #", "remote, path try: primary, secondaries, _ = socket.gethostbyname_ex(remote) hostnames =", "if use_iam: aws_creds_uri = options.get('awscredsuri') if aws_creds_uri: kwargs = {'aws_creds_uri':", "'default - mount.log' return log_stream_name def check_if_cloudwatch_log_enabled(config): if config.has_option(CLOUDWATCH_LOG_SECTION, 'enabled'):", "%s -pkeyopt rsa_keygen_bits:3072' % key subprocess_call(cmd, 'Failed to create private", "check_and_create_private_key(base_path) if security_credentials: public_key = os.path.join(tls_paths['mount_dir'], 'publicKey.pem') create_public_key(private_key, public_key) create_ca_conf(certificate_config,", "iam_role_url_error_msg = 'Unable to reach %s to retrieve IAM role", "the value is used to signify the number of unused", "retrieval of AWS security credentials at %s.' % STS_ENDPOINT_URL url_error_msg", "efs_client_auth_str += '\\nsessionToken = EXPLICIT:0,UTF8String:' + session_token return efs_client_auth_str def", "verify\\n\" % mountpoint) logging.warning(\"%s is already mounted, mount aborted\" %", "incorrectly, %s' % (log_group_name, retention_days, e.response)) return False else: handle_general_botocore_exceptions(e)", "header should embeded with metadata token if e.code == 401", "== 'init': proc = subprocess.Popen( ['/sbin/status', WATCHDOG_SERVICE], stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)", "WATCHDOG_SERVICE) elif init_system == 'systemd': rc = subprocess.call(['systemctl', 'is-active', '--quiet',", "'awscredsuri' in options and 'awsprofile' in options: fatal_error('The \"awscredsuri\" and", "aborted\" % mountpoint) return with bootstrap_tls(config, init_system, dns_name, fs_id, mountpoint,", "# DER encoding TLV (Tag, Length, Value) # - the", "to your mount options' % fs_id, exit_code=0) def check_network_status(fs_id, init_system):", "when mounting with named profile option, \"awsprofile\"') if 'awscredsuri' in", "are used to encode the number of octets that follow", "configuration:\\n%s', stunnel_config) stunnel_config_file = os.path.join(state_file_dir, 'stunnel-config.%s' % mount_filename) with open(stunnel_config_file,", "-config %s -in %s -out %s' % \\ (not_before, not_after,", "proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) out, err = proc.communicate()", "= '%s.%s' % (CONFIG_SECTION, region) if config.has_section(region_specific_config_section): config_section = region_specific_config_section", "unsuccessful_resp = 'Error reading token file %s: %s' % (token_file,", "return resp_dict except ValueError as e: logging.info('ValueError parsing \"%s\" into", "def get_credential_scope(date, region): return '/'.join([date.strftime(DATE_ONLY_FORMAT), region, SERVICE, AWS4_REQUEST]) def match_device(config,", "ocsp_enabled, options, cert_details=cert_details) tunnel_args = [_stunnel_bin(), stunnel_config_file] if 'netns' in", "level = logging.INFO max_bytes = config.getint(CONFIG_SECTION, 'logging_max_bytes') file_count = config.getint(CONFIG_SECTION,", "devnull: rc = subprocess.call(['systemctl', 'status', 'network.target'], stdout=devnull, stderr=devnull, close_fds=True) if", "supported and has been ignored, as amazon-efs-utils relies on a", "instance_identity = get_instance_identity_info_from_instance_metadata('region') if not instance_identity: raise Exception(\"Cannot retrieve region", "options = parse_options(args[options_index]) if not fsname or not mountpoint: usage(out=sys.stderr)", "cert_details: efs_config['cert'] = cert_details['certificate'] efs_config['key'] = cert_details['privateKey'] check_host_supported, ocsp_aia_supported =", "# - 018f - length of 399 # - 00", "it. \"\"\" mount_filename = get_mount_specific_filename(fs_id, mountpoint, tls_port) global_config = dict(STUNNEL_GLOBAL_CONFIG)", "'https://docs.aws.amazon.com/console/efs/troubleshooting-tls') if config.getboolean(CONFIG_SECTION, 'stunnel_check_cert_hostname'): if check_host_supported: efs_config['checkHost'] = dns_name else:", "threading.Thread(target=poll_tunnel_process, args=(tunnel_proc, fs_id, mount_completed)) t.daemon = True t.start() mount_nfs(dns_name, path,", "args = sys.argv fsname = None mountpoint = None options", "options): if 'tlsport' in options: ports_to_try = [int(options['tlsport'])] else: lower_bound,", "been tested with systemd # (Amazon Linux 2, CentOS 7,", "'{region}' in dns_name_format: expected_replacement_field_ct += 1 format_args['region'] = get_target_region(config) if", "days to %s' % retention_days) def put_cloudwatch_log_retention_policy(cloudwatchlog_client, log_group_name, retention_days): try:", "= EXPLICIT:0,UTF8String:' + session_token return efs_client_auth_str def efs_client_info_builder(client_info): efs_client_info_str =", "%s does not exist, %s' % (cloudwatchlog_agent.get('log_group_name'), cloudwatchlog_agent.get('log_stream_name'), e.response)) else:", "instance metadata.' % INSTANCE_METADATA_SERVICE_URL instance_identity = url_request_helper(INSTANCE_METADATA_SERVICE_URL, ec2_metadata_unsuccessful_resp, ec2_metadata_url_error_msg, retry_with_new_header_token=True)", "get_aws_profile(options, use_iam): awsprofile = options.get('awsprofile') if not awsprofile and use_iam:", "except EndpointConnectionError as e: logging.warning('Could not connect to the endpoint,", "as %d ' 'must be strictly greater than \"port_range_lower_bound\" defined", "efs_config['connect'] % dns_name efs_config['verify'] = verify_level if verify_level > 0:", "request_resp = urlopen(req, timeout=1) return get_resp_obj(request_resp, url, unsuccessful_resp) err_msg =", "create_default_cloudwatchlog_agent_if_not_exist(config) fatal_error( 'The specified domain name \"%s\" did not resolve", "private key is # atomically created, as mounts occurring in", "return sha1.hexdigest() def create_canonical_request(public_key_hash, date, access_key, region, fs_id, session_token=None): \"\"\"", "(instance_id) elif fs_id: log_stream_name = '%s - mount.log' % (fs_id)", "logging.debug('User is not authorized to perform the action, %s' %", "config_section = region_specific_config_section format_args['dns_name_suffix'] = config.get(config_section, 'dns_name_suffix') logging.debug(\"Using dns_name_suffix %s", "f.read() except Exception as e: if is_fatal: unsuccessful_resp = 'Error", "retry_with_new_header_token: token = get_aws_ec2_metadata_token() req.add_header('X-aws-ec2-metadata-token', token) request_resp = urlopen(req, timeout=1)", "BIT STRING, the first octet of the value is used", "= {'X-aws-ec2-metadata-token-ttl-seconds': 21600} req = Request(INSTANCE_METADATA_TOKEN_URL, headers=headers, method='PUT') res =", "DNS name the CNAME resolves to if hostname == expected_dns_name:", "the \"region\" parameter in the efs-utils configuration file.', message) metadata_exception", "> 1: fsname = args[1] if len(args) > 2: mountpoint", "already mounted, please run 'mount' command to verify\\n\" % mountpoint)", "choose_tls_port(config, options) # override the tlsport option so that we", "'nfsvers' not in options and 'vers' not in options: options['nfsvers']", "the private key is # atomically created, as mounts occurring", "'%s:%s' % (dns_name, path) command = ['/sbin/mount.nfs4', mount_path, mountpoint, '-o',", "path, mountpoint, options): if 'tls' in options: mount_path = '127.0.0.1:%s'", "cmd = 'openssl ca -startdate %s -enddate %s -selfsign -batch", "15 NOT_AFTER_HOURS = 3 EFS_ONLY_OPTIONS = [ 'accesspoint', 'awscredsuri', 'awsprofile',", "Amazon.com, Inc. and its affiliates. All Rights Reserved. # #", "= quote_plus(access_key + '/' + get_credential_scope(date, region)) request = HTTP_REQUEST_METHOD", "raw_level, level) def get_dns_name(config, fs_id): def _validate_replacement_field_count(format_str, expected_ct): if format_str.count('{')", "(8) set to 1 # - the remaining 127 bits", "tls_port, tunnel_proc.pid, tunnel_args, [stunnel_config_file], state_file_dir, cert_details=cert_details) try: yield tunnel_proc finally:", "- %s' % (command, env_path, install_method), e) return path.strip().decode() def", "is slow, so we will create one private key and", "iam_role_name = url_request_helper(INSTANCE_IAM_URL, iam_role_unsuccessful_resp, iam_role_url_error_msg, retry_with_new_header_token=True) return iam_role_name def credentials_file_helper(file_path,", "containing TLS tunnel state, prefixed with a '~'. This file", "parameter to put log events is not valid, %s' %", "%s %s \"\"\" # SigV4 Auth ALGORITHM = 'AWS4-HMAC-SHA256' AWS4_REQUEST", "valid, %s' % e.response) return False elif exception == 'InvalidParameterException':", "%s' % public_key output, err = subprocess_call(cmd, 'Unable to ASN1", "iam_role_url_error_msg, retry_with_new_header_token=True) return iam_role_name def credentials_file_helper(file_path, awsprofile): aws_credentials_configs = read_config(file_path)", "patching purposes in unit tests \"\"\" return datetime.utcnow() def assert_root():", "if os.path.exists(file_path): credentials = credentials_file_helper(file_path, awsprofile) if credentials['AccessKeyId']: return credentials,", "is max 64 characters cert_details['commonName'] = socket.gethostname()[0:64] cert_details['region'] = get_target_region(config)", "None except Exception as e: logging.warning('Unknown error, %s' % e)", "return ','.join(nfs_options) def mount_nfs(dns_name, path, mountpoint, options): if 'tls' in", "= 'AWS_ROLE_ARN' WEB_IDENTITY_TOKEN_FILE_ENV = 'AWS_WEB_IDENTITY_TOKEN_FILE' STS_ENDPOINT_URL = 'https://sts.amazonaws.com/' INSTANCE_METADATA_TOKEN_URL =", "% (dns_name, mountpoint) logging.info(message) publish_cloudwatch_log(CLOUDWATCHLOG_AGENT, message) else: message = 'Failed", "not os.path.isfile(rand_path): open(rand_path, 'w').close() def get_certificate_timestamp(current_time, **kwargs): updated_time = current_time", "def get_aws_security_credentials_from_instance_metadata(iam_role_name): security_creds_lookup_url = INSTANCE_IAM_URL + iam_role_name unsuccessful_resp = 'Unsuccessful", "os.open(lock_file, os.O_CREAT | os.O_DSYNC | os.O_EXCL | os.O_RDWR) try: lock_file_contents", "if instance_identity: try: return instance_identity[property] except KeyError as e: logging.warning('%s", "subprocess_call(cmd, 'Failed to create self-signed client-side certificate') return current_time.strftime(CERT_DATETIME_FORMAT) def", "return hmac.new(key, msg.encode('utf-8'), hashlib.sha256) key_date = _sign(('AWS4' + secret_access_key).encode('utf-8'), date.strftime(DATE_ONLY_FORMAT)).digest()", "'from ECS credentials relative uri, or from the instance security", "% e.response) return False elif exception == 'InvalidParameterException': logging.debug('One of", "# If you change these options, update the man page", "options: warn_message = 'The \"%s\" option is not supported and", "= aws_credentials_configs.get(awsprofile, 'aws_access_key_id') secret_key = aws_credentials_configs.get(awsprofile, 'aws_secret_access_key') session_token = aws_credentials_configs.get(awsprofile,", "pair to avoid replay attacks 'PublicKeyHash': quote_plus(public_key_hash), 'X-Amz-Algorithm': ALGORITHM, 'X-Amz-Credential':", "as e: logging.info('ValueError parsing \"%s\" into json: %s. Returning response", "config.get(CONFIG_SECTION, 'state_file_dir_mode') try: mode = int(mode_str, 8) except ValueError: logging.warning('Bad", "to create self-signed client-side certificate') return current_time.strftime(CERT_DATETIME_FORMAT) def get_private_key_path(): \"\"\"Wrapped", "process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) (output, err) = process.communicate()", "'SecretAccessKey': None, 'Token': None} try: access_key = aws_credentials_configs.get(awsprofile, 'aws_access_key_id') secret_key", "system can be mounted with: # # sudo mount /mount_point", "% INSTANCE_METADATA_SERVICE_URL ec2_metadata_url_error_msg = 'Unable to reach %s to retrieve", "and return 'default' if so try: access_key = aws_credentials_configs.get('default', 'aws_access_key_id')", "= 'Red Hat Enterprise Linux release 8' CENTOS8_RELEASE_NAME = 'CentOS", "purposes in unit tests \"\"\" return datetime.utcnow() def assert_root(): if", "len(client_source) <= CLIENT_SOURCE_STR_LEN_LIMIT: client_info['source'] = client_source return client_info def create_certificate(config,", "'%s, error is: %s' % (error_message, err) fatal_error(error_message, error_message) def", "env_path) path = subprocess.check_output(['which', command]) except subprocess.CalledProcessError as e: fatal_error('Failed", "needs to be renamed to a non-temporary version following a", "exception == 'ResourceNotFoundException': logging.error('Log group %s does not exist, %s'", "fatal_error('The \"tls\" option is required when mounting via \"iam\"') if", "logging.warning('Unknown error, %s' % e) return None try: log_stream =", "init system that the # 'efs' type is a networked", "!= 0: sys.stderr.write('only root can run mount.efs\\n') sys.exit(1) def read_config(config_file=CONFIG_FILE):", "WATCHDOG_SERVICE = 'amazon-efs-mount-watchdog' SYSTEM_RELEASE_PATH = '/etc/system-release' OS_RELEASE_PATH = '/etc/os-release' RHEL8_RELEASE_NAME", "if not supported: logging.warning('stunnel does not support \"%s\"', stunnel_option_name) return", "under named profile [%s]', file_path, awsprofile) if 'aws_session_token' in str(e):", "(CONFIG_SECTION, region) if config.has_section(region_specific_config_section): config_section = region_specific_config_section format_args['dns_name_suffix'] = config.get(config_section,", "file %s: %s' % (token_file, e) fatal_error(unsuccessful_resp, unsuccessful_resp) else: return", "= CA_CONFIG_BODY % (directory, private_key, common_name, ca_extension_body, efs_client_auth_body, efs_client_info_body) with", "the user has specified tlsport=X at the command line this", "to start TLS tunnel (errno=%d). stdout=\"%s\" stderr=\"%s\"' % (tunnel_proc.returncode, out.strip(),", "%s - %s' % (command, env_path, install_method), e) return path.strip().decode()", "prim: BIT STRING cmd = 'openssl asn1parse -inform PEM -in", "[%s]' % \\ (AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE, awsprofile) fatal_error(log_message) else: return None,", "return None put_retention_policy_completed = put_cloudwatch_log_retention_policy(cloudwatchlog_client, log_group_name, retention_days) if not put_retention_policy_completed:", "req = Request(INSTANCE_METADATA_TOKEN_URL, headers=headers, method='PUT') res = urlopen(req) return res.read()", "read %s', comm_file) logging.debug('Identified init system: %s', init_system) return init_system", "% (k, item)) else: lines.append('%s = %s' % (k, v))", "if 'rsize' not in options: options['rsize'] = '1048576' if 'wsize'", "= fs_id start_watchdog(init_system) if not os.path.exists(state_file_dir): create_required_directory(config, state_file_dir) verify_level =", "HTTPHandler from urllib import urlencode except ImportError: from urllib.request import", "date, region, fs_id, security_credentials['Token']) if security_credentials else '' efs_client_info_body =", "= get_iam_role_name() if iam_role_name: credentials, credentials_source = get_aws_security_credentials_from_instance_metadata(iam_role_name) if credentials", "minutes=-NOT_BEFORE_MINS) not_after = get_certificate_timestamp(current_time, hours=NOT_AFTER_HOURS) cmd = 'openssl ca -startdate", "l= 399 prim: BIT STRING cmd = 'openssl asn1parse -inform", "for mounting with DNS names for examples: %s' % (remote,", "check_and_create_private_key(base_path=STATE_FILE_DIR): # Creating RSA private keys is slow, so we", "(log_group_name, log_stream_name, e.response)) return False elif exception == 'ResourceNotFoundException': logging.error('Log", "'InvalidParameterException': logging.error('Either parameter log group name %s or retention in", "add_stunnel_ca_options(efs_config, config, options): if 'cafile' in options: stunnel_cafile = options['cafile']", "levels = { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error':", "for file_path in [AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE]: if os.path.exists(file_path): credentials = credentials_file_helper(file_path,", "= bytearray(base64.b64decode(key)) # Parse the public key to pull out", "error_message) def ca_dirs_check(config, database_dir, certs_dir): \"\"\"Check if mount's database and", "e) return None except Exception as e: logging.warning('Unknown error, %s'", "lacks sufficient controls to properly enforce TLS. Please upgrade stunnel,", "days %s is specified incorrectly, %s' % (log_group_name, retention_days, e.response))", "in options: fatal_error('The \"awscredsuri\" and \"awsprofile\" options are mutually exclusive')", "'\\n'.join(['%s:%s' % (k, v) for k, v in sorted(CANONICAL_HEADERS_DICT.items())]) SIGNED_HEADERS", "% e.response) return False elif exception == 'ResourceNotFoundException': logging.error('Either log", "+= 1 format_args['region'] = get_target_region(config) if '{dns_name_suffix}' in dns_name_format: expected_replacement_field_ct", "os.path.join(tls_paths['mount_dir'], 'request.csr') certificate = os.path.join(tls_paths['mount_dir'], 'certificate.pem') ca_dirs_check(config, tls_paths['database_dir'], tls_paths['certs_dir']) ca_supporting_files_check(tls_paths['index'],", "The syntax of an fstab entry is: # # [Device]", "hmac.new(key, msg.encode('utf-8'), hashlib.sha256) key_date = _sign(('AWS4' + secret_access_key).encode('utf-8'), date.strftime(DATE_ONLY_FORMAT)).digest() add_region", "'1048576' if 'wsize' not in options: options['wsize'] = '1048576' if", "option [%s] is not an integer' % options['tlsport']) if 'ocsp'", "exit conditions only\"\"\" if args is None: args = sys.argv", "efs_client_info_str = '[ efs_client_info ]' for key, value in client_info.items():", "assert_root(): if os.geteuid() != 0: sys.stderr.write('only root can run mount.efs\\n')", "'[ efs_client_info ]' for key, value in client_info.items(): efs_client_info_str +=", "create_required_directory(config, database_dir) if not os.path.exists(certs_dir): create_required_directory(config, certs_dir) def ca_supporting_files_check(index_path, index_attr_path,", "# [Device] [Mount Point] [File System Type] [Options] [Dump] [Pass]", "fetched from the given aws_creds_uri if is_fatal: fatal_error(unsuccessful_resp, unsuccessful_resp) else:", "if aws access key id is found under [default] section", "'0', 'TIMEOUTidle': '70', 'delay': 'yes', } WATCHDOG_SERVICE = 'amazon-efs-mount-watchdog' SYSTEM_RELEASE_PATH", "status=%d, reason is %s' % (url, e.code, e.reason) except URLError", "LOG_FILE), maxBytes=max_bytes, backupCount=file_count) handler.setFormatter(logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(message)s')) logger =", "= DEFAULT_RETENTION_DAYS if config.has_option(CLOUDWATCH_LOG_SECTION, 'retention_in_days'): retention_days = config.get(CLOUDWATCH_LOG_SECTION, 'retention_in_days') log_stream_name", "if ecs_security_dict and all(k in ecs_security_dict for k in CREDENTIALS_KEYS):", "ap_id: cert_details['accessPoint'] = ap_id # additional symbol appended to avoid", "+ '\\n' sha256 = hashlib.sha256() sha256.update(REQUEST_PAYLOAD.encode()) request += sha256.hexdigest() return", ") if not hostnames: create_default_cloudwatchlog_agent_if_not_exist(config) fatal_error( 'The specified domain name", "efs_client_auth_str = '[ efs_client_auth ]' efs_client_auth_str += '\\naccessKeyId = UTF8String:'", "return 'default' if so try: access_key = aws_credentials_configs.get('default', 'aws_access_key_id') if", "private_key = %s cert = $dir/certificate.pem new_certs_dir = $dir/certs default_md", "init_system == 'init': proc = subprocess.Popen( ['/sbin/status', WATCHDOG_SERVICE], stdout=subprocess.PIPE, stderr=subprocess.PIPE,", "args[1] if len(args) > 2: mountpoint = args[2] if len(args)", "cloudwatchlog_client.put_retention_policy( logGroupName=log_group_name, retentionInDays=retention_days ) logging.debug('Set cloudwatch log group retention days", "supplied [ req ] prompt = no distinguished_name = req_distinguished_name", "fatal_error('The specified CNAME \"%s\" did not resolve to a valid", "option is required when mounting via \"iam\"') if 'awsprofile' in", "rc = process.poll() if rc != 0: logging.error('Command %s failed,", "# truncating public key to remove the header and footer", "path, mountpoint, options = parse_arguments(config) logging.info('version=%s options=%s', VERSION, options) global", "import logging import os import pwd import random import re", "not connect to the endpoint, %s' % e) return None", "'mount' command to verify\\n\" % mountpoint) logging.warning(\"%s is already mounted,", "not in options: options['hard'] = None if 'timeo' not in", "mounts occurring in parallel may try to create the key", "https://tools.ietf.org/html/rfc5280#section-4.2.1.2 # # Example: # 0382018f00...<subjectPublicKey> # - 03 -", ") logging.info('Created cloudwatch log group %s' % log_group_name) def create_cloudwatch_log_group(cloudwatchlog_client,", "- 2 length octets to follow (ignore high order bit)", "try: socket.gethostbyname(dns_name) except socket.gaierror: fatal_error('Failed to resolve \"%s\" - check", "(property, instance_identity, e)) except TypeError as e: logging.warning('response %s is", "\"%%s\" in %s.\\nSee %s for more detail.' % (CONFIG_FILE, 'https://docs.aws.amazon.com/console/efs/troubleshooting-tls')", "an EFS mount target. ' 'Please refer to the EFS", "id and the remote path to mount\"\"\" try: remote, path", "\"%s\"' % (WATCHDOG_SERVICE, init_system) sys.stderr.write('%s\\n' % error_message) logging.warning(error_message) def create_required_directory(config,", "expected_replacement_field_ct) dns_name = dns_name_format.format(**format_args) try: socket.gethostbyname(dns_name) except socket.gaierror: fatal_error('Failed to", "to mount %s at %s: returncode=%d, stderr=\"%s\"' % (dns_name, mountpoint,", "%s' % (log_stream_name, log_group_name, e.response)) return True elif exception ==", "has the high order bit (8) set to 1 #", "# through IAM role name security credentials lookup uri iam_role_name", "octets encode, as big-endian, the length (which may be 0)", "'CentOS Linux release 8' FEDORA_RELEASE_NAME = 'Fedora release' SUSE_RELEASE_NAME =", "[AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE]: aws_credentials_configs = read_config(file_path) # check if aws access", "option, \"awsprofile\"') if 'awscredsuri' in options and 'iam' not in", "= args[1] if len(args) > 2: mountpoint = args[2] if", "early exit conditions only\"\"\" if args is None: args =", "SECURITY_CREDS_WEBIDENTITY_HELP_URL) resp = url_request_helper(webidentity_url, unsuccessful_resp, url_error_msg, headers={'Accept': 'application/json'}) if resp:", "return session.create_client(service, aws_access_key_id=credentials['AccessKeyId'], aws_secret_access_key=credentials['SecretAccessKey'], aws_session_token=credentials['Token'], region_name=region) return session.create_client(service, region_name=region) def", "3 EFS_ONLY_OPTIONS = [ 'accesspoint', 'awscredsuri', 'awsprofile', 'cafile', 'iam', 'netns',", "= v else: opts[o] = None return opts def get_tls_port_range(config):", "with fresh configurations at every mount since SigV4 signature can", "return iam_security_dict, 'metadata:' else: return None, None def get_iam_role_name(): iam_role_unsuccessful_resp", "is not called from the main thread, if the tunnel", "in range(retry_times): process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) (output, err)", "is not supported and has been ignored, as amazon-efs-utils relies", "symbol appended to avoid naming collisions cert_details['mountStateDir'] = get_mount_specific_filename(fs_id, mountpoint,", "f: return f.read().strip() except IOError: logging.debug('Unable to read %s', SYSTEM_RELEASE_PATH)", "port range in %s' % (lower_bound, upper_bound, CONFIG_FILE)) def is_ocsp_enabled(config,", "TypeError, KeyError): pass return None def handle_general_botocore_exceptions(error): exception = error.response['Error']['Code']", "iam_security_dict = url_request_helper(security_creds_lookup_url, unsuccessful_resp, url_error_msg, retry_with_new_header_token=True) if iam_security_dict and all(k", "% (WATCHDOG_SERVICE, init_system) sys.stderr.write('%s\\n' % error_message) logging.warning(error_message) def create_required_directory(config, directory):", "except SystemExit as e: os._exit(e.code) mount_completed.wait(.5) def get_init_system(comm_file='/proc/1/comm'): init_system =", "get_aws_security_credentials_from_webidentity( os.environ[WEB_IDENTITY_ROLE_ARN_ENV], os.environ[WEB_IDENTITY_TOKEN_FILE_ENV], False ) if credentials and credentials_source: return", "RotatingFileHandler try: import ConfigParser from ConfigParser import NoOptionError, NoSectionError except", "able to mount an EFS file system by its short", "file_path in [AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE]: if os.path.exists(file_path): credentials = credentials_file_helper(file_path, awsprofile)", "check_unsupported_options(options) check_options_validity(options) init_system = get_init_system() check_network_status(fs_id, init_system) dns_name = get_dns_name(config,", "exception = e.response['Error']['Code'] if exception == 'ResourceNotFoundException': logging.error('Log group %s", "= '/var/log/amazon/efs' LOG_FILE = 'mount.log' STATE_FILE_DIR = '/var/run/efs' PRIVATE_KEY_FILE =", "that follow # - the following octets encode, as big-endian,", "ca_extension_builder(ap_id, security_credentials, fs_id, client_info): ca_extension_str = '[ v3_ca ]\\nsubjectKeyIdentifier =", "for more info.' % \\ (STS_ENDPOINT_URL, SECURITY_CREDS_WEBIDENTITY_HELP_URL) resp = url_request_helper(webidentity_url,", "get_certificate_timestamp(current_time, hours=NOT_AFTER_HOURS) cmd = 'openssl ca -startdate %s -enddate %s", "dns_name_format = config.get(CONFIG_SECTION, 'dns_name_format') if '{fs_id}' not in dns_name_format: raise", "= 'https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html' SECURITY_CREDS_IAM_ROLE_HELP_URL = 'https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html' DEFAULT_STUNNEL_VERIFY_LEVEL = 2 DEFAULT_STUNNEL_CAFILE =", "in options: stunnel_cafile = options['cafile'] else: try: stunnel_cafile = config.get(CONFIG_SECTION,", "= os.path.join(log_dir, '%s.stunnel.log' % mount_filename) efs_config = dict(STUNNEL_EFS_CONFIG) efs_config['accept'] =", "e.response)) return False else: handle_general_botocore_exceptions(e) return False except NoCredentialsError as", "hostname in hostnames: efs_fqdn_match = EFS_FQDN_RE.match(hostname) if efs_fqdn_match: fs_id =", "= 'Unknown error' try: return config.get(CONFIG_SECTION, 'region') except NoOptionError: pass", "'noocsp' in options: fatal_error('The \"ocsp\" and \"noocsp\" options are mutually", "used to encode the number of octets that follow #", "remove the header and footer '-----(BEGIN|END) PUBLIC KEY-----' with open(public_key,", "region) + '\\n' sha256 = hashlib.sha256() sha256.update(canonical_request.encode()) string_to_sign += sha256.hexdigest()", "dns_name = get_dns_name(config, fs_id) if 'tls' in options: mount_tls(config, init_system,", "= logging.getLogger() logger.setLevel(level) logger.addHandler(handler) if level_error: logging.error('Malformed logging level \"%s\",", "client_info = {} # source key/value pair in config file", "options: options['rsize'] = '1048576' if 'wsize' not in options: options['wsize']", "is not valid, %s' % e.response) return False elif exception", "'http://169.254.169.254/latest/dynamic/instance-identity/document/' INSTANCE_IAM_URL = 'http://169.254.169.254/latest/meta-data/iam/security-credentials/' SECURITY_CREDS_ECS_URI_HELP_URL = 'https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html' SECURITY_CREDS_WEBIDENTITY_HELP_URL = 'https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html'", "of multi-threading support in openssl 'database_dir': os.path.join(base_path, mount_name, 'database'), 'certs_dir':", "\"\"\" state_file = '~' + get_mount_specific_filename(fs_id, mountpoint, tls_port) state =", "urllib.parse import quote_plus except ImportError: from urllib import quote_plus try:", "adding it # to /etc/fstab. The syntax of an fstab", "date, region, fs_id, security_credentials, ap_id, client_info): \"\"\"Populate ca/req configuration file", "urlencode({ 'Version': '2011-06-15', 'Action': 'AssumeRoleWithWebIdentity', 'RoleArn': role_arn, 'RoleSessionName': 'efs-mount-helper', 'WebIdentityToken':", "lower_bound, upper_bound def choose_tls_port(config, options): if 'tlsport' in options: ports_to_try", "state, prefixed with a '~'. This file needs to be", "return None cloudwatchlog_client = get_botocore_client(config, 'logs') if not cloudwatchlog_client: return", "key, value in client_info.items(): efs_client_info_str += '\\n%s = UTF8String:%s' %", "e: if 'aws_access_key_id' in str(e) or 'aws_secret_access_key' in str(e): logging.debug('aws_access_key_id", "every mount will have its own ca mode assets due", "fs_id, path else: create_default_cloudwatchlog_agent_if_not_exist(config) fatal_error('The specified CNAME \"%s\" did not", "try: os.makedirs(directory, mode) except OSError as e: if errno.EEXIST !=", "options['tlsport']) if 'ocsp' in options and 'noocsp' in options: fatal_error('The", "%s' % (cloudwatchlog_agent.get('log_group_name'), cloudwatchlog_agent.get('log_stream_name'), e.response)) elif exception == 'ResourceNotFoundException': logging.debug('Either", "ECS credentials relative uri, or from the instance security credentials", "return session.create_client(service, region_name=region) def get_cloudwatchlog_config(config, fs_id=None): log_group_name = DEFAULT_CLOUDWATCH_LOG_GROUP if", "0:d=0 hl=4 l= 418 cons: SEQUENCE # 4:d=1 hl=2 l=", "fail fast if the tunnel dies - since this is", "(fs_id, instance_id) elif instance_id: log_stream_name = '%s - mount.log' %", "% (url, e.reason) if err_msg: logging.debug('%s %s', url_error_msg, err_msg) return", "more detail.' % (CONFIG_FILE, 'https://docs.aws.amazon.com/console/efs/troubleshooting-tls') if config.getboolean(CONFIG_SECTION, 'stunnel_check_cert_hostname'): if check_host_supported:", "{}) \\ .get('Credentials', {}) if all(k in creds for k", "Create a String to Sign - https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html \"\"\" string_to_sign =", "Adapted credentials provider chain from: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html and https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html \"\"\" if", "= dns_name_format.split('.') if '{dns_name_suffix}' in dns_name_format: return split_dns_name_format[-2] elif 'amazonaws.com'", "is required when mounting via \"iam\"') if 'awsprofile' in options", "exclusive') def bootstrap_cloudwatch_logging(config, fs_id=None): if not check_if_cloudwatch_log_enabled(config): return None cloudwatchlog_client", "'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL } level", "'-----(BEGIN|END) PUBLIC KEY-----' with open(public_key, 'r') as f: lines =", "def create_certificate_signing_request(config_path, private_key, csr_path): cmd = 'openssl req -new -config", "config section [%s]\", format_args.get('dns_name_suffix'), config_section) _validate_replacement_field_count(dns_name_format, expected_replacement_field_ct) dns_name = dns_name_format.format(**format_args)", "file_path, awsprofile) if 'aws_session_token' in str(e): logging.debug('aws_session_token not found in", "in hostnames: efs_fqdn_match = EFS_FQDN_RE.match(hostname) if efs_fqdn_match: fs_id = efs_fqdn_match.group('fs_id')", "in dns_name_format: split_dns_name_format = dns_name_format.split('.') if '{dns_name_suffix}' in dns_name_format: return", "read_config(config_file=CONFIG_FILE): try: p = ConfigParser.SafeConfigParser() except AttributeError: p = ConfigParser()", "+= SIGNED_HEADERS + '\\n' sha256 = hashlib.sha256() sha256.update(REQUEST_PAYLOAD.encode()) request +=", "err_msg = 'Unable to reach the url at %s, reason", "if security_credentials: ca_extension_str += '\\n1.3.6.1.4.1.4843.7.2 = ASN1:SEQUENCE:efs_client_auth' ca_extension_str += '\\n1.3.6.1.4.1.4843.7.3", "line.startswith(stunnel_option_name): supported = True break if not supported: logging.warning('stunnel does", "ec2_metadata_url_error_msg = 'Unable to reach %s to retrieve EC2 instance", "and '-o' in args[:-1]: options_index = args.index('-o') + 1 options", "if they don't exist).\"\"\" if not os.path.exists(database_dir): create_required_directory(config, database_dir) if", "in options: if 'port' in options: fatal_error('The \"port\" and \"tls\"", "release in SKIP_NO_LIBWRAP_RELEASES): efs_config['libwrap'] = 'no' stunnel_config = '\\n'.join(serialize_stunnel_config(global_config) +", "by its short name, by adding it # to /etc/fstab.", "-enddate %s -selfsign -batch -notext -config %s -in %s -out", "'%s - %s - mount.log' % (fs_id, instance_id) elif instance_id:", "SEQUENCE # 6:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption #", "Key are not found in AWS credentials file (%s), config", "big-endian, the length (which may be 0) as a number", "error: %s' % error) def main(): parse_arguments_early_exit() assert_root() config =", "return state_file def test_tunnel_process(tunnel_proc, fs_id): tunnel_proc.poll() if tunnel_proc.returncode is not", "or retention in days %s is specified incorrectly, %s' %", "= botocore.session.get_session() region = get_target_region(config) iam_role_name = get_iam_role_name() if iam_role_name:", "return get_aws_security_credentials_from_awsprofile(awsprofile, True) # attempt to lookup AWS security credentials", "check_host_supported: efs_config['checkHost'] = dns_name else: fatal_error(tls_controls_message % 'stunnel_check_cert_hostname') # Only", "in [AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE]: if os.path.exists(file_path): credentials = credentials_file_helper(file_path, awsprofile) if", "if 'ocsp' in options: return True elif 'noocsp' in options:", "%s' % (log_group_name, e.response)) return True elif exception == 'LimitExceededException':", "response = cloudwatch_describe_log_streams_helper(cloudwatchlog_agent) except ClientError as e: exception = e.response['Error']['Code']", "err_msg: logging.debug('%s %s', url_error_msg, err_msg) return None def get_resp_obj(request_resp, url,", "json.dump(state, f) return state_file def test_tunnel_process(tunnel_proc, fs_id): tunnel_proc.poll() if tunnel_proc.returncode", "%s -outform PEM -pubout -out %s' % (private_key, public_key) subprocess_call(cmd,", "stunnel_config_file = write_stunnel_config_file(config, state_file_dir, fs_id, mountpoint, tls_port, dns_name, verify_level, ocsp_enabled,", "\"\"\"Parse arguments, checking for early exit conditions only\"\"\" if args", "key is # atomically created, as mounts occurring in parallel", "if '-h' in args[1:] or '--help' in args[1:]: usage(out=sys.stdout, exit_code=0)", "+ command logging.info('Executing: \"%s\"', ' '.join(command)) proc = subprocess.Popen(command, stdout=subprocess.PIPE,", "CREDENTIALS_KEYS): return iam_security_dict, 'metadata:' else: return None, None def get_iam_role_name():", "(config_path, private_key, csr_path) subprocess_call(cmd, 'Failed to create certificate signing request", "stunnel_config_file = os.path.join(state_file_dir, 'stunnel-config.%s' % mount_filename) with open(stunnel_config_file, 'w') as", "= config.get(CLOUDWATCH_LOG_SECTION, 'retention_in_days') log_stream_name = get_cloudwatch_log_stream_name(fs_id) return { 'log_group_name': log_group_name,", "successful mount. \"\"\" state_file = '~' + get_mount_specific_filename(fs_id, mountpoint, tls_port)", "cmd = 'openssl req -new -config %s -key %s -out", "ecs_security_dict, 'ecs:' + aws_creds_uri # Fail if credentials cannot be", "return None stream_creation_completed = create_cloudwatch_log_stream(cloudwatchlog_client, log_group_name, log_stream_name) if not stream_creation_completed:", "fsname = args[1] if len(args) > 2: mountpoint = args[2]", "See %s for more info.' \\ % (ecs_uri, SECURITY_CREDS_ECS_URI_HELP_URL) ecs_security_dict", "{'fs_id': fs_id} expected_replacement_field_ct = 1 if '{region}' in dns_name_format: expected_replacement_field_ct", "f.read().strip() except IOError: logging.warning('Unable to read %s', comm_file) logging.debug('Identified init", "state_file_dir, cert_details=None): \"\"\" Return the name of the temporary file", "'noresvport' not in options: options['noresvport'] = None if 'tls' in", "get_aws_ec2_metadata_token() req.add_header('X-aws-ec2-metadata-token', token) request_resp = urlopen(req, timeout=1) return get_resp_obj(request_resp, url,", "018f - length of 399 # - 00 - no", "e.response)) return False elif exception == 'OperationAbortedException': logging.debug('Multiple requests to", "0: fatal_error('Failed to mount %s because the network was not", "already running', WATCHDOG_SERVICE) elif init_system == 'systemd': rc = subprocess.call(['systemctl',", "length - \"definite form\" # - the first octet always", "mountpoint, tls_port) state = { 'pid': tunnel_pid, 'cmd': command, 'files':", "lines[1:-1] key = ''.join(lines) key = bytearray(base64.b64decode(key)) # Parse the", "cloudwatchlog_agent.get('log_stream_name'), 'logEvents': [ { 'timestamp': int(round(time.time() * 1000)), 'message': message", "_sign(key, msg): return hmac.new(key, msg.encode('utf-8'), hashlib.sha256) key_date = _sign(('AWS4' +", "AWS access key ID or secret Key, %s' % e.response)", "port.' % options['tlsport']) else: fatal_error('Failed to locate an available port", "option is not supported and has been ignored, as amazon-efs-utils", "not, create directories (also create all intermediate directories if they", "mutually exclusive') if 'accesspoint' in options: if 'tls' not in", "= os.path.join(tls_paths['mount_dir'], 'config.conf') certificate_signing_request = os.path.join(tls_paths['mount_dir'], 'request.csr') certificate = os.path.join(tls_paths['mount_dir'],", "%s', init_system) return init_system def check_network_target(fs_id): with open(os.devnull, 'w') as", "sys.stderr.write('only root can run mount.efs\\n') sys.exit(1) def read_config(config_file=CONFIG_FILE): try: p", "% (instance_id) elif fs_id: log_stream_name = '%s - mount.log' %", "= 'mount.log' STATE_FILE_DIR = '/var/run/efs' PRIVATE_KEY_FILE = '/etc/amazon/efs/privateKey.pem' DATE_ONLY_FORMAT =", "with open(serial_path, 'w+') as f: f.write('00') if not os.path.isfile(rand_path): open(rand_path,", "= Request(url) for k, v in headers.items(): req.add_header(k, v) request_resp", "mountpoint, options) mount_completed.set() t.join() def check_unsupported_options(options): for unsupported_option in UNSUPPORTED_OPTIONS:", "config.has_option(CONFIG_SECTION, 'stunnel_logs_file'): global_config['output'] = config.get(CONFIG_SECTION, 'stunnel_logs_file').replace('{fs_id}', fs_id) else: global_config['output'] =", "return None, None # attempt to lookup AWS security credentials", "group name %s is specified incorrectly, %s' % (log_group_name, e.response))", "in options and 'iam' not in options: fatal_error('The \"iam\" option", "conform to Python's config file format, so we have to", "aws_creds_uri if is_fatal: fatal_error(unsuccessful_resp, unsuccessful_resp) else: return None, None def", "state_file_dir, fs_id, mountpoint, tls_port, dns_name, verify_level, ocsp_enabled, options, log_dir=LOG_DIR, cert_details=None):", "mountpoint, tls_port) global_config = dict(STUNNEL_GLOBAL_CONFIG) if config.getboolean(CONFIG_SECTION, 'stunnel_debug_enabled'): global_config['debug'] =", "key simultaneously. key = get_private_key_path() @contextmanager def open_lock_file(): lock_file =", "serialize_stunnel_config(efs_config, 'efs')) logging.debug('Writing stunnel configuration:\\n%s', stunnel_config) stunnel_config_file = os.path.join(state_file_dir, 'stunnel-config.%s'", "False else: handle_general_botocore_exceptions(e) return False except NoCredentialsError as e: logging.warning('Credentials", "try: return instance_identity[property] except KeyError as e: logging.warning('%s not present", "get_utc_now(): \"\"\" Wrapped for patching purposes in unit tests \"\"\"", "if ocsp_enabled: if ocsp_aia_supported: efs_config['OCSPaia'] = 'yes' else: fatal_error(tls_controls_message %", "\"\"\"Populate ca/req configuration file with fresh configurations at every mount", "# 17:d=2 hl=2 l= 0 prim: NULL # 19:d=1 hl=4", "present in the config file and metadata calls fail. \"\"\"", "%s', SYSTEM_RELEASE_PATH) try: with open(OS_RELEASE_PATH) as f: for line in", "access_key, region, fs_id, session_token=None): \"\"\" Create a Canonical Request -", "option is required when mounting with \"awscredsuri\"') if 'awscredsuri' in", "file, %s, is incorrectly formatted' % public_key fatal_error(err_msg, err_msg) key_line", "4:d=1 hl=2 l= 13 cons: SEQUENCE # 6:d=2 hl=2 l=", "log_stream_name) except ClientError as e: exception = e.response['Error']['Code'] if exception", "find CAfile \"%s\"' % stunnel_cafile) efs_config['CAfile'] = stunnel_cafile def is_stunnel_option_supported(stunnel_output,", "else '' efs_client_info_body = efs_client_info_builder(client_info) if client_info else '' full_config_body", "sequence token is not valid, %s' % e.response) return False", "session_token=None): public_key_hash = get_public_key_sha1(public_key_path) canonical_request = create_canonical_request(public_key_hash, date, access_key_id, region,", "PRIVATE_KEY_FILE def check_and_create_private_key(base_path=STATE_FILE_DIR): # Creating RSA private keys is slow,", "check_if_cloudwatch_log_enabled(config): return None global CLOUDWATCHLOG_AGENT if not CLOUDWATCHLOG_AGENT: CLOUDWATCHLOG_AGENT =", "add recommended mount options, if not provided in fstab. import", "except ImportError: from configparser import ConfigParser, NoOptionError, NoSectionError try: from", "'1048576' if 'soft' not in options and 'hard' not in", "as f: json.dump(state, f) return state_file def test_tunnel_process(tunnel_proc, fs_id): tunnel_proc.poll()", "awsprofile) fatal_error(log_message) else: return None, None def get_aws_security_credentials_from_ecs(aws_creds_uri, is_fatal=False): ecs_uri", "put log events is not valid, %s' % e.response) return", "urlencode except ImportError: from urllib.request import urlopen, Request from urllib.error", "os.path.isdir(directory): raise @contextmanager def bootstrap_tls(config, init_system, dns_name, fs_id, mountpoint, options,", "'InvalidParameterException': logging.debug('Either parameter log group name %s or log stream", "if ap_id: ca_extension_str += '\\n1.3.6.1.4.1.4843.7.1 = ASN1:UTF8String:' + ap_id if", "% user_message) logging.error(log_message) publish_cloudwatch_log(CLOUDWATCHLOG_AGENT, 'Mount failed, %s' % log_message) sys.exit(exit_code)", "can be created, %s' % e.response) return False elif exception", "% \\ (not_before, not_after, certificate_config, certificate_signing_request, certificate) subprocess_call(cmd, 'Failed to", "name %s is specified incorrectly, %s' % (cloudwatchlog_agent.get('log_group_name'), cloudwatchlog_agent.get('log_stream_name'), e.response))", "+ '\\n' request += create_canonical_query_string(public_key_hash, credential, formatted_datetime, session_token) + '\\n'", "credentials and credentials_source: return credentials, credentials_source # attempt to lookup", "be fetched from the given aws_creds_uri if is_fatal: fatal_error(ecs_unsuccessful_resp, ecs_unsuccessful_resp)", "= get_aws_security_credentials_from_instance_metadata(iam_role_name) if credentials: return session.create_client(service, aws_access_key_id=credentials['AccessKeyId'], aws_secret_access_key=credentials['SecretAccessKey'], aws_session_token=credentials['Token'], region_name=region)", "'iam', 'netns', 'noocsp', 'ocsp', 'tls', 'tlsport', 'verify' ] UNSUPPORTED_OPTIONS =", "% fs_id, 'Failed to start TLS tunnel (errno=%d). stdout=\"%s\" stderr=\"%s\"'", "try: return config.get(CONFIG_SECTION, 'region') except NoOptionError: pass try: return get_region_from_instance_metadata()", "in current file and return 'default' if so try: access_key", "res = urlopen(req) return res.read() def get_aws_security_credentials(use_iam, awsprofile=None, aws_creds_uri=None): \"\"\"", "% (upper_bound, lower_bound)) return lower_bound, upper_bound def choose_tls_port(config, options): if", "!= expected_ct: raise ValueError('DNS name format has an incorrect number", "= '/aws/efs/utils' DEFAULT_RETENTION_DAYS = 14 # Cloudwatchlog agent dict includes", "tunnel dies - since this is not called from the", "'ocsp', 'tls', 'tlsport', 'verify' ] UNSUPPORTED_OPTIONS = [ 'capath' ]", "in options: options['hard'] = None if 'timeo' not in options:", "elif exception == 'OperationAbortedException': logging.debug('Multiple requests to update the same", "a valid DNS name for an EFS mount target. '", "= 'AWS_WEB_IDENTITY_TOKEN_FILE' STS_ENDPOINT_URL = 'https://sts.amazonaws.com/' INSTANCE_METADATA_TOKEN_URL = 'http://169.254.169.254/latest/api/token' INSTANCE_METADATA_SERVICE_URL =", "'credentials')) AWS_CONFIG_FILE = os.path.expanduser(os.path.join('~' + pwd.getpwuid(os.getuid()).pw_name, '.aws', 'config')) CA_CONFIG_BODY =", "NoOptionError: pass try: os.makedirs(directory, mode) except OSError as e: if", "ca_supporting_files_check(index_path, index_attr_path, serial_path, rand_path): \"\"\"Recreate all supporting openssl ca and", "CLOUDWATCHLOG_AGENT = bootstrap_cloudwatch_logging(config) def get_botocore_client(config, service): if not BOTOCORE_PRESENT: logging.error('Failed", "in os.environ and WEB_IDENTITY_TOKEN_FILE_ENV in os.environ: credentials, credentials_source = get_aws_security_credentials_from_webidentity(", "get_credential_scope(date, region) + '\\n' sha256 = hashlib.sha256() sha256.update(canonical_request.encode()) string_to_sign +=", "timeout=1) return get_resp_obj(request_resp, url, unsuccessful_resp) err_msg = 'Unable to reach", "- the next octets are the length - \"definite form\"", "'dns_name_format') if '{region}' not in dns_name_format: split_dns_name_format = dns_name_format.split('.') if", "fstab entry is: # # [Device] [Mount Point] [File System", "returncode=%d, stderr=\"%s\"' % (dns_name, mountpoint, proc.returncode, err.strip()) fatal_error(err.strip(), message, proc.returncode)", "the mount watchdog logging.info('Starting TLS tunnel: \"%s\"', ' '.join(tunnel_args)) tunnel_proc", "<= CLIENT_SOURCE_STR_LEN_LIMIT: client_info['source'] = client_source return client_info def create_certificate(config, mount_name,", "'\\n1.3.6.1.4.1.4843.7.2 = ASN1:SEQUENCE:efs_client_auth' ca_extension_str += '\\n1.3.6.1.4.1.4843.7.3 = ASN1:UTF8String:' + fs_id", "CA_CONFIG_BODY = \"\"\"dir = %s RANDFILE = $dir/database/.rand [ ca", "specifying a different port range in %s' % (lower_bound, upper_bound,", "if 'tls' in options: mount_path = '127.0.0.1:%s' % path else:", "is executable. # # You will be able to mount", "tls_paths = tls_paths_dictionary(mount_name, base_path) certificate_config = os.path.join(tls_paths['mount_dir'], 'config.conf') certificate_signing_request =", "exception = error.response['Error']['Code'] if exception == 'ServiceUnavailableException': logging.debug('The service cannot", "options and 'hard' not in options: options['hard'] = None if", "role name at %s.' % INSTANCE_IAM_URL iam_role_url_error_msg = 'Unable to", "to ensure that the private key is # atomically created,", "if tunnel_proc.returncode is not None: out, err = tunnel_proc.communicate() fatal_error('Failed", "credentials cannot be fetched from the given aws_creds_uri if is_fatal:", "['nsenter', '--net=' + options['netns']] + tunnel_args # launch the tunnel", "fs_id: log_stream_name = '%s - %s - mount.log' % (fs_id,", "f: f.write(full_config_body) return full_config_body def ca_extension_builder(ap_id, security_credentials, fs_id, client_info): ca_extension_str", "client_info.items(): efs_client_info_str += '\\n%s = UTF8String:%s' % (key, value) return", "matches exactly the DNS name the CNAME resolves to if", "'w+') as f: f.write('unique_subject = no') if not os.path.isfile(serial_path): with", "aws_creds_uri=None): \"\"\" Lookup AWS security credentials (access key ID and", "updated_time.strftime(CERT_DATETIME_FORMAT) def get_utc_now(): \"\"\" Wrapped for patching purposes in unit", "Leap' SKIP_NO_LIBWRAP_RELEASES = [RHEL8_RELEASE_NAME, CENTOS8_RELEASE_NAME, FEDORA_RELEASE_NAME, SUSE_RELEASE_NAME] def fatal_error(user_message, log_message=None,", "upper_bound = config.getint(CONFIG_SECTION, 'port_range_upper_bound') if lower_bound >= upper_bound: fatal_error('Configuration option", "'netns' in options: command = ['nsenter', '--net=' + options['netns']] +", "object: %s' % (instance_identity, e)) return None def get_region_from_legacy_dns_format(config): \"\"\"", "in log group %s' % (log_stream_name, log_group_name)) def create_cloudwatch_log_stream(cloudwatchlog_client, log_group_name,", "else: return config.getboolean(CONFIG_SECTION, 'stunnel_check_cert_validity') def get_mount_specific_filename(fs_id, mountpoint, tls_port): return '%s.%s.%d'", "'metadata:' else: return None, None def get_iam_role_name(): iam_role_unsuccessful_resp = 'Unsuccessful", "v) for k, v in options.items() if k not in", "'enabled'): return config.getboolean(CLOUDWATCH_LOG_SECTION, 'enabled') return False def cloudwatch_create_log_group_helper(cloudwatchlog_client, log_group_name): cloudwatchlog_client.create_log_group(", "= subprocess_call(cmd, 'Unable to ASN1 parse public key file, %s,", "rsa -in %s -outform PEM -pubout -out %s' % (private_key,", "e: fatal_error('Failed to locate %s in %s - %s' %", "CA_CONFIG_BODY % (directory, private_key, common_name, ca_extension_body, efs_client_auth_body, efs_client_info_body) with open(config_path,", "(message, e.response)) return False elif exception == 'UnrecognizedClientException': logging.debug('The most", "open(os.path.join(state_file_dir, state_file), 'w') as f: json.dump(state, f) return state_file def", "in AWS credentials file (~/.aws/credentials) # and configs file (~/.aws/config)", "'w') as devnull: subprocess.Popen(['/sbin/start', WATCHDOG_SERVICE], stdout=devnull, stderr=devnull, close_fds=True) elif 'start'", "options.split(','): if '=' in o: k, v = o.split('=') opts[k]", "region = get_target_region(config) iam_role_name = get_iam_role_name() if iam_role_name: credentials, _", "[%s] is not an integer' % options['tlsport']) if 'ocsp' in", "enable with IMDSv2, Unauthorized 401 error will be thrown, #", "directories (also create all intermediate directories if they don't exist).\"\"\"", "% (dns_name, 'https://docs.aws.amazon.com/console/efs/mount-dns-name'), 'Failed to resolve \"%s\"' % dns_name) return", "override the tlsport option so that we can later override", "file and metadata service call failed, falling back ' 'to", "man page as well at man/mount.efs.8 if 'nfsvers' not in", "required when mounting with \"awscredsuri\"') if 'awscredsuri' in options and", "name for certificate signing request is max 64 characters cert_details['commonName']", "!= 0: logging.error('Command %s failed, rc=%s, stdout=\"%s\", stderr=\"%s\"' % (cmd,", "= p.communicate() return output and 'nfs' in str(output) def mount_tls(config,", "sha256.update(canonical_request.encode()) string_to_sign += sha256.hexdigest() return string_to_sign def calculate_signature(string_to_sign, date, secret_access_key,", "logging.info('Created cloudwatch log group %s' % log_group_name) def create_cloudwatch_log_group(cloudwatchlog_client, log_group_name):", "length (which may be 0) as a number of octets", "will have its own ca mode assets due to lack", "ocsp_enabled: if ocsp_aia_supported: efs_config['OCSPaia'] = 'yes' else: fatal_error(tls_controls_message % 'stunnel_check_cert_validity')", "dns_name, verify_level, ocsp_enabled, options, cert_details=cert_details) tunnel_args = [_stunnel_bin(), stunnel_config_file] if", "== 'ResourceNotFoundException': logging.debug('Either log group %s or log stream %s", "+ iam_role_name unsuccessful_resp = 'Unsuccessful retrieval of AWS security credentials", "rc = subprocess.call(['systemctl', 'is-active', '--quiet', WATCHDOG_SERVICE], close_fds=True) if rc !=", "key = ''.join(lines) key = bytearray(base64.b64decode(key)) # Parse the public", "specified incorrectly, %s' % (log_group_name, log_stream_name, e.response)) return False elif", "< len(client_source) <= CLIENT_SOURCE_STR_LEN_LIMIT: client_info['source'] = client_source return client_info def", "headers={}, retry_with_new_header_token=False): try: req = Request(url) for k, v in", "v else: opts[o] = None return opts def get_tls_port_range(config): lower_bound", "e: logging.warning('Could not connect to the endpoint, %s' % e)", "\"noocsp\" options are mutually exclusive') if 'accesspoint' in options: if", "path else: create_default_cloudwatchlog_agent_if_not_exist(config) fatal_error('The specified CNAME \"%s\" did not resolve", "raise ValueError('DNS name format has an incorrect number of replacement", "cloudwatch_create_log_stream_helper(cloudwatchlog_client, log_group_name, log_stream_name): cloudwatchlog_client.create_log_stream( logGroupName=log_group_name, logStreamName=log_stream_name ) logging.info('Created cloudwatch log", "tunnel fails, exit uncleanly with os._exit \"\"\" while not mount_completed.is_set():", "body.' % (str(resp_body), e)) return resp_body if resp_body_type is str", "check_unsupported_options(options): for unsupported_option in UNSUPPORTED_OPTIONS: if unsupported_option in options: warn_message", "Rights Reserved. # # Licensed under the MIT License. See", "BIT STRING # Example: # 0:d=0 hl=4 l= 418 cons:", "'http://169.254.169.254/latest/meta-data/iam/security-credentials/' SECURITY_CREDS_ECS_URI_HELP_URL = 'https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html' SECURITY_CREDS_WEBIDENTITY_HELP_URL = 'https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html' SECURITY_CREDS_IAM_ROLE_HELP_URL = 'https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html'", "\"tls\" option is required when mounting via \"iam\"') if 'awsprofile'", "= '\\n'.join(['%s:%s' % (k, v) for k, v in sorted(CANONICAL_HEADERS_DICT.items())])", "None return { 'client': cloudwatchlog_client, 'log_group_name': log_group_name, 'log_stream_name': log_stream_name }", "init_system def check_network_target(fs_id): with open(os.devnull, 'w') as devnull: rc =", "[AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE]: if os.path.exists(file_path): credentials = credentials_file_helper(file_path, awsprofile) if credentials['AccessKeyId']:", "% (log_group_name, e.response)) return False else: handle_general_botocore_exceptions(e) return False except", "= options.get('accesspoint') cert_details = {} security_credentials = None client_info =", "retrieve AWS security credentials. See %s for more info.' \\", "efs_config['OCSPaia'] = 'yes' else: fatal_error(tls_controls_message % 'stunnel_check_cert_validity') system_release_version = get_system_release_version()", "WEB_IDENTITY_TOKEN_FILE_ENV = 'AWS_WEB_IDENTITY_TOKEN_FILE' STS_ENDPOINT_URL = 'https://sts.amazonaws.com/' INSTANCE_METADATA_TOKEN_URL = 'http://169.254.169.254/latest/api/token' INSTANCE_METADATA_SERVICE_URL", "options.get('awscredsuri') if aws_creds_uri: kwargs = {'aws_creds_uri': aws_creds_uri} else: kwargs =", "'InvalidParameterException': logging.debug('One of the parameter to put log events is", "metadata_exception = e logging.warning('Region not found in config file and", "expected_dns_name = get_dns_name(config, fs_id) # check that the DNS name", "ValueError: remote = device path = '/' if FS_ID_RE.match(remote): return", "or not cloudwatchlog_agent.get('client'): return False token = get_log_stream_next_token(cloudwatchlog_agent) try: cloudwatch_put_log_events_helper(cloudwatchlog_agent,", "command, files, state_file_dir, cert_details=None): \"\"\" Return the name of the", "Parse the public key to pull out the actual key", "retention_days) if not put_retention_policy_completed: return None stream_creation_completed = create_cloudwatch_log_stream(cloudwatchlog_client, log_group_name,", "] UNSUPPORTED_OPTIONS = [ 'capath' ] STUNNEL_GLOBAL_CONFIG = { 'fips':", "fatal_error(error_msg, error_msg) def get_aws_security_credentials_from_awsprofile(awsprofile, is_fatal=False): for file_path in [AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE]:", "in options ap_id = options.get('accesspoint') cert_details = {} security_credentials =", "if resp_body_type is str else resp_body.decode('utf-8') def parse_options(options): opts =", "log_group_name, log_stream_name) if not stream_creation_completed: return None return { 'client':", "following a successful mount. \"\"\" state_file = '~' + get_mount_specific_filename(fs_id,", "return None, None def get_iam_role_name(): iam_role_unsuccessful_resp = 'Unsuccessful retrieval of", "credentials['AccessKeyId']: return credentials, os.path.basename(file_path) + ':' + awsprofile # Fail", "'error': logging.ERROR, 'critical': logging.CRITICAL } level = levels.get(raw_level.lower()) level_error =", "asn1parse -inform PEM -in %s' % public_key output, err =", "is not a json object: %s' % (instance_identity, e)) return", "secret_key = aws_credentials_configs.get(awsprofile, 'aws_secret_access_key') session_token = aws_credentials_configs.get(awsprofile, 'aws_session_token') credentials['AccessKeyId'] =", "fs_id, mountpoint, options): if os.path.ismount(mountpoint) and is_nfs_mount(mountpoint): sys.stdout.write(\"%s is already", "= subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) (output, err) = process.communicate() rc", "[_stunnel_bin(), stunnel_config_file] if 'netns' in options: tunnel_args = ['nsenter', '--net='", "= os.path.join(directory, 'publicKey.pem') ca_extension_body = ca_extension_builder(ap_id, security_credentials, fs_id, client_info) efs_client_auth_body", "} if cert_details: state.update(cert_details) with open(os.path.join(state_file_dir, state_file), 'w') as f:", "WATCHDOG_SERVICE], close_fds=True) if rc != 0: with open(os.devnull, 'w') as", "CLOUDWATCHLOG_AGENT: CLOUDWATCHLOG_AGENT = bootstrap_cloudwatch_logging(config) def get_botocore_client(config, service): if not BOTOCORE_PRESENT:", "private_key, csr_path): cmd = 'openssl req -new -config %s -key", "socket.gaierror: fatal_error('Failed to resolve \"%s\" - check that your file", "of unused bits (1) offset = 1 + 1 +", "'certificate.pem') cert_details['privateKey'] = get_private_key_path() cert_details['fsId'] = fs_id start_watchdog(init_system) if not", "logging.INFO max_bytes = config.getint(CONFIG_SECTION, 'logging_max_bytes') file_count = config.getint(CONFIG_SECTION, 'logging_file_count') handler", "None, None webidentity_url = STS_ENDPOINT_URL + '?' + urlencode({ 'Version':", "\"\"\" # SigV4 Auth ALGORITHM = 'AWS4-HMAC-SHA256' AWS4_REQUEST = 'aws4_request'", "+ signature efs_client_auth_str += '\\nsigv4DateTime = UTCTIME:' + date.strftime(CERT_DATETIME_FORMAT) if", "not cloudwatchlog_agent.get('client'): return False token = get_log_stream_next_token(cloudwatchlog_agent) try: cloudwatch_put_log_events_helper(cloudwatchlog_agent, message,", "ap_id: ca_extension_str += '\\n1.3.6.1.4.1.4843.7.1 = ASN1:UTF8String:' + ap_id if security_credentials:", "backupCount=file_count) handler.setFormatter(logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(message)s')) logger = logging.getLogger() logger.setLevel(level)", "by adding it # to /etc/fstab. The syntax of an", "and use_iam: for file_path in [AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE]: aws_credentials_configs = read_config(file_path)", "'Failed to mount %s at %s: returncode=%d, stderr=\"%s\"' % (dns_name,", "# source key/value pair in config file if config.has_option(CLIENT_INFO_SECTION, 'source'):", "it following the instructions at ' 'https://docs.aws.amazon.com/efs/latest/ug/using-amazon-efs-utils.html#upgrading-stunnel') def find_command_path(command, install_method):", "SYSTEM_RELEASE_PATH) try: with open(OS_RELEASE_PATH) as f: for line in f:", "certificate) subprocess_call(cmd, 'Failed to create self-signed client-side certificate') return current_time.strftime(CERT_DATETIME_FORMAT)", "if ap_id: cert_details['accessPoint'] = ap_id # additional symbol appended to", "in dns_name_format') def get_aws_ec2_metadata_token(): try: opener = build_opener(HTTPHandler) request =", "0: with open(os.devnull, 'w') as devnull: subprocess.Popen(['systemctl', 'start', WATCHDOG_SERVICE], stdout=devnull,", "= get_aws_ec2_metadata_token() req.add_header('X-aws-ec2-metadata-token', token) request_resp = urlopen(req, timeout=1) return get_resp_obj(request_resp,", "] CN = supplied [ req ] prompt = no", "profile [%s]', file_path, awsprofile) if 'aws_session_token' in str(e): logging.debug('aws_session_token not", "'logEvents': [ { 'timestamp': int(round(time.time() * 1000)), 'message': message }", "os.write(f, lock_file_contents.encode('utf-8')) yield f finally: os.close(f) os.remove(lock_file) def do_with_lock(function): while", "# Copyright 2017-2018 Amazon.com, Inc. and its affiliates. All Rights", "aws_credentials_configs.get(awsprofile, 'aws_secret_access_key') session_token = aws_credentials_configs.get(awsprofile, 'aws_session_token') credentials['AccessKeyId'] = access_key credentials['SecretAccessKey']", "except ImportError: BOTOCORE_PRESENT = False VERSION = '1.28.2' SERVICE =", "False elif exception == 'InvalidParameterException': logging.debug('One of the parameter to", "except TypeError as e: logging.warning('response %s is not a json", "file. Unfortunately this does not conform to Python's config file", "dns_name) return dns_name def tls_paths_dictionary(mount_name, base_path=STATE_FILE_DIR): tls_dict = { 'mount_dir':", "not properly configured, %s' % e) return False except EndpointConnectionError", "else '' full_config_body = CA_CONFIG_BODY % (directory, private_key, common_name, ca_extension_body,", "tls_paths_dictionary(mount_name, base_path) certificate_config = os.path.join(tls_paths['mount_dir'], 'config.conf') certificate_signing_request = os.path.join(tls_paths['mount_dir'], 'request.csr')", "range(retry_times): process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) (output, err) =", "a random midpoint, and then try ports in-order from there", "credentials at %s.' % ecs_uri ecs_url_error_msg = 'Unable to reach", "URLError as e: err_msg = 'Unable to reach the url", "Licensed under the MIT License. See the LICENSE accompanying this", "# - 00 - no unused bits in the last", "backwards compatibility check dns_name_format to obtain the target region. This", "'-o', get_nfs_mount_options(options)] if 'netns' in options: command = ['nsenter', '--net='", "13 cons: SEQUENCE # 6:d=2 hl=2 l= 9 prim: OBJECT", "the following octets encode, as big-endian, the length (which may", "f) return state_file def test_tunnel_process(tunnel_proc, fs_id): tunnel_proc.poll() if tunnel_proc.returncode is", "= e.response['Error']['Code'] if exception == 'ResourceAlreadyExistsException': logging.debug('Log group %s already", "= %s cert = $dir/certificate.pem new_certs_dir = $dir/certs default_md =", "detail.' % (dns_name, 'https://docs.aws.amazon.com/console/efs/mount-dns-name'), 'Failed to resolve \"%s\"' % dns_name)", "_validate_replacement_field_count(dns_name_format, expected_replacement_field_ct) dns_name = dns_name_format.format(**format_args) try: socket.gethostbyname(dns_name) except socket.gaierror: fatal_error('Failed", "BOTOCORE_PRESENT = False VERSION = '1.28.2' SERVICE = 'elasticfilesystem' CONFIG_FILE", "contextmanager from datetime import datetime, timedelta from logging.handlers import RotatingFileHandler", "Using the 'efs' type will cause '/sbin/mount.efs' to be called", "that we have to include a locking mechanism to ensure", "else: try: stunnel_cafile = config.get(CONFIG_SECTION, 'stunnel_cafile') except NoOptionError: logging.debug('No CA", "e.reason) if err_msg: logging.debug('%s %s', url_error_msg, err_msg) return None def", "(command, env_path, install_method), e) return path.strip().decode() def get_system_release_version(): try: with", "and certs directories exist and if not, create directories (also", "retry_with_new_header_token=True) if iam_security_dict and all(k in iam_security_dict for k in", "at %s' % (dns_name, mountpoint) logging.info(message) publish_cloudwatch_log(CLOUDWATCHLOG_AGENT, message) else: message", "k in CREDENTIALS_KEYS): return ecs_security_dict, 'ecs:' + aws_creds_uri # Fail", "log_group_name, log_stream_name): cloudwatchlog_client.create_log_stream( logGroupName=log_group_name, logStreamName=log_stream_name ) logging.info('Created cloudwatch log stream", "fs_id, mountpoint, options) else: mount_nfs(dns_name, path, mountpoint, options) if '__main__'", "networked file system type. This has been tested with systemd", "the network was not yet available, add \"_netdev\" to your", "v in config.items(): if type(v) is list: for item in", "options) # override the tlsport option so that we can", "tls_port, dns_name, verify_level, ocsp_enabled, options, cert_details=cert_details) tunnel_args = [_stunnel_bin(), stunnel_config_file]", "For a BIT STRING, the first octet of the value", "in openssl 'database_dir': os.path.join(base_path, mount_name, 'database'), 'certs_dir': os.path.join(base_path, mount_name, 'certs'),", "valid EFS DNS ' 'name' % remote, 'Failed to resolve", "type(v) is list: for item in v: lines.append('%s = %s'", "to follow (ignore high order bit) # - 018f -", "ecs_url_error_msg = 'Unable to reach %s to retrieve AWS security", "v = o.split('=') opts[k] = v else: opts[o] = None", "stdout=devnull, stderr=devnull, close_fds=True) else: logging.debug('%s is already running', WATCHDOG_SERVICE) else:", "response['logStreams'][0] return log_stream.get('uploadSequenceToken') except (IndexError, TypeError, KeyError): pass return None", "(log_group_name, e.response)) return False else: handle_general_botocore_exceptions(e) return False except NoCredentialsError", "len(tls_ports) == len(ports_to_try) sock = socket.socket() for tls_port in ports_to_try:", "0) as a number of octets # - the remaining", "the endpoint, %s' % e) return False except Exception as", "'efs')) logging.debug('Writing stunnel configuration:\\n%s', stunnel_config) stunnel_config_file = os.path.join(state_file_dir, 'stunnel-config.%s' %", "sys.stderr.write('%s\\n' % error_message) logging.warning(error_message) def create_required_directory(config, directory): mode = 0o750", "= 'elasticfilesystem' CONFIG_FILE = '/etc/amazon/efs/efs-utils.conf' CONFIG_SECTION = 'mount' CLIENT_INFO_SECTION =", "CANONICAL_HEADERS_DICT = { 'host': '%s' } CANONICAL_HEADERS = '\\n'.join(['%s:%s' %", "service' % \\ (AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE) fatal_error(error_msg, error_msg) def get_aws_security_credentials_from_awsprofile(awsprofile, is_fatal=False):", "is not set if ocsp_enabled: if ocsp_aia_supported: efs_config['OCSPaia'] = 'yes'", "or log stream name %s is specified incorrectly, %s' %", "str(e) or 'aws_secret_access_key' in str(e): logging.debug('aws_access_key_id or aws_secret_access_key not found", "if not hostnames: create_default_cloudwatchlog_agent_if_not_exist(config) fatal_error( 'The specified domain name \"%s\"", "for more detail.' % (CONFIG_FILE, 'https://docs.aws.amazon.com/console/efs/troubleshooting-tls') if config.getboolean(CONFIG_SECTION, 'stunnel_check_cert_hostname'): if", "'logStreamName': cloudwatchlog_agent.get('log_stream_name'), 'logEvents': [ { 'timestamp': int(round(time.time() * 1000)), 'message':", "fatal_error('tlsport option [%s] is not an integer' % options['tlsport']) if", "options: if 'tls' not in options: fatal_error('The \"tls\" option is", "conditions only\"\"\" if args is None: args = sys.argv if", "CLIENT_INFO_SECTION = 'client-info' CLIENT_SOURCE_STR_LEN_LIMIT = 100 CLOUDWATCH_LOG_SECTION = 'cloudwatch-log' DEFAULT_CLOUDWATCH_LOG_GROUP", "%s', OS_RELEASE_PATH) return 'unknown' def write_stunnel_config_file(config, state_file_dir, fs_id, mountpoint, tls_port,", "LOG_FILE = 'mount.log' STATE_FILE_DIR = '/var/run/efs' PRIVATE_KEY_FILE = '/etc/amazon/efs/privateKey.pem' DATE_ONLY_FORMAT", "an entry like this: # # fs-deadbeef /mount_point efs _netdev", "ms') time.sleep(0.05) else: raise def generate_key(): if os.path.isfile(key): return cmd", "mounting with named profile option, \"awsprofile\"') if 'awscredsuri' in options", "the last # content byte. Note that this is explicitly", "tunnel_proc.pid) temp_tls_state_file = write_tls_tunnel_state_file(fs_id, mountpoint, tls_port, tunnel_proc.pid, tunnel_args, [stunnel_config_file], state_file_dir,", "- 00 - no unused bits in the last content", "+ pwd.getpwuid(os.getuid()).pw_name, '.aws', 'credentials')) AWS_CONFIG_FILE = os.path.expanduser(os.path.join('~' + pwd.getpwuid(os.getuid()).pw_name, '.aws',", "% (log_group_name, retention_days, e.response)) return False else: handle_general_botocore_exceptions(e) return False", "= 'openssl ca -startdate %s -enddate %s -selfsign -batch -notext", "certificate_config, certificate_signing_request, certificate) subprocess_call(cmd, 'Failed to create self-signed client-side certificate')", "set if ocsp_enabled: if ocsp_aia_supported: efs_config['OCSPaia'] = 'yes' else: fatal_error(tls_controls_message", "resolve to a valid DNS name for an EFS mount", "+ 1 + num_length_octets + 1 key = key[offset:] sha1", "device): \"\"\"Return the EFS id and the remote path to", "check_host_supported, ocsp_aia_supported def _stunnel_bin(): return find_command_path('stunnel', 'Please install it following", "[-h|--help] <fsname> <mountpoint> [-o <options>]\\n') sys.exit(exit_code) def parse_arguments_early_exit(args=None): \"\"\"Parse arguments,", "'dns_name_format') if '{fs_id}' not in dns_name_format: raise ValueError('DNS name format", "will be thrown, # to retrieve metadata, the header should", "message = 'Failed to mount %s at %s: returncode=%d, stderr=\"%s\"'", "(dns_name, mountpoint, proc.returncode, err.strip()) fatal_error(err.strip(), message, proc.returncode) def usage(out, exit_code=1):", "not provided in fstab. import base64 import errno import hashlib", "aws_credentials_configs.get(awsprofile, 'aws_access_key_id') secret_key = aws_credentials_configs.get(awsprofile, 'aws_secret_access_key') session_token = aws_credentials_configs.get(awsprofile, 'aws_session_token')", "subprocess_call(cmd, 'Failed to create certificate signing request (csr)') def create_ca_conf(config_path,", "stunnel_cafile = config.get(CONFIG_SECTION, 'stunnel_cafile') except NoOptionError: logging.debug('No CA file configured,", "not supported and has been ignored, as amazon-efs-utils relies on", "string_to_sign = create_string_to_sign(canonical_request, date, region) signature = calculate_signature(string_to_sign, date, secret_access_key,", "'PID: %s' % os.getpid() os.write(f, lock_file_contents.encode('utf-8')) yield f finally: os.close(f)", "sys.stdout.write('Warning: region obtained from \"dns_name_format\" field. Please set the \"region\"", "hash is included in canonical request to tie the signature", "proc.communicate() if 'stop' in status: with open(os.devnull, 'w') as devnull:", "' 'Please refer to the EFS documentation for mounting with", "value in client_info.items(): efs_client_info_str += '\\n%s = UTF8String:%s' % (key,", "can be killed easily by the mount watchdog logging.info('Starting TLS", "(log_stream_name, log_group_name, e.response)) return True elif exception == 'InvalidParameterException': logging.error('Either", "# attempt to lookup AWS security credentials through AssumeRoleWithWebIdentity #", "start TLS tunnel (errno=%d). stdout=\"%s\" stderr=\"%s\"' % (tunnel_proc.returncode, out.strip(), err.strip()))", "get_resp_obj(request_resp, url, unsuccessful_resp) except HTTPError as e: # For instance", "% options['tlsport']) else: fatal_error('Failed to locate an available port in", "check for region in \"dns_name_format\" failed') _fatal_error(metadata_exception) def get_region_from_instance_metadata(): instance_identity", "'systemd': rc = subprocess.call(['systemctl', 'is-active', '--quiet', WATCHDOG_SERVICE], close_fds=True) if rc", "to lookup AWS security credentials with IAM role name attached", "] database = $dir/database/index.txt serial = $dir/database/serial private_key = %s", "in fstab, the file system can be mounted with: #", "NOT_BEFORE_MINS = 15 NOT_AFTER_HOURS = 3 EFS_ONLY_OPTIONS = [ 'accesspoint',", "'tls' in options: mount_tls(config, init_system, dns_name, path, fs_id, mountpoint, options)", "'logs') if not cloudwatchlog_client: return None cloudwatchlog_config = get_cloudwatchlog_config(config, fs_id)", "first octet of the value is used to signify the", "return { 'client': cloudwatchlog_client, 'log_group_name': log_group_name, 'log_stream_name': log_stream_name } def", "that we can later override the port the NFS client", "os.path.join(base_path, mount_name, 'database/serial'), 'rand': os.path.join(base_path, mount_name, 'database/.rand') } return tls_dict", "session_token=None): \"\"\" Create a Canonical Request - https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html \"\"\" formatted_datetime", "in args[1:]: usage(out=sys.stdout, exit_code=0) if '--version' in args[1:]: sys.stdout.write('%s Version:", "to an EFS mount target' % remote ) for hostname", "the CNAME resolves to if hostname == expected_dns_name: return fs_id,", "retention_days): try: cloudwatch_put_retention_policy_helper(cloudwatchlog_client, log_group_name, retention_days) except ClientError as e: exception", "return res.read() except NameError: headers = {'X-aws-ec2-metadata-token-ttl-seconds': 21600} req =", "True break if not supported: logging.warning('stunnel does not support \"%s\"',", "get_instance_identity_info_from_instance_metadata('instanceId') if instance_id and fs_id: log_stream_name = '%s - %s", "to initialize TLS tunnel for %s' % fs_id, 'Failed to", "examples: %s' % (remote, 'https://docs.aws.amazon.com/efs/latest/ug/mounting-fs-mount-cmd-dns-name.html')) def is_nfs_mount(mountpoint): cmd = ['stat',", "RHEL8_RELEASE_NAME = 'Red Hat Enterprise Linux release 8' CENTOS8_RELEASE_NAME =", "cert_details['commonName'] = socket.gethostname()[0:64] cert_details['region'] = get_target_region(config) cert_details['certificateCreationTime'] = create_certificate(config, cert_details['mountStateDir'],", "EC2 instance metadata.' % INSTANCE_METADATA_SERVICE_URL instance_identity = url_request_helper(INSTANCE_METADATA_SERVICE_URL, ec2_metadata_unsuccessful_resp, ec2_metadata_url_error_msg,", "processes, they can be killed easily by the mount watchdog", "k not in EFS_ONLY_OPTIONS] return ','.join(nfs_options) def mount_nfs(dns_name, path, mountpoint,", "get_instance_identity_info_from_instance_metadata(property): ec2_metadata_unsuccessful_resp = 'Unsuccessful retrieval of EC2 metadata at %s.'", "== 'ResourceNotFoundException': logging.error('Log group %s does not exist, %s' %", "in days %s is specified incorrectly, %s' % (log_group_name, retention_days,", "Key ID and Secret Access Key are not found in", "try: log_stream = response['logStreams'][0] return log_stream.get('uploadSequenceToken') except (IndexError, TypeError, KeyError):", "subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) (output, err) = process.communicate() rc =", "if os.geteuid() != 0: sys.stderr.write('only root can run mount.efs\\n') sys.exit(1)", "and has been ignored, as amazon-efs-utils relies on a built-in", "status, _ = proc.communicate() if 'stop' in status: with open(os.devnull,", "logging.debug('Unable to read %s', SYSTEM_RELEASE_PATH) try: with open(OS_RELEASE_PATH) as f:", "= '/etc/system-release' OS_RELEASE_PATH = '/etc/os-release' RHEL8_RELEASE_NAME = 'Red Hat Enterprise", "we will create one private key and allow mounts to", "Python's config file format, so we have to hand-serialize it.", "% INSTANCE_IAM_URL iam_role_url_error_msg = 'Unable to reach %s to retrieve", "= 'Unable to reach %s to retrieve EC2 instance metadata.'", "order bit) # - 018f - length of 399 #", "aws_credentials_configs = read_config(file_path) # check if aws access key id", "fresh configurations at every mount since SigV4 signature can change\"\"\"", "message) metadata_exception = 'Unknown error' try: return config.get(CONFIG_SECTION, 'region') except", "'Failed to resolve \"%s\"' % remote ) if not hostnames:", "fatal_error(user_message, log_message=None, exit_code=1): if log_message is None: log_message = user_message", "credentials: return session.create_client(service, aws_access_key_id=credentials['AccessKeyId'], aws_secret_access_key=credentials['SecretAccessKey'], aws_session_token=credentials['Token'], region_name=region) return session.create_client(service, region_name=region)", "date.strftime(CERT_DATETIME_FORMAT) if session_token: efs_client_auth_str += '\\nsessionToken = EXPLICIT:0,UTF8String:' + session_token", "urllib.request import urlopen, Request from urllib.error import URLError, HTTPError from", "args[1:]: sys.stdout.write('%s Version: %s\\n' % (args[0], VERSION)) sys.exit(0) def parse_arguments(config,", "retrieval of IAM role name at %s.' % INSTANCE_IAM_URL iam_role_url_error_msg", "out.strip(), err.strip())) def poll_tunnel_process(tunnel_proc, fs_id, mount_completed): \"\"\" poll the tunnel", "ca_extension_str = '[ v3_ca ]\\nsubjectKeyIdentifier = hash' if ap_id: ca_extension_str", "finally: os.rename(os.path.join(state_file_dir, temp_tls_state_file), os.path.join(state_file_dir, temp_tls_state_file[1:])) def get_nfs_mount_options(options): # If you", "+= '\\n%s = UTF8String:%s' % (key, value) return efs_client_info_str def", "get_system_release_version(): try: with open(SYSTEM_RELEASE_PATH) as f: return f.read().strip() except IOError:", "return credentials def get_aws_profile(options, use_iam): awsprofile = options.get('awsprofile') if not", "mode) except OSError as e: if errno.EEXIST != e.errno or", "mount attempt to fail fast if the tunnel dies -", "Request, HTTPHandler from urllib import urlencode except ImportError: from urllib.request", "% (log_stream_name, log_group_name)) def create_cloudwatch_log_stream(cloudwatchlog_client, log_group_name, log_stream_name): try: cloudwatch_create_log_stream_helper(cloudwatchlog_client, log_group_name,", "dns_name_format') def get_aws_ec2_metadata_token(): try: opener = build_opener(HTTPHandler) request = Request(INSTANCE_METADATA_TOKEN_URL)", "efs_client_auth ]' efs_client_auth_str += '\\naccessKeyId = UTF8String:' + access_key_id efs_client_auth_str", "exactly the DNS name the CNAME resolves to if hostname", "url, unsuccessful_resp): if request_resp.getcode() != 200: logging.debug(unsuccessful_resp + ' %s:", "formatted_datetime = date.strftime(SIGV4_DATETIME_FORMAT) credential = quote_plus(access_key + '/' + get_credential_scope(date,", "options: command = ['nsenter', '--net=' + options['netns']] + command logging.info('Executing:", "00 - no unused bits in the last content byte", "session_token: canonical_query_params['X-Amz-Security-Token'] = quote_plus(session_token) # Cannot use urllib.urlencode because it", "'%s.%s.%d' % (fs_id, os.path.abspath(mountpoint).replace(os.sep, '.').lstrip('.'), tls_port) def serialize_stunnel_config(config, header=None): lines", "unsuccessful_resp) else: return None, None def get_aws_security_credentials_from_instance_metadata(iam_role_name): security_creds_lookup_url = INSTANCE_IAM_URL", "region): \"\"\" Calculate the Signature - https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html \"\"\" def _sign(key,", "DEFAULT_RETENTION_DAYS if config.has_option(CLOUDWATCH_LOG_SECTION, 'retention_in_days'): retention_days = config.get(CLOUDWATCH_LOG_SECTION, 'retention_in_days') log_stream_name =", "# content byte. Note that this is explicitly excluded from", "own ca mode assets due to lack of multi-threading support", "def get_botocore_client(config, service): if not BOTOCORE_PRESENT: logging.error('Failed to import botocore,", "resp_body_type = type(resp_body) try: if resp_body_type is str: resp_dict =", "% mount_filename) with open(stunnel_config_file, 'w') as f: f.write(stunnel_config) return stunnel_config_file", "logging.error('Either parameter log group name %s or log stream name", "cert_details['privateKey'] = get_private_key_path() cert_details['fsId'] = fs_id start_watchdog(init_system) if not os.path.exists(state_file_dir):", "\"\"\"Wrapped for mocking purposes in unit tests\"\"\" return PRIVATE_KEY_FILE def", "the License. # # # Copy this script to /sbin/mount.efs", "security credentials. See %s for more info.' % \\ (STS_ENDPOINT_URL,", "return supported def get_version_specific_stunnel_options(): stunnel_command = [_stunnel_bin(), '-help'] proc =", "return False except NoCredentialsError as e: logging.warning('Credentials are not properly", "% (k, v) for k, v in sorted(canonical_query_params.items())]) def create_string_to_sign(canonical_request,", "the subprocess has exited already pass else: return output, err", "group %s' % (log_stream_name, log_group_name)) def create_cloudwatch_log_stream(cloudwatchlog_client, log_group_name, log_stream_name): try:", "setting if the override is not set if ocsp_enabled: if", "base64 import errno import hashlib import hmac import json import", "in options: try: int(options['tlsport']) except ValueError: fatal_error('tlsport option [%s] is", "in config file and metadata service call failed, falling back", "retry_with_new_header_token=True) if instance_identity: try: return instance_identity[property] except KeyError as e:", "certificate') return current_time.strftime(CERT_DATETIME_FORMAT) def get_private_key_path(): \"\"\"Wrapped for mocking purposes in", "create_cloudwatch_log_group(cloudwatchlog_client, log_group_name) if not group_creation_completed: return None put_retention_policy_completed = put_cloudwatch_log_retention_policy(cloudwatchlog_client,", "fs_id, client_info): ca_extension_str = '[ v3_ca ]\\nsubjectKeyIdentifier = hash' if", "ecs_uri = ECS_TASK_METADATA_API + aws_creds_uri ecs_unsuccessful_resp = 'Unsuccessful retrieval of", "credentials provider chain from: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html and https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html \"\"\" if not", "to stunnel. # if the user has specified tlsport=X at", "usage(out=sys.stderr) fs_id, path = match_device(config, fsname) return fs_id, path, mountpoint,", "client_info) create_certificate_signing_request(certificate_config, private_key, certificate_signing_request) not_before = get_certificate_timestamp(current_time, minutes=-NOT_BEFORE_MINS) not_after =", "Sign - https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html \"\"\" string_to_sign = ALGORITHM + '\\n' string_to_sign", "# # Example: # 0382018f00...<subjectPublicKey> # - 03 - BIT", "\"tls\" option is required when mounting via \"accesspoint\"') if not", "cannot be fetched from the given aws_creds_uri if is_fatal: fatal_error(ecs_unsuccessful_resp,", "def efs_client_info_builder(client_info): efs_client_info_str = '[ efs_client_info ]' for key, value", "' 'name' % remote, 'Failed to resolve \"%s\"' % remote", "out.write('Usage: mount.efs [--version] [-h|--help] <fsname> <mountpoint> [-o <options>]\\n') sys.exit(exit_code) def", "ecs_unsuccessful_resp = 'Unsuccessful retrieval of AWS security credentials at %s.'", "socket.error: continue sock.close() if 'tlsport' in options: fatal_error('Specified port [%s]", "else: logging.debug('%s is already running', WATCHDOG_SERVICE) else: error_message = 'Could", "% (url, e.code, e.reason) except URLError as e: err_msg =", "%s or log stream %s does not exist, %s' %", "# Exclude the tag (1), length (1 + num_length_octets), and", "found in AWS credentials file (%s), config file (%s), '", "CLIENT_SOURCE_STR_LEN_LIMIT = 100 CLOUDWATCH_LOG_SECTION = 'cloudwatch-log' DEFAULT_CLOUDWATCH_LOG_GROUP = '/aws/efs/utils' DEFAULT_RETENTION_DAYS", "in options and 'awsprofile' in options: fatal_error('The \"awscredsuri\" and \"awsprofile\"", "mount_nfs(dns_name, path, mountpoint, options) mount_completed.set() t.join() def check_unsupported_options(options): for unsupported_option", "config.has_section(region_specific_config_section): config_section = region_specific_config_section format_args['dns_name_suffix'] = config.get(config_section, 'dns_name_suffix') logging.debug(\"Using dns_name_suffix", "'a:SO_BINDTODEVICE=lo', ], } STUNNEL_EFS_CONFIG = { 'client': 'yes', 'accept': '127.0.0.1:%s',", "% ecs_uri ecs_url_error_msg = 'Unable to reach %s to retrieve", "= 'amazon-efs-mount-watchdog' SYSTEM_RELEASE_PATH = '/etc/system-release' OS_RELEASE_PATH = '/etc/os-release' RHEL8_RELEASE_NAME =", "install_method): try: env_path = '/sbin:/usr/sbin:/usr/local/sbin:/root/bin:/usr/local/bin:/usr/bin:/bin' os.putenv('PATH', env_path) path = subprocess.check_output(['which',", "'stunnel_check_cert_hostname'): if check_host_supported: efs_config['checkHost'] = dns_name else: fatal_error(tls_controls_message % 'stunnel_check_cert_hostname')", "(errno=%d). stdout=\"%s\" stderr=\"%s\"' % (tunnel_proc.returncode, out.strip(), err.strip())) def poll_tunnel_process(tunnel_proc, fs_id,", "as f: for line in f: if 'PRETTY_NAME' in line:", "% \\ (security_creds_lookup_url, SECURITY_CREDS_IAM_ROLE_HELP_URL) iam_security_dict = url_request_helper(security_creds_lookup_url, unsuccessful_resp, url_error_msg, retry_with_new_header_token=True)", "ca_dirs_check(config, database_dir, certs_dir): \"\"\"Check if mount's database and certs directories", "iam_security_dict, 'metadata:' else: return None, None def get_iam_role_name(): iam_role_unsuccessful_resp =", "['AccessKeyId', 'SecretAccessKey', 'Token'] ECS_URI_ENV = 'AWS_CONTAINER_CREDENTIALS_RELATIVE_URI' ECS_TASK_METADATA_API = 'http://169.254.170.2' WEB_IDENTITY_ROLE_ARN_ENV", "close_fds=True) if rc != 0: fatal_error('Failed to mount %s because", "if init_system != 'systemd': logging.debug('Not testing network on non-systemd init", "def cloudwatch_create_log_stream_helper(cloudwatchlog_client, log_group_name, log_stream_name): cloudwatchlog_client.create_log_stream( logGroupName=log_group_name, logStreamName=log_stream_name ) logging.info('Created cloudwatch", "INSTANCE_IAM_URL + iam_role_name unsuccessful_resp = 'Unsuccessful retrieval of AWS security", "locking mechanism to ensure that the private key is #", "cert_details['commonName'], cert_details['region'], fs_id, security_credentials, ap_id, client_info, base_path=state_file_dir) cert_details['certificate'] = os.path.join(state_file_dir,", "= { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR,", "# for this file system. The '_netdev' option tells the", "creation lock, sleeping 50 ms') time.sleep(0.05) else: raise def generate_key():", "with open(os.path.join(state_file_dir, state_file), 'w') as f: json.dump(state, f) return state_file", "Length, Value) # - the first octet (byte) is the", "with systemd # (Amazon Linux 2, CentOS 7, RHEL 7,", "available, add \"_netdev\" to your mount options' % fs_id, exit_code=0)", "subprocess_call(cmd, error_message): \"\"\"Helper method to run shell openssl command and", "Add an entry like this: # # fs-deadbeef /mount_point efs", "not check_if_cloudwatch_log_enabled(config): return None cloudwatchlog_client = get_botocore_client(config, 'logs') if not", "= subprocess.Popen( tunnel_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, preexec_fn=os.setsid, close_fds=True) logging.info('Started TLS tunnel,", "hmac import json import logging import os import pwd import", "= efsPolicy x509_extensions = v3_ca [ efsPolicy ] CN =", "the key BIT STRING # Example: # 0:d=0 hl=4 l=", "-notext -config %s -in %s -out %s' % \\ (not_before,", "\"\"\" return datetime.utcnow() def assert_root(): if os.geteuid() != 0: sys.stderr.write('only", "f: f.write(stunnel_config) return stunnel_config_file def write_tls_tunnel_state_file(fs_id, mountpoint, tls_port, tunnel_pid, command,", "in dns_name_format: expected_replacement_field_ct += 1 config_section = CONFIG_SECTION region =", "options and 'noocsp' in options: fatal_error('The \"ocsp\" and \"noocsp\" options", "None: log_message = user_message sys.stderr.write('%s\\n' % user_message) logging.error(log_message) publish_cloudwatch_log(CLOUDWATCHLOG_AGENT, 'Mount", "' '.join(command)) proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) out, err", "token: kwargs['sequenceToken'] = token cloudwatchlog_agent.get('client').put_log_events(**kwargs) def publish_cloudwatch_log(cloudwatchlog_agent, message): if not", "credentials_source if ap_id: cert_details['accessPoint'] = ap_id # additional symbol appended", "the next octets are the length - \"definite form\" #", "attacks 'PublicKeyHash': quote_plus(public_key_hash), 'X-Amz-Algorithm': ALGORITHM, 'X-Amz-Credential': credential, 'X-Amz-Date': quote_plus(formatted_datetime), 'X-Amz-Expires':", "is_fatal=False): for file_path in [AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE]: if os.path.exists(file_path): credentials =", "%s' % retention_days) def put_cloudwatch_log_retention_policy(cloudwatchlog_client, log_group_name, retention_days): try: cloudwatch_put_retention_policy_helper(cloudwatchlog_client, log_group_name,", "from logging.handlers import RotatingFileHandler try: import ConfigParser from ConfigParser import", "logging.debug('No CA file configured, using default CA file %s', DEFAULT_STUNNEL_CAFILE)", "instance # through IAM role name security credentials lookup uri", "parse_options(args[options_index]) if not fsname or not mountpoint: usage(out=sys.stderr) fs_id, path", "os.path.isfile(key): return cmd = 'openssl genpkey -algorithm RSA -out %s", "does not exist, %s' % (log_group_name, e.response)) return False else:", "logging.info('Created cloudwatch log stream %s in log group %s' %", "args=None): \"\"\"Parse arguments, return (fsid, path, mountpoint, options)\"\"\" if args", "= format_args.get('region') if region: region_specific_config_section = '%s.%s' % (CONFIG_SECTION, region)", "a valid EFS DNS ' 'name' % remote, 'Failed to", "= get_aws_security_credentials(use_iam, **kwargs) if credentials_source: cert_details['awsCredentialsMethod'] = credentials_source if ap_id:", "= os.open(lock_file, os.O_CREAT | os.O_DSYNC | os.O_EXCL | os.O_RDWR) try:", "(1), length (1 + num_length_octets), and number of unused bits", "% (remote, 'https://docs.aws.amazon.com/efs/latest/ug/mounting-fs-mount-cmd-dns-name.html')) def is_nfs_mount(mountpoint): cmd = ['stat', '-f', '-L',", "config.get(CLOUDWATCH_LOG_SECTION, 'retention_in_days') log_stream_name = get_cloudwatch_log_stream_name(fs_id) return { 'log_group_name': log_group_name, 'retention_days':", "None stream_creation_completed = create_cloudwatch_log_stream(cloudwatchlog_client, log_group_name, log_stream_name) if not stream_creation_completed: return", "as devnull: subprocess.Popen(['systemctl', 'start', WATCHDOG_SERVICE], stdout=devnull, stderr=devnull, close_fds=True) else: logging.debug('%s", "in options: options['nfsvers'] = '4.1' if 'rsize' not in options:", "credentials URI the ECS agent generated if aws_creds_uri: return get_aws_security_credentials_from_ecs(aws_creds_uri,", "contextlib import contextmanager from datetime import datetime, timedelta from logging.handlers", "get_nfs_mount_options(options)] if 'netns' in options: command = ['nsenter', '--net=' +", "%s' % (log_stream_name, log_group_name)) def create_cloudwatch_log_stream(cloudwatchlog_client, log_group_name, log_stream_name): try: cloudwatch_create_log_stream_helper(cloudwatchlog_client,", "make sure it is executable. # # You will be", "'.join(command)) proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) out, err =", "systems') return check_network_target(fs_id) def start_watchdog(init_system): if init_system == 'init': proc", "-in %s' % public_key output, err = subprocess_call(cmd, 'Unable to", "get_init_system() check_network_status(fs_id, init_system) dns_name = get_dns_name(config, fs_id) if 'tls' in", "path, mountpoint, options) mount_completed.set() t.join() def check_unsupported_options(options): for unsupported_option in", "86400, 'X-Amz-SignedHeaders': SIGNED_HEADERS, } if session_token: canonical_query_params['X-Amz-Security-Token'] = quote_plus(session_token) #", "%s \"\"\" # SigV4 Auth ALGORITHM = 'AWS4-HMAC-SHA256' AWS4_REQUEST =", "region, fs_id, security_credentials, ap_id, client_info): \"\"\"Populate ca/req configuration file with", "with open(os.devnull, 'w') as devnull: rc = subprocess.call(['systemctl', 'status', 'network.target'],", "mount_tls(config, init_system, dns_name, path, fs_id, mountpoint, options) else: mount_nfs(dns_name, path,", "CONFIG_SECTION region = format_args.get('region') if region: region_specific_config_section = '%s.%s' %", "command to verify\\n\" % mountpoint) logging.warning(\"%s is already mounted, mount", "This file needs to be renamed to a non-temporary version", "%s', url_error_msg, err_msg) return None def get_resp_obj(request_resp, url, unsuccessful_resp): if", "used to signify the number of unused bits that exist", "timeout=1) return get_resp_obj(request_resp, url, unsuccessful_resp) except HTTPError as e: #", "log events is not valid, %s' % e.response) return False", "use_iam = 'iam' in options ap_id = options.get('accesspoint') cert_details =", "= get_private_key_path() cert_details['fsId'] = fs_id start_watchdog(init_system) if not os.path.exists(state_file_dir): create_required_directory(config,", "request += create_canonical_query_string(public_key_hash, credential, formatted_datetime, session_token) + '\\n' request +=", "'cafile', 'iam', 'netns', 'noocsp', 'ocsp', 'tls', 'tlsport', 'verify' ] UNSUPPORTED_OPTIONS", "init_system, dns_name, fs_id, mountpoint, options, state_file_dir=STATE_FILE_DIR): tls_port = choose_tls_port(config, options)", "the EFS id and the remote path to mount\"\"\" try:", "the public key to pull out the actual key material", "at %s: status=%d, reason is %s' % (url, e.code, e.reason)", "if 'tlsport' in options: try: int(options['tlsport']) except ValueError: fatal_error('tlsport option", "'--net=' + options['netns']] + command logging.info('Executing: \"%s\"', ' '.join(command)) proc", "output, err), exc_info=True) try: process.kill() except OSError: # Silently fail", "= 'Could not start %s, unrecognized init system \"%s\"' %", "err = tunnel_proc.communicate() fatal_error('Failed to initialize TLS tunnel for %s'", "+ '\\n' sha256 = hashlib.sha256() sha256.update(canonical_request.encode()) string_to_sign += sha256.hexdigest() return", "match_device(config, fsname) return fs_id, path, mountpoint, options def get_client_info(config): client_info", "log_group_name, 'log_stream_name': log_stream_name } def create_default_cloudwatchlog_agent_if_not_exist(config): if not check_if_cloudwatch_log_enabled(config): return", "\"region\" parameter in the efs-utils configuration file.', message) metadata_exception =", "!= e.errno or not os.path.isdir(directory): raise @contextmanager def bootstrap_tls(config, init_system,", "encode, as big-endian, the length (which may be 0) as", "the target region. This functionality should only be used if", "STRING # Example: # 0:d=0 hl=4 l= 418 cons: SEQUENCE", "{ 'AccessKeyId': creds['AccessKeyId'], 'SecretAccessKey': creds['SecretAccessKey'], 'Token': creds['SessionToken'] }, 'webidentity:' +", "False elif exception == 'InvalidParameterException': logging.error('Log group name %s is", "\"accesspoint\"') if not AP_ID_RE.match(options['accesspoint']): fatal_error('Access Point ID %s is malformed'", "{'aws_creds_uri': aws_creds_uri} else: kwargs = {'awsprofile': get_aws_profile(options, use_iam)} security_credentials, credentials_source", "ASN1:SEQUENCE:efs_client_info' return ca_extension_str def efs_client_auth_builder(public_key_path, access_key_id, secret_access_key, date, region, fs_id,", "os.path.join(tls_paths['mount_dir'], 'config.conf') certificate_signing_request = os.path.join(tls_paths['mount_dir'], 'request.csr') certificate = os.path.join(tls_paths['mount_dir'], 'certificate.pem')", "k, v in options.items() if k not in EFS_ONLY_OPTIONS] return", "file format, so we have to hand-serialize it. \"\"\" mount_filename", "config, options) if cert_details: efs_config['cert'] = cert_details['certificate'] efs_config['key'] = cert_details['privateKey']", "options: options['retrans'] = '2' if 'noresvport' not in options: options['noresvport']", "env_path, install_method), e) return path.strip().decode() def get_system_release_version(): try: with open(SYSTEM_RELEASE_PATH)", "= choose_tls_port(config, options) # override the tlsport option so that", "fs_id, path = match_device(config, fsname) return fs_id, path, mountpoint, options", "= hashlib.sha1() sha1.update(key) return sha1.hexdigest() def create_canonical_request(public_key_hash, date, access_key, region,", "= 100 CLOUDWATCH_LOG_SECTION = 'cloudwatch-log' DEFAULT_CLOUDWATCH_LOG_GROUP = '/aws/efs/utils' DEFAULT_RETENTION_DAYS =", "is_fatal: unsuccessful_resp = 'Error reading token file %s: %s' %", "client_info = get_client_info(config) if use_iam: aws_creds_uri = options.get('awscredsuri') if aws_creds_uri:", "tests\"\"\" return PRIVATE_KEY_FILE def check_and_create_private_key(base_path=STATE_FILE_DIR): # Creating RSA private keys", "length (1 + num_length_octets), and number of unused bits (1)", "IOError: logging.warning('Unable to read %s', comm_file) logging.debug('Identified init system: %s',", "ALGORITHM + '\\n' string_to_sign += date.strftime(SIGV4_DATETIME_FORMAT) + '\\n' string_to_sign +=", "if credentials['AccessKeyId']: return credentials, os.path.basename(file_path) + ':' + awsprofile #", "rc, output, err), exc_info=True) try: process.kill() except OSError: # Silently", "name is a CNAME record resolving to a valid EFS", "EFS DNS ' 'name' % remote, 'Failed to resolve \"%s\"'", "None, None def get_iam_role_name(): iam_role_unsuccessful_resp = 'Unsuccessful retrieval of IAM", "exception = e.response['Error']['Code'] if exception == 'InvalidSequenceTokenException': logging.debug('The sequence token", "retry_with_new_header_token=False): try: req = Request(url) for k, v in headers.items():", "False elif exception == 'OperationAbortedException': logging.debug('Multiple requests to update the", "if not cloudwatchlog_agent or not cloudwatchlog_agent.get('client'): return False token =", "can be mounted with: # # sudo mount /mount_point #", "already mounted, mount aborted\" % mountpoint) return with bootstrap_tls(config, init_system,", "as e: logging.warning('Credentials are not properly configured, %s' % e)", "% 'stunnel_check_cert_validity') system_release_version = get_system_release_version() if not any(release in system_release_version", "pid: %d', tunnel_proc.pid) temp_tls_state_file = write_tls_tunnel_state_file(fs_id, mountpoint, tls_port, tunnel_proc.pid, tunnel_args,", "= '/etc/amazon/efs/privateKey.pem' DATE_ONLY_FORMAT = '%Y%m%d' SIGV4_DATETIME_FORMAT = '%Y%m%dT%H%M%SZ' CERT_DATETIME_FORMAT =", "get_dns_name(config, fs_id) if 'tls' in options: mount_tls(config, init_system, dns_name, path,", "falling back ' 'to legacy \"dns_name_format\" check') try: region =", "cloudwatch log group retention days to %s' % retention_days) def", "= 'Fedora release' SUSE_RELEASE_NAME = 'openSUSE Leap' SKIP_NO_LIBWRAP_RELEASES = [RHEL8_RELEASE_NAME,", "None mountpoint = None options = {} if len(args) >", "= 1 if '{region}' in dns_name_format: expected_replacement_field_ct += 1 format_args['region']", "path = '/' if FS_ID_RE.match(remote): return remote, path try: primary,", "ecs_unsuccessful_resp, ecs_url_error_msg) if ecs_security_dict and all(k in ecs_security_dict for k", "int(retention_days), 'log_stream_name': log_stream_name } def get_cloudwatch_log_stream_name(fs_id=None): instance_id = get_instance_identity_info_from_instance_metadata('instanceId') if", "+ awsprofile # Fail if credentials cannot be fetched from", "pwd import random import re import socket import subprocess import", "has been ignored, as amazon-efs-utils relies on a built-in '", "%s' % e) return False except NoCredentialsError as e: logging.warning('Credentials", "awsprofile) if credentials['AccessKeyId']: return credentials, os.path.basename(file_path) + ':' + awsprofile", "= is_stunnel_option_supported(stunnel_output, b'checkHost') ocsp_aia_supported = is_stunnel_option_supported(stunnel_output, b'OCSPaia') return check_host_supported, ocsp_aia_supported", "\"\"\" Return the name of the temporary file containing TLS", "use_iam: for file_path in [AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE]: aws_credentials_configs = read_config(file_path) #", "e.reason) except URLError as e: err_msg = 'Unable to reach", "HTTP_REQUEST_METHOD + '\\n' request += CANONICAL_URI + '\\n' request +=", "return check_network_target(fs_id) def start_watchdog(init_system): if init_system == 'init': proc =", "not support \"%s\"', stunnel_option_name) return supported def get_version_specific_stunnel_options(): stunnel_command =", "valid, %s' % e.response) return False elif exception == 'DataAlreadyAcceptedException':", "the first octet always has the high order bit (8)", "is str else resp_body.decode('utf-8') def parse_options(options): opts = {} for", "properly enforce TLS. Please upgrade stunnel, ' \\ 'or disable", "(ignore high order bit) # - 018f - length of", "secret_access_key, region) efs_client_auth_str = '[ efs_client_auth ]' efs_client_auth_str += '\\naccessKeyId", "public_key) key_line = '' for line in output.splitlines(): if 'BIT", "(type) # - the next octets are the length -", "the # 'efs' type is a networked file system type.", "-in %s -outform PEM -pubout -out %s' % (private_key, public_key)", "'ResourceAlreadyExistsException': logging.debug('Log group %s already exist, %s' % (log_group_name, e.response))", "iam_role_name: credentials, credentials_source = get_aws_security_credentials_from_instance_metadata(iam_role_name) if credentials and credentials_source: return", "try: with open_lock_file(): return function() except OSError as e: if", "path.strip().decode() def get_system_release_version(): try: with open(SYSTEM_RELEASE_PATH) as f: return f.read().strip()", "'openssl req -new -config %s -key %s -out %s' %", "req -new -config %s -key %s -out %s' % (config_path,", "= 'Unable to reach the url at %s: status=%d, reason", "database and certs directories exist and if not, create directories", "security credentials through AWS_CONTAINER_CREDENTIALS_RELATIVE_URI environment variable if ECS_URI_ENV in os.environ:", "line in stunnel_output: if line.startswith(stunnel_option_name): supported = True break if", "'ocsp' in options: return True elif 'noocsp' in options: return", "exist, %s' % (cloudwatchlog_agent.get('log_group_name'), cloudwatchlog_agent.get('log_stream_name'), e.response)) return False else: logging.debug('Unexpected", "AWS security credentials with IAM role name attached to instance", "actual key material by looking for the key BIT STRING", "in options: options['noresvport'] = None if 'tls' in options: options['port']", "cert_details=cert_details) tunnel_args = [_stunnel_bin(), stunnel_config_file] if 'netns' in options: tunnel_args", "security_credentials, fs_id, client_info): ca_extension_str = '[ v3_ca ]\\nsubjectKeyIdentifier = hash'", "is_ocsp_enabled(config, options) stunnel_config_file = write_stunnel_config_file(config, state_file_dir, fs_id, mountpoint, tls_port, dns_name,", "upper_bound)) # Choose a random midpoint, and then try ports", "dns_name, path, fs_id, mountpoint, options): if os.path.ismount(mountpoint) and is_nfs_mount(mountpoint): sys.stdout.write(\"%s", "is already mounted, please run 'mount' command to verify\\n\" %", "the first octet of the value is used to signify", "client_info): \"\"\"Populate ca/req configuration file with fresh configurations at every", "2: mountpoint = args[2] if len(args) > 4 and '-o'", "add_region = _sign(key_date, region).digest() add_service = _sign(add_region, SERVICE).digest() signing_key =", "was not yet available, add \"_netdev\" to your mount options'", "access key). Adapted credentials provider chain from: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html and https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html", "e.response['Error']['Code'] if exception == 'ResourceAlreadyExistsException': logging.debug('Log stream %s already exist", "'UnrecognizedClientException': logging.debug('The most likely cause is an invalid AWS access", "1 + 1 + num_length_octets + 1 key = key[offset:]", "did not resolve to an EFS mount target' % remote", "fs_id = efs_fqdn_match.group('fs_id') expected_dns_name = get_dns_name(config, fs_id) # check that", "Exception('Region not found in dns_name_format') def get_aws_ec2_metadata_token(): try: opener =", "return '/'.join([date.strftime(DATE_ONLY_FORMAT), region, SERVICE, AWS4_REQUEST]) def match_device(config, device): \"\"\"Return the", "'cafile' in options: stunnel_cafile = options['cafile'] else: try: stunnel_cafile =", "get_system_release_version() if not any(release in system_release_version for release in SKIP_NO_LIBWRAP_RELEASES):", "= { 'host': '%s' } CANONICAL_HEADERS = '\\n'.join(['%s:%s' % (k,", "% (tunnel_proc.returncode, out.strip(), err.strip())) def poll_tunnel_process(tunnel_proc, fs_id, mount_completed): \"\"\" poll", "number of unused bits (1) offset = 1 + 1", "init_system) return init_system def check_network_target(fs_id): with open(os.devnull, 'w') as devnull:", "except NameError: headers = {'X-aws-ec2-metadata-token-ttl-seconds': 21600} req = Request(INSTANCE_METADATA_TOKEN_URL, headers=headers,", "if the subprocess has exited already pass else: return output,", "SERVICE, AWS4_REQUEST]) def match_device(config, device): \"\"\"Return the EFS id and", "e.response)) return True elif exception == 'LimitExceededException': logging.error('Reached the maximum", "logging.info('Executing: \"%s\"', ' '.join(command)) proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)", "credential, formatted_datetime, session_token=None): canonical_query_params = { 'Action': 'Connect', # Public", "failed') _fatal_error(metadata_exception) def get_region_from_instance_metadata(): instance_identity = get_instance_identity_info_from_instance_metadata('region') if not instance_identity:", "\"\"\" def _sign(key, msg): return hmac.new(key, msg.encode('utf-8'), hashlib.sha256) key_date =", "retrieve IAM role name. See %s for more info.' %", "f: token = f.read() except Exception as e: if is_fatal:", "Ubuntu 16.04), and upstart # (Amazon Linux 2017.09). # #", "in str(output) def mount_tls(config, init_system, dns_name, path, fs_id, mountpoint, options):", "= '/etc/amazon/efs/efs-utils.conf' CONFIG_SECTION = 'mount' CLIENT_INFO_SECTION = 'client-info' CLIENT_SOURCE_STR_LEN_LIMIT =", "'awsprofile' in options: fatal_error('The \"awscredsuri\" and \"awsprofile\" options are mutually", "for the key BIT STRING # Example: # 0:d=0 hl=4", "it replaces the %s's return '&'.join(['%s=%s' % (k, v) for", "return _sign(signing_key, string_to_sign).hexdigest() def get_credential_scope(date, region): return '/'.join([date.strftime(DATE_ONLY_FORMAT), region, SERVICE,", "return function() except OSError as e: if e.errno == errno.EEXIST:", "'BIT STRING' in line.decode('utf-8'): key_line = line.decode('utf-8') if not key_line:", "in the config file and metadata calls fail. \"\"\" dns_name_format", "mountpoint, tls_port, dns_name, verify_level, ocsp_enabled, options, cert_details=cert_details) tunnel_args = [_stunnel_bin(),", "# # [Device] [Mount Point] [File System Type] [Options] [Dump]", "file %s', DEFAULT_STUNNEL_CAFILE) stunnel_cafile = DEFAULT_STUNNEL_CAFILE if not os.path.exists(stunnel_cafile): fatal_error('Failed", "\"\"\"Helper method to run shell openssl command and to handle", "for %s' % fs_id, 'Failed to start TLS tunnel (errno=%d).", "'') # DER encoding TLV (Tag, Length, Value) # -", "log_group_name, retention_days): try: cloudwatch_put_retention_policy_helper(cloudwatchlog_client, log_group_name, retention_days) except ClientError as e:", "log_stream_name = 'default - mount.log' return log_stream_name def check_if_cloudwatch_log_enabled(config): if", "logging level \"%s\", setting logging level to %s', raw_level, level)", "from instance_metadata\") return instance_identity def get_instance_identity_info_from_instance_metadata(property): ec2_metadata_unsuccessful_resp = 'Unsuccessful retrieval", "the DNS name the CNAME resolves to if hostname ==", "init_system) dns_name = get_dns_name(config, fs_id) if 'tls' in options: mount_tls(config,", "form\" # - the first octet always has the high", "except IOError: logging.warning('Unable to read %s', comm_file) logging.debug('Identified init system:", "cert_details: state.update(cert_details) with open(os.path.join(state_file_dir, state_file), 'w') as f: json.dump(state, f)", "return resp_body if resp_body_type is str else resp_body.decode('utf-8') def parse_options(options):", "SECURITY_CREDS_IAM_ROLE_HELP_URL = 'https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html' DEFAULT_STUNNEL_VERIFY_LEVEL = 2 DEFAULT_STUNNEL_CAFILE = '/etc/amazon/efs/efs-utils.crt' NOT_BEFORE_MINS", "'yes', } WATCHDOG_SERVICE = 'amazon-efs-mount-watchdog' SYSTEM_RELEASE_PATH = '/etc/system-release' OS_RELEASE_PATH =", "can later override the port the NFS client uses to", "(IRSA) approach on EKS) if WEB_IDENTITY_ROLE_ARN_ENV in os.environ and WEB_IDENTITY_TOKEN_FILE_ENV", "cert_details['certificate'] = os.path.join(state_file_dir, cert_details['mountStateDir'], 'certificate.pem') cert_details['privateKey'] = get_private_key_path() cert_details['fsId'] =", "reach %s to retrieve EC2 instance metadata.' % INSTANCE_METADATA_SERVICE_URL instance_identity", "are not found in AWS credentials file (%s), config file", "profile option, \"awsprofile\"') if 'awscredsuri' in options and 'iam' not", "to a specific key pair to avoid replay attacks 'PublicKeyHash':", "'127.0.0.1:%s' % path else: mount_path = '%s:%s' % (dns_name, path)", "# Example: # 0382018f00...<subjectPublicKey> # - 03 - BIT STRING", "True except ImportError: BOTOCORE_PRESENT = False VERSION = '1.28.2' SERVICE", "created, %s' % e.response) return False elif exception == 'OperationAbortedException':", "logging.warning('Credentials are not properly configured, %s' % e) return None", "not in options: fatal_error('The \"tls\" option is required when mounting", "lock_file_contents = 'PID: %s' % os.getpid() os.write(f, lock_file_contents.encode('utf-8')) yield f", "'noocsp', 'ocsp', 'tls', 'tlsport', 'verify' ] UNSUPPORTED_OPTIONS = [ 'capath'", "in line.decode('utf-8'): key_line = line.decode('utf-8') if not key_line: err_msg =", "cert_details['certificate'] efs_config['key'] = cert_details['privateKey'] check_host_supported, ocsp_aia_supported = get_version_specific_stunnel_options() tls_controls_message =", "logging.warning('Bad state_file_dir_mode \"%s\" in config file \"%s\"', mode_str, CONFIG_FILE) except", "take out private key creation lock, sleeping 50 ms') time.sleep(0.05)", "err), exc_info=True) try: process.kill() except OSError: # Silently fail if", "Your client lacks sufficient controls to properly enforce TLS. Please", "except Exception: logging.warning('Legacy check for region in \"dns_name_format\" failed') _fatal_error(metadata_exception)", "specified domain name \"%s\" did not resolve to an EFS", "all(k in iam_security_dict for k in CREDENTIALS_KEYS): return iam_security_dict, 'metadata:'", "else: raise def generate_key(): if os.path.isfile(key): return cmd = 'openssl", "secret_key credentials['Token'] = session_token except NoOptionError as e: if 'aws_access_key_id'", "unsuccessful_resp, url_error_msg, headers={}, retry_with_new_header_token=False): try: req = Request(url) for k,", "logStreamName=log_stream_name ) logging.info('Created cloudwatch log stream %s in log group", "# # Add an entry like this: # # fs-deadbeef", "urllib2 import URLError, HTTPError, build_opener, urlopen, Request, HTTPHandler from urllib", "private_key, date, region, fs_id, security_credentials, ap_id, client_info): \"\"\"Populate ca/req configuration", "if 'iam' in options and 'tls' not in options: fatal_error('The", "= [_stunnel_bin(), stunnel_config_file] if 'netns' in options: tunnel_args = ['nsenter',", "in str(e) or 'aws_secret_access_key' in str(e): logging.debug('aws_access_key_id or aws_secret_access_key not", "file configured, using default CA file %s', DEFAULT_STUNNEL_CAFILE) stunnel_cafile =", "14 # Cloudwatchlog agent dict includes cloudwatchlog botocore client, cloudwatchlog", "401 error will be thrown, # to retrieve metadata, the", "efs_config['accept'] % tls_port efs_config['connect'] = efs_config['connect'] % dns_name efs_config['verify'] =", "import random import re import socket import subprocess import sys", "EFS_FQDN_RE.match(hostname) if efs_fqdn_match: fs_id = efs_fqdn_match.group('fs_id') expected_dns_name = get_dns_name(config, fs_id)", "will cause '/sbin/mount.efs' to be called by 'mount -a' #", "tls_port = choose_tls_port(config, options) # override the tlsport option so", "except NoSectionError: logging.debug('No [%s] section found in config file %s',", "this script to /sbin/mount.efs and make sure it is executable.", "region except Exception: logging.warning('Legacy check for region in \"dns_name_format\" failed')", "str: resp_dict = json.loads(resp_body) else: resp_dict = json.loads(resp_body.decode(request_resp.headers.get_content_charset() or 'us-ascii'))", "Calculate the Signature - https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html \"\"\" def _sign(key, msg): return", "!= 0: with open(os.devnull, 'w') as devnull: subprocess.Popen(['systemctl', 'start', WATCHDOG_SERVICE],", "UTCTIME:' + date.strftime(CERT_DATETIME_FORMAT) if session_token: efs_client_auth_str += '\\nsessionToken = EXPLICIT:0,UTF8String:'", "port the NFS client uses to connect to stunnel. #", "at ' 'https://docs.aws.amazon.com/efs/latest/ug/using-amazon-efs-utils.html#upgrading-stunnel') def find_command_path(command, install_method): try: env_path = '/sbin:/usr/sbin:/usr/local/sbin:/root/bin:/usr/local/bin:/usr/bin:/bin'", "in os.environ: credentials, credentials_source = get_aws_security_credentials_from_ecs(os.environ[ECS_URI_ENV], False) if credentials and", "o in options.split(','): if '=' in o: k, v =", "endpoint, %s' % e) return None except Exception as e:", "log_stream_name def check_if_cloudwatch_log_enabled(config): if config.has_option(CLOUDWATCH_LOG_SECTION, 'enabled'): return config.getboolean(CLOUDWATCH_LOG_SECTION, 'enabled') return", "%s' % (token_file, e) fatal_error(unsuccessful_resp, unsuccessful_resp) else: return None, None", "not use_iam: return None, None # attempt to lookup AWS", "'.aws', 'credentials')) AWS_CONFIG_FILE = os.path.expanduser(os.path.join('~' + pwd.getpwuid(os.getuid()).pw_name, '.aws', 'config')) CA_CONFIG_BODY", "(WATCHDOG_SERVICE, init_system) sys.stderr.write('%s\\n' % error_message) logging.warning(error_message) def create_required_directory(config, directory): mode", "= build_opener(HTTPHandler) request = Request(INSTANCE_METADATA_TOKEN_URL) request.add_header('X-aws-ec2-metadata-token-ttl-seconds', 21600) request.get_method = lambda:", "# (e.g. for IAM Role for Service Accounts (IRSA) approach", "import URLError, HTTPError from urllib.parse import urlencode try: import botocore.session", "all(k in ecs_security_dict for k in CREDENTIALS_KEYS): return ecs_security_dict, 'ecs:'", "ca_supporting_files_check(tls_paths['index'], tls_paths['index_attr'], tls_paths['serial'], tls_paths['rand']) private_key = check_and_create_private_key(base_path) if security_credentials: public_key", "%s' % (remote, 'https://docs.aws.amazon.com/efs/latest/ug/mounting-fs-mount-cmd-dns-name.html')) def is_nfs_mount(mountpoint): cmd = ['stat', '-f',", "while True: try: with open_lock_file(): return function() except OSError as", "message } ] } if token: kwargs['sequenceToken'] = token cloudwatchlog_agent.get('client').put_log_events(**kwargs)", "% dns_name efs_config['verify'] = verify_level if verify_level > 0: add_stunnel_ca_options(efs_config,", "log_dir=LOG_DIR, cert_details=None): \"\"\" Serializes stunnel configuration to a file. Unfortunately", "efs_config['connect'] = efs_config['connect'] % dns_name efs_config['verify'] = verify_level if verify_level", "follow (ignore high order bit) # - 018f - length", "config.get(CONFIG_SECTION, 'logging_level') levels = { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning':", "return get_region_from_instance_metadata() except Exception as e: metadata_exception = e logging.warning('Region", "= 'PID: %s' % os.getpid() os.write(f, lock_file_contents.encode('utf-8')) yield f finally:", "# (Amazon Linux 2017.09). # # Once there is an", "raw_level = config.get(CONFIG_SECTION, 'logging_level') levels = { 'debug': logging.DEBUG, 'info':", "{'awsprofile': get_aws_profile(options, use_iam)} security_credentials, credentials_source = get_aws_security_credentials(use_iam, **kwargs) if credentials_source:", "cause is an invalid AWS access key ID or secret", "_sign(add_service, 'aws4_request').digest() return _sign(signing_key, string_to_sign).hexdigest() def get_credential_scope(date, region): return '/'.join([date.strftime(DATE_ONLY_FORMAT),", "reach %s to retrieve IAM role name. See %s for", "in CREDENTIALS_KEYS): return iam_security_dict, 'metadata:' else: return None, None def", "or log stream %s does not exist, %s' % (cloudwatchlog_agent.get('log_group_name'),", "sha256 = hashlib.sha256() sha256.update(REQUEST_PAYLOAD.encode()) request += sha256.hexdigest() return request def", "try specifying a different port range in %s' % (lower_bound,", "mount_name, 'database/index.txt.attr'), 'serial': os.path.join(base_path, mount_name, 'database/serial'), 'rand': os.path.join(base_path, mount_name, 'database/.rand')", "the key simultaneously. key = get_private_key_path() @contextmanager def open_lock_file(): lock_file", "attempt to lookup AWS security credentials through AWS_CONTAINER_CREDENTIALS_RELATIVE_URI environment variable", "= config.get(CONFIG_SECTION, 'stunnel_logs_file').replace('{fs_id}', fs_id) else: global_config['output'] = os.path.join(log_dir, '%s.stunnel.log' %", "tag (type) # - the next octets are the length", "NoCredentialsError, EndpointConnectionError BOTOCORE_PRESENT = True except ImportError: BOTOCORE_PRESENT = False", "thread, if the tunnel fails, exit uncleanly with os._exit \"\"\"", "has an incorrect number of replacement fields') dns_name_format = config.get(CONFIG_SECTION,", "[stunnel_config_file], state_file_dir, cert_details=cert_details) try: yield tunnel_proc finally: os.rename(os.path.join(state_file_dir, temp_tls_state_file), os.path.join(state_file_dir,", "= {'awsprofile': get_aws_profile(options, use_iam)} security_credentials, credentials_source = get_aws_security_credentials(use_iam, **kwargs) if", "init_system = 'unknown' try: with open(comm_file) as f: init_system =", "a specific key pair to avoid replay attacks 'PublicKeyHash': quote_plus(public_key_hash),", "unsuccessful_resp) else: return None, None webidentity_url = STS_ENDPOINT_URL + '?'", "'client': 'yes', 'accept': '127.0.0.1:%s', 'connect': '%s:2049', 'sslVersion': 'TLSv1.2', 'renegotiation': 'no',", "= sha256 preserve = no policy = efsPolicy x509_extensions =", "short name, by adding it # to /etc/fstab. The syntax", "cloudwatch_put_log_events_helper(cloudwatchlog_agent, message, token) except ClientError as e: exception = e.response['Error']['Code']", "create_cloudwatch_log_stream(cloudwatchlog_client, log_group_name, log_stream_name) if not stream_creation_completed: return None return {", "except Exception as e: logging.warning('Unknown error, %s.' % e) return", "if client_info else '' full_config_body = CA_CONFIG_BODY % (directory, private_key,", "get_dns_name(config, fs_id): def _validate_replacement_field_count(format_str, expected_ct): if format_str.count('{') != expected_ct or", "local_ca [ local_ca ] database = $dir/database/index.txt serial = $dir/database/serial", "fails, exit uncleanly with os._exit \"\"\" while not mount_completed.is_set(): try:", "and all(k in iam_security_dict for k in CREDENTIALS_KEYS): return iam_security_dict,", "file (%s), ' \\ 'from ECS credentials relative uri, or", "write_tls_tunnel_state_file(fs_id, mountpoint, tls_port, tunnel_pid, command, files, state_file_dir, cert_details=None): \"\"\" Return", "msg): return hmac.new(key, msg.encode('utf-8'), hashlib.sha256) key_date = _sign(('AWS4' + secret_access_key).encode('utf-8'),", "as e: logging.warning('Unknown error, %s' % e) return None try:", "ca_extension_body, efs_client_auth_body, efs_client_info_body) with open(config_path, 'w') as f: f.write(full_config_body) return", "None client_info = get_client_info(config) if use_iam: aws_creds_uri = options.get('awscredsuri') if", "is not present in the config file and metadata calls", "%s', raw_level, level) def get_dns_name(config, fs_id): def _validate_replacement_field_count(format_str, expected_ct): if", "lookup uri iam_role_name = get_iam_role_name() if iam_role_name: credentials, credentials_source =", "'ecs:' + aws_creds_uri # Fail if credentials cannot be fetched", "a successful mount. \"\"\" state_file = '~' + get_mount_specific_filename(fs_id, mountpoint,", "parse_arguments_early_exit(args=None): \"\"\"Parse arguments, checking for early exit conditions only\"\"\" if", "'-h' in args[1:] or '--help' in args[1:]: usage(out=sys.stdout, exit_code=0) if", "rc=%s, stdout=\"%s\", stderr=\"%s\"' % (cmd, rc, output, err), exc_info=True) try:", "'/' + get_credential_scope(date, region)) request = HTTP_REQUEST_METHOD + '\\n' request", "usage(out=sys.stdout, exit_code=0) if '--version' in args[1:]: sys.stdout.write('%s Version: %s\\n' %", "= 'AWS4-HMAC-SHA256' AWS4_REQUEST = 'aws4_request' HTTP_REQUEST_METHOD = 'GET' CANONICAL_URI =", "ConfigParser import NoOptionError, NoSectionError except ImportError: from configparser import ConfigParser,", "'Failed to resolve \"%s\" - check that the specified DNS", "lower_bound)) return lower_bound, upper_bound def choose_tls_port(config, options): if 'tlsport' in", ".get('AssumeRoleWithWebIdentityResult', {}) \\ .get('Credentials', {}) if all(k in creds for", "logging.info(message) publish_cloudwatch_log(CLOUDWATCHLOG_AGENT, message) else: message = 'Failed to mount %s", "Exception as e: metadata_exception = e logging.warning('Region not found in", "\"port_range_upper_bound\" defined as %d ' 'must be strictly greater than", "% (fs_id, instance_id) elif instance_id: log_stream_name = '%s - mount.log'", "sys import threading import time from contextlib import contextmanager from", "- the remaining 127 bits are used to encode the", "socket.gethostbyname(dns_name) except socket.gaierror: fatal_error('Failed to resolve \"%s\" - check that", "%s.' % ecs_uri ecs_url_error_msg = 'Unable to reach %s to", "to retrieve IAM role name. See %s for more info.'", "not properly configured, %s' % e) return None except EndpointConnectionError", "since SigV4 signature can change\"\"\" public_key_path = os.path.join(directory, 'publicKey.pem') ca_extension_body", "logging.error(log_message) publish_cloudwatch_log(CLOUDWATCHLOG_AGENT, 'Mount failed, %s' % log_message) sys.exit(exit_code) def get_target_region(config):", "botocore.session from botocore.exceptions import ClientError, NoCredentialsError, EndpointConnectionError BOTOCORE_PRESENT = True", "'--net=' + options['netns']] + tunnel_args # launch the tunnel in", "as mounts occurring in parallel may try to create the", "= 0o400 os.chmod(key, read_only_mode) do_with_lock(generate_key) return key def create_certificate_signing_request(config_path, private_key,", "not in EFS_ONLY_OPTIONS] return ','.join(nfs_options) def mount_nfs(dns_name, path, mountpoint, options):", "= '%Y%m%d' SIGV4_DATETIME_FORMAT = '%Y%m%dT%H%M%SZ' CERT_DATETIME_FORMAT = '%y%m%d%H%M%SZ' AWS_CREDENTIALS_FILE =", "False elif exception == 'ResourceNotFoundException': logging.error('Log group %s does not", "e.response)) else: handle_general_botocore_exceptions(e) return None except NoCredentialsError as e: logging.warning('Credentials", "if unsupported_option in options: warn_message = 'The \"%s\" option is", "HTTPError from urllib.parse import urlencode try: import botocore.session from botocore.exceptions", "\\ (AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE, awsprofile) fatal_error(log_message) else: return None, None def", "connect to the endpoint, %s' % e) return None except", "if 'netns' in options: command = ['nsenter', '--net=' + options['netns']]", "always has the high order bit (8) set to 1", "return efs_client_auth_str def efs_client_info_builder(client_info): efs_client_info_str = '[ efs_client_info ]' for", "in stunnel_output: if line.startswith(stunnel_option_name): supported = True break if not", "be killed easily by the mount watchdog logging.info('Starting TLS tunnel:", "else: fatal_error('Failed to locate an available port in the range", "is_fatal=False): try: with open(token_file, 'r') as f: token = f.read()", "retrieval of AWS security credentials at %s.' % ecs_uri ecs_url_error_msg", "License. # # # Copy this script to /sbin/mount.efs and", "os.geteuid() != 0: sys.stderr.write('only root can run mount.efs\\n') sys.exit(1) def", "def test_tunnel_process(tunnel_proc, fs_id): tunnel_proc.poll() if tunnel_proc.returncode is not None: out,", "def add_stunnel_ca_options(efs_config, config, options): if 'cafile' in options: stunnel_cafile =", "os.path.join(tls_paths['mount_dir'], 'publicKey.pem') create_public_key(private_key, public_key) create_ca_conf(certificate_config, common_name, tls_paths['mount_dir'], private_key, current_time, region,", "retention_days) def put_cloudwatch_log_retention_policy(cloudwatchlog_client, log_group_name, retention_days): try: cloudwatch_put_retention_policy_helper(cloudwatchlog_client, log_group_name, retention_days) except", "checking for early exit conditions only\"\"\" if args is None:", "is correct.\\nSee %s for more detail.' % (dns_name, 'https://docs.aws.amazon.com/console/efs/mount-dns-name'), 'Failed", "error_msg = 'AWS Access Key ID and Secret Access Key", "num_length_octets = key[1] & 0b01111111 # Exclude the tag (1),", "options: fatal_error('Specified port [%s] is unavailable. Try selecting a different", "security_credentials, ap_id, client_info): \"\"\"Populate ca/req configuration file with fresh configurations", "mounting with DNS names for examples: %s' % (remote, 'https://docs.aws.amazon.com/efs/latest/ug/mounting-fs-mount-cmd-dns-name.html'))", "in options and 'noocsp' in options: fatal_error('The \"ocsp\" and \"noocsp\"", "instance_id and fs_id: log_stream_name = '%s - %s - mount.log'", "= '4.1' if 'rsize' not in options: options['rsize'] = '1048576'", "with open_lock_file(): return function() except OSError as e: if e.errno", "datetime, timedelta from logging.handlers import RotatingFileHandler try: import ConfigParser from", "not check_if_cloudwatch_log_enabled(config): return None global CLOUDWATCHLOG_AGENT if not CLOUDWATCHLOG_AGENT: CLOUDWATCHLOG_AGENT", "domain name \"%s\" did not resolve to an EFS mount", "get_aws_security_credentials_from_instance_metadata(iam_role_name) if credentials and credentials_source: return credentials, credentials_source error_msg =", "if not os.path.exists(state_file_dir): create_required_directory(config, state_file_dir) verify_level = int(options.get('verify', DEFAULT_STUNNEL_VERIFY_LEVEL)) ocsp_enabled", "# delay logging error about malformed log level until after", "SECURITY_CREDS_ECS_URI_HELP_URL = 'https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html' SECURITY_CREDS_WEBIDENTITY_HELP_URL = 'https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html' SECURITY_CREDS_IAM_ROLE_HELP_URL = 'https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html' DEFAULT_STUNNEL_VERIFY_LEVEL", "hashlib.sha1() sha1.update(key) return sha1.hexdigest() def create_canonical_request(public_key_hash, date, access_key, region, fs_id,", "\"%s\"', stunnel_option_name) return supported def get_version_specific_stunnel_options(): stunnel_command = [_stunnel_bin(), '-help']", "return current_time.strftime(CERT_DATETIME_FORMAT) def get_private_key_path(): \"\"\"Wrapped for mocking purposes in unit", "try: cloudwatch_create_log_stream_helper(cloudwatchlog_client, log_group_name, log_stream_name) except ClientError as e: exception =", "resolve \"%s\" - check that the specified DNS name is", "'AWS_CONTAINER_CREDENTIALS_RELATIVE_URI' ECS_TASK_METADATA_API = 'http://169.254.170.2' WEB_IDENTITY_ROLE_ARN_ENV = 'AWS_ROLE_ARN' WEB_IDENTITY_TOKEN_FILE_ENV = 'AWS_WEB_IDENTITY_TOKEN_FILE'", "'4.1' if 'rsize' not in options: options['rsize'] = '1048576' if", "if resp: creds = resp \\ .get('AssumeRoleWithWebIdentityResponse', {}) \\ .get('AssumeRoleWithWebIdentityResult',", "ImportError: BOTOCORE_PRESENT = False VERSION = '1.28.2' SERVICE = 'elasticfilesystem'", "not os.path.isfile(index_attr_path): with open(index_attr_path, 'w+') as f: f.write('unique_subject = no')", "content # # For a BIT STRING, the first octet", "byte. Note that this is explicitly excluded from the SubjectKeyIdentifier", "mountpoint] p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) output, _ =", "formatted_datetime, session_token) + '\\n' request += CANONICAL_HEADERS % fs_id +", "} CANONICAL_HEADERS = '\\n'.join(['%s:%s' % (k, v) for k, v", "level \"%s\", setting logging level to %s', raw_level, level) def", "'\\n' request += create_canonical_query_string(public_key_hash, credential, formatted_datetime, session_token) + '\\n' request", "signature can change\"\"\" public_key_path = os.path.join(directory, 'publicKey.pem') ca_extension_body = ca_extension_builder(ap_id,", "fs-deadbeef /mount_point efs _netdev 0 0 # # Using the", "os.path.isfile(index_path): open(index_path, 'w').close() if not os.path.isfile(index_attr_path): with open(index_attr_path, 'w+') as", "- 018f - length of 399 # - 00 -", "\\ (STS_ENDPOINT_URL, SECURITY_CREDS_WEBIDENTITY_HELP_URL) resp = url_request_helper(webidentity_url, unsuccessful_resp, url_error_msg, headers={'Accept': 'application/json'})", "'aws4_request').digest() return _sign(signing_key, string_to_sign).hexdigest() def get_credential_scope(date, region): return '/'.join([date.strftime(DATE_ONLY_FORMAT), region,", "'' full_config_body = CA_CONFIG_BODY % (directory, private_key, common_name, ca_extension_body, efs_client_auth_body,", ") logging.info('Created cloudwatch log stream %s in log group %s'", "security credentials in AWS credentials file (~/.aws/credentials) # and configs", "None, 'Token': None} try: access_key = aws_credentials_configs.get(awsprofile, 'aws_access_key_id') secret_key =", "efs_config['accept'] = efs_config['accept'] % tls_port efs_config['connect'] = efs_config['connect'] % dns_name", "logging.debug('The most likely cause is an invalid AWS access key", "token }) unsuccessful_resp = 'Unsuccessful retrieval of AWS security credentials", "malformed' % options['accesspoint']) if 'iam' in options and 'tls' not", "os.putenv('PATH', env_path) path = subprocess.check_output(['which', command]) except subprocess.CalledProcessError as e:", "tunnel_args = [_stunnel_bin(), stunnel_config_file] if 'netns' in options: tunnel_args =", "not os.path.isdir(directory): raise @contextmanager def bootstrap_tls(config, init_system, dns_name, fs_id, mountpoint,", "= 'http://169.254.170.2' WEB_IDENTITY_ROLE_ARN_ENV = 'AWS_ROLE_ARN' WEB_IDENTITY_TOKEN_FILE_ENV = 'AWS_WEB_IDENTITY_TOKEN_FILE' STS_ENDPOINT_URL =", "config.get(CONFIG_SECTION, 'stunnel_logs_file').replace('{fs_id}', fs_id) else: global_config['output'] = os.path.join(log_dir, '%s.stunnel.log' % mount_filename)", "= int(key_line.split(':')[0]) key = key[offset:] num_length_octets = key[1] & 0b01111111", "return region except Exception: logging.warning('Legacy check for region in \"dns_name_format\"", "current file and return 'default' if so try: access_key =", "resp_body = request_resp.read() resp_body_type = type(resp_body) try: if resp_body_type is", "if 'netns' in options: tunnel_args = ['nsenter', '--net=' + options['netns']]", "out the actual key material by looking for the key", "if config.has_option(CLOUDWATCH_LOG_SECTION, 'log_group_name'): log_group_name = config.get(CLOUDWATCH_LOG_SECTION, 'log_group_name') retention_days = DEFAULT_RETENTION_DAYS", "a CNAME record resolving to a valid EFS DNS '", "get_target_region(config) if '{dns_name_suffix}' in dns_name_format: expected_replacement_field_ct += 1 config_section =", "remote, 'Failed to resolve \"%s\"' % remote ) if not", "in dns_name_format: raise ValueError('DNS name format must include {fs_id}') format_args", "pwd.getpwuid(os.getuid()).pw_name, '.aws', 'credentials')) AWS_CONFIG_FILE = os.path.expanduser(os.path.join('~' + pwd.getpwuid(os.getuid()).pw_name, '.aws', 'config'))", "'20', 'TIMEOUTclose': '0', 'TIMEOUTidle': '70', 'delay': 'yes', } WATCHDOG_SERVICE =", "CANONICAL_HEADERS = '\\n'.join(['%s:%s' % (k, v) for k, v in", "secret_access_key, date, region, fs_id, session_token=None): public_key_hash = get_public_key_sha1(public_key_path) canonical_request =", "'Connect', # Public key hash is included in canonical request", "}) unsuccessful_resp = 'Unsuccessful retrieval of AWS security credentials at", "avoid naming collisions cert_details['mountStateDir'] = get_mount_specific_filename(fs_id, mountpoint, tls_port) + '+'", "(ecs_uri, SECURITY_CREDS_ECS_URI_HELP_URL) ecs_security_dict = url_request_helper(ecs_uri, ecs_unsuccessful_resp, ecs_url_error_msg) if ecs_security_dict and", "0: add_stunnel_ca_options(efs_config, config, options) if cert_details: efs_config['cert'] = cert_details['certificate'] efs_config['key']", "'elasticfilesystem' CONFIG_FILE = '/etc/amazon/efs/efs-utils.conf' CONFIG_SECTION = 'mount' CLIENT_INFO_SECTION = 'client-info'", "None LOG_DIR = '/var/log/amazon/efs' LOG_FILE = 'mount.log' STATE_FILE_DIR = '/var/run/efs'", "tlsport option so that we can later override the port", "relative uri, or from the instance security credentials service' %", "'DataAlreadyAcceptedException': logging.debug('The event %s was already logged, %s' % (message,", "{ 'Action': 'Connect', # Public key hash is included in", "it. # This means, however, that we have to include", "create_ca_conf(certificate_config, common_name, tls_paths['mount_dir'], private_key, current_time, region, fs_id, security_credentials, ap_id, client_info)", "https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html \"\"\" formatted_datetime = date.strftime(SIGV4_DATETIME_FORMAT) credential = quote_plus(access_key + '/'", "log_group_name, retention_days): cloudwatchlog_client.put_retention_policy( logGroupName=log_group_name, retentionInDays=retention_days ) logging.debug('Set cloudwatch log group", "mount an EFS file system by its short name, by", "+ ':' + awsprofile # Fail if credentials cannot be", "2017.09). # # Once there is an entry in fstab,", "sys.stderr.write('%s\\n' % user_message) logging.error(log_message) publish_cloudwatch_log(CLOUDWATCHLOG_AGENT, 'Mount failed, %s' % log_message)", "for k in CREDENTIALS_KEYS): return ecs_security_dict, 'ecs:' + aws_creds_uri #", "**kwargs): updated_time = current_time + timedelta(**kwargs) return updated_time.strftime(CERT_DATETIME_FORMAT) def get_utc_now():", "for region in \"dns_name_format\" failed') _fatal_error(metadata_exception) def get_region_from_instance_metadata(): instance_identity =", "'stunnel_check_cert_hostname') # Only use the config setting if the override", "not exist, %s' % (log_group_name, e.response)) return False else: handle_general_botocore_exceptions(e)", "specific language governing permissions and limitations under # the License.", "'~'. This file needs to be renamed to a non-temporary", "%s' % (k, v)) return lines def add_stunnel_ca_options(efs_config, config, options):", "fatal_error(tls_controls_message % 'stunnel_check_cert_hostname') # Only use the config setting if", "= type(resp_body) try: if resp_body_type is str: resp_dict = json.loads(resp_body)", "call failed, falling back ' 'to legacy \"dns_name_format\" check') try:", "cert_details=cert_details) try: yield tunnel_proc finally: os.rename(os.path.join(state_file_dir, temp_tls_state_file), os.path.join(state_file_dir, temp_tls_state_file[1:])) def", "return credentials, os.path.basename(file_path) + ':' + awsprofile # Fail if", "'aws_access_key_id') secret_key = aws_credentials_configs.get(awsprofile, 'aws_secret_access_key') session_token = aws_credentials_configs.get(awsprofile, 'aws_session_token') credentials['AccessKeyId']", "base_path) certificate_config = os.path.join(tls_paths['mount_dir'], 'config.conf') certificate_signing_request = os.path.join(tls_paths['mount_dir'], 'request.csr') certificate", "if 0 < len(client_source) <= CLIENT_SOURCE_STR_LEN_LIMIT: client_info['source'] = client_source return", "unsuccessful_resp) err_msg = 'Unable to reach the url at %s:", "path try: primary, secondaries, _ = socket.gethostbyname_ex(remote) hostnames = list(filter(lambda", "state_file_dir_mode \"%s\" in config file \"%s\"', mode_str, CONFIG_FILE) except NoOptionError:", "# every mount will have its own ca mode assets", "AWS security credentials at %s.' % STS_ENDPOINT_URL url_error_msg = 'Unable", "key[offset:] sha1 = hashlib.sha1() sha1.update(key) return sha1.hexdigest() def create_canonical_request(public_key_hash, date,", "from urllib.parse import urlencode try: import botocore.session from botocore.exceptions import", "sys.exit(exit_code) def get_target_region(config): def _fatal_error(message): fatal_error('Error retrieving region. Please set", "logging.CRITICAL } level = levels.get(raw_level.lower()) level_error = False if not", "{ 'log_group_name': log_group_name, 'retention_days': int(retention_days), 'log_stream_name': log_stream_name } def get_cloudwatch_log_stream_name(fs_id=None):", "== 'InvalidParameterException': logging.error('Either parameter log group name %s or log", "= request_resp.read() resp_body_type = type(resp_body) try: if resp_body_type is str:", "if e.errno == errno.EEXIST: logging.info('Failed to take out private key", "path else: mount_path = '%s:%s' % (dns_name, path) command =", "- https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html \"\"\" formatted_datetime = date.strftime(SIGV4_DATETIME_FORMAT) credential = quote_plus(access_key +", "create all intermediate directories if they don't exist).\"\"\" if not", "%s in %s - %s' % (command, env_path, install_method), e)", "'mount_dir': os.path.join(base_path, mount_name), # every mount will have its own", "url_request_helper(security_creds_lookup_url, unsuccessful_resp, url_error_msg, retry_with_new_header_token=True) if iam_security_dict and all(k in iam_security_dict", "cloudwatch_put_retention_policy_helper(cloudwatchlog_client, log_group_name, retention_days) except ClientError as e: exception = e.response['Error']['Code']", "datetime import datetime, timedelta from logging.handlers import RotatingFileHandler try: import", "if credentials_source: cert_details['awsCredentialsMethod'] = credentials_source if ap_id: cert_details['accessPoint'] = ap_id", "return f.read().strip() except IOError: logging.debug('Unable to read %s', SYSTEM_RELEASE_PATH) try:", "= 'openssl rsa -in %s -outform PEM -pubout -out %s'", "= credentials_file_helper(file_path, awsprofile) if credentials['AccessKeyId']: return credentials, os.path.basename(file_path) + ':'", "not group_creation_completed: return None put_retention_policy_completed = put_cloudwatch_log_retention_policy(cloudwatchlog_client, log_group_name, retention_days) if", "error, %s.' % e) return False return True def cloudwatch_put_retention_policy_helper(cloudwatchlog_client,", "% (log_stream_name, log_group_name, e.response)) return True elif exception == 'InvalidParameterException':", "{ 'mount_dir': os.path.join(base_path, mount_name), # every mount will have its", "init system: %s', init_system) return init_system def check_network_target(fs_id): with open(os.devnull,", "else: return None, None def get_aws_security_credentials_from_instance_metadata(iam_role_name): security_creds_lookup_url = INSTANCE_IAM_URL +", "check dns_name_format to obtain the target region. This functionality should", "open(rand_path, 'w').close() def get_certificate_timestamp(current_time, **kwargs): updated_time = current_time + timedelta(**kwargs)", "local_ca ] database = $dir/database/index.txt serial = $dir/database/serial private_key =", "'ServiceUnavailableException': logging.debug('The service cannot complete the request, %s' % error.response)", "fatal_error(tls_controls_message % 'stunnel_check_cert_validity') system_release_version = get_system_release_version() if not any(release in", "ca mode assets due to lack of multi-threading support in", "import hashlib import hmac import json import logging import os", "key = get_private_key_path() @contextmanager def open_lock_file(): lock_file = os.path.join(base_path, 'efs-utils-lock')", "%s under named profile [%s]' % \\ (AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE, awsprofile)", "dict(STUNNEL_EFS_CONFIG) efs_config['accept'] = efs_config['accept'] % tls_port efs_config['connect'] = efs_config['connect'] %", "**kwargs) if credentials_source: cert_details['awsCredentialsMethod'] = credentials_source if ap_id: cert_details['accessPoint'] =", "exception == 'ResourceAlreadyExistsException': logging.debug('Log stream %s already exist in log", "options['hard'] = None if 'timeo' not in options: options['timeo'] =", "'timeo' not in options: options['timeo'] = '600' if 'retrans' not", "if the tunnel fails, exit uncleanly with os._exit \"\"\" while", "already pass else: return output, err error_message = '%s, error", "follow # - the following octets encode, as big-endian, the", "bit) # - 018f - length of 399 # -", "under [default] section in current file and return 'default' if", "return False elif exception == 'InvalidParameterException': logging.error('Either parameter log group", "_ = get_aws_security_credentials_from_instance_metadata(iam_role_name) if credentials: return session.create_client(service, aws_access_key_id=credentials['AccessKeyId'], aws_secret_access_key=credentials['SecretAccessKey'], aws_session_token=credentials['Token'],", "1) except ValueError: remote = device path = '/' if", "logging.getLogger() logger.setLevel(level) logger.addHandler(handler) if level_error: logging.error('Malformed logging level \"%s\", setting", "logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL } level = levels.get(raw_level.lower()) level_error", "metadata token if e.code == 401 and retry_with_new_header_token: token =", "start_watchdog(init_system): if init_system == 'init': proc = subprocess.Popen( ['/sbin/status', WATCHDOG_SERVICE],", "create_certificate_signing_request(config_path, private_key, csr_path): cmd = 'openssl req -new -config %s", "args[1:]: usage(out=sys.stdout, exit_code=0) if '--version' in args[1:]: sys.stdout.write('%s Version: %s\\n'", "service): if not BOTOCORE_PRESENT: logging.error('Failed to import botocore, please install", "subprocess.call(['systemctl', 'status', 'network.target'], stdout=devnull, stderr=devnull, close_fds=True) if rc != 0:", "a Canonical Request - https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html \"\"\" formatted_datetime = date.strftime(SIGV4_DATETIME_FORMAT) credential", "if 'PRETTY_NAME' in line: return line.split('=')[1].strip() except IOError: logging.debug('Unable to", "else: lower_bound, upper_bound = get_tls_port_range(config) tls_ports = list(range(lower_bound, upper_bound)) #", "socket import subprocess import sys import threading import time from", "cert_details['privateKey'] check_host_supported, ocsp_aia_supported = get_version_specific_stunnel_options() tls_controls_message = 'WARNING: Your client", "is configured level_error = True level = logging.INFO max_bytes =", "CLOUDWATCHLOG_AGENT = None LOG_DIR = '/var/log/amazon/efs' LOG_FILE = 'mount.log' STATE_FILE_DIR", "if 'accesspoint' in options: if 'tls' not in options: fatal_error('The", "# Silently fail if the subprocess has exited already pass", "(Tag, Length, Value) # - the first octet (byte) is", "in options: options['retrans'] = '2' if 'noresvport' not in options:", "'/' CANONICAL_HEADERS_DICT = { 'host': '%s' } CANONICAL_HEADERS = '\\n'.join(['%s:%s'", "%s does not exist, %s' % (log_group_name, e.response)) return False", "not level: # delay logging error about malformed log level", "more info.' \\ % (ecs_uri, SECURITY_CREDS_ECS_URI_HELP_URL) ecs_security_dict = url_request_helper(ecs_uri, ecs_unsuccessful_resp,", "certificate signing request (csr)') def create_ca_conf(config_path, common_name, directory, private_key, date,", "urlopen, Request from urllib.error import URLError, HTTPError from urllib.parse import", "create_canonical_request(public_key_hash, date, access_key, region, fs_id, session_token=None): \"\"\" Create a Canonical", "log_group_name, log_stream_name): try: cloudwatch_create_log_stream_helper(cloudwatchlog_client, log_group_name, log_stream_name) except ClientError as e:", "options['retrans'] = '2' if 'noresvport' not in options: options['noresvport'] =", "not None: out, err = tunnel_proc.communicate() fatal_error('Failed to initialize TLS", "get_mount_specific_filename(fs_id, mountpoint, tls_port) state = { 'pid': tunnel_pid, 'cmd': command,", "'%s=%s' % (str(k), str(v)) nfs_options = [to_nfs_option(k, v) for k,", "urlopen(req) return res.read() def get_aws_security_credentials(use_iam, awsprofile=None, aws_creds_uri=None): \"\"\" Lookup AWS", "(output, err) = process.communicate() rc = process.poll() if rc !=", "'LimitExceededException': logging.error('Reached the maximum number of log groups that can", "except Exception as e: metadata_exception = e logging.warning('Region not found", "of the mount target matches exactly the DNS name the", "# The script will add recommended mount options, if not", "key_line.replace(' ', '') # DER encoding TLV (Tag, Length, Value)", "this is explicitly excluded from the SubjectKeyIdentifier hash, per #", "instance_identity, e)) except TypeError as e: logging.warning('response %s is not", "options['rsize'] = '1048576' if 'wsize' not in options: options['wsize'] =", "new_certs_dir = $dir/certs default_md = sha256 preserve = no policy", "message = 'Successfully mounted %s at %s' % (dns_name, mountpoint)", "logging.debug('aws_session_token not found in %s', file_path) credentials['AccessKeyId'] = aws_credentials_configs.get(awsprofile, 'aws_access_key_id')", "config.getboolean(CONFIG_SECTION, 'stunnel_check_cert_hostname'): if check_host_supported: efs_config['checkHost'] = dns_name else: fatal_error(tls_controls_message %", "return tls_dict def get_public_key_sha1(public_key): # truncating public key to remove", "log_group_name) except ClientError as e: exception = e.response['Error']['Code'] if exception", "private key creation lock, sleeping 50 ms') time.sleep(0.05) else: raise", "= stunnel_cafile def is_stunnel_option_supported(stunnel_output, stunnel_option_name): supported = False for line", "if lower_bound >= upper_bound: fatal_error('Configuration option \"port_range_upper_bound\" defined as %d", "cert_details=None): \"\"\" Return the name of the temporary file containing", "is unavailable. Try selecting a different port.' % options['tlsport']) else:", "specified incorrectly, %s' % (log_group_name, retention_days, e.response)) return False else:", "k, v = o.split('=') opts[k] = v else: opts[o] =", "- %s - mount.log' % (fs_id, instance_id) elif instance_id: log_stream_name", "# fs-deadbeef /mount_point efs _netdev 0 0 # # Using", "request_resp.getcode() != 200: logging.debug(unsuccessful_resp + ' %s: ResponseCode=%d', url, request_resp.getcode())", "SUSE_RELEASE_NAME = 'openSUSE Leap' SKIP_NO_LIBWRAP_RELEASES = [RHEL8_RELEASE_NAME, CENTOS8_RELEASE_NAME, FEDORA_RELEASE_NAME, SUSE_RELEASE_NAME]", "info.' \\ % (ecs_uri, SECURITY_CREDS_ECS_URI_HELP_URL) ecs_security_dict = url_request_helper(ecs_uri, ecs_unsuccessful_resp, ecs_url_error_msg)", "using default CA file %s', DEFAULT_STUNNEL_CAFILE) stunnel_cafile = DEFAULT_STUNNEL_CAFILE if", "failed, %s' % log_message) sys.exit(exit_code) def get_target_region(config): def _fatal_error(message): fatal_error('Error", "cloudwatch_describe_log_streams_helper(cloudwatchlog_agent): return cloudwatchlog_agent.get('client').describe_log_streams( logGroupName=cloudwatchlog_agent.get('log_group_name'), logStreamNamePrefix=cloudwatchlog_agent.get('log_stream_name') ) def get_log_stream_next_token(cloudwatchlog_agent): try: response", "from botocore.exceptions import ClientError, NoCredentialsError, EndpointConnectionError BOTOCORE_PRESENT = True except", "import contextmanager from datetime import datetime, timedelta from logging.handlers import", "f.write('unique_subject = no') if not os.path.isfile(serial_path): with open(serial_path, 'w+') as", "token file %s: %s' % (token_file, e) fatal_error(unsuccessful_resp, unsuccessful_resp) else:", "except (NoSectionError, NoOptionError): continue return awsprofile def url_request_helper(url, unsuccessful_resp, url_error_msg,", "error_message = 'Could not start %s, unrecognized init system \"%s\"'", "= create_canonical_request(public_key_hash, date, access_key_id, region, fs_id, session_token) string_to_sign = create_string_to_sign(canonical_request,", "logging.warning(\"%s is already mounted, mount aborted\" % mountpoint) return with", "upgrade stunnel, ' \\ 'or disable \"%%s\" in %s.\\nSee %s", "service cannot complete the request, %s' % error.response) elif exception", "is not None, [primary] + secondaries)) except socket.gaierror: create_default_cloudwatchlog_agent_if_not_exist(config) fatal_error(", "%s. Returning response body.' % (str(resp_body), e)) return resp_body if", "config.has_option(CLOUDWATCH_LOG_SECTION, 'enabled'): return config.getboolean(CLOUDWATCH_LOG_SECTION, 'enabled') return False def cloudwatch_create_log_group_helper(cloudwatchlog_client, log_group_name):", "{ 'fips': 'no', 'foreground': 'yes', 'socket': [ 'l:SO_REUSEADDR=yes', 'a:SO_BINDTODEVICE=lo', ],", "SIGNED_HEADERS + '\\n' sha256 = hashlib.sha256() sha256.update(REQUEST_PAYLOAD.encode()) request += sha256.hexdigest()", "one private key and allow mounts to share it. #", "if rc != 0: with open(os.devnull, 'w') as devnull: subprocess.Popen(['systemctl',", "for k, v in options.items() if k not in EFS_ONLY_OPTIONS]", "os.path.join(base_path, mount_name, 'database'), 'certs_dir': os.path.join(base_path, mount_name, 'certs'), 'index': os.path.join(base_path, mount_name,", "options' % fs_id, exit_code=0) def check_network_status(fs_id, init_system): if init_system !=", "max 64 characters cert_details['commonName'] = socket.gethostname()[0:64] cert_details['region'] = get_target_region(config) cert_details['certificateCreationTime']", "= is_ocsp_enabled(config, options) stunnel_config_file = write_stunnel_config_file(config, state_file_dir, fs_id, mountpoint, tls_port,", "cloudwatchlog botocore client, cloudwatchlog group name, cloudwatchlog stream name CLOUDWATCHLOG_AGENT", "to read %s', SYSTEM_RELEASE_PATH) try: with open(OS_RELEASE_PATH) as f: for", "mounted %s at %s' % (dns_name, mountpoint) logging.info(message) publish_cloudwatch_log(CLOUDWATCHLOG_AGENT, message)", "# (Amazon Linux 2, CentOS 7, RHEL 7, Debian 9,", "def do_with_lock(function): while True: try: with open_lock_file(): return function() except", "of AWS security credentials at %s.' % security_creds_lookup_url url_error_msg =", "is not None: return 'default' except (NoSectionError, NoOptionError): continue return", "lines = f.readlines() lines = lines[1:-1] key = ''.join(lines) key", "EFS id and the remote path to mount\"\"\" try: remote,", "ClientError as e: exception = e.response['Error']['Code'] if exception == 'InvalidSequenceTokenException':", "handler.setFormatter(logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(message)s')) logger = logging.getLogger() logger.setLevel(level) logger.addHandler(handler)", "%s for more detail.' % (dns_name, 'https://docs.aws.amazon.com/console/efs/mount-dns-name'), 'Failed to resolve", "tunnel state, prefixed with a '~'. This file needs to", "renamed to a non-temporary version following a successful mount. \"\"\"", "cloudwatch_put_log_events_helper(cloudwatchlog_agent, message, token=None): kwargs = { 'logGroupName': cloudwatchlog_agent.get('log_group_name'), 'logStreamName': cloudwatchlog_agent.get('log_stream_name'),", "def bootstrap_tls(config, init_system, dns_name, fs_id, mountpoint, options, state_file_dir=STATE_FILE_DIR): tls_port =", "'Unable to reach %s to retrieve EC2 instance metadata.' %", "%s.' % INSTANCE_IAM_URL iam_role_url_error_msg = 'Unable to reach %s to", "= { 'logGroupName': cloudwatchlog_agent.get('log_group_name'), 'logStreamName': cloudwatchlog_agent.get('log_stream_name'), 'logEvents': [ { 'timestamp':", "'TIMEOUTbusy': '20', 'TIMEOUTclose': '0', 'TIMEOUTidle': '70', 'delay': 'yes', } WATCHDOG_SERVICE", "CNAME resolves to if hostname == expected_dns_name: return fs_id, path", "or 'us-ascii')) return resp_dict except ValueError as e: logging.info('ValueError parsing", "get_aws_security_credentials_from_ecs(aws_creds_uri, True) # attempt to lookup AWS security credentials in", "in config file if config.has_option(CLIENT_INFO_SECTION, 'source'): client_source = config.get(CLIENT_INFO_SECTION, 'source')", "1: fsname = args[1] if len(args) > 2: mountpoint =", "'Action': 'Connect', # Public key hash is included in canonical", "fatal_error('Failed to mount %s because the network was not yet", "aws_credentials_configs = read_config(file_path) credentials = {'AccessKeyId': None, 'SecretAccessKey': None, 'Token':", "ca_extension_str += '\\n1.3.6.1.4.1.4843.7.1 = ASN1:UTF8String:' + ap_id if security_credentials: ca_extension_str", "logging.error('Reached the maximum number of log groups that can be", "def read_config(config_file=CONFIG_FILE): try: p = ConfigParser.SafeConfigParser() except AttributeError: p =", "> 4 and '-o' in args[:-1]: options_index = args.index('-o') +", "levels.get(raw_level.lower()) level_error = False if not level: # delay logging", "obtained from \"dns_name_format\" field. Please set the \"region\" ' 'parameter", "error: %s' % e) return False except NoCredentialsError as e:", "path, mountpoint, options)\"\"\" if args is None: args = sys.argv", "resp \\ .get('AssumeRoleWithWebIdentityResponse', {}) \\ .get('AssumeRoleWithWebIdentityResult', {}) \\ .get('Credentials', {})", "%s' % (dns_name, mountpoint) logging.info(message) publish_cloudwatch_log(CLOUDWATCHLOG_AGENT, message) else: message =", "if not os.path.isfile(serial_path): with open(serial_path, 'w+') as f: f.write('00') if", "def efs_client_auth_builder(public_key_path, access_key_id, secret_access_key, date, region, fs_id, session_token=None): public_key_hash =", "k, v in config.items(): if type(v) is list: for item", "NoOptionError, NoSectionError except ImportError: from configparser import ConfigParser, NoOptionError, NoSectionError", "lower_bound, upper_bound = get_tls_port_range(config) tls_ports = list(range(lower_bound, upper_bound)) # Choose", "# Creating RSA private keys is slow, so we will", "x509_extensions = v3_ca [ efsPolicy ] CN = supplied [", "to read %s', OS_RELEASE_PATH) return 'unknown' def write_stunnel_config_file(config, state_file_dir, fs_id,", "tested with systemd # (Amazon Linux 2, CentOS 7, RHEL", "with IAM role name attached to instance # through IAM", "given aws_creds_uri if is_fatal: fatal_error(unsuccessful_resp, unsuccessful_resp) else: return None, None", "is malformed' % options['accesspoint']) if 'iam' in options and 'tls'", "args[1:] or '--help' in args[1:]: usage(out=sys.stdout, exit_code=0) if '--version' in", "exit_code=1): if log_message is None: log_message = user_message sys.stderr.write('%s\\n' %", "'unknown' try: with open(comm_file) as f: init_system = f.read().strip() except", "if mount's database and certs directories exist and if not,", "lower_bound = config.getint(CONFIG_SECTION, 'port_range_lower_bound') upper_bound = config.getint(CONFIG_SECTION, 'port_range_upper_bound') if lower_bound", "type(resp_body) try: if resp_body_type is str: resp_dict = json.loads(resp_body) else:", "awsprofile if awsprofile: return get_aws_security_credentials_from_awsprofile(awsprofile, True) # attempt to lookup", "cloudwatchlog_agent.get('log_stream_name'), e.response)) else: handle_general_botocore_exceptions(e) return None except NoCredentialsError as e:", "detail.' % (CONFIG_FILE, 'https://docs.aws.amazon.com/console/efs/troubleshooting-tls') if config.getboolean(CONFIG_SECTION, 'stunnel_check_cert_hostname'): if check_host_supported: efs_config['checkHost']", "devnull: subprocess.Popen(['systemctl', 'start', WATCHDOG_SERVICE], stdout=devnull, stderr=devnull, close_fds=True) else: logging.debug('%s is", "iam_role_name unsuccessful_resp = 'Unsuccessful retrieval of AWS security credentials at", "return p def bootstrap_logging(config, log_dir=LOG_DIR): raw_level = config.get(CONFIG_SECTION, 'logging_level') levels", "and 'tls' not in options: fatal_error('The \"tls\" option is required", "is a CNAME record resolving to a valid EFS DNS", "== 'InvalidParameterException': logging.debug('Either parameter log group name %s or log", "region) efs_client_auth_str = '[ efs_client_auth ]' efs_client_auth_str += '\\naccessKeyId =", "credentials_source error_msg = 'AWS Access Key ID and Secret Access", "= parse_arguments(config) logging.info('version=%s options=%s', VERSION, options) global CLOUDWATCHLOG_AGENT CLOUDWATCHLOG_AGENT =", "fs_id, mountpoint, tls_port, dns_name, verify_level, ocsp_enabled, options, log_dir=LOG_DIR, cert_details=None): \"\"\"", "ValueError: logging.warning('Bad state_file_dir_mode \"%s\" in config file \"%s\"', mode_str, CONFIG_FILE)", "in args[1:]: sys.stdout.write('%s Version: %s\\n' % (args[0], VERSION)) sys.exit(0) def", "name format must include {fs_id}') format_args = {'fs_id': fs_id} expected_replacement_field_ct", "the SubjectKeyIdentifier hash, per # https://tools.ietf.org/html/rfc5280#section-4.2.1.2 # # Example: #", "is an entry in fstab, the file system can be", "maxBytes=max_bytes, backupCount=file_count) handler.setFormatter(logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(message)s')) logger = logging.getLogger()", "'parameter in the efs-utils configuration file.') return region except Exception:", "'log_group_name': log_group_name, 'log_stream_name': log_stream_name } def create_default_cloudwatchlog_agent_if_not_exist(config): if not check_if_cloudwatch_log_enabled(config):", "True elif 'noocsp' in options: return False else: return config.getboolean(CONFIG_SECTION,", "credentials_source # attempt to lookup AWS security credentials through AssumeRoleWithWebIdentity", "mode assets due to lack of multi-threading support in openssl", "= match_device(config, fsname) return fs_id, path, mountpoint, options def get_client_info(config):", "incorrectly, %s' % (log_group_name, e.response)) return False else: handle_general_botocore_exceptions(e) return", "target. ' 'Please refer to the EFS documentation for mounting", "NameError: headers = {'X-aws-ec2-metadata-token-ttl-seconds': 21600} req = Request(INSTANCE_METADATA_TOKEN_URL, headers=headers, method='PUT')", "of AWS security credentials at %s.' % ecs_uri ecs_url_error_msg =", "not hostnames: create_default_cloudwatchlog_agent_if_not_exist(config) fatal_error( 'The specified domain name \"%s\" did", "retrieval of EC2 metadata at %s.' % INSTANCE_METADATA_SERVICE_URL ec2_metadata_url_error_msg =", "mid = random.randrange(len(tls_ports)) ports_to_try = tls_ports[mid:] + tls_ports[:mid] assert len(tls_ports)", "policy = efsPolicy x509_extensions = v3_ca [ efsPolicy ] CN", "date.strftime(SIGV4_DATETIME_FORMAT) credential = quote_plus(access_key + '/' + get_credential_scope(date, region)) request", "write_stunnel_config_file(config, state_file_dir, fs_id, mountpoint, tls_port, dns_name, verify_level, ocsp_enabled, options, log_dir=LOG_DIR,", "return None except Exception as e: logging.warning('Unknown error, %s' %", "os.remove(lock_file) def do_with_lock(function): while True: try: with open_lock_file(): return function()", "os.path.join(directory, 'publicKey.pem') ca_extension_body = ca_extension_builder(ap_id, security_credentials, fs_id, client_info) efs_client_auth_body =", "if k not in EFS_ONLY_OPTIONS] return ','.join(nfs_options) def mount_nfs(dns_name, path,", "def cloudwatch_put_log_events_helper(cloudwatchlog_agent, message, token=None): kwargs = { 'logGroupName': cloudwatchlog_agent.get('log_group_name'), 'logStreamName':", "resp_body_type is str: resp_dict = json.loads(resp_body) else: resp_dict = json.loads(resp_body.decode(request_resp.headers.get_content_charset()", "secret access key). Adapted credentials provider chain from: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html and", "more detail.' % (dns_name, 'https://docs.aws.amazon.com/console/efs/mount-dns-name'), 'Failed to resolve \"%s\"' %", "'state_file_dir_mode') try: mode = int(mode_str, 8) except ValueError: logging.warning('Bad state_file_dir_mode", "dns_name_format to obtain the target region. This functionality should only", "= urlopen(req, timeout=1) return get_resp_obj(request_resp, url, unsuccessful_resp) err_msg = 'Unable", "import botocore, please install botocore first.') return None session =", "' \\ 'from ECS credentials relative uri, or from the", "proc.communicate() if proc.returncode == 0: message = 'Successfully mounted %s", "TLS tunnel, pid: %d', tunnel_proc.pid) temp_tls_state_file = write_tls_tunnel_state_file(fs_id, mountpoint, tls_port,", "to a valid DNS name for an EFS mount target.", "dns_name else: fatal_error(tls_controls_message % 'stunnel_check_cert_hostname') # Only use the config", "def create_certificate(config, mount_name, common_name, region, fs_id, security_credentials, ap_id, client_info, base_path=STATE_FILE_DIR):", "| os.O_RDWR) try: lock_file_contents = 'PID: %s' % os.getpid() os.write(f,", "= os.path.expanduser(os.path.join('~' + pwd.getpwuid(os.getuid()).pw_name, '.aws', 'credentials')) AWS_CONFIG_FILE = os.path.expanduser(os.path.join('~' +", "log group %s, %s' % (log_stream_name, log_group_name, e.response)) return True", "as e: if errno.EEXIST != e.errno or not os.path.isdir(directory): raise", "if config.has_option(CONFIG_SECTION, 'stunnel_logs_file'): global_config['output'] = config.get(CONFIG_SECTION, 'stunnel_logs_file').replace('{fs_id}', fs_id) else: global_config['output']", "token = get_aws_ec2_metadata_token() req.add_header('X-aws-ec2-metadata-token', token) request_resp = urlopen(req, timeout=1) return", "error_message) logging.warning(error_message) def create_required_directory(config, directory): mode = 0o750 try: mode_str", "format has an incorrect number of replacement fields') dns_name_format =", "security credentials at %s.' % STS_ENDPOINT_URL url_error_msg = 'Unable to", "100 CLOUDWATCH_LOG_SECTION = 'cloudwatch-log' DEFAULT_CLOUDWATCH_LOG_GROUP = '/aws/efs/utils' DEFAULT_RETENTION_DAYS = 14", "state = { 'pid': tunnel_pid, 'cmd': command, 'files': files, }", "cloudwatchlog_agent or not cloudwatchlog_agent.get('client'): return False token = get_log_stream_next_token(cloudwatchlog_agent) try:", "credential = quote_plus(access_key + '/' + get_credential_scope(date, region)) request =", "cannot complete the request, %s' % error.response) elif exception ==", "% unsupported_option sys.stderr.write('WARN: %s\\n' % warn_message) logging.warning(warn_message) del options[unsupported_option] def", "if not key_line: err_msg = 'Public key file, %s, is", "if '{dns_name_suffix}' in dns_name_format: return split_dns_name_format[-2] elif 'amazonaws.com' in dns_name_format:", "\"\"\" For backwards compatibility check dns_name_format to obtain the target", "','.join([role_arn, token_file]) # Fail if credentials cannot be fetched from", "l= 9 prim: OBJECT :rsaEncryption # 17:d=2 hl=2 l= 0", "% (CONFIG_SECTION, region) if config.has_section(region_specific_config_section): config_section = region_specific_config_section format_args['dns_name_suffix'] =", "resp_dict = json.loads(resp_body.decode(request_resp.headers.get_content_charset() or 'us-ascii')) return resp_dict except ValueError as", "create_cloudwatch_log_stream(cloudwatchlog_client, log_group_name, log_stream_name): try: cloudwatch_create_log_stream_helper(cloudwatchlog_client, log_group_name, log_stream_name) except ClientError as", "public key') def subprocess_call(cmd, error_message): \"\"\"Helper method to run shell", "at %s.' % INSTANCE_METADATA_SERVICE_URL ec2_metadata_url_error_msg = 'Unable to reach %s", "with bootstrap_tls(config, init_system, dns_name, fs_id, mountpoint, options) as tunnel_proc: mount_completed", "https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html \"\"\" def _sign(key, msg): return hmac.new(key, msg.encode('utf-8'), hashlib.sha256) key_date", "= ASN1:UTF8String:' + ap_id if security_credentials: ca_extension_str += '\\n1.3.6.1.4.1.4843.7.2 =", "options['netns']] + command logging.info('Executing: \"%s\"', ' '.join(command)) proc = subprocess.Popen(command,", "invalid AWS access key ID or secret Key, %s' %", "tunnel_proc: mount_completed = threading.Event() t = threading.Thread(target=poll_tunnel_process, args=(tunnel_proc, fs_id, mount_completed))", "'https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html' SECURITY_CREDS_IAM_ROLE_HELP_URL = 'https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html' DEFAULT_STUNNEL_VERIFY_LEVEL = 2 DEFAULT_STUNNEL_CAFILE = '/etc/amazon/efs/efs-utils.crt'", "= 'Unable to reach the url at %s, reason is", "= ECS_TASK_METADATA_API + aws_creds_uri ecs_unsuccessful_resp = 'Unsuccessful retrieval of AWS", "None, None def get_aws_security_credentials_from_instance_metadata(iam_role_name): security_creds_lookup_url = INSTANCE_IAM_URL + iam_role_name unsuccessful_resp", "that the specified DNS name is a CNAME record resolving", "err.strip()) fatal_error(err.strip(), message, proc.returncode) def usage(out, exit_code=1): out.write('Usage: mount.efs [--version]", "def check_unsupported_options(options): for unsupported_option in UNSUPPORTED_OPTIONS: if unsupported_option in options:", "ValueError: fatal_error('tlsport option [%s] is not an integer' % options['tlsport'])", "-config %s -key %s -out %s' % (config_path, private_key, csr_path)", "method='PUT') res = urlopen(req) return res.read() def get_aws_security_credentials(use_iam, awsprofile=None, aws_creds_uri=None):", "% (log_group_name, e.response)) return False elif exception == 'InvalidParameterException': logging.error('Either", "certificate authority file for verification', 'Failed to find CAfile \"%s\"'", "try: yield tunnel_proc finally: os.rename(os.path.join(state_file_dir, temp_tls_state_file), os.path.join(state_file_dir, temp_tls_state_file[1:])) def get_nfs_mount_options(options):", "# # Licensed under the MIT License. See the LICENSE", "specific key pair to avoid replay attacks 'PublicKeyHash': quote_plus(public_key_hash), 'X-Amz-Algorithm':", "if not os.path.exists(certs_dir): create_required_directory(config, certs_dir) def ca_supporting_files_check(index_path, index_attr_path, serial_path, rand_path):", "Returning response body.' % (str(resp_body), e)) return resp_body if resp_body_type", "if instance_id and fs_id: log_stream_name = '%s - %s -", "fs_id, mountpoint, options) as tunnel_proc: mount_completed = threading.Event() t =", "\"%s\", setting logging level to %s', raw_level, level) def get_dns_name(config,", "Linux release 8' CENTOS8_RELEASE_NAME = 'CentOS Linux release 8' FEDORA_RELEASE_NAME", "def get_aws_profile(options, use_iam): awsprofile = options.get('awsprofile') if not awsprofile and", "= ConfigParser() p.read(config_file) return p def bootstrap_logging(config, log_dir=LOG_DIR): raw_level =", "install botocore first.') return None session = botocore.session.get_session() region =", "logging.debug('Not testing network on non-systemd init systems') return check_network_target(fs_id) def", "get_aws_profile(options, use_iam)} security_credentials, credentials_source = get_aws_security_credentials(use_iam, **kwargs) if credentials_source: cert_details['awsCredentialsMethod']", "\\ (AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE) fatal_error(error_msg, error_msg) def get_aws_security_credentials_from_awsprofile(awsprofile, is_fatal=False): for file_path", "state_file = '~' + get_mount_specific_filename(fs_id, mountpoint, tls_port) state = {", "except URLError as e: err_msg = 'Unable to reach the", "v in sorted(CANONICAL_HEADERS_DICT.items())]) SIGNED_HEADERS = ';'.join(CANONICAL_HEADERS_DICT.keys()) REQUEST_PAYLOAD = '' FS_ID_RE", "key_line = '' for line in output.splitlines(): if 'BIT STRING'", "(1) offset = 1 + 1 + num_length_octets + 1", "= {'AccessKeyId': None, 'SecretAccessKey': None, 'Token': None} try: access_key =", "bootstrap_tls(config, init_system, dns_name, fs_id, mountpoint, options, state_file_dir=STATE_FILE_DIR): tls_port = choose_tls_port(config,", "log_group_name, retention_days) if not put_retention_policy_completed: return None stream_creation_completed = create_cloudwatch_log_stream(cloudwatchlog_client,", "except NoOptionError as e: if 'aws_access_key_id' in str(e) or 'aws_secret_access_key'", "attempt to lookup AWS security credentials with IAM role name", "'database/.rand') } return tls_dict def get_public_key_sha1(public_key): # truncating public key", "watchdog logging.info('Starting TLS tunnel: \"%s\"', ' '.join(tunnel_args)) tunnel_proc = subprocess.Popen(", "name of the mount target matches exactly the DNS name", "True) # attempt to lookup AWS security credentials through AWS_CONTAINER_CREDENTIALS_RELATIVE_URI", "its own ca mode assets due to lack of multi-threading", "logging.debug(\"Using dns_name_suffix %s in config section [%s]\", format_args.get('dns_name_suffix'), config_section) _validate_replacement_field_count(dns_name_format,", "% \\ (AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE, awsprofile) fatal_error(log_message) else: return None, None", "(not_before, not_after, certificate_config, certificate_signing_request, certificate) subprocess_call(cmd, 'Failed to create self-signed", "base_path=STATE_FILE_DIR): tls_dict = { 'mount_dir': os.path.join(base_path, mount_name), # every mount", "csr_path) subprocess_call(cmd, 'Failed to create certificate signing request (csr)') def", "= urlopen(req) return res.read() def get_aws_security_credentials(use_iam, awsprofile=None, aws_creds_uri=None): \"\"\" Lookup", "TypeError as e: logging.warning('response %s is not a json object:", "is %s' % (url, e.code, e.reason) except URLError as e:", "def ca_supporting_files_check(index_path, index_attr_path, serial_path, rand_path): \"\"\"Recreate all supporting openssl ca", "initialize TLS tunnel for %s' % fs_id, 'Failed to start", "log_group_name = DEFAULT_CLOUDWATCH_LOG_GROUP if config.has_option(CLOUDWATCH_LOG_SECTION, 'log_group_name'): log_group_name = config.get(CLOUDWATCH_LOG_SECTION, 'log_group_name')", "are not properly configured, %s' % e) return None except", "request += SIGNED_HEADERS + '\\n' sha256 = hashlib.sha256() sha256.update(REQUEST_PAYLOAD.encode()) request", "= 'Error reading token file %s: %s' % (token_file, e)", "file (~/.aws/credentials) # and configs file (~/.aws/config) with given awsprofile", "in %s', file_path) credentials['AccessKeyId'] = aws_credentials_configs.get(awsprofile, 'aws_access_key_id') credentials['SecretAccessKey'] = aws_credentials_configs.get(awsprofile,", "quote_plus try: from urllib2 import URLError, HTTPError, build_opener, urlopen, Request,", "(log_group_name, e.response)) return False elif exception == 'InvalidParameterException': logging.error('Log group", "in ports_to_try: try: sock.bind(('localhost', tls_port)) sock.close() return tls_port except socket.error:", "is_ocsp_enabled(config, options): if 'ocsp' in options: return True elif 'noocsp'", "check that your file system ID is correct.\\nSee %s for", "is already mounted, mount aborted\" % mountpoint) return with bootstrap_tls(config,", "explicitly excluded from the SubjectKeyIdentifier hash, per # https://tools.ietf.org/html/rfc5280#section-4.2.1.2 #", "'X-Amz-Date': quote_plus(formatted_datetime), 'X-Amz-Expires': 86400, 'X-Amz-SignedHeaders': SIGNED_HEADERS, } if session_token: canonical_query_params['X-Amz-Security-Token']", "SIGNED_HEADERS = ';'.join(CANONICAL_HEADERS_DICT.keys()) REQUEST_PAYLOAD = '' FS_ID_RE = re.compile('^(?P<fs_id>fs-[0-9a-f]+)$') EFS_FQDN_RE", "fatal_error(err.strip(), message, proc.returncode) def usage(out, exit_code=1): out.write('Usage: mount.efs [--version] [-h|--help]", "from there mid = random.randrange(len(tls_ports)) ports_to_try = tls_ports[mid:] + tls_ports[:mid]", "log_group_name)) def create_cloudwatch_log_stream(cloudwatchlog_client, log_group_name, log_stream_name): try: cloudwatch_create_log_stream_helper(cloudwatchlog_client, log_group_name, log_stream_name) except", "options['netns']] + tunnel_args # launch the tunnel in a process", "opener.open(request) return res.read() except NameError: headers = {'X-aws-ec2-metadata-token-ttl-seconds': 21600} req", "% error.response) elif exception == 'AccessDeniedException': logging.debug('User is not authorized", "create_certificate(config, mount_name, common_name, region, fs_id, security_credentials, ap_id, client_info, base_path=STATE_FILE_DIR): current_time", "non-temporary version following a successful mount. \"\"\" state_file = '~'", "t = threading.Thread(target=poll_tunnel_process, args=(tunnel_proc, fs_id, mount_completed)) t.daemon = True t.start()", "to put log events is not valid, %s' % e.response)", "mounted, mount aborted\" % mountpoint) return with bootstrap_tls(config, init_system, dns_name,", "CLOUDWATCH_LOG_SECTION = 'cloudwatch-log' DEFAULT_CLOUDWATCH_LOG_GROUP = '/aws/efs/utils' DEFAULT_RETENTION_DAYS = 14 #", "public_key) create_ca_conf(certificate_config, common_name, tls_paths['mount_dir'], private_key, current_time, region, fs_id, security_credentials, ap_id,", "% key subprocess_call(cmd, 'Failed to create private key') read_only_mode =", "and Ubuntu 16.04), and upstart # (Amazon Linux 2017.09). #", "if awsprofile: return get_aws_security_credentials_from_awsprofile(awsprofile, True) # attempt to lookup AWS", "= socket.gethostname()[0:64] cert_details['region'] = get_target_region(config) cert_details['certificateCreationTime'] = create_certificate(config, cert_details['mountStateDir'], cert_details['commonName'],", "efs_client_auth_str += '\\nsignature = OCTETSTRING:' + signature efs_client_auth_str += '\\nsigv4DateTime", "url_request_helper(url, unsuccessful_resp, url_error_msg, headers={}, retry_with_new_header_token=False): try: req = Request(url) for", "#!/usr/bin/env python # # Copyright 2017-2018 Amazon.com, Inc. and its", "/mount_point efs _netdev 0 0 # # Using the 'efs'", "'netns', 'noocsp', 'ocsp', 'tls', 'tlsport', 'verify' ] UNSUPPORTED_OPTIONS = [", "certificate_signing_request = os.path.join(tls_paths['mount_dir'], 'request.csr') certificate = os.path.join(tls_paths['mount_dir'], 'certificate.pem') ca_dirs_check(config, tls_paths['database_dir'],", "SigV4 signature can change\"\"\" public_key_path = os.path.join(directory, 'publicKey.pem') ca_extension_body =", "%s is specified incorrectly, %s' % (log_group_name, log_stream_name, e.response)) return", "except HTTPError as e: # For instance enable with IMDSv2,", "mounting via \"iam\"') if 'awsprofile' in options and 'iam' not", "retrieve region from instance_metadata\") return instance_identity def get_instance_identity_info_from_instance_metadata(property): ec2_metadata_unsuccessful_resp =", "= quote_plus(session_token) # Cannot use urllib.urlencode because it replaces the", "import threading import time from contextlib import contextmanager from datetime", "for k in ['AccessKeyId', 'SecretAccessKey', 'SessionToken']): return { 'AccessKeyId': creds['AccessKeyId'],", "418 cons: SEQUENCE # 4:d=1 hl=2 l= 13 cons: SEQUENCE", "not resolve to an EFS mount target' % remote )", "sorted(CANONICAL_HEADERS_DICT.items())]) SIGNED_HEADERS = ';'.join(CANONICAL_HEADERS_DICT.keys()) REQUEST_PAYLOAD = '' FS_ID_RE = re.compile('^(?P<fs_id>fs-[0-9a-f]+)$')", "level) def get_dns_name(config, fs_id): def _validate_replacement_field_count(format_str, expected_ct): if format_str.count('{') !=", "credentials lookup uri iam_role_name = get_iam_role_name() if iam_role_name: credentials, credentials_source", "section found in config file %s', awsprofile, file_path) return credentials", "directories\"\"\" if not os.path.isfile(index_path): open(index_path, 'w').close() if not os.path.isfile(index_attr_path): with", "try: cloudwatch_put_retention_policy_helper(cloudwatchlog_client, log_group_name, retention_days) except ClientError as e: exception =", "provided in fstab. import base64 import errno import hashlib import", "get_aws_security_credentials_from_instance_metadata(iam_role_name): security_creds_lookup_url = INSTANCE_IAM_URL + iam_role_name unsuccessful_resp = 'Unsuccessful retrieval", "RSA -out %s -pkeyopt rsa_keygen_bits:3072' % key subprocess_call(cmd, 'Failed to", "aws_credentials_configs.get(awsprofile, 'aws_access_key_id') credentials['SecretAccessKey'] = aws_credentials_configs.get(awsprofile, 'aws_secret_access_key') except NoSectionError: logging.debug('No [%s]", "21600) request.get_method = lambda: 'PUT' res = opener.open(request) return res.read()", "env_path = '/sbin:/usr/sbin:/usr/local/sbin:/root/bin:/usr/local/bin:/usr/bin:/bin' os.putenv('PATH', env_path) path = subprocess.check_output(['which', command]) except", "mount.log' % (fs_id, instance_id) elif instance_id: log_stream_name = '%s -", "uncleanly with os._exit \"\"\" while not mount_completed.is_set(): try: test_tunnel_process(tunnel_proc, fs_id)", "% log_message) sys.exit(exit_code) def get_target_region(config): def _fatal_error(message): fatal_error('Error retrieving region.", "NoOptionError, NoSectionError try: from urllib.parse import quote_plus except ImportError: from", "botocore.exceptions import ClientError, NoCredentialsError, EndpointConnectionError BOTOCORE_PRESENT = True except ImportError:", "'https://sts.amazonaws.com/' INSTANCE_METADATA_TOKEN_URL = 'http://169.254.169.254/latest/api/token' INSTANCE_METADATA_SERVICE_URL = 'http://169.254.169.254/latest/dynamic/instance-identity/document/' INSTANCE_IAM_URL = 'http://169.254.169.254/latest/meta-data/iam/security-credentials/'", "stderr=subprocess.PIPE, close_fds=True) proc.wait() _, err = proc.communicate() stunnel_output = err.splitlines()", "file_count = config.getint(CONFIG_SECTION, 'logging_file_count') handler = RotatingFileHandler(os.path.join(log_dir, LOG_FILE), maxBytes=max_bytes, backupCount=file_count)", "create_default_cloudwatchlog_agent_if_not_exist(config) fatal_error( 'Failed to resolve \"%s\" - check that the", "def create_canonical_query_string(public_key_hash, credential, formatted_datetime, session_token=None): canonical_query_params = { 'Action': 'Connect',", "sha256 preserve = no policy = efsPolicy x509_extensions = v3_ca", "'Red Hat Enterprise Linux release 8' CENTOS8_RELEASE_NAME = 'CentOS Linux", "openssl command and to handle response error messages\"\"\" retry_times =", "';'.join(CANONICAL_HEADERS_DICT.keys()) REQUEST_PAYLOAD = '' FS_ID_RE = re.compile('^(?P<fs_id>fs-[0-9a-f]+)$') EFS_FQDN_RE = re.compile(r'^(?P<fs_id>fs-[0-9a-f]+)\\.efs\\.(?P<region>[a-z0-9-]+)\\.(?P<dns_name_suffix>[a-z0-9.]+)$')", "return None resp_body = request_resp.read() resp_body_type = type(resp_body) try: if", "to find CAfile \"%s\"' % stunnel_cafile) efs_config['CAfile'] = stunnel_cafile def", "except Exception as e: if is_fatal: unsuccessful_resp = 'Error reading", "EKS) if WEB_IDENTITY_ROLE_ARN_ENV in os.environ and WEB_IDENTITY_TOKEN_FILE_ENV in os.environ: credentials,", "and \"tls\" options are mutually exclusive') if 'tlsport' in options:", "'ResourceNotFoundException': logging.debug('Either log group %s or log stream %s does", "quote_plus(session_token) # Cannot use urllib.urlencode because it replaces the %s's", "mountpoint) logging.info(message) publish_cloudwatch_log(CLOUDWATCHLOG_AGENT, message) else: message = 'Failed to mount", "return False return True def cloudwatch_describe_log_streams_helper(cloudwatchlog_agent): return cloudwatchlog_agent.get('client').describe_log_streams( logGroupName=cloudwatchlog_agent.get('log_group_name'), logStreamNamePrefix=cloudwatchlog_agent.get('log_stream_name')", "= e.response['Error']['Code'] if exception == 'ResourceAlreadyExistsException': logging.debug('Log stream %s already", "] default_ca = local_ca [ local_ca ] database = $dir/database/index.txt", "options: ports_to_try = [int(options['tlsport'])] else: lower_bound, upper_bound = get_tls_port_range(config) tls_ports", "return iam_role_name def credentials_file_helper(file_path, awsprofile): aws_credentials_configs = read_config(file_path) credentials =", "create_string_to_sign(canonical_request, date, region): \"\"\" Create a String to Sign -", "None: return 'default' except (NoSectionError, NoOptionError): continue return awsprofile def", "else: lines.append('%s = %s' % (k, v)) return lines def", "except IOError: logging.debug('Unable to read %s', SYSTEM_RELEASE_PATH) try: with open(OS_RELEASE_PATH)", "output, err error_message = '%s, error is: %s' % (error_message,", "to avoid replay attacks 'PublicKeyHash': quote_plus(public_key_hash), 'X-Amz-Algorithm': ALGORITHM, 'X-Amz-Credential': credential,", "DNS name for an EFS mount target. ' 'Please refer", "399 prim: BIT STRING cmd = 'openssl asn1parse -inform PEM", "# 19:d=1 hl=4 l= 399 prim: BIT STRING cmd =", "os.path.join(tls_paths['mount_dir'], 'certificate.pem') ca_dirs_check(config, tls_paths['database_dir'], tls_paths['certs_dir']) ca_supporting_files_check(tls_paths['index'], tls_paths['index_attr'], tls_paths['serial'], tls_paths['rand']) private_key", "'X-Amz-SignedHeaders': SIGNED_HEADERS, } if session_token: canonical_query_params['X-Amz-Security-Token'] = quote_plus(session_token) # Cannot", "an available port in the range [%d, %d], try specifying", "ALGORITHM = 'AWS4-HMAC-SHA256' AWS4_REQUEST = 'aws4_request' HTTP_REQUEST_METHOD = 'GET' CANONICAL_URI", "session_token except NoOptionError as e: if 'aws_access_key_id' in str(e) or", "82 - 2 length octets to follow (ignore high order", "CAfile \"%s\"' % stunnel_cafile) efs_config['CAfile'] = stunnel_cafile def is_stunnel_option_supported(stunnel_output, stunnel_option_name):", "= subprocess.check_output(['which', command]) except subprocess.CalledProcessError as e: fatal_error('Failed to locate", "% retention_days) def put_cloudwatch_log_retention_policy(cloudwatchlog_client, log_group_name, retention_days): try: cloudwatch_put_retention_policy_helper(cloudwatchlog_client, log_group_name, retention_days)", "% e) return False return True def cloudwatch_describe_log_streams_helper(cloudwatchlog_agent): return cloudwatchlog_agent.get('client').describe_log_streams(", "current_time = get_utc_now() tls_paths = tls_paths_dictionary(mount_name, base_path) certificate_config = os.path.join(tls_paths['mount_dir'],", "]\\nsubjectKeyIdentifier = hash' if ap_id: ca_extension_str += '\\n1.3.6.1.4.1.4843.7.1 = ASN1:UTF8String:'", "incorrectly formatted' % public_key fatal_error(err_msg, err_msg) key_line = key_line.replace(' ',", "= cloudwatchlog_config.get('retention_days') group_creation_completed = create_cloudwatch_log_group(cloudwatchlog_client, log_group_name) if not group_creation_completed: return", "Request(INSTANCE_METADATA_TOKEN_URL) request.add_header('X-aws-ec2-metadata-token-ttl-seconds', 21600) request.get_method = lambda: 'PUT' res = opener.open(request)", "'cmd': command, 'files': files, } if cert_details: state.update(cert_details) with open(os.path.join(state_file_dir,", "log_group_name, e.response)) return True elif exception == 'InvalidParameterException': logging.error('Either parameter", "tells the init system that the # 'efs' type is", "fatal_error('The \"tls\" option is required when mounting via \"accesspoint\"') if", "'%s - mount.log' % (instance_id) elif fs_id: log_stream_name = '%s", "dns_name, fs_id, mountpoint, options) as tunnel_proc: mount_completed = threading.Event() t", "+ 1 options = parse_options(args[options_index]) if not fsname or not", "'amazonaws.com' in dns_name_format: return split_dns_name_format[-3] raise Exception('Region not found in", "sha256 = hashlib.sha256() sha256.update(canonical_request.encode()) string_to_sign += sha256.hexdigest() return string_to_sign def", "for more detail.' % (dns_name, 'https://docs.aws.amazon.com/console/efs/mount-dns-name'), 'Failed to resolve \"%s\"'", "str(e): logging.debug('aws_session_token not found in %s', file_path) credentials['AccessKeyId'] = aws_credentials_configs.get(awsprofile,", "ALGORITHM, 'X-Amz-Credential': credential, 'X-Amz-Date': quote_plus(formatted_datetime), 'X-Amz-Expires': 86400, 'X-Amz-SignedHeaders': SIGNED_HEADERS, }", "Reserved. # # Licensed under the MIT License. See the", "executable. # # You will be able to mount an", "'openssl rsa -in %s -outform PEM -pubout -out %s' %", "mounted, please run 'mount' command to verify\\n\" % mountpoint) logging.warning(\"%s", "in options: options['timeo'] = '600' if 'retrans' not in options:", "instance enable with IMDSv2, Unauthorized 401 error will be thrown,", "return init_system def check_network_target(fs_id): with open(os.devnull, 'w') as devnull: rc", ") for hostname in hostnames: efs_fqdn_match = EFS_FQDN_RE.match(hostname) if efs_fqdn_match:", "== 'DataAlreadyAcceptedException': logging.debug('The event %s was already logged, %s' %", "= %s %s %s %s \"\"\" # SigV4 Auth ALGORITHM", "aws_secret_access_key not found in %s under named profile [%s]', file_path,", "not key_line: err_msg = 'Public key file, %s, is incorrectly", "try to create the key simultaneously. key = get_private_key_path() @contextmanager", "= check_and_create_private_key(base_path) if security_credentials: public_key = os.path.join(tls_paths['mount_dir'], 'publicKey.pem') create_public_key(private_key, public_key)", ") if credentials and credentials_source: return credentials, credentials_source # attempt", "return None session = botocore.session.get_session() region = get_target_region(config) iam_role_name =", "in client_info.items(): efs_client_info_str += '\\n%s = UTF8String:%s' % (key, value)", "e) fatal_error(unsuccessful_resp, unsuccessful_resp) else: return None, None webidentity_url = STS_ENDPOINT_URL", "has any child processes, they can be killed easily by", "if credentials and credentials_source: return credentials, credentials_source error_msg = 'AWS", "Unfortunately this does not conform to Python's config file format,", "header: lines.append('[%s]' % header) for k, v in config.items(): if", "= logging.INFO max_bytes = config.getint(CONFIG_SECTION, 'logging_max_bytes') file_count = config.getint(CONFIG_SECTION, 'logging_file_count')", "expected_replacement_field_ct += 1 config_section = CONFIG_SECTION region = format_args.get('region') if", "= 'yes' else: fatal_error(tls_controls_message % 'stunnel_check_cert_validity') system_release_version = get_system_release_version() if", "credentials_source: return credentials, credentials_source # attempt to lookup AWS security", "\"\"\" while not mount_completed.is_set(): try: test_tunnel_process(tunnel_proc, fs_id) except SystemExit as", "\"region\" ' 'parameter in the efs-utils configuration file.') return region", "options['noresvport'] = None if 'tls' in options: options['port'] = options['tlsport']", "fs_id} expected_replacement_field_ct = 1 if '{region}' in dns_name_format: expected_replacement_field_ct +=", "'tlsport' in options: fatal_error('Specified port [%s] is unavailable. Try selecting", "does not conform to Python's config file format, so we", "is_stunnel_option_supported(stunnel_output, stunnel_option_name): supported = False for line in stunnel_output: if", "if the user has specified tlsport=X at the command line", "dns_name_suffix %s in config section [%s]\", format_args.get('dns_name_suffix'), config_section) _validate_replacement_field_count(dns_name_format, expected_replacement_field_ct)", "cloudwatch_describe_log_streams_helper(cloudwatchlog_agent) except ClientError as e: exception = e.response['Error']['Code'] if exception", "DEFAULT_RETENTION_DAYS = 14 # Cloudwatchlog agent dict includes cloudwatchlog botocore", "= sys.argv fsname = None mountpoint = None options =", "use_iam)} security_credentials, credentials_source = get_aws_security_credentials(use_iam, **kwargs) if credentials_source: cert_details['awsCredentialsMethod'] =", "'/etc/amazon/efs/efs-utils.crt' NOT_BEFORE_MINS = 15 NOT_AFTER_HOURS = 3 EFS_ONLY_OPTIONS = [", "== 'ResourceAlreadyExistsException': logging.debug('Log stream %s already exist in log group", "\"%s\" option is not supported and has been ignored, as", "None, 'SecretAccessKey': None, 'Token': None} try: access_key = aws_credentials_configs.get(awsprofile, 'aws_access_key_id')", "efs_client_info ]' for key, value in client_info.items(): efs_client_info_str += '\\n%s", "efs_config['verify'] = verify_level if verify_level > 0: add_stunnel_ca_options(efs_config, config, options)", "# Choose a random midpoint, and then try ports in-order", "fail if the subprocess has exited already pass else: return", "read_config(file_path) credentials = {'AccessKeyId': None, 'SecretAccessKey': None, 'Token': None} try:", "def mount_nfs(dns_name, path, mountpoint, options): if 'tls' in options: mount_path", "date, region): \"\"\" Create a String to Sign - https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html", "= 3 for retry in range(retry_times): process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE,", "region, fs_id, session_token=None): public_key_hash = get_public_key_sha1(public_key_path) canonical_request = create_canonical_request(public_key_hash, date,", "FEDORA_RELEASE_NAME, SUSE_RELEASE_NAME] def fatal_error(user_message, log_message=None, exit_code=1): if log_message is None:", "to resolve \"%s\" - check that the specified DNS name", "mount.log' % (instance_id) elif fs_id: log_stream_name = '%s - mount.log'", "options = {} if len(args) > 1: fsname = args[1]", "fields') dns_name_format = config.get(CONFIG_SECTION, 'dns_name_format') if '{fs_id}' not in dns_name_format:", "Cannot use urllib.urlencode because it replaces the %s's return '&'.join(['%s=%s'", "DNS name of the mount target matches exactly the DNS", "None def get_resp_obj(request_resp, url, unsuccessful_resp): if request_resp.getcode() != 200: logging.debug(unsuccessful_resp", "v3_ca [ efsPolicy ] CN = supplied [ req ]", "option is required when mounting with named profile option, \"awsprofile\"')", "= [to_nfs_option(k, v) for k, v in options.items() if k", "include a locking mechanism to ensure that the private key", "import sys import threading import time from contextlib import contextmanager", "- https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html \"\"\" def _sign(key, msg): return hmac.new(key, msg.encode('utf-8'), hashlib.sha256)", "remote ) if not hostnames: create_default_cloudwatchlog_agent_if_not_exist(config) fatal_error( 'The specified domain", "def url_request_helper(url, unsuccessful_resp, url_error_msg, headers={}, retry_with_new_header_token=False): try: req = Request(url)", "= os.path.join(state_file_dir, cert_details['mountStateDir'], 'certificate.pem') cert_details['privateKey'] = get_private_key_path() cert_details['fsId'] = fs_id", "log_stream_name = cloudwatchlog_config.get('log_stream_name') retention_days = cloudwatchlog_config.get('retention_days') group_creation_completed = create_cloudwatch_log_group(cloudwatchlog_client, log_group_name)", "return False return True def cloudwatch_create_log_stream_helper(cloudwatchlog_client, log_group_name, log_stream_name): cloudwatchlog_client.create_log_stream( logGroupName=log_group_name,", "def create_ca_conf(config_path, common_name, directory, private_key, date, region, fs_id, security_credentials, ap_id,", "'stunnel_debug_enabled'): global_config['debug'] = 'debug' if config.has_option(CONFIG_SECTION, 'stunnel_logs_file'): global_config['output'] = config.get(CONFIG_SECTION,", "mountpoint = args[2] if len(args) > 4 and '-o' in", "req files if they're not present in their respective directories\"\"\"", "opts = {} for o in options.split(','): if '=' in", "% STS_ENDPOINT_URL url_error_msg = 'Unable to reach %s to retrieve", "# # The script will add recommended mount options, if", "if aws_creds_uri: kwargs = {'aws_creds_uri': aws_creds_uri} else: kwargs = {'awsprofile':", "\"\"\"dir = %s RANDFILE = $dir/database/.rand [ ca ] default_ca", "%s' % e.response) return False elif exception == 'InvalidParameterException': logging.debug('One", "url at %s, reason is %s' % (url, e.reason) if", "= _sign(key_date, region).digest() add_service = _sign(add_region, SERVICE).digest() signing_key = _sign(add_service,", "None global CLOUDWATCHLOG_AGENT if not CLOUDWATCHLOG_AGENT: CLOUDWATCHLOG_AGENT = bootstrap_cloudwatch_logging(config) def", "log_group_name): try: cloudwatch_create_log_group_helper(cloudwatchlog_client, log_group_name) except ClientError as e: exception =", "= region_specific_config_section format_args['dns_name_suffix'] = config.get(config_section, 'dns_name_suffix') logging.debug(\"Using dns_name_suffix %s in", "'/sbin/mount.efs' to be called by 'mount -a' # for this", "the EFS documentation for mounting with DNS names for examples:", "cloudwatchlog_agent.get('log_stream_name'), e.response)) elif exception == 'ResourceNotFoundException': logging.debug('Either log group %s", "in the efs-utils configuration file.') return region except Exception: logging.warning('Legacy", "mount_filename = get_mount_specific_filename(fs_id, mountpoint, tls_port) global_config = dict(STUNNEL_GLOBAL_CONFIG) if config.getboolean(CONFIG_SECTION,", "CANONICAL_URI + '\\n' request += create_canonical_query_string(public_key_hash, credential, formatted_datetime, session_token) +", "should embeded with metadata token if e.code == 401 and", "# and configs file (~/.aws/config) with given awsprofile if awsprofile:", "mount. \"\"\" state_file = '~' + get_mount_specific_filename(fs_id, mountpoint, tls_port) state", "(directory, private_key, common_name, ca_extension_body, efs_client_auth_body, efs_client_info_body) with open(config_path, 'w') as", "- no unused bits in the last content byte offset", "to remove the header and footer '-----(BEGIN|END) PUBLIC KEY-----' with", "file for verification', 'Failed to find CAfile \"%s\"' % stunnel_cafile)", "the request, %s' % error.response) elif exception == 'AccessDeniedException': logging.debug('User", "cloudwatchlog_agent.get('log_stream_name'), e.response)) return False else: logging.debug('Unexpected error: %s' % e)", "mount.efs\\n') sys.exit(1) def read_config(config_file=CONFIG_FILE): try: p = ConfigParser.SafeConfigParser() except AttributeError:", "= ASN1:UTF8String:' + fs_id if client_info: ca_extension_str += '\\n1.3.6.1.4.1.4843.7.4 =", "os.path.exists(file_path): credentials = credentials_file_helper(file_path, awsprofile) if credentials['AccessKeyId']: return credentials, os.path.basename(file_path)", "assert len(tls_ports) == len(ports_to_try) sock = socket.socket() for tls_port in", "options['accesspoint']) if 'iam' in options and 'tls' not in options:", "= dns_name else: fatal_error(tls_controls_message % 'stunnel_check_cert_hostname') # Only use the", "retry_with_new_header_token=True) return iam_role_name def credentials_file_helper(file_path, awsprofile): aws_credentials_configs = read_config(file_path) credentials", "= get_log_stream_next_token(cloudwatchlog_agent) try: cloudwatch_put_log_events_helper(cloudwatchlog_agent, message, token) except ClientError as e:", "'amazon-efs-mount-watchdog' SYSTEM_RELEASE_PATH = '/etc/system-release' OS_RELEASE_PATH = '/etc/os-release' RHEL8_RELEASE_NAME = 'Red", "to tie the signature to a specific key pair to", "AWS4_REQUEST]) def match_device(config, device): \"\"\"Return the EFS id and the", "the port the NFS client uses to connect to stunnel.", "% (log_group_name, e.response)) return False elif exception == 'InvalidParameterException': logging.error('Log", "return split_dns_name_format[-2] elif 'amazonaws.com' in dns_name_format: return split_dns_name_format[-3] raise Exception('Region", "after logging is configured level_error = True level = logging.INFO", "WEB_IDENTITY_TOKEN_FILE_ENV in os.environ: credentials, credentials_source = get_aws_security_credentials_from_webidentity( os.environ[WEB_IDENTITY_ROLE_ARN_ENV], os.environ[WEB_IDENTITY_TOKEN_FILE_ENV], False", "See %s for more info.' % \\ (STS_ENDPOINT_URL, SECURITY_CREDS_WEBIDENTITY_HELP_URL) resp", "def match_device(config, device): \"\"\"Return the EFS id and the remote", "return lower_bound, upper_bound def choose_tls_port(config, options): if 'tlsport' in options:", "err.splitlines() check_host_supported = is_stunnel_option_supported(stunnel_output, b'checkHost') ocsp_aia_supported = is_stunnel_option_supported(stunnel_output, b'OCSPaia') return", "are mutually exclusive') if 'tlsport' in options: try: int(options['tlsport']) except", "\"\"\"Parse arguments, return (fsid, path, mountpoint, options)\"\"\" if args is", "or not os.path.isdir(directory): raise @contextmanager def bootstrap_tls(config, init_system, dns_name, fs_id,", "fs_id + '\\n' request += SIGNED_HEADERS + '\\n' sha256 =", "log_group_name) def create_cloudwatch_log_group(cloudwatchlog_client, log_group_name): try: cloudwatch_create_log_group_helper(cloudwatchlog_client, log_group_name) except ClientError as", "= no policy = efsPolicy x509_extensions = v3_ca [ efsPolicy", "return '%s=%s' % (str(k), str(v)) nfs_options = [to_nfs_option(k, v) for", "' %s: ResponseCode=%d', url, request_resp.getcode()) return None resp_body = request_resp.read()", "credentials with IAM role name attached to instance # through", "occurring in parallel may try to create the key simultaneously.", "Try selecting a different port.' % options['tlsport']) else: fatal_error('Failed to", "tests \"\"\" return datetime.utcnow() def assert_root(): if os.geteuid() != 0:", "%s.' % INSTANCE_METADATA_SERVICE_URL ec2_metadata_url_error_msg = 'Unable to reach %s to", "the mount attempt to fail fast if the tunnel dies", "to locate %s in %s - %s' % (command, env_path,", "that exist in the last # content byte. Note that", "-out %s' % (config_path, private_key, csr_path) subprocess_call(cmd, 'Failed to create", "string_to_sign def calculate_signature(string_to_sign, date, secret_access_key, region): \"\"\" Calculate the Signature", "if type(v) is list: for item in v: lines.append('%s =", "for patching purposes in unit tests \"\"\" return datetime.utcnow() def", "lookup AWS security credentials through the credentials URI the ECS", "under # the License. # # # Copy this script", "the remote path to mount\"\"\" try: remote, path = device.split(':',", "headers = {'X-aws-ec2-metadata-token-ttl-seconds': 21600} req = Request(INSTANCE_METADATA_TOKEN_URL, headers=headers, method='PUT') res", "by looking for the key BIT STRING # Example: #", "threading import time from contextlib import contextmanager from datetime import", "# # Using the 'efs' type will cause '/sbin/mount.efs' to", "access_key_id efs_client_auth_str += '\\nsignature = OCTETSTRING:' + signature efs_client_auth_str +=", "= config.getint(CONFIG_SECTION, 'logging_file_count') handler = RotatingFileHandler(os.path.join(log_dir, LOG_FILE), maxBytes=max_bytes, backupCount=file_count) handler.setFormatter(logging.Formatter(fmt='%(asctime)s", "default_md = sha256 preserve = no policy = efsPolicy x509_extensions", "in the last # content byte. Note that this is", "get_utc_now() tls_paths = tls_paths_dictionary(mount_name, base_path) certificate_config = os.path.join(tls_paths['mount_dir'], 'config.conf') certificate_signing_request", "ignored, as amazon-efs-utils relies on a built-in ' \\ 'trust", "'Public key file, %s, is incorrectly formatted' % public_key fatal_error(err_msg,", "'Unsuccessful retrieval of AWS security credentials at %s.' % ecs_uri", "options.items() if k not in EFS_ONLY_OPTIONS] return ','.join(nfs_options) def mount_nfs(dns_name,", "id is found under [default] section in current file and", "AWS4_REQUEST = 'aws4_request' HTTP_REQUEST_METHOD = 'GET' CANONICAL_URI = '/' CANONICAL_HEADERS_DICT", "if not BOTOCORE_PRESENT: logging.error('Failed to import botocore, please install botocore", "iam_role_name def credentials_file_helper(file_path, awsprofile): aws_credentials_configs = read_config(file_path) credentials = {'AccessKeyId':", "a file. Unfortunately this does not conform to Python's config", "open(OS_RELEASE_PATH) as f: for line in f: if 'PRETTY_NAME' in", "% (fs_id) else: log_stream_name = 'default - mount.log' return log_stream_name", "create_canonical_query_string(public_key_hash, credential, formatted_datetime, session_token) + '\\n' request += CANONICAL_HEADERS %", "don't exist).\"\"\" if not os.path.exists(database_dir): create_required_directory(config, database_dir) if not os.path.exists(certs_dir):", "run 'mount' command to verify\\n\" % mountpoint) logging.warning(\"%s is already", "ImportError: from configparser import ConfigParser, NoOptionError, NoSectionError try: from urllib.parse", "defined as %d.' % (upper_bound, lower_bound)) return lower_bound, upper_bound def", "fs_id, security_credentials['Token']) if security_credentials else '' efs_client_info_body = efs_client_info_builder(client_info) if", "is_fatal: log_message = 'AWS security credentials not found in %s", "8' CENTOS8_RELEASE_NAME = 'CentOS Linux release 8' FEDORA_RELEASE_NAME = 'Fedora", "stderr=subprocess.PIPE, close_fds=True) (output, err) = process.communicate() rc = process.poll() if", "socket.socket() for tls_port in ports_to_try: try: sock.bind(('localhost', tls_port)) sock.close() return", "pass try: os.makedirs(directory, mode) except OSError as e: if errno.EEXIST", "that the # 'efs' type is a networked file system", "num_length_octets), and number of unused bits (1) offset = 1", "'tlsport' in options: ports_to_try = [int(options['tlsport'])] else: lower_bound, upper_bound =", "'Error reading token file %s: %s' % (token_file, e) fatal_error(unsuccessful_resp,", "with metadata token if e.code == 401 and retry_with_new_header_token: token", "SIGNED_HEADERS, } if session_token: canonical_query_params['X-Amz-Security-Token'] = quote_plus(session_token) # Cannot use", "% (ecs_uri, SECURITY_CREDS_ECS_URI_HELP_URL) ecs_security_dict = url_request_helper(ecs_uri, ecs_unsuccessful_resp, ecs_url_error_msg) if ecs_security_dict", "= [] if header: lines.append('[%s]' % header) for k, v", "region = get_region_from_legacy_dns_format(config) sys.stdout.write('Warning: region obtained from \"dns_name_format\" field. Please", "access_key_id, region, fs_id, session_token) string_to_sign = create_string_to_sign(canonical_request, date, region) signature", "' 'must be strictly greater than \"port_range_lower_bound\" defined as %d.'", "False else: logging.debug('Unexpected error: %s' % e) return False except", "%s', DEFAULT_STUNNEL_CAFILE) stunnel_cafile = DEFAULT_STUNNEL_CAFILE if not os.path.exists(stunnel_cafile): fatal_error('Failed to", "# # Copyright 2017-2018 Amazon.com, Inc. and its affiliates. All", "header and footer '-----(BEGIN|END) PUBLIC KEY-----' with open(public_key, 'r') as", "ID and Secret Access Key are not found in AWS", "config file %s', awsprofile, file_path) return credentials def get_aws_profile(options, use_iam):", "(remote, 'https://docs.aws.amazon.com/efs/latest/ug/mounting-fs-mount-cmd-dns-name.html')) def is_nfs_mount(mountpoint): cmd = ['stat', '-f', '-L', '-c',", "stderr=subprocess.PIPE, preexec_fn=os.setsid, close_fds=True) logging.info('Started TLS tunnel, pid: %d', tunnel_proc.pid) temp_tls_state_file", "sha256.hexdigest() return request def create_canonical_query_string(public_key_hash, credential, formatted_datetime, session_token=None): canonical_query_params =", "% (key, value) return efs_client_info_str def create_public_key(private_key, public_key): cmd =", "{ 'logGroupName': cloudwatchlog_agent.get('log_group_name'), 'logStreamName': cloudwatchlog_agent.get('log_stream_name'), 'logEvents': [ { 'timestamp': int(round(time.time()", "logging.info('version=%s options=%s', VERSION, options) global CLOUDWATCHLOG_AGENT CLOUDWATCHLOG_AGENT = bootstrap_cloudwatch_logging(config, fs_id)", "all(k in creds for k in ['AccessKeyId', 'SecretAccessKey', 'SessionToken']): return", "options = parse_arguments(config) logging.info('version=%s options=%s', VERSION, options) global CLOUDWATCHLOG_AGENT CLOUDWATCHLOG_AGENT", "the range [%d, %d], try specifying a different port range", "open(stunnel_config_file, 'w') as f: f.write(stunnel_config) return stunnel_config_file def write_tls_tunnel_state_file(fs_id, mountpoint,", "replacement fields') dns_name_format = config.get(CONFIG_SECTION, 'dns_name_format') if '{fs_id}' not in", "(lower_bound, upper_bound, CONFIG_FILE)) def is_ocsp_enabled(config, options): if 'ocsp' in options:", "to locate an available port in the range [%d, %d],", "later override the port the NFS client uses to connect", "None, None def get_aws_security_credentials_from_webidentity(role_arn, token_file, is_fatal=False): try: with open(token_file, 'r')", "use_iam): awsprofile = options.get('awsprofile') if not awsprofile and use_iam: for", "the mount target matches exactly the DNS name the CNAME", "if config.has_option(CLIENT_INFO_SECTION, 'source'): client_source = config.get(CLIENT_INFO_SECTION, 'source') if 0 <", "botocore.session.get_session() region = get_target_region(config) iam_role_name = get_iam_role_name() if iam_role_name: credentials,", "\"\"\" Create a Canonical Request - https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html \"\"\" formatted_datetime =", "from urllib import quote_plus try: from urllib2 import URLError, HTTPError,", "token = f.read() except Exception as e: if is_fatal: unsuccessful_resp", "os._exit \"\"\" while not mount_completed.is_set(): try: test_tunnel_process(tunnel_proc, fs_id) except SystemExit", "not mountpoint: usage(out=sys.stderr) fs_id, path = match_device(config, fsname) return fs_id,", "slow, so we will create one private key and allow", "encode the number of octets that follow # - the", "resolves to if hostname == expected_dns_name: return fs_id, path else:", "+ '\\n' request += CANONICAL_HEADERS % fs_id + '\\n' request", "upper_bound: fatal_error('Configuration option \"port_range_upper_bound\" defined as %d ' 'must be", "to the endpoint, %s' % e) return None except Exception", "= get_init_system() check_network_status(fs_id, init_system) dns_name = get_dns_name(config, fs_id) if 'tls'", "dns_name efs_config['verify'] = verify_level if verify_level > 0: add_stunnel_ca_options(efs_config, config,", "{ 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical':", "None def handle_general_botocore_exceptions(error): exception = error.response['Error']['Code'] if exception == 'ServiceUnavailableException':", "a process group so if it has any child processes,", "to lookup AWS security credentials through AssumeRoleWithWebIdentity # (e.g. for", "p = ConfigParser() p.read(config_file) return p def bootstrap_logging(config, log_dir=LOG_DIR): raw_level", "to be called by 'mount -a' # for this file", "+ access_key_id efs_client_auth_str += '\\nsignature = OCTETSTRING:' + signature efs_client_auth_str", "well at man/mount.efs.8 if 'nfsvers' not in options and 'vers'", "should only be used if region is not present in", "mount_completed.is_set(): try: test_tunnel_process(tunnel_proc, fs_id) except SystemExit as e: os._exit(e.code) mount_completed.wait(.5)", "get_cloudwatchlog_config(config, fs_id) log_group_name = cloudwatchlog_config.get('log_group_name') log_stream_name = cloudwatchlog_config.get('log_stream_name') retention_days =", "logging.debug(unsuccessful_resp + ' %s: ResponseCode=%d', url, request_resp.getcode()) return None resp_body", "socket.gethostname()[0:64] cert_details['region'] = get_target_region(config) cert_details['certificateCreationTime'] = create_certificate(config, cert_details['mountStateDir'], cert_details['commonName'], cert_details['region'],", "if exception == 'InvalidSequenceTokenException': logging.debug('The sequence token is not valid,", "cannot be fetched from the given aws_creds_uri if is_fatal: fatal_error(unsuccessful_resp,", "not cloudwatchlog_agent or not cloudwatchlog_agent.get('client'): return False token = get_log_stream_next_token(cloudwatchlog_agent)", "CA file configured, using default CA file %s', DEFAULT_STUNNEL_CAFILE) stunnel_cafile", "ID %s is malformed' % options['accesspoint']) if 'iam' in options", "in options: mount_path = '127.0.0.1:%s' % path else: mount_path =", "rc != 0: logging.error('Command %s failed, rc=%s, stdout=\"%s\", stderr=\"%s\"' %", "%s is specified incorrectly, %s' % (log_group_name, retention_days, e.response)) return", "% e) return None try: log_stream = response['logStreams'][0] return log_stream.get('uploadSequenceToken')", "stream %s does not exist, %s' % (cloudwatchlog_agent.get('log_group_name'), cloudwatchlog_agent.get('log_stream_name'), e.response))", "ecs_security_dict for k in CREDENTIALS_KEYS): return ecs_security_dict, 'ecs:' + aws_creds_uri", "publish_cloudwatch_log(CLOUDWATCHLOG_AGENT, 'Mount failed, %s' % log_message) sys.exit(exit_code) def get_target_region(config): def", "SystemExit as e: os._exit(e.code) mount_completed.wait(.5) def get_init_system(comm_file='/proc/1/comm'): init_system = 'unknown'", "except socket.gaierror: fatal_error('Failed to resolve \"%s\" - check that your", "mount_completed.wait(.5) def get_init_system(comm_file='/proc/1/comm'): init_system = 'unknown' try: with open(comm_file) as", "release' SUSE_RELEASE_NAME = 'openSUSE Leap' SKIP_NO_LIBWRAP_RELEASES = [RHEL8_RELEASE_NAME, CENTOS8_RELEASE_NAME, FEDORA_RELEASE_NAME,", "NoOptionError: logging.debug('No CA file configured, using default CA file %s',", "b'checkHost') ocsp_aia_supported = is_stunnel_option_supported(stunnel_output, b'OCSPaia') return check_host_supported, ocsp_aia_supported def _stunnel_bin():", "else: fatal_error(tls_controls_message % 'stunnel_check_cert_hostname') # Only use the config setting", "canonical_request = create_canonical_request(public_key_hash, date, access_key_id, region, fs_id, session_token) string_to_sign =", "= False if not level: # delay logging error about", "of replacement fields') dns_name_format = config.get(CONFIG_SECTION, 'dns_name_format') if '{fs_id}' not", "from ConfigParser import NoOptionError, NoSectionError except ImportError: from configparser import", "'openssl ca -startdate %s -enddate %s -selfsign -batch -notext -config", "NOT_AFTER_HOURS = 3 EFS_ONLY_OPTIONS = [ 'accesspoint', 'awscredsuri', 'awsprofile', 'cafile',", "pass try: return get_region_from_instance_metadata() except Exception as e: metadata_exception =", "NFS client uses to connect to stunnel. # if the", "OSError: # Silently fail if the subprocess has exited already", "False return True def cloudwatch_put_retention_policy_helper(cloudwatchlog_client, log_group_name, retention_days): cloudwatchlog_client.put_retention_policy( logGroupName=log_group_name, retentionInDays=retention_days", "type will cause '/sbin/mount.efs' to be called by 'mount -a'", "= subprocess.call(['systemctl', 'is-active', '--quiet', WATCHDOG_SERVICE], close_fds=True) if rc != 0:", "= 'debug' if config.has_option(CONFIG_SECTION, 'stunnel_logs_file'): global_config['output'] = config.get(CONFIG_SECTION, 'stunnel_logs_file').replace('{fs_id}', fs_id)", "release 8' FEDORA_RELEASE_NAME = 'Fedora release' SUSE_RELEASE_NAME = 'openSUSE Leap'", "failed, rc=%s, stdout=\"%s\", stderr=\"%s\"' % (cmd, rc, output, err), exc_info=True)", "if iam_role_name: credentials, _ = get_aws_security_credentials_from_instance_metadata(iam_role_name) if credentials: return session.create_client(service,", "awsprofile # Fail if credentials cannot be fetched from the", "AP_ID_RE = re.compile('^fsap-[0-9a-f]{17}$') CREDENTIALS_KEYS = ['AccessKeyId', 'SecretAccessKey', 'Token'] ECS_URI_ENV =", "elif 'noocsp' in options: return False else: return config.getboolean(CONFIG_SECTION, 'stunnel_check_cert_validity')", "token = get_log_stream_next_token(cloudwatchlog_agent) try: cloudwatch_put_log_events_helper(cloudwatchlog_agent, message, token) except ClientError as", "os.path.exists(stunnel_cafile): fatal_error('Failed to find certificate authority file for verification', 'Failed", "options: return True elif 'noocsp' in options: return False else:", "file # for the specific language governing permissions and limitations", "options: if 'port' in options: fatal_error('The \"port\" and \"tls\" options", "f.write('00') if not os.path.isfile(rand_path): open(rand_path, 'w').close() def get_certificate_timestamp(current_time, **kwargs): updated_time", "'/sbin:/usr/sbin:/usr/local/sbin:/root/bin:/usr/local/bin:/usr/bin:/bin' os.putenv('PATH', env_path) path = subprocess.check_output(['which', command]) except subprocess.CalledProcessError as", "else: return None, None def get_aws_security_credentials_from_ecs(aws_creds_uri, is_fatal=False): ecs_uri = ECS_TASK_METADATA_API", "credentials = {'AccessKeyId': None, 'SecretAccessKey': None, 'Token': None} try: access_key", "logging.handlers import RotatingFileHandler try: import ConfigParser from ConfigParser import NoOptionError,", "# Cloudwatchlog agent dict includes cloudwatchlog botocore client, cloudwatchlog group", "else: handle_general_botocore_exceptions(e) return False except NoCredentialsError as e: logging.warning('Credentials are", "error about malformed log level until after logging is configured", "opts[o] = None return opts def get_tls_port_range(config): lower_bound = config.getint(CONFIG_SECTION,", "elif 'amazonaws.com' in dns_name_format: return split_dns_name_format[-3] raise Exception('Region not found", "in %s: %s' % (property, instance_identity, e)) except TypeError as", "else: message = 'Failed to mount %s at %s: returncode=%d,", "return False else: handle_general_botocore_exceptions(e) return False except NoCredentialsError as e:", "logging.debug('aws_access_key_id or aws_secret_access_key not found in %s under named profile", "amazon-efs-utils relies on a built-in ' \\ 'trust store.' %", "o.split('=') opts[k] = v else: opts[o] = None return opts", "set the \"region\" parameter in the efs-utils configuration file.', message)", "aka content # # For a BIT STRING, the first", "'verify' ] UNSUPPORTED_OPTIONS = [ 'capath' ] STUNNEL_GLOBAL_CONFIG = {", "'/' if FS_ID_RE.match(remote): return remote, path try: primary, secondaries, _", "mountpoint, options)\"\"\" if args is None: args = sys.argv fsname", "parallel may try to create the key simultaneously. key =", "region. Please set the \"region\" parameter in the efs-utils configuration", "def is_ocsp_enabled(config, options): if 'ocsp' in options: return True elif", "[-o <options>]\\n') sys.exit(exit_code) def parse_arguments_early_exit(args=None): \"\"\"Parse arguments, checking for early", "credentials_file_helper(file_path, awsprofile): aws_credentials_configs = read_config(file_path) credentials = {'AccessKeyId': None, 'SecretAccessKey':", "unsupported_option sys.stderr.write('WARN: %s\\n' % warn_message) logging.warning(warn_message) del options[unsupported_option] def check_options_validity(options):", "log_dir=LOG_DIR): raw_level = config.get(CONFIG_SECTION, 'logging_level') levels = { 'debug': logging.DEBUG,", "logging.warning('Unknown error, %s.' % e) return False return True def", "the Signature - https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html \"\"\" def _sign(key, msg): return hmac.new(key,", "sha256.hexdigest() return string_to_sign def calculate_signature(string_to_sign, date, secret_access_key, region): \"\"\" Calculate", "security credentials with IAM role name attached to instance #", "is None: return k return '%s=%s' % (str(k), str(v)) nfs_options", "for unsupported_option in UNSUPPORTED_OPTIONS: if unsupported_option in options: warn_message =", "event %s was already logged, %s' % (message, e.response)) return", "cloudwatchlog stream name CLOUDWATCHLOG_AGENT = None LOG_DIR = '/var/log/amazon/efs' LOG_FILE", "True def cloudwatch_put_retention_policy_helper(cloudwatchlog_client, log_group_name, retention_days): cloudwatchlog_client.put_retention_policy( logGroupName=log_group_name, retentionInDays=retention_days ) logging.debug('Set", "last # content byte. Note that this is explicitly excluded", "response error messages\"\"\" retry_times = 3 for retry in range(retry_times):", "'-L', '-c', '%T', mountpoint] p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)", "an incorrect number of replacement fields') dns_name_format = config.get(CONFIG_SECTION, 'dns_name_format')", "if 'soft' not in options and 'hard' not in options:", "logging.debug('Multiple requests to update the same log group %s were", "return fs_id, path else: create_default_cloudwatchlog_agent_if_not_exist(config) fatal_error('The specified CNAME \"%s\" did", "handle response error messages\"\"\" retry_times = 3 for retry in", "'WebIdentityToken': token }) unsuccessful_resp = 'Unsuccessful retrieval of AWS security", "global_config['output'] = os.path.join(log_dir, '%s.stunnel.log' % mount_filename) efs_config = dict(STUNNEL_EFS_CONFIG) efs_config['accept']", "botocore client, cloudwatchlog group name, cloudwatchlog stream name CLOUDWATCHLOG_AGENT =", "an EFS mount target' % remote ) for hostname in", "(error_message, err) fatal_error(error_message, error_message) def ca_dirs_check(config, database_dir, certs_dir): \"\"\"Check if", "BIT STRING cmd = 'openssl asn1parse -inform PEM -in %s'", "subprocess.call(['systemctl', 'is-active', '--quiet', WATCHDOG_SERVICE], close_fds=True) if rc != 0: with", "region_specific_config_section = '%s.%s' % (CONFIG_SECTION, region) if config.has_section(region_specific_config_section): config_section =", "= '[ efs_client_info ]' for key, value in client_info.items(): efs_client_info_str", "https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html \"\"\" string_to_sign = ALGORITHM + '\\n' string_to_sign += date.strftime(SIGV4_DATETIME_FORMAT)", "bits in the last content byte offset = int(key_line.split(':')[0]) key", "mounts to share it. # This means, however, that we", "ecs_url_error_msg) if ecs_security_dict and all(k in ecs_security_dict for k in", "1 # - the remaining 127 bits are used to", "common_name, directory, private_key, date, region, fs_id, security_credentials, ap_id, client_info): \"\"\"Populate", "- mount.log' % (fs_id, instance_id) elif instance_id: log_stream_name = '%s", "%(message)s')) logger = logging.getLogger() logger.setLevel(level) logger.addHandler(handler) if level_error: logging.error('Malformed logging", "ca -startdate %s -enddate %s -selfsign -batch -notext -config %s", "ca_extension_body = ca_extension_builder(ap_id, security_credentials, fs_id, client_info) efs_client_auth_body = efs_client_auth_builder(public_key_path, security_credentials['AccessKeyId'],", "section [%s]\", format_args.get('dns_name_suffix'), config_section) _validate_replacement_field_count(dns_name_format, expected_replacement_field_ct) dns_name = dns_name_format.format(**format_args) try:", "%s RANDFILE = $dir/database/.rand [ ca ] default_ca = local_ca", "ca_extension_str def efs_client_auth_builder(public_key_path, access_key_id, secret_access_key, date, region, fs_id, session_token=None): public_key_hash", "and all(k in ecs_security_dict for k in CREDENTIALS_KEYS): return ecs_security_dict,", "entry in fstab, the file system can be mounted with:", "to lookup AWS security credentials through the credentials URI the", "'certs_dir': os.path.join(base_path, mount_name, 'certs'), 'index': os.path.join(base_path, mount_name, 'database/index.txt'), 'index_attr': os.path.join(base_path,", "open(config_path, 'w') as f: f.write(full_config_body) return full_config_body def ca_extension_builder(ap_id, security_credentials,", "error is: %s' % (error_message, err) fatal_error(error_message, error_message) def ca_dirs_check(config,", "= o.split('=') opts[k] = v else: opts[o] = None return", "import os import pwd import random import re import socket", "secondaries)) except socket.gaierror: create_default_cloudwatchlog_agent_if_not_exist(config) fatal_error( 'Failed to resolve \"%s\" -", "6:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption # 17:d=2 hl=2", "name CLOUDWATCHLOG_AGENT = None LOG_DIR = '/var/log/amazon/efs' LOG_FILE = 'mount.log'", "= [ 'accesspoint', 'awscredsuri', 'awsprofile', 'cafile', 'iam', 'netns', 'noocsp', 'ocsp',", "f.read().strip() except IOError: logging.debug('Unable to read %s', SYSTEM_RELEASE_PATH) try: with", "this file system. The '_netdev' option tells the init system", "CN = %s %s %s %s \"\"\" # SigV4 Auth", "Secret Access Key are not found in AWS credentials file", "def get_cloudwatch_log_stream_name(fs_id=None): instance_id = get_instance_identity_info_from_instance_metadata('instanceId') if instance_id and fs_id: log_stream_name", "ocsp_enabled = is_ocsp_enabled(config, options) stunnel_config_file = write_stunnel_config_file(config, state_file_dir, fs_id, mountpoint,", "if region is not present in the config file and", "pass return None def handle_general_botocore_exceptions(error): exception = error.response['Error']['Code'] if exception", "\\ 'or disable \"%%s\" in %s.\\nSee %s for more detail.'", "and footer '-----(BEGIN|END) PUBLIC KEY-----' with open(public_key, 'r') as f:", "FS_ID_RE.match(remote): return remote, path try: primary, secondaries, _ = socket.gethostbyname_ex(remote)", "config.get(CLIENT_INFO_SECTION, 'source') if 0 < len(client_source) <= CLIENT_SOURCE_STR_LEN_LIMIT: client_info['source'] =", "else: opts[o] = None return opts def get_tls_port_range(config): lower_bound =", "os.path.abspath(mountpoint).replace(os.sep, '.').lstrip('.'), tls_port) def serialize_stunnel_config(config, header=None): lines = [] if", "= access_key credentials['SecretAccessKey'] = secret_key credentials['Token'] = session_token except NoOptionError", "%s or log stream name %s is specified incorrectly, %s'", "disable \"%%s\" in %s.\\nSee %s for more detail.' % (CONFIG_FILE,", "in options: options['rsize'] = '1048576' if 'wsize' not in options:", "def main(): parse_arguments_early_exit() assert_root() config = read_config() bootstrap_logging(config) fs_id, path,", "file with fresh configurations at every mount since SigV4 signature", "update the same log group %s were in conflict, %s'", "cloudwatchlog_config.get('log_group_name') log_stream_name = cloudwatchlog_config.get('log_stream_name') retention_days = cloudwatchlog_config.get('retention_days') group_creation_completed = create_cloudwatch_log_group(cloudwatchlog_client,", "canonical_query_params = { 'Action': 'Connect', # Public key hash is", "fast if the tunnel dies - since this is not", "IOError: logging.debug('Unable to read %s', OS_RELEASE_PATH) return 'unknown' def write_stunnel_config_file(config,", "file_path in [AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE]: aws_credentials_configs = read_config(file_path) # check if", "client_source = config.get(CLIENT_INFO_SECTION, 'source') if 0 < len(client_source) <= CLIENT_SOURCE_STR_LEN_LIMIT:", "file system by its short name, by adding it #", "request.get_method = lambda: 'PUT' res = opener.open(request) return res.read() except", "options, state_file_dir=STATE_FILE_DIR): tls_port = choose_tls_port(config, options) # override the tlsport", "for an EFS mount target. ' 'Please refer to the", "= urlopen(req, timeout=1) return get_resp_obj(request_resp, url, unsuccessful_resp) except HTTPError as", "get_aws_security_credentials(use_iam, **kwargs) if credentials_source: cert_details['awsCredentialsMethod'] = credentials_source if ap_id: cert_details['accessPoint']", "= get_instance_identity_info_from_instance_metadata('instanceId') if instance_id and fs_id: log_stream_name = '%s -", "process.poll() if rc != 0: logging.error('Command %s failed, rc=%s, stdout=\"%s\",", "json object: %s' % (instance_identity, e)) return None def get_region_from_legacy_dns_format(config):", "cert_details['certificateCreationTime'] = create_certificate(config, cert_details['mountStateDir'], cert_details['commonName'], cert_details['region'], fs_id, security_credentials, ap_id, client_info,", "cmd = 'openssl rsa -in %s -outform PEM -pubout -out", "run mount.efs\\n') sys.exit(1) def read_config(config_file=CONFIG_FILE): try: p = ConfigParser.SafeConfigParser() except", "str(v)) nfs_options = [to_nfs_option(k, v) for k, v in options.items()", "length of 399 # - 00 - no unused bits", "not BOTOCORE_PRESENT: logging.error('Failed to import botocore, please install botocore first.')", "mount target. ' 'Please refer to the EFS documentation for", "= proc.communicate() if 'stop' in status: with open(os.devnull, 'w') as", "path = match_device(config, fsname) return fs_id, path, mountpoint, options def", "'https://docs.aws.amazon.com/efs/latest/ug/mounting-fs-mount-cmd-dns-name.html')) def is_nfs_mount(mountpoint): cmd = ['stat', '-f', '-L', '-c', '%T',", "fetched from the given aws_creds_uri if is_fatal: fatal_error(ecs_unsuccessful_resp, ecs_unsuccessful_resp) else:", "mount_name, 'certs'), 'index': os.path.join(base_path, mount_name, 'database/index.txt'), 'index_attr': os.path.join(base_path, mount_name, 'database/index.txt.attr'),", "False else: return config.getboolean(CONFIG_SECTION, 'stunnel_check_cert_validity') def get_mount_specific_filename(fs_id, mountpoint, tls_port): return", "if not check_if_cloudwatch_log_enabled(config): return None cloudwatchlog_client = get_botocore_client(config, 'logs') if", "Request(url) for k, v in headers.items(): req.add_header(k, v) request_resp =", "generated if aws_creds_uri: return get_aws_security_credentials_from_ecs(aws_creds_uri, True) # attempt to lookup", "if WEB_IDENTITY_ROLE_ARN_ENV in os.environ and WEB_IDENTITY_TOKEN_FILE_ENV in os.environ: credentials, credentials_source", "def _stunnel_bin(): return find_command_path('stunnel', 'Please install it following the instructions", "mountpoint, options, state_file_dir=STATE_FILE_DIR): tls_port = choose_tls_port(config, options) # override the", "on a built-in ' \\ 'trust store.' % unsupported_option sys.stderr.write('WARN:", "%s were in conflict, %s' % (log_group_name, e.response)) return False", "options) else: mount_nfs(dns_name, path, mountpoint, options) if '__main__' == __name__:", "credentials, credentials_source error_msg = 'AWS Access Key ID and Secret", "cloudwatchlog_client: return None cloudwatchlog_config = get_cloudwatchlog_config(config, fs_id) log_group_name = cloudwatchlog_config.get('log_group_name')", "'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL } level = levels.get(raw_level.lower())", "fatal_error('The \"port\" and \"tls\" options are mutually exclusive') if 'tlsport'", "aws_credentials_configs.get('default', 'aws_access_key_id') if access_key is not None: return 'default' except", "'Unable to reach %s to retrieve IAM role name. See", "exist, %s' % (log_group_name, e.response)) return False elif exception ==", "it # to /etc/fstab. The syntax of an fstab entry", "and retry_with_new_header_token: token = get_aws_ec2_metadata_token() req.add_header('X-aws-ec2-metadata-token', token) request_resp = urlopen(req,", "return awsprofile def url_request_helper(url, unsuccessful_resp, url_error_msg, headers={}, retry_with_new_header_token=False): try: req", "generate_key(): if os.path.isfile(key): return cmd = 'openssl genpkey -algorithm RSA", "'stunnel_logs_file').replace('{fs_id}', fs_id) else: global_config['output'] = os.path.join(log_dir, '%s.stunnel.log' % mount_filename) efs_config", "try: env_path = '/sbin:/usr/sbin:/usr/local/sbin:/root/bin:/usr/local/bin:/usr/bin:/bin' os.putenv('PATH', env_path) path = subprocess.check_output(['which', command])", "% tls_port efs_config['connect'] = efs_config['connect'] % dns_name efs_config['verify'] = verify_level", "valid DNS name for an EFS mount target. ' 'Please", "level until after logging is configured level_error = True level", "%s -out %s' % (config_path, private_key, csr_path) subprocess_call(cmd, 'Failed to", "1 config_section = CONFIG_SECTION region = format_args.get('region') if region: region_specific_config_section", "= no distinguished_name = req_distinguished_name [ req_distinguished_name ] CN =", "error, %s.' % e) return False return True def cloudwatch_put_log_events_helper(cloudwatchlog_agent,", "%s' % (error_message, err) fatal_error(error_message, error_message) def ca_dirs_check(config, database_dir, certs_dir):", "= threading.Event() t = threading.Thread(target=poll_tunnel_process, args=(tunnel_proc, fs_id, mount_completed)) t.daemon =", "not conform to Python's config file format, so we have", "full_config_body def ca_extension_builder(ap_id, security_credentials, fs_id, client_info): ca_extension_str = '[ v3_ca", "webidentity_url = STS_ENDPOINT_URL + '?' + urlencode({ 'Version': '2011-06-15', 'Action':", "if 'BIT STRING' in line.decode('utf-8'): key_line = line.decode('utf-8') if not", "check_if_cloudwatch_log_enabled(config): return None cloudwatchlog_client = get_botocore_client(config, 'logs') if not cloudwatchlog_client:", "credentials['SecretAccessKey'] = aws_credentials_configs.get(awsprofile, 'aws_secret_access_key') except NoSectionError: logging.debug('No [%s] section found", "hash' if ap_id: ca_extension_str += '\\n1.3.6.1.4.1.4843.7.1 = ASN1:UTF8String:' + ap_id", "= config.get(CONFIG_SECTION, 'state_file_dir_mode') try: mode = int(mode_str, 8) except ValueError:", "'certificate.pem') ca_dirs_check(config, tls_paths['database_dir'], tls_paths['certs_dir']) ca_supporting_files_check(tls_paths['index'], tls_paths['index_attr'], tls_paths['serial'], tls_paths['rand']) private_key =", "= response['logStreams'][0] return log_stream.get('uploadSequenceToken') except (IndexError, TypeError, KeyError): pass return", "True elif exception == 'LimitExceededException': logging.error('Reached the maximum number of", "init_system != 'systemd': logging.debug('Not testing network on non-systemd init systems')", "'webidentity:' + ','.join([role_arn, token_file]) # Fail if credentials cannot be", "rc != 0: fatal_error('Failed to mount %s because the network", "if not stream_creation_completed: return None return { 'client': cloudwatchlog_client, 'log_group_name':", "device.split(':', 1) except ValueError: remote = device path = '/'", "e.response) return False elif exception == 'OperationAbortedException': logging.debug('Multiple requests to", "def credentials_file_helper(file_path, awsprofile): aws_credentials_configs = read_config(file_path) credentials = {'AccessKeyId': None,", "the first octet (byte) is the tag (type) # -", "in canonical request to tie the signature to a specific", "= 'Unable to reach %s to retrieve IAM role name.", "ImportError: from urllib import quote_plus try: from urllib2 import URLError,", "args=(tunnel_proc, fs_id, mount_completed)) t.daemon = True t.start() mount_nfs(dns_name, path, mountpoint,", "parse_options(options): opts = {} for o in options.split(','): if '='", "find_command_path('stunnel', 'Please install it following the instructions at ' 'https://docs.aws.amazon.com/efs/latest/ug/using-amazon-efs-utils.html#upgrading-stunnel')", "key_date = _sign(('AWS4' + secret_access_key).encode('utf-8'), date.strftime(DATE_ONLY_FORMAT)).digest() add_region = _sign(key_date, region).digest()", "the maximum number of log groups that can be created,", "get_private_key_path() cert_details['fsId'] = fs_id start_watchdog(init_system) if not os.path.exists(state_file_dir): create_required_directory(config, state_file_dir)", "get_mount_specific_filename(fs_id, mountpoint, tls_port) global_config = dict(STUNNEL_GLOBAL_CONFIG) if config.getboolean(CONFIG_SECTION, 'stunnel_debug_enabled'): global_config['debug']", "return None def get_region_from_legacy_dns_format(config): \"\"\" For backwards compatibility check dns_name_format", "logging.warning('response %s is not a json object: %s' % (instance_identity,", "'Version': '2011-06-15', 'Action': 'AssumeRoleWithWebIdentity', 'RoleArn': role_arn, 'RoleSessionName': 'efs-mount-helper', 'WebIdentityToken': token", "logger.addHandler(handler) if level_error: logging.error('Malformed logging level \"%s\", setting logging level", "for line in output.splitlines(): if 'BIT STRING' in line.decode('utf-8'): key_line", "args is None: args = sys.argv fsname = None mountpoint", "'AWS_WEB_IDENTITY_TOKEN_FILE' STS_ENDPOINT_URL = 'https://sts.amazonaws.com/' INSTANCE_METADATA_TOKEN_URL = 'http://169.254.169.254/latest/api/token' INSTANCE_METADATA_SERVICE_URL = 'http://169.254.169.254/latest/dynamic/instance-identity/document/'", "get_target_region(config): def _fatal_error(message): fatal_error('Error retrieving region. Please set the \"region\"", "expected_replacement_field_ct = 1 if '{region}' in dns_name_format: expected_replacement_field_ct += 1", "tag (1), length (1 + num_length_octets), and number of unused", "return res.read() def get_aws_security_credentials(use_iam, awsprofile=None, aws_creds_uri=None): \"\"\" Lookup AWS security", "last content byte offset = int(key_line.split(':')[0]) key = key[offset:] num_length_octets", "with open(os.devnull, 'w') as devnull: subprocess.Popen(['/sbin/start', WATCHDOG_SERVICE], stdout=devnull, stderr=devnull, close_fds=True)", "check if aws access key id is found under [default]", "if '=' in o: k, v = o.split('=') opts[k] =", "cmd = 'openssl asn1parse -inform PEM -in %s' % public_key", "format must include {fs_id}') format_args = {'fs_id': fs_id} expected_replacement_field_ct =", "try: process.kill() except OSError: # Silently fail if the subprocess", "through the credentials URI the ECS agent generated if aws_creds_uri:", "%s' % error.response) else: logging.debug('Unexpected error: %s' % error) def", "resolving to a valid EFS DNS ' 'name' % remote,", "options: fatal_error('The \"ocsp\" and \"noocsp\" options are mutually exclusive') if", "assert_root() config = read_config() bootstrap_logging(config) fs_id, path, mountpoint, options =", "'enabled') return False def cloudwatch_create_log_group_helper(cloudwatchlog_client, log_group_name): cloudwatchlog_client.create_log_group( logGroupName=log_group_name ) logging.info('Created", "Return the name of the temporary file containing TLS tunnel", "tunnel (errno=%d). stdout=\"%s\" stderr=\"%s\"' % (tunnel_proc.returncode, out.strip(), err.strip())) def poll_tunnel_process(tunnel_proc,", "OSError as e: if errno.EEXIST != e.errno or not os.path.isdir(directory):", "efs_client_info_builder(client_info) if client_info else '' full_config_body = CA_CONFIG_BODY % (directory,", "e) return False return True def cloudwatch_put_log_events_helper(cloudwatchlog_agent, message, token=None): kwargs", "efs-utils configuration file.', message) metadata_exception = 'Unknown error' try: return", "except ImportError: from urllib.request import urlopen, Request from urllib.error import", "logging.debug('The sequence token is not valid, %s' % e.response) return", "subprocess_call(cmd, 'Failed to create private key') read_only_mode = 0o400 os.chmod(key,", "%s.' % e) return False return True def cloudwatch_put_retention_policy_helper(cloudwatchlog_client, log_group_name,", "user_message sys.stderr.write('%s\\n' % user_message) logging.error(log_message) publish_cloudwatch_log(CLOUDWATCHLOG_AGENT, 'Mount failed, %s' %", "{} security_credentials = None client_info = get_client_info(config) if use_iam: aws_creds_uri", "in dns_name_format: return split_dns_name_format[-3] raise Exception('Region not found in dns_name_format')", "file and return 'default' if so try: access_key = aws_credentials_configs.get('default',", "None, None def get_aws_security_credentials_from_ecs(aws_creds_uri, is_fatal=False): ecs_uri = ECS_TASK_METADATA_API + aws_creds_uri", "close_fds=True) (output, err) = process.communicate() rc = process.poll() if rc", "tunnel_proc = subprocess.Popen( tunnel_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, preexec_fn=os.setsid, close_fds=True) logging.info('Started TLS", "import quote_plus except ImportError: from urllib import quote_plus try: from", "hostnames: create_default_cloudwatchlog_agent_if_not_exist(config) fatal_error( 'The specified domain name \"%s\" did not", "%s\\n' % (args[0], VERSION)) sys.exit(0) def parse_arguments(config, args=None): \"\"\"Parse arguments,", "e) return False return True def cloudwatch_create_log_stream_helper(cloudwatchlog_client, log_group_name, log_stream_name): cloudwatchlog_client.create_log_stream(", "except socket.gaierror: create_default_cloudwatchlog_agent_if_not_exist(config) fatal_error( 'Failed to resolve \"%s\" - check", "any child processes, they can be killed easily by the", "if not group_creation_completed: return None put_retention_policy_completed = put_cloudwatch_log_retention_policy(cloudwatchlog_client, log_group_name, retention_days)", "= [RHEL8_RELEASE_NAME, CENTOS8_RELEASE_NAME, FEDORA_RELEASE_NAME, SUSE_RELEASE_NAME] def fatal_error(user_message, log_message=None, exit_code=1): if", "%s\\n' % warn_message) logging.warning(warn_message) del options[unsupported_option] def check_options_validity(options): if 'tls'", "e: logging.warning('response %s is not a json object: %s' %", "log_group_name, 'retention_days': int(retention_days), 'log_stream_name': log_stream_name } def get_cloudwatch_log_stream_name(fs_id=None): instance_id =", "= config.get(CONFIG_SECTION, 'logging_level') levels = { 'debug': logging.DEBUG, 'info': logging.INFO,", "except ValueError: remote = device path = '/' if FS_ID_RE.match(remote):", "hashlib.sha256() sha256.update(canonical_request.encode()) string_to_sign += sha256.hexdigest() return string_to_sign def calculate_signature(string_to_sign, date,", "_stunnel_bin(): return find_command_path('stunnel', 'Please install it following the instructions at", "exception == 'UnrecognizedClientException': logging.debug('The most likely cause is an invalid", "[ 'accesspoint', 'awscredsuri', 'awsprofile', 'cafile', 'iam', 'netns', 'noocsp', 'ocsp', 'tls',", "for Service Accounts (IRSA) approach on EKS) if WEB_IDENTITY_ROLE_ARN_ENV in", "% e.response) return False elif exception == 'DataAlreadyAcceptedException': logging.debug('The event", "incorrectly, %s' % (cloudwatchlog_agent.get('log_group_name'), cloudwatchlog_agent.get('log_stream_name'), e.response)) elif exception == 'ResourceNotFoundException':", "'/etc/amazon/efs/efs-utils.conf' CONFIG_SECTION = 'mount' CLIENT_INFO_SECTION = 'client-info' CLIENT_SOURCE_STR_LEN_LIMIT = 100", "'or disable \"%%s\" in %s.\\nSee %s for more detail.' %", "'AWS security credentials not found in %s or %s under", "def cloudwatch_create_log_group_helper(cloudwatchlog_client, log_group_name): cloudwatchlog_client.create_log_group( logGroupName=log_group_name ) logging.info('Created cloudwatch log group", "True def cloudwatch_create_log_stream_helper(cloudwatchlog_client, log_group_name, log_stream_name): cloudwatchlog_client.create_log_stream( logGroupName=log_group_name, logStreamName=log_stream_name ) logging.info('Created", "% header) for k, v in config.items(): if type(v) is", "\\ 'trust store.' % unsupported_option sys.stderr.write('WARN: %s\\n' % warn_message) logging.warning(warn_message)", "/sbin/mount.efs and make sure it is executable. # # You", "'w').close() if not os.path.isfile(index_attr_path): with open(index_attr_path, 'w+') as f: f.write('unique_subject", "exception == 'ResourceNotFoundException': logging.debug('Either log group %s or log stream", "region) if config.has_section(region_specific_config_section): config_section = region_specific_config_section format_args['dns_name_suffix'] = config.get(config_section, 'dns_name_suffix')", "\"awscredsuri\"') if 'awscredsuri' in options and 'awsprofile' in options: fatal_error('The", "enforce TLS. Please upgrade stunnel, ' \\ 'or disable \"%%s\"", "True level = logging.INFO max_bytes = config.getint(CONFIG_SECTION, 'logging_max_bytes') file_count =", "e: if e.errno == errno.EEXIST: logging.info('Failed to take out private", "put_cloudwatch_log_retention_policy(cloudwatchlog_client, log_group_name, retention_days): try: cloudwatch_put_retention_policy_helper(cloudwatchlog_client, log_group_name, retention_days) except ClientError as", "] prompt = no distinguished_name = req_distinguished_name [ req_distinguished_name ]", "string_to_sign += get_credential_scope(date, region) + '\\n' sha256 = hashlib.sha256() sha256.update(canonical_request.encode())", "the tlsport option so that we can later override the", "file.') return region except Exception: logging.warning('Legacy check for region in", "of unused bits that exist in the last # content", "present in %s: %s' % (property, instance_identity, e)) except TypeError", "avoid replay attacks 'PublicKeyHash': quote_plus(public_key_hash), 'X-Amz-Algorithm': ALGORITHM, 'X-Amz-Credential': credential, 'X-Amz-Date':", "no unused bits in the last content byte offset =", "cert_details['mountStateDir'], cert_details['commonName'], cert_details['region'], fs_id, security_credentials, ap_id, client_info, base_path=state_file_dir) cert_details['certificate'] =", "logging.debug('Either log group %s or log stream %s does not", "try: return get_region_from_instance_metadata() except Exception as e: metadata_exception = e", "bits that exist in the last # content byte. Note", "== 'LimitExceededException': logging.error('Reached the maximum number of log groups that", "# - 03 - BIT STRING tag # - 82", "e: logging.warning('%s not present in %s: %s' % (property, instance_identity,", "mount options' % fs_id, exit_code=0) def check_network_status(fs_id, init_system): if init_system", "does not exist, %s' % (log_group_name, e.response)) return False elif", "metadata.' % INSTANCE_METADATA_SERVICE_URL instance_identity = url_request_helper(INSTANCE_METADATA_SERVICE_URL, ec2_metadata_unsuccessful_resp, ec2_metadata_url_error_msg, retry_with_new_header_token=True) if", "return True def cloudwatch_describe_log_streams_helper(cloudwatchlog_agent): return cloudwatchlog_agent.get('client').describe_log_streams( logGroupName=cloudwatchlog_agent.get('log_group_name'), logStreamNamePrefix=cloudwatchlog_agent.get('log_stream_name') ) def", "os.environ: credentials, credentials_source = get_aws_security_credentials_from_webidentity( os.environ[WEB_IDENTITY_ROLE_ARN_ENV], os.environ[WEB_IDENTITY_TOKEN_FILE_ENV], False ) if", "-in %s -out %s' % \\ (not_before, not_after, certificate_config, certificate_signing_request,", "= opener.open(request) return res.read() except NameError: headers = {'X-aws-ec2-metadata-token-ttl-seconds': 21600}", "], } STUNNEL_EFS_CONFIG = { 'client': 'yes', 'accept': '127.0.0.1:%s', 'connect':", "[File System Type] [Options] [Dump] [Pass] # # Add an", "None, [primary] + secondaries)) except socket.gaierror: create_default_cloudwatchlog_agent_if_not_exist(config) fatal_error( 'Failed to", "config file and metadata service call failed, falling back '", "group %s does not exist, %s' % (log_group_name, e.response)) return", "Accounts (IRSA) approach on EKS) if WEB_IDENTITY_ROLE_ARN_ENV in os.environ and", "\"tls\" options are mutually exclusive') if 'tlsport' in options: try:", "state_file def test_tunnel_process(tunnel_proc, fs_id): tunnel_proc.poll() if tunnel_proc.returncode is not None:", "return 'unknown' def write_stunnel_config_file(config, state_file_dir, fs_id, mountpoint, tls_port, dns_name, verify_level,", "if aws_creds_uri: return get_aws_security_credentials_from_ecs(aws_creds_uri, True) # attempt to lookup AWS", "== 0: message = 'Successfully mounted %s at %s' %", "return False elif exception == 'DataAlreadyAcceptedException': logging.debug('The event %s was", "region from instance_metadata\") return instance_identity def get_instance_identity_info_from_instance_metadata(property): ec2_metadata_unsuccessful_resp = 'Unsuccessful", "= cert_details['privateKey'] check_host_supported, ocsp_aia_supported = get_version_specific_stunnel_options() tls_controls_message = 'WARNING: Your", "verify_level if verify_level > 0: add_stunnel_ca_options(efs_config, config, options) if cert_details:", "\"port_range_lower_bound\" defined as %d.' % (upper_bound, lower_bound)) return lower_bound, upper_bound", "exception == 'InvalidParameterException': logging.error('Log group name %s is specified incorrectly,", "option tells the init system that the # 'efs' type", "+= '\\n1.3.6.1.4.1.4843.7.4 = ASN1:SEQUENCE:efs_client_info' return ca_extension_str def efs_client_auth_builder(public_key_path, access_key_id, secret_access_key,", "options): if 'ocsp' in options: return True elif 'noocsp' in", "they don't exist).\"\"\" if not os.path.exists(database_dir): create_required_directory(config, database_dir) if not", "write_stunnel_config_file(config, state_file_dir, fs_id, mountpoint, tls_port, dns_name, verify_level, ocsp_enabled, options, cert_details=cert_details)", "efs_client_auth_builder(public_key_path, access_key_id, secret_access_key, date, region, fs_id, session_token=None): public_key_hash = get_public_key_sha1(public_key_path)", "%s' % (url, e.code, e.reason) except URLError as e: err_msg", "output, _ = p.communicate() return output and 'nfs' in str(output)", "DEFAULT_STUNNEL_CAFILE) stunnel_cafile = DEFAULT_STUNNEL_CAFILE if not os.path.exists(stunnel_cafile): fatal_error('Failed to find", "threading.Event() t = threading.Thread(target=poll_tunnel_process, args=(tunnel_proc, fs_id, mount_completed)) t.daemon = True", "read_config() bootstrap_logging(config) fs_id, path, mountpoint, options = parse_arguments(config) logging.info('version=%s options=%s',", "'-f', '-L', '-c', '%T', mountpoint] p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,", "- check that the specified DNS name is a CNAME", "malformed log level until after logging is configured level_error =", "retention_days = cloudwatchlog_config.get('retention_days') group_creation_completed = create_cloudwatch_log_group(cloudwatchlog_client, log_group_name) if not group_creation_completed:", "import datetime, timedelta from logging.handlers import RotatingFileHandler try: import ConfigParser", "IAM Role for Service Accounts (IRSA) approach on EKS) if", "json import logging import os import pwd import random import", "else: return None, None def get_aws_security_credentials_from_webidentity(role_arn, token_file, is_fatal=False): try: with", "file system type. This has been tested with systemd #", "%s: %s' % (property, instance_identity, e)) except TypeError as e:", "WATCHDOG_SERVICE], stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) status, _ = proc.communicate() if 'stop'", "'tlsport', 'verify' ] UNSUPPORTED_OPTIONS = [ 'capath' ] STUNNEL_GLOBAL_CONFIG =", "None if 'timeo' not in options: options['timeo'] = '600' if", "mount_name, 'database/.rand') } return tls_dict def get_public_key_sha1(public_key): # truncating public", "called from the main thread, if the tunnel fails, exit", "not AP_ID_RE.match(options['accesspoint']): fatal_error('Access Point ID %s is malformed' % options['accesspoint'])", "'aws_session_token' in str(e): logging.debug('aws_session_token not found in %s', file_path) credentials['AccessKeyId']", "Creating RSA private keys is slow, so we will create", "awsprofile): aws_credentials_configs = read_config(file_path) credentials = {'AccessKeyId': None, 'SecretAccessKey': None,", "credentials_source = get_aws_security_credentials(use_iam, **kwargs) if credentials_source: cert_details['awsCredentialsMethod'] = credentials_source if", "are mutually exclusive') if 'accesspoint' in options: if 'tls' not", "TLS. Please upgrade stunnel, ' \\ 'or disable \"%%s\" in", "'600' if 'retrans' not in options: options['retrans'] = '2' if", "key to pull out the actual key material by looking", "% (cloudwatchlog_agent.get('log_group_name'), cloudwatchlog_agent.get('log_stream_name'), e.response)) elif exception == 'ResourceNotFoundException': logging.debug('Either log", "quote_plus except ImportError: from urllib import quote_plus try: from urllib2", "urllib.parse import urlencode try: import botocore.session from botocore.exceptions import ClientError,", "%s' % log_message) sys.exit(exit_code) def get_target_region(config): def _fatal_error(message): fatal_error('Error retrieving", "e.code == 401 and retry_with_new_header_token: token = get_aws_ec2_metadata_token() req.add_header('X-aws-ec2-metadata-token', token)", "} if token: kwargs['sequenceToken'] = token cloudwatchlog_agent.get('client').put_log_events(**kwargs) def publish_cloudwatch_log(cloudwatchlog_agent, message):", "= None client_info = get_client_info(config) if use_iam: aws_creds_uri = options.get('awscredsuri')", "= { 'pid': tunnel_pid, 'cmd': command, 'files': files, } if", "credentials = credentials_file_helper(file_path, awsprofile) if credentials['AccessKeyId']: return credentials, os.path.basename(file_path) +", "SYSTEM_RELEASE_PATH = '/etc/system-release' OS_RELEASE_PATH = '/etc/os-release' RHEL8_RELEASE_NAME = 'Red Hat", "fatal_error('The \"awscredsuri\" and \"awsprofile\" options are mutually exclusive') def bootstrap_cloudwatch_logging(config,", "group so if it has any child processes, they can", "'Successfully mounted %s at %s' % (dns_name, mountpoint) logging.info(message) publish_cloudwatch_log(CLOUDWATCHLOG_AGENT,", "\"%s\" did not resolve to a valid DNS name for", "AWS security credentials through the credentials URI the ECS agent", "ECS_URI_ENV = 'AWS_CONTAINER_CREDENTIALS_RELATIVE_URI' ECS_TASK_METADATA_API = 'http://169.254.170.2' WEB_IDENTITY_ROLE_ARN_ENV = 'AWS_ROLE_ARN' WEB_IDENTITY_TOKEN_FILE_ENV", "exist and if not, create directories (also create all intermediate", "tls_paths['certs_dir']) ca_supporting_files_check(tls_paths['index'], tls_paths['index_attr'], tls_paths['serial'], tls_paths['rand']) private_key = check_and_create_private_key(base_path) if security_credentials:", "return None cloudwatchlog_config = get_cloudwatchlog_config(config, fs_id) log_group_name = cloudwatchlog_config.get('log_group_name') log_stream_name", "use the config setting if the override is not set", "credentials, credentials_source # attempt to lookup AWS security credentials with", "def check_if_cloudwatch_log_enabled(config): if config.has_option(CLOUDWATCH_LOG_SECTION, 'enabled'): return config.getboolean(CLOUDWATCH_LOG_SECTION, 'enabled') return False", "err) = process.communicate() rc = process.poll() if rc != 0:", "<fsname> <mountpoint> [-o <options>]\\n') sys.exit(exit_code) def parse_arguments_early_exit(args=None): \"\"\"Parse arguments, checking", "credentials (access key ID and secret access key). Adapted credentials", "found in %s or %s under named profile [%s]' %", "if not CLOUDWATCHLOG_AGENT: CLOUDWATCHLOG_AGENT = bootstrap_cloudwatch_logging(config) def get_botocore_client(config, service): if", "(k, v) for k, v in sorted(CANONICAL_HEADERS_DICT.items())]) SIGNED_HEADERS = ';'.join(CANONICAL_HEADERS_DICT.keys())", "mountpoint: usage(out=sys.stderr) fs_id, path = match_device(config, fsname) return fs_id, path,", "lower_bound >= upper_bound: fatal_error('Configuration option \"port_range_upper_bound\" defined as %d '", "not in options: fatal_error('The \"iam\" option is required when mounting", "in the efs-utils configuration file.', message) metadata_exception = 'Unknown error'", "token if e.code == 401 and retry_with_new_header_token: token = get_aws_ec2_metadata_token()", "rc != 0: with open(os.devnull, 'w') as devnull: subprocess.Popen(['systemctl', 'start',", "else: return None, None def get_iam_role_name(): iam_role_unsuccessful_resp = 'Unsuccessful retrieval", "= ASN1:SEQUENCE:efs_client_info' return ca_extension_str def efs_client_auth_builder(public_key_path, access_key_id, secret_access_key, date, region,", "called by 'mount -a' # for this file system. The", "strictly greater than \"port_range_lower_bound\" defined as %d.' % (upper_bound, lower_bound))", "= get_cloudwatchlog_config(config, fs_id) log_group_name = cloudwatchlog_config.get('log_group_name') log_stream_name = cloudwatchlog_config.get('log_stream_name') retention_days", "if 'tls' in options: mount_tls(config, init_system, dns_name, path, fs_id, mountpoint,", "to retrieve EC2 instance metadata.' % INSTANCE_METADATA_SERVICE_URL instance_identity = url_request_helper(INSTANCE_METADATA_SERVICE_URL,", "'capath' ] STUNNEL_GLOBAL_CONFIG = { 'fips': 'no', 'foreground': 'yes', 'socket':", "create_cloudwatch_log_group(cloudwatchlog_client, log_group_name): try: cloudwatch_create_log_group_helper(cloudwatchlog_client, log_group_name) except ClientError as e: exception", "try: response = cloudwatch_describe_log_streams_helper(cloudwatchlog_agent) except ClientError as e: exception =", "exception = e.response['Error']['Code'] if exception == 'InvalidParameterException': logging.debug('Either parameter log", "= ['nsenter', '--net=' + options['netns']] + tunnel_args # launch the", "for retry in range(retry_times): process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)", "(~/.aws/config) with given awsprofile if awsprofile: return get_aws_security_credentials_from_awsprofile(awsprofile, True) #", "message, proc.returncode) def usage(out, exit_code=1): out.write('Usage: mount.efs [--version] [-h|--help] <fsname>", "fatal_error(unsuccessful_resp, unsuccessful_resp) else: return None, None def get_aws_security_credentials_from_instance_metadata(iam_role_name): security_creds_lookup_url =", "return client_info def create_certificate(config, mount_name, common_name, region, fs_id, security_credentials, ap_id,", "CentOS 7, RHEL 7, Debian 9, and Ubuntu 16.04), and", "AP_ID_RE.match(options['accesspoint']): fatal_error('Access Point ID %s is malformed' % options['accesspoint']) if", "subprocess.Popen( tunnel_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, preexec_fn=os.setsid, close_fds=True) logging.info('Started TLS tunnel, pid:", "by 'mount -a' # for this file system. The '_netdev'", "level_error = True level = logging.INFO max_bytes = config.getint(CONFIG_SECTION, 'logging_max_bytes')", "+= sha256.hexdigest() return request def create_canonical_query_string(public_key_hash, credential, formatted_datetime, session_token=None): canonical_query_params", "mount target' % remote ) for hostname in hostnames: efs_fqdn_match", "% path else: mount_path = '%s:%s' % (dns_name, path) command", "log stream name %s is specified incorrectly, %s' % (cloudwatchlog_agent.get('log_group_name'),", "logging.info('ValueError parsing \"%s\" into json: %s. Returning response body.' %", "format_str.count('{') != expected_ct or format_str.count('}') != expected_ct: raise ValueError('DNS name", "'index_attr': os.path.join(base_path, mount_name, 'database/index.txt.attr'), 'serial': os.path.join(base_path, mount_name, 'database/serial'), 'rand': os.path.join(base_path,", "= False VERSION = '1.28.2' SERVICE = 'elasticfilesystem' CONFIG_FILE =", "= ASN1:SEQUENCE:efs_client_auth' ca_extension_str += '\\n1.3.6.1.4.1.4843.7.3 = ASN1:UTF8String:' + fs_id if", "DEFAULT_CLOUDWATCH_LOG_GROUP if config.has_option(CLOUDWATCH_LOG_SECTION, 'log_group_name'): log_group_name = config.get(CLOUDWATCH_LOG_SECTION, 'log_group_name') retention_days =", "we can later override the port the NFS client uses", "def ca_extension_builder(ap_id, security_credentials, fs_id, client_info): ca_extension_str = '[ v3_ca ]\\nsubjectKeyIdentifier", "ap_id, client_info) create_certificate_signing_request(certificate_config, private_key, certificate_signing_request) not_before = get_certificate_timestamp(current_time, minutes=-NOT_BEFORE_MINS) not_after", "security credentials through AssumeRoleWithWebIdentity # (e.g. for IAM Role for", "= socket.socket() for tls_port in ports_to_try: try: sock.bind(('localhost', tls_port)) sock.close()", "def handle_general_botocore_exceptions(error): exception = error.response['Error']['Code'] if exception == 'ServiceUnavailableException': logging.debug('The", "credentials cannot be fetched from the given awsprofile if is_fatal:", "'stop' in status: with open(os.devnull, 'w') as devnull: subprocess.Popen(['/sbin/start', WATCHDOG_SERVICE],", "in system_release_version for release in SKIP_NO_LIBWRAP_RELEASES): efs_config['libwrap'] = 'no' stunnel_config", "_sign(add_region, SERVICE).digest() signing_key = _sign(add_service, 'aws4_request').digest() return _sign(signing_key, string_to_sign).hexdigest() def", "ocsp_aia_supported: efs_config['OCSPaia'] = 'yes' else: fatal_error(tls_controls_message % 'stunnel_check_cert_validity') system_release_version =", "NoSectionError try: from urllib.parse import quote_plus except ImportError: from urllib", "return None def handle_general_botocore_exceptions(error): exception = error.response['Error']['Code'] if exception ==", "system that the # 'efs' type is a networked file", "%s: ResponseCode=%d', url, request_resp.getcode()) return None resp_body = request_resp.read() resp_body_type", "fs_id, path, mountpoint, options def get_client_info(config): client_info = {} #", "logging import os import pwd import random import re import", "hl=2 l= 9 prim: OBJECT :rsaEncryption # 17:d=2 hl=2 l=", "authority file for verification', 'Failed to find CAfile \"%s\"' %", "NoSectionError: logging.debug('No [%s] section found in config file %s', awsprofile,", "fs_id, session_token) string_to_sign = create_string_to_sign(canonical_request, date, region) signature = calculate_signature(string_to_sign,", "in os.environ: credentials, credentials_source = get_aws_security_credentials_from_webidentity( os.environ[WEB_IDENTITY_ROLE_ARN_ENV], os.environ[WEB_IDENTITY_TOKEN_FILE_ENV], False )", "% e) return None except EndpointConnectionError as e: logging.warning('Could not", "'source'): client_source = config.get(CLIENT_INFO_SECTION, 'source') if 0 < len(client_source) <=", "= threading.Thread(target=poll_tunnel_process, args=(tunnel_proc, fs_id, mount_completed)) t.daemon = True t.start() mount_nfs(dns_name,", "None resp_body = request_resp.read() resp_body_type = type(resp_body) try: if resp_body_type", "if not use_iam: return None, None # attempt to lookup", "os.path.isfile(rand_path): open(rand_path, 'w').close() def get_certificate_timestamp(current_time, **kwargs): updated_time = current_time +", "+ aws_creds_uri # Fail if credentials cannot be fetched from", "# - the remaining octets are the \"value\" aka content", "\"iam\" option is required when mounting with named profile option,", "options['tlsport'] def to_nfs_option(k, v): if v is None: return k", "e) return None except EndpointConnectionError as e: logging.warning('Could not connect", "os.path.join(base_path, mount_name, 'database/index.txt'), 'index_attr': os.path.join(base_path, mount_name, 'database/index.txt.attr'), 'serial': os.path.join(base_path, mount_name,", "e logging.warning('Region not found in config file and metadata service", "back ' 'to legacy \"dns_name_format\" check') try: region = get_region_from_legacy_dns_format(config)", "stunnel_cafile = options['cafile'] else: try: stunnel_cafile = config.get(CONFIG_SECTION, 'stunnel_cafile') except", "- mount.log' % (instance_id) elif fs_id: log_stream_name = '%s -", "os import pwd import random import re import socket import", "dns_name_format: return split_dns_name_format[-3] raise Exception('Region not found in dns_name_format') def", "then try ports in-order from there mid = random.randrange(len(tls_ports)) ports_to_try", "stunnel_command = [_stunnel_bin(), '-help'] proc = subprocess.Popen(stunnel_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)", "= config.get(CONFIG_SECTION, 'stunnel_cafile') except NoOptionError: logging.debug('No CA file configured, using", "use_iam: aws_creds_uri = options.get('awscredsuri') if aws_creds_uri: kwargs = {'aws_creds_uri': aws_creds_uri}", "ocsp_enabled, options, log_dir=LOG_DIR, cert_details=None): \"\"\" Serializes stunnel configuration to a", "err_msg) key_line = key_line.replace(' ', '') # DER encoding TLV", "create_required_directory(config, certs_dir) def ca_supporting_files_check(index_path, index_attr_path, serial_path, rand_path): \"\"\"Recreate all supporting", "variable if ECS_URI_ENV in os.environ: credentials, credentials_source = get_aws_security_credentials_from_ecs(os.environ[ECS_URI_ENV], False)", "= get_version_specific_stunnel_options() tls_controls_message = 'WARNING: Your client lacks sufficient controls", "to the endpoint, %s' % e) return False except Exception", "if len(args) > 2: mountpoint = args[2] if len(args) >", "a networked file system type. This has been tested with", "err_msg = 'Unable to reach the url at %s: status=%d,", "files if they're not present in their respective directories\"\"\" if", "= cloudwatchlog_config.get('log_stream_name') retention_days = cloudwatchlog_config.get('retention_days') group_creation_completed = create_cloudwatch_log_group(cloudwatchlog_client, log_group_name) if", "in options.items() if k not in EFS_ONLY_OPTIONS] return ','.join(nfs_options) def", "action, %s' % error.response) else: logging.debug('Unexpected error: %s' % error)", "aws_access_key_id=credentials['AccessKeyId'], aws_secret_access_key=credentials['SecretAccessKey'], aws_session_token=credentials['Token'], region_name=region) return session.create_client(service, region_name=region) def get_cloudwatchlog_config(config, fs_id=None):", "'.join(tunnel_args)) tunnel_proc = subprocess.Popen( tunnel_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, preexec_fn=os.setsid, close_fds=True) logging.info('Started", "f: f.write('unique_subject = no') if not os.path.isfile(serial_path): with open(serial_path, 'w+')", "req.add_header(k, v) request_resp = urlopen(req, timeout=1) return get_resp_obj(request_resp, url, unsuccessful_resp)", "aws_credentials_configs.get(awsprofile, 'aws_secret_access_key') except NoSectionError: logging.debug('No [%s] section found in config", "https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html and https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html \"\"\" if not use_iam: return None, None", "hl=2 l= 13 cons: SEQUENCE # 6:d=2 hl=2 l= 9", "def choose_tls_port(config, options): if 'tlsport' in options: ports_to_try = [int(options['tlsport'])]", "credentials in AWS credentials file (~/.aws/credentials) # and configs file", "access_key is not None: return 'default' except (NoSectionError, NoOptionError): continue", "secret_access_key).encode('utf-8'), date.strftime(DATE_ONLY_FORMAT)).digest() add_region = _sign(key_date, region).digest() add_service = _sign(add_region, SERVICE).digest()", "return credentials, credentials_source # attempt to lookup AWS security credentials", "credentials and credentials_source: return credentials, credentials_source error_msg = 'AWS Access", "sys.stdout.write(\"%s is already mounted, please run 'mount' command to verify\\n\"", "and 'iam' not in options: fatal_error('The \"iam\" option is required", "}, 'webidentity:' + ','.join([role_arn, token_file]) # Fail if credentials cannot", "\"\"\" Wrapped for patching purposes in unit tests \"\"\" return", "!= 'systemd': logging.debug('Not testing network on non-systemd init systems') return", "= subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) out, err = proc.communicate() if", "1 format_args['region'] = get_target_region(config) if '{dns_name_suffix}' in dns_name_format: expected_replacement_field_ct +=", "= re.compile('^(?P<fs_id>fs-[0-9a-f]+)$') EFS_FQDN_RE = re.compile(r'^(?P<fs_id>fs-[0-9a-f]+)\\.efs\\.(?P<region>[a-z0-9-]+)\\.(?P<dns_name_suffix>[a-z0-9.]+)$') AP_ID_RE = re.compile('^fsap-[0-9a-f]{17}$') CREDENTIALS_KEYS =", "than \"port_range_lower_bound\" defined as %d.' % (upper_bound, lower_bound)) return lower_bound,", "via \"accesspoint\"') if not AP_ID_RE.match(options['accesspoint']): fatal_error('Access Point ID %s is", "'\\n' request += SIGNED_HEADERS + '\\n' sha256 = hashlib.sha256() sha256.update(REQUEST_PAYLOAD.encode())", "process.kill() except OSError: # Silently fail if the subprocess has", "no') if not os.path.isfile(serial_path): with open(serial_path, 'w+') as f: f.write('00')", "'{dns_name_suffix}' in dns_name_format: expected_replacement_field_ct += 1 config_section = CONFIG_SECTION region", "fs_id, mount_completed)) t.daemon = True t.start() mount_nfs(dns_name, path, mountpoint, options)", "else: log_stream_name = 'default - mount.log' return log_stream_name def check_if_cloudwatch_log_enabled(config):", "'SecretAccessKey', 'SessionToken']): return { 'AccessKeyId': creds['AccessKeyId'], 'SecretAccessKey': creds['SecretAccessKey'], 'Token': creds['SessionToken']", "PUBLIC KEY-----' with open(public_key, 'r') as f: lines = f.readlines()", "res.read() except NameError: headers = {'X-aws-ec2-metadata-token-ttl-seconds': 21600} req = Request(INSTANCE_METADATA_TOKEN_URL,", "'PRETTY_NAME' in line: return line.split('=')[1].strip() except IOError: logging.debug('Unable to read", "create self-signed client-side certificate') return current_time.strftime(CERT_DATETIME_FORMAT) def get_private_key_path(): \"\"\"Wrapped for", "format_args['dns_name_suffix'] = config.get(config_section, 'dns_name_suffix') logging.debug(\"Using dns_name_suffix %s in config section", "same log group %s were in conflict, %s' % (log_group_name,", "at the command line this will just re-set tlsport to", "ECS_URI_ENV in os.environ: credentials, credentials_source = get_aws_security_credentials_from_ecs(os.environ[ECS_URI_ENV], False) if credentials", "lock, sleeping 50 ms') time.sleep(0.05) else: raise def generate_key(): if", "not called from the main thread, if the tunnel fails,", "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI environment variable if ECS_URI_ENV in os.environ: credentials, credentials_source =", "most likely cause is an invalid AWS access key ID", "Point] [File System Type] [Options] [Dump] [Pass] # # Add", "import RotatingFileHandler try: import ConfigParser from ConfigParser import NoOptionError, NoSectionError", "os.O_RDWR) try: lock_file_contents = 'PID: %s' % os.getpid() os.write(f, lock_file_contents.encode('utf-8'))", "Signature - https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html \"\"\" def _sign(key, msg): return hmac.new(key, msg.encode('utf-8'),", "% remote ) if not hostnames: create_default_cloudwatchlog_agent_if_not_exist(config) fatal_error( 'The specified", "options: options['timeo'] = '600' if 'retrans' not in options: options['retrans']", "'AccessKeyId': creds['AccessKeyId'], 'SecretAccessKey': creds['SecretAccessKey'], 'Token': creds['SessionToken'] }, 'webidentity:' + ','.join([role_arn,", "name. See %s for more info.' % \\ (INSTANCE_IAM_URL, SECURITY_CREDS_IAM_ROLE_HELP_URL)", "log_group_name = config.get(CLOUDWATCH_LOG_SECTION, 'log_group_name') retention_days = DEFAULT_RETENTION_DAYS if config.has_option(CLOUDWATCH_LOG_SECTION, 'retention_in_days'):", "True def cloudwatch_describe_log_streams_helper(cloudwatchlog_agent): return cloudwatchlog_agent.get('client').describe_log_streams( logGroupName=cloudwatchlog_agent.get('log_group_name'), logStreamNamePrefix=cloudwatchlog_agent.get('log_stream_name') ) def get_log_stream_next_token(cloudwatchlog_agent):", "fstab. import base64 import errno import hashlib import hmac import", "aws_secret_access_key=credentials['SecretAccessKey'], aws_session_token=credentials['Token'], region_name=region) return session.create_client(service, region_name=region) def get_cloudwatchlog_config(config, fs_id=None): log_group_name", "stream %s already exist in log group %s, %s' %", "url_error_msg, headers={'Accept': 'application/json'}) if resp: creds = resp \\ .get('AssumeRoleWithWebIdentityResponse',", "'-c', '%T', mountpoint] p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) output,", "% (str(resp_body), e)) return resp_body if resp_body_type is str else", "subprocess has exited already pass else: return output, err error_message", "'--quiet', WATCHDOG_SERVICE], close_fds=True) if rc != 0: with open(os.devnull, 'w')", "ca_extension_str += '\\n1.3.6.1.4.1.4843.7.2 = ASN1:SEQUENCE:efs_client_auth' ca_extension_str += '\\n1.3.6.1.4.1.4843.7.3 = ASN1:UTF8String:'", "return False token = get_log_stream_next_token(cloudwatchlog_agent) try: cloudwatch_put_log_events_helper(cloudwatchlog_agent, message, token) except", "= config.getint(CONFIG_SECTION, 'port_range_lower_bound') upper_bound = config.getint(CONFIG_SECTION, 'port_range_upper_bound') if lower_bound >=", "private key') read_only_mode = 0o400 os.chmod(key, read_only_mode) do_with_lock(generate_key) return key", "is required when mounting with \"awscredsuri\"') if 'awscredsuri' in options", "to retrieve metadata, the header should embeded with metadata token", "[%s] is unavailable. Try selecting a different port.' % options['tlsport'])", "PRIVATE_KEY_FILE = '/etc/amazon/efs/privateKey.pem' DATE_ONLY_FORMAT = '%Y%m%d' SIGV4_DATETIME_FORMAT = '%Y%m%dT%H%M%SZ' CERT_DATETIME_FORMAT", "== errno.EEXIST: logging.info('Failed to take out private key creation lock,", "'\\n1.3.6.1.4.1.4843.7.3 = ASN1:UTF8String:' + fs_id if client_info: ca_extension_str += '\\n1.3.6.1.4.1.4843.7.4", "lines.append('%s = %s' % (k, item)) else: lines.append('%s = %s'", ".get('Credentials', {}) if all(k in creds for k in ['AccessKeyId',", "if 'awscredsuri' in options and 'iam' not in options: fatal_error('The", "tunnel_args, [stunnel_config_file], state_file_dir, cert_details=cert_details) try: yield tunnel_proc finally: os.rename(os.path.join(state_file_dir, temp_tls_state_file),", "finally: os.close(f) os.remove(lock_file) def do_with_lock(function): while True: try: with open_lock_file():", "as devnull: rc = subprocess.call(['systemctl', 'status', 'network.target'], stdout=devnull, stderr=devnull, close_fds=True)", "# attempt to lookup AWS security credentials through the credentials", "is: # # [Device] [Mount Point] [File System Type] [Options]", "'aws_secret_access_key') session_token = aws_credentials_configs.get(awsprofile, 'aws_session_token') credentials['AccessKeyId'] = access_key credentials['SecretAccessKey'] =", "cert_details['region'], fs_id, security_credentials, ap_id, client_info, base_path=state_file_dir) cert_details['certificate'] = os.path.join(state_file_dir, cert_details['mountStateDir'],", "and 'hard' not in options: options['hard'] = None if 'timeo'", "upper_bound, CONFIG_FILE)) def is_ocsp_enabled(config, options): if 'ocsp' in options: return", "request += CANONICAL_HEADERS % fs_id + '\\n' request += SIGNED_HEADERS", "key = bytearray(base64.b64decode(key)) # Parse the public key to pull", "socket.gethostbyname_ex(remote) hostnames = list(filter(lambda e: e is not None, [primary]", "tlsport=X at the command line this will just re-set tlsport", "ca_extension_str += '\\n1.3.6.1.4.1.4843.7.4 = ASN1:SEQUENCE:efs_client_info' return ca_extension_str def efs_client_auth_builder(public_key_path, access_key_id,", "return ecs_security_dict, 'ecs:' + aws_creds_uri # Fail if credentials cannot", "get_private_key_path(): \"\"\"Wrapped for mocking purposes in unit tests\"\"\" return PRIVATE_KEY_FILE", "# - the first octet always has the high order", "credentials through AWS_CONTAINER_CREDENTIALS_RELATIVE_URI environment variable if ECS_URI_ENV in os.environ: credentials,", "'database_dir': os.path.join(base_path, mount_name, 'database'), 'certs_dir': os.path.join(base_path, mount_name, 'certs'), 'index': os.path.join(base_path,", "sock.close() return tls_port except socket.error: continue sock.close() if 'tlsport' in", "logging.debug('One of the parameter to put log events is not", "'/etc/system-release' OS_RELEASE_PATH = '/etc/os-release' RHEL8_RELEASE_NAME = 'Red Hat Enterprise Linux", "fs_id) else: global_config['output'] = os.path.join(log_dir, '%s.stunnel.log' % mount_filename) efs_config =", "%s for more info.' % \\ (INSTANCE_IAM_URL, SECURITY_CREDS_IAM_ROLE_HELP_URL) iam_role_name =", "cloudwatchlog group name, cloudwatchlog stream name CLOUDWATCHLOG_AGENT = None LOG_DIR", "if the tunnel dies - since this is not called", "for k in CREDENTIALS_KEYS): return iam_security_dict, 'metadata:' else: return None,", "if credentials cannot be fetched from the given aws_creds_uri if", "request += sha256.hexdigest() return request def create_canonical_query_string(public_key_hash, credential, formatted_datetime, session_token=None):", "options: options['port'] = options['tlsport'] def to_nfs_option(k, v): if v is", "= dict(STUNNEL_GLOBAL_CONFIG) if config.getboolean(CONFIG_SECTION, 'stunnel_debug_enabled'): global_config['debug'] = 'debug' if config.has_option(CONFIG_SECTION,", "options: mount_path = '127.0.0.1:%s' % path else: mount_path = '%s:%s'", "botocore first.') return None session = botocore.session.get_session() region = get_target_region(config)", "# 6:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption # 17:d=2", "content byte. Note that this is explicitly excluded from the", "private_key, csr_path) subprocess_call(cmd, 'Failed to create certificate signing request (csr)')", "%s' % (log_group_name, e.response)) return False elif exception == 'InvalidParameterException':", "cmd = ['stat', '-f', '-L', '-c', '%T', mountpoint] p =", "unsuccessful_resp = 'Unsuccessful retrieval of AWS security credentials at %s.'", "False except EndpointConnectionError as e: logging.warning('Could not connect to the", "no distinguished_name = req_distinguished_name [ req_distinguished_name ] CN = %s", "or %s under named profile [%s]' % \\ (AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE,", "' 'to legacy \"dns_name_format\" check') try: region = get_region_from_legacy_dns_format(config) sys.stdout.write('Warning:", "False elif exception == 'InvalidParameterException': logging.error('Either parameter log group name", "= tls_paths_dictionary(mount_name, base_path) certificate_config = os.path.join(tls_paths['mount_dir'], 'config.conf') certificate_signing_request = os.path.join(tls_paths['mount_dir'],", "fsname = None mountpoint = None options = {} if", "is specified incorrectly, %s' % (log_group_name, e.response)) return False else:", "in v: lines.append('%s = %s' % (k, item)) else: lines.append('%s", "+ '/' + get_credential_scope(date, region)) request = HTTP_REQUEST_METHOD + '\\n'", "in AWS credentials file (%s), config file (%s), ' \\", "key creation lock, sleeping 50 ms') time.sleep(0.05) else: raise def", "return { 'AccessKeyId': creds['AccessKeyId'], 'SecretAccessKey': creds['SecretAccessKey'], 'Token': creds['SessionToken'] }, 'webidentity:'", "hashlib.sha256() sha256.update(REQUEST_PAYLOAD.encode()) request += sha256.hexdigest() return request def create_canonical_query_string(public_key_hash, credential,", "DEFAULT_STUNNEL_VERIFY_LEVEL = 2 DEFAULT_STUNNEL_CAFILE = '/etc/amazon/efs/efs-utils.crt' NOT_BEFORE_MINS = 15 NOT_AFTER_HOURS", "'w') as devnull: rc = subprocess.call(['systemctl', 'status', 'network.target'], stdout=devnull, stderr=devnull,", "greater than \"port_range_lower_bound\" defined as %d.' % (upper_bound, lower_bound)) return", "open_lock_file(): return function() except OSError as e: if e.errno ==", "AWS credentials file (%s), config file (%s), ' \\ 'from", "for early exit conditions only\"\"\" if args is None: args", "Hat Enterprise Linux release 8' CENTOS8_RELEASE_NAME = 'CentOS Linux release", "def get_dns_name(config, fs_id): def _validate_replacement_field_count(format_str, expected_ct): if format_str.count('{') != expected_ct", "they can be killed easily by the mount watchdog logging.info('Starting", "logged, %s' % (message, e.response)) return False elif exception ==", "the 'efs' type will cause '/sbin/mount.efs' to be called by", "sys.exit(exit_code) def parse_arguments_early_exit(args=None): \"\"\"Parse arguments, checking for early exit conditions", "in output.splitlines(): if 'BIT STRING' in line.decode('utf-8'): key_line = line.decode('utf-8')", ") def get_log_stream_next_token(cloudwatchlog_agent): try: response = cloudwatch_describe_log_streams_helper(cloudwatchlog_agent) except ClientError as", "the header should embeded with metadata token if e.code ==", "exception == 'LimitExceededException': logging.error('Reached the maximum number of log groups", "error, %s.' % e) return False return True def cloudwatch_describe_log_streams_helper(cloudwatchlog_agent):", "the high order bit (8) set to 1 # -", "options are mutually exclusive') if 'tlsport' in options: try: int(options['tlsport'])", "the temporary file containing TLS tunnel state, prefixed with a", "= levels.get(raw_level.lower()) level_error = False if not level: # delay", "+ options['netns']] + command logging.info('Executing: \"%s\"', ' '.join(command)) proc =", "return remote, path try: primary, secondaries, _ = socket.gethostbyname_ex(remote) hostnames", "create_certificate(config, cert_details['mountStateDir'], cert_details['commonName'], cert_details['region'], fs_id, security_credentials, ap_id, client_info, base_path=state_file_dir) cert_details['certificate']", "ClientError, NoCredentialsError, EndpointConnectionError BOTOCORE_PRESENT = True except ImportError: BOTOCORE_PRESENT =", "\"\"\" mount_filename = get_mount_specific_filename(fs_id, mountpoint, tls_port) global_config = dict(STUNNEL_GLOBAL_CONFIG) if", "0 # # Using the 'efs' type will cause '/sbin/mount.efs'", "return get_resp_obj(request_resp, url, unsuccessful_resp) except HTTPError as e: # For", "= get_botocore_client(config, 'logs') if not cloudwatchlog_client: return None cloudwatchlog_config =", "err.strip())) def poll_tunnel_process(tunnel_proc, fs_id, mount_completed): \"\"\" poll the tunnel process", "_ = p.communicate() return output and 'nfs' in str(output) def", "%s, reason is %s' % (url, e.reason) if err_msg: logging.debug('%s", "def create_public_key(private_key, public_key): cmd = 'openssl rsa -in %s -outform", "as e: metadata_exception = e logging.warning('Region not found in config", "= '1048576' if 'soft' not in options and 'hard' not", "instance_id: log_stream_name = '%s - mount.log' % (instance_id) elif fs_id:", "= e logging.warning('Region not found in config file and metadata", "if token: kwargs['sequenceToken'] = token cloudwatchlog_agent.get('client').put_log_events(**kwargs) def publish_cloudwatch_log(cloudwatchlog_agent, message): if", "line.split('=')[1].strip() except IOError: logging.debug('Unable to read %s', OS_RELEASE_PATH) return 'unknown'", "%s' % e.response) return False elif exception == 'ResourceNotFoundException': logging.error('Either", "affiliates. All Rights Reserved. # # Licensed under the MIT", "ports in-order from there mid = random.randrange(len(tls_ports)) ports_to_try = tls_ports[mid:]", "key BIT STRING # Example: # 0:d=0 hl=4 l= 418", "was already logged, %s' % (message, e.response)) return False elif", "= tls_ports[mid:] + tls_ports[:mid] assert len(tls_ports) == len(ports_to_try) sock =", "directory): mode = 0o750 try: mode_str = config.get(CONFIG_SECTION, 'state_file_dir_mode') try:", "remote ) for hostname in hostnames: efs_fqdn_match = EFS_FQDN_RE.match(hostname) if", "if 'aws_session_token' in str(e): logging.debug('aws_session_token not found in %s', file_path)", "options: try: int(options['tlsport']) except ValueError: fatal_error('tlsport option [%s] is not", "item in v: lines.append('%s = %s' % (k, item)) else:", "stderr=\"%s\"' % (dns_name, mountpoint, proc.returncode, err.strip()) fatal_error(err.strip(), message, proc.returncode) def", "exclusive') if 'tlsport' in options: try: int(options['tlsport']) except ValueError: fatal_error('tlsport", "try: import ConfigParser from ConfigParser import NoOptionError, NoSectionError except ImportError:", "type. This has been tested with systemd # (Amazon Linux", "'AWS_ROLE_ARN' WEB_IDENTITY_TOKEN_FILE_ENV = 'AWS_WEB_IDENTITY_TOKEN_FILE' STS_ENDPOINT_URL = 'https://sts.amazonaws.com/' INSTANCE_METADATA_TOKEN_URL = 'http://169.254.169.254/latest/api/token'", "fs_id, mount_completed): \"\"\" poll the tunnel process health every .5s", "verify_level, ocsp_enabled, options, log_dir=LOG_DIR, cert_details=None): \"\"\" Serializes stunnel configuration to", "as f: f.write('unique_subject = no') if not os.path.isfile(serial_path): with open(serial_path,", "fs_id) if 'tls' in options: mount_tls(config, init_system, dns_name, path, fs_id,", "} if session_token: canonical_query_params['X-Amz-Security-Token'] = quote_plus(session_token) # Cannot use urllib.urlencode", "to %s', raw_level, level) def get_dns_name(config, fs_id): def _validate_replacement_field_count(format_str, expected_ct):", "= local_ca [ local_ca ] database = $dir/database/index.txt serial =", "lines.append('[%s]' % header) for k, v in config.items(): if type(v)", "(k, v) for k, v in sorted(canonical_query_params.items())]) def create_string_to_sign(canonical_request, date,", "stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) status, _ = proc.communicate() if 'stop' in", "stderr=subprocess.PIPE, close_fds=True) output, _ = p.communicate() return output and 'nfs'", "= None options = {} if len(args) > 1: fsname", "to reach %s to retrieve EC2 instance metadata.' % INSTANCE_METADATA_SERVICE_URL", "sufficient controls to properly enforce TLS. Please upgrade stunnel, '", "% log_group_name) def create_cloudwatch_log_group(cloudwatchlog_client, log_group_name): try: cloudwatch_create_log_group_helper(cloudwatchlog_client, log_group_name) except ClientError", "as tunnel_proc: mount_completed = threading.Event() t = threading.Thread(target=poll_tunnel_process, args=(tunnel_proc, fs_id,", "UTF8String:%s' % (key, value) return efs_client_info_str def create_public_key(private_key, public_key): cmd", "e: metadata_exception = e logging.warning('Region not found in config file", "private_key, common_name, ca_extension_body, efs_client_auth_body, efs_client_info_body) with open(config_path, 'w') as f:", "EC2 metadata at %s.' % INSTANCE_METADATA_SERVICE_URL ec2_metadata_url_error_msg = 'Unable to", "not os.path.exists(certs_dir): create_required_directory(config, certs_dir) def ca_supporting_files_check(index_path, index_attr_path, serial_path, rand_path): \"\"\"Recreate", "(AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE) fatal_error(error_msg, error_msg) def get_aws_security_credentials_from_awsprofile(awsprofile, is_fatal=False): for file_path in", "urllib.urlencode because it replaces the %s's return '&'.join(['%s=%s' % (k,", "'w') as f: f.write(stunnel_config) return stunnel_config_file def write_tls_tunnel_state_file(fs_id, mountpoint, tls_port,", "exception == 'InvalidParameterException': logging.error('Either parameter log group name %s or", "(cloudwatchlog_agent.get('log_group_name'), cloudwatchlog_agent.get('log_stream_name'), e.response)) else: handle_general_botocore_exceptions(e) return None except NoCredentialsError as", "# to /etc/fstab. The syntax of an fstab entry is:", "dns_name_format.split('.') if '{dns_name_suffix}' in dns_name_format: return split_dns_name_format[-2] elif 'amazonaws.com' in", "subprocess.CalledProcessError as e: fatal_error('Failed to locate %s in %s -", "Example: # 0382018f00...<subjectPublicKey> # - 03 - BIT STRING tag", "PEM -in %s' % public_key output, err = subprocess_call(cmd, 'Unable", "already exist in log group %s, %s' % (log_stream_name, log_group_name,", "at %s: returncode=%d, stderr=\"%s\"' % (dns_name, mountpoint, proc.returncode, err.strip()) fatal_error(err.strip(),", "%s' % e.response) return False elif exception == 'DataAlreadyAcceptedException': logging.debug('The", "subprocess.Popen(['/sbin/start', WATCHDOG_SERVICE], stdout=devnull, stderr=devnull, close_fds=True) elif 'start' in status: logging.debug('%s", "= 'Unsuccessful retrieval of AWS security credentials at %s.' %", "= HTTP_REQUEST_METHOD + '\\n' request += CANONICAL_URI + '\\n' request", "if not, create directories (also create all intermediate directories if", "correctly' % public_key) key_line = '' for line in output.splitlines():", "efs_client_info_body = efs_client_info_builder(client_info) if client_info else '' full_config_body = CA_CONFIG_BODY", "put_retention_policy_completed = put_cloudwatch_log_retention_policy(cloudwatchlog_client, log_group_name, retention_days) if not put_retention_policy_completed: return None", "= 'http://169.254.169.254/latest/dynamic/instance-identity/document/' INSTANCE_IAM_URL = 'http://169.254.169.254/latest/meta-data/iam/security-credentials/' SECURITY_CREDS_ECS_URI_HELP_URL = 'https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html' SECURITY_CREDS_WEBIDENTITY_HELP_URL =", "fatal_error(error_message, error_message) def ca_dirs_check(config, database_dir, certs_dir): \"\"\"Check if mount's database", "get_aws_security_credentials_from_awsprofile(awsprofile, is_fatal=False): for file_path in [AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE]: if os.path.exists(file_path): credentials", "False VERSION = '1.28.2' SERVICE = 'elasticfilesystem' CONFIG_FILE = '/etc/amazon/efs/efs-utils.conf'", "import ConfigParser from ConfigParser import NoOptionError, NoSectionError except ImportError: from", "in sorted(CANONICAL_HEADERS_DICT.items())]) SIGNED_HEADERS = ';'.join(CANONICAL_HEADERS_DICT.keys()) REQUEST_PAYLOAD = '' FS_ID_RE =", "log group %s' % log_group_name) def create_cloudwatch_log_group(cloudwatchlog_client, log_group_name): try: cloudwatch_create_log_group_helper(cloudwatchlog_client,", "client_info, base_path=state_file_dir) cert_details['certificate'] = os.path.join(state_file_dir, cert_details['mountStateDir'], 'certificate.pem') cert_details['privateKey'] = get_private_key_path()", "logging.debug('Unable to read %s', OS_RELEASE_PATH) return 'unknown' def write_stunnel_config_file(config, state_file_dir,", "logging error about malformed log level until after logging is", "is not an integer' % options['tlsport']) if 'ocsp' in options", "get_certificate_timestamp(current_time, minutes=-NOT_BEFORE_MINS) not_after = get_certificate_timestamp(current_time, hours=NOT_AFTER_HOURS) cmd = 'openssl ca", "calls fail. \"\"\" dns_name_format = config.get(CONFIG_SECTION, 'dns_name_format') if '{region}' not", "e: exception = e.response['Error']['Code'] if exception == 'ResourceAlreadyExistsException': logging.debug('Log stream", "= int(options.get('verify', DEFAULT_STUNNEL_VERIFY_LEVEL)) ocsp_enabled = is_ocsp_enabled(config, options) stunnel_config_file = write_stunnel_config_file(config,", "dict includes cloudwatchlog botocore client, cloudwatchlog group name, cloudwatchlog stream", "date.strftime(SIGV4_DATETIME_FORMAT) + '\\n' string_to_sign += get_credential_scope(date, region) + '\\n' sha256", "prompt = no distinguished_name = req_distinguished_name [ req_distinguished_name ] CN", "open(index_path, 'w').close() if not os.path.isfile(index_attr_path): with open(index_attr_path, 'w+') as f:", "cloudwatch log stream %s in log group %s' % (log_stream_name,", "is found under [default] section in current file and return", "STS_ENDPOINT_URL url_error_msg = 'Unable to reach %s to retrieve AWS", "'foreground': 'yes', 'socket': [ 'l:SO_REUSEADDR=yes', 'a:SO_BINDTODEVICE=lo', ], } STUNNEL_EFS_CONFIG =", "'TIMEOUTclose': '0', 'TIMEOUTidle': '70', 'delay': 'yes', } WATCHDOG_SERVICE = 'amazon-efs-mount-watchdog'", "region): return '/'.join([date.strftime(DATE_ONLY_FORMAT), region, SERVICE, AWS4_REQUEST]) def match_device(config, device): \"\"\"Return", "'source') if 0 < len(client_source) <= CLIENT_SOURCE_STR_LEN_LIMIT: client_info['source'] = client_source", "logging.warning('Region not found in config file and metadata service call", "'database/index.txt.attr'), 'serial': os.path.join(base_path, mount_name, 'database/serial'), 'rand': os.path.join(base_path, mount_name, 'database/.rand') }", "AWS security credentials at %s.' % security_creds_lookup_url url_error_msg = 'Unable", "directories exist and if not, create directories (also create all", "(token_file, e) fatal_error(unsuccessful_resp, unsuccessful_resp) else: return None, None webidentity_url =", "handle_general_botocore_exceptions(e) return False except NoCredentialsError as e: logging.warning('Credentials are not", "NoSectionError except ImportError: from configparser import ConfigParser, NoOptionError, NoSectionError try:", "hostname == expected_dns_name: return fs_id, path else: create_default_cloudwatchlog_agent_if_not_exist(config) fatal_error('The specified", "= os.path.join(tls_paths['mount_dir'], 'certificate.pem') ca_dirs_check(config, tls_paths['database_dir'], tls_paths['certs_dir']) ca_supporting_files_check(tls_paths['index'], tls_paths['index_attr'], tls_paths['serial'], tls_paths['rand'])", "= subprocess.call(['systemctl', 'status', 'network.target'], stdout=devnull, stderr=devnull, close_fds=True) if rc !=", "Silently fail if the subprocess has exited already pass else:", "'w') as devnull: subprocess.Popen(['systemctl', 'start', WATCHDOG_SERVICE], stdout=devnull, stderr=devnull, close_fds=True) else:", "'%s - mount.log' % (fs_id) else: log_stream_name = 'default -", "will create one private key and allow mounts to share", "efs_fqdn_match = EFS_FQDN_RE.match(hostname) if efs_fqdn_match: fs_id = efs_fqdn_match.group('fs_id') expected_dns_name =", "\\ .get('AssumeRoleWithWebIdentityResponse', {}) \\ .get('AssumeRoleWithWebIdentityResult', {}) \\ .get('Credentials', {}) if", "efs_config['libwrap'] = 'no' stunnel_config = '\\n'.join(serialize_stunnel_config(global_config) + serialize_stunnel_config(efs_config, 'efs')) logging.debug('Writing", "not instance_identity: raise Exception(\"Cannot retrieve region from instance_metadata\") return instance_identity", "None} try: access_key = aws_credentials_configs.get(awsprofile, 'aws_access_key_id') secret_key = aws_credentials_configs.get(awsprofile, 'aws_secret_access_key')", "EFS_ONLY_OPTIONS = [ 'accesspoint', 'awscredsuri', 'awsprofile', 'cafile', 'iam', 'netns', 'noocsp',", "os.environ[WEB_IDENTITY_ROLE_ARN_ENV], os.environ[WEB_IDENTITY_TOKEN_FILE_ENV], False ) if credentials and credentials_source: return credentials,", "'yes', 'accept': '127.0.0.1:%s', 'connect': '%s:2049', 'sslVersion': 'TLSv1.2', 'renegotiation': 'no', 'TIMEOUTbusy':", "is str: resp_dict = json.loads(resp_body) else: resp_dict = json.loads(resp_body.decode(request_resp.headers.get_content_charset() or", "log_stream_name = get_cloudwatch_log_stream_name(fs_id) return { 'log_group_name': log_group_name, 'retention_days': int(retention_days), 'log_stream_name':", "attached to instance # through IAM role name security credentials", "'{dns_name_suffix}' in dns_name_format: return split_dns_name_format[-2] elif 'amazonaws.com' in dns_name_format: return", "HTTPError, build_opener, urlopen, Request, HTTPHandler from urllib import urlencode except", "is_nfs_mount(mountpoint): cmd = ['stat', '-f', '-L', '-c', '%T', mountpoint] p", "in %s - %s' % (command, env_path, install_method), e) return", "e.response)) return True elif exception == 'InvalidParameterException': logging.error('Either parameter log", "stdout=subprocess.PIPE, stderr=subprocess.PIPE, preexec_fn=os.setsid, close_fds=True) logging.info('Started TLS tunnel, pid: %d', tunnel_proc.pid)", "{'X-aws-ec2-metadata-token-ttl-seconds': 21600} req = Request(INSTANCE_METADATA_TOKEN_URL, headers=headers, method='PUT') res = urlopen(req)", "access_key = aws_credentials_configs.get('default', 'aws_access_key_id') if access_key is not None: return", "(%s), ' \\ 'from ECS credentials relative uri, or from", "For backwards compatibility check dns_name_format to obtain the target region.", "tunnel_proc.poll() if tunnel_proc.returncode is not None: out, err = tunnel_proc.communicate()", "dns_name def tls_paths_dictionary(mount_name, base_path=STATE_FILE_DIR): tls_dict = { 'mount_dir': os.path.join(base_path, mount_name),", "not in options: options['rsize'] = '1048576' if 'wsize' not in", "iam_role_name = get_iam_role_name() if iam_role_name: credentials, credentials_source = get_aws_security_credentials_from_instance_metadata(iam_role_name) if", "exception = e.response['Error']['Code'] if exception == 'ResourceAlreadyExistsException': logging.debug('Log group %s", "through IAM role name security credentials lookup uri iam_role_name =", "-pkeyopt rsa_keygen_bits:3072' % key subprocess_call(cmd, 'Failed to create private key')", "about malformed log level until after logging is configured level_error", "v): if v is None: return k return '%s=%s' %", "= '/' if FS_ID_RE.match(remote): return remote, path try: primary, secondaries,", "+ tunnel_args # launch the tunnel in a process group", "return None try: log_stream = response['logStreams'][0] return log_stream.get('uploadSequenceToken') except (IndexError,", "DNS names for examples: %s' % (remote, 'https://docs.aws.amazon.com/efs/latest/ug/mounting-fs-mount-cmd-dns-name.html')) def is_nfs_mount(mountpoint):", "message): if not cloudwatchlog_agent or not cloudwatchlog_agent.get('client'): return False token", "= cloudwatch_describe_log_streams_helper(cloudwatchlog_agent) except ClientError as e: exception = e.response['Error']['Code'] if", "not os.path.isfile(index_path): open(index_path, 'w').close() if not os.path.isfile(index_attr_path): with open(index_attr_path, 'w+')", "= DEFAULT_CLOUDWATCH_LOG_GROUP if config.has_option(CLOUDWATCH_LOG_SECTION, 'log_group_name'): log_group_name = config.get(CLOUDWATCH_LOG_SECTION, 'log_group_name') retention_days", "to share it. # This means, however, that we have", "4 and '-o' in args[:-1]: options_index = args.index('-o') + 1", "bootstrap_cloudwatch_logging(config, fs_id=None): if not check_if_cloudwatch_log_enabled(config): return None cloudwatchlog_client = get_botocore_client(config,", "if '{region}' in dns_name_format: expected_replacement_field_ct += 1 format_args['region'] = get_target_region(config)", "'\\n%s = UTF8String:%s' % (key, value) return efs_client_info_str def create_public_key(private_key,", "'Failed to create self-signed client-side certificate') return current_time.strftime(CERT_DATETIME_FORMAT) def get_private_key_path():", "'is-active', '--quiet', WATCHDOG_SERVICE], close_fds=True) if rc != 0: with open(os.devnull,", "credentials at %s.' % STS_ENDPOINT_URL url_error_msg = 'Unable to reach", "if exception == 'ResourceAlreadyExistsException': logging.debug('Log group %s already exist, %s'", "+= 1 config_section = CONFIG_SECTION region = format_args.get('region') if region:", "\"\"\" if not use_iam: return None, None # attempt to", "opener = build_opener(HTTPHandler) request = Request(INSTANCE_METADATA_TOKEN_URL) request.add_header('X-aws-ec2-metadata-token-ttl-seconds', 21600) request.get_method =", "def create_string_to_sign(canonical_request, date, region): \"\"\" Create a String to Sign", "'files': files, } if cert_details: state.update(cert_details) with open(os.path.join(state_file_dir, state_file), 'w')", "'message': message } ] } if token: kwargs['sequenceToken'] = token", "log_message = user_message sys.stderr.write('%s\\n' % user_message) logging.error(log_message) publish_cloudwatch_log(CLOUDWATCHLOG_AGENT, 'Mount failed,", "\\ % (ecs_uri, SECURITY_CREDS_ECS_URI_HELP_URL) ecs_security_dict = url_request_helper(ecs_uri, ecs_unsuccessful_resp, ecs_url_error_msg) if", "configuration file with fresh configurations at every mount since SigV4", "'?' + urlencode({ 'Version': '2011-06-15', 'Action': 'AssumeRoleWithWebIdentity', 'RoleArn': role_arn, 'RoleSessionName':", "errno.EEXIST != e.errno or not os.path.isdir(directory): raise @contextmanager def bootstrap_tls(config,", "test_tunnel_process(tunnel_proc, fs_id) except SystemExit as e: os._exit(e.code) mount_completed.wait(.5) def get_init_system(comm_file='/proc/1/comm'):", "'accesspoint' in options: if 'tls' not in options: fatal_error('The \"tls\"", "Only use the config setting if the override is not", "init system \"%s\"' % (WATCHDOG_SERVICE, init_system) sys.stderr.write('%s\\n' % error_message) logging.warning(error_message)", "License. See the LICENSE accompanying this file # for the", "sudo mount /mount_point # # The script will add recommended", "import URLError, HTTPError, build_opener, urlopen, Request, HTTPHandler from urllib import", "def create_required_directory(config, directory): mode = 0o750 try: mode_str = config.get(CONFIG_SECTION,", "'+' # common name for certificate signing request is max", "sorted(canonical_query_params.items())]) def create_string_to_sign(canonical_request, date, region): \"\"\" Create a String to", "'aws4_request' HTTP_REQUEST_METHOD = 'GET' CANONICAL_URI = '/' CANONICAL_HEADERS_DICT = {", "config.get(CLOUDWATCH_LOG_SECTION, 'log_group_name') retention_days = DEFAULT_RETENTION_DAYS if config.has_option(CLOUDWATCH_LOG_SECTION, 'retention_in_days'): retention_days =", "calculate_signature(string_to_sign, date, secret_access_key, region) efs_client_auth_str = '[ efs_client_auth ]' efs_client_auth_str", "group_creation_completed: return None put_retention_policy_completed = put_cloudwatch_log_retention_policy(cloudwatchlog_client, log_group_name, retention_days) if not", "client_info['source'] = client_source return client_info def create_certificate(config, mount_name, common_name, region,", "and fs_id: log_stream_name = '%s - %s - mount.log' %", "INSTANCE_METADATA_SERVICE_URL = 'http://169.254.169.254/latest/dynamic/instance-identity/document/' INSTANCE_IAM_URL = 'http://169.254.169.254/latest/meta-data/iam/security-credentials/' SECURITY_CREDS_ECS_URI_HELP_URL = 'https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html' SECURITY_CREDS_WEBIDENTITY_HELP_URL", "ec2_metadata_unsuccessful_resp = 'Unsuccessful retrieval of EC2 metadata at %s.' %", "group name, cloudwatchlog stream name CLOUDWATCHLOG_AGENT = None LOG_DIR =", "common_name, region, fs_id, security_credentials, ap_id, client_info, base_path=STATE_FILE_DIR): current_time = get_utc_now()", "return True elif exception == 'InvalidParameterException': logging.error('Either parameter log group", ".get('AssumeRoleWithWebIdentityResponse', {}) \\ .get('AssumeRoleWithWebIdentityResult', {}) \\ .get('Credentials', {}) if all(k", "os.O_CREAT | os.O_DSYNC | os.O_EXCL | os.O_RDWR) try: lock_file_contents =", "killed easily by the mount watchdog logging.info('Starting TLS tunnel: \"%s\"',", "$dir/database/index.txt serial = $dir/database/serial private_key = %s cert = $dir/certificate.pem", "False except NoCredentialsError as e: logging.warning('Credentials are not properly configured,", "if not fsname or not mountpoint: usage(out=sys.stderr) fs_id, path =", "stdout=devnull, stderr=devnull, close_fds=True) elif 'start' in status: logging.debug('%s is already", "'no', 'TIMEOUTbusy': '20', 'TIMEOUTclose': '0', 'TIMEOUTidle': '70', 'delay': 'yes', }", "write_tls_tunnel_state_file(fs_id, mountpoint, tls_port, tunnel_proc.pid, tunnel_args, [stunnel_config_file], state_file_dir, cert_details=cert_details) try: yield", "get_cloudwatch_log_stream_name(fs_id) return { 'log_group_name': log_group_name, 'retention_days': int(retention_days), 'log_stream_name': log_stream_name }", "options and 'iam' not in options: fatal_error('The \"iam\" option is", "and limitations under # the License. # # # Copy", "to take out private key creation lock, sleeping 50 ms')", "first octet (byte) is the tag (type) # - the", "return check_host_supported, ocsp_aia_supported def _stunnel_bin(): return find_command_path('stunnel', 'Please install it", "[ req_distinguished_name ] CN = %s %s %s %s \"\"\"", "(access key ID and secret access key). Adapted credentials provider", "as e: err_msg = 'Unable to reach the url at", "if 'stop' in status: with open(os.devnull, 'w') as devnull: subprocess.Popen(['/sbin/start',", "'OperationAbortedException': logging.debug('Multiple requests to update the same log group %s", "# Fail if credentials cannot be fetched from the given", "= '%y%m%d%H%M%SZ' AWS_CREDENTIALS_FILE = os.path.expanduser(os.path.join('~' + pwd.getpwuid(os.getuid()).pw_name, '.aws', 'credentials')) AWS_CONFIG_FILE", "STS_ENDPOINT_URL = 'https://sts.amazonaws.com/' INSTANCE_METADATA_TOKEN_URL = 'http://169.254.169.254/latest/api/token' INSTANCE_METADATA_SERVICE_URL = 'http://169.254.169.254/latest/dynamic/instance-identity/document/' INSTANCE_IAM_URL", "%s does not exist, %s' % (cloudwatchlog_agent.get('log_group_name'), cloudwatchlog_agent.get('log_stream_name'), e.response)) return", "%s' % (cloudwatchlog_agent.get('log_group_name'), cloudwatchlog_agent.get('log_stream_name'), e.response)) return False else: logging.debug('Unexpected error:", "e.response)) return False elif exception == 'UnrecognizedClientException': logging.debug('The most likely", "be fetched from the given aws_creds_uri if is_fatal: fatal_error(unsuccessful_resp, unsuccessful_resp)", "'sslVersion': 'TLSv1.2', 'renegotiation': 'no', 'TIMEOUTbusy': '20', 'TIMEOUTclose': '0', 'TIMEOUTidle': '70',", "pull out the actual key material by looking for the", "following octets encode, as big-endian, the length (which may be", "genpkey -algorithm RSA -out %s -pkeyopt rsa_keygen_bits:3072' % key subprocess_call(cmd,", "config.get(CONFIG_SECTION, 'dns_name_format') if '{fs_id}' not in dns_name_format: raise ValueError('DNS name", "so try: access_key = aws_credentials_configs.get('default', 'aws_access_key_id') if access_key is not", "and allow mounts to share it. # This means, however,", "incorrect number of replacement fields') dns_name_format = config.get(CONFIG_SECTION, 'dns_name_format') if", "False) if credentials and credentials_source: return credentials, credentials_source # attempt", "quote_plus(access_key + '/' + get_credential_scope(date, region)) request = HTTP_REQUEST_METHOD +", "mocking purposes in unit tests\"\"\" return PRIVATE_KEY_FILE def check_and_create_private_key(base_path=STATE_FILE_DIR): #", "logging.error('Either parameter log group name %s or retention in days", "%s, is incorrectly formatted' % public_key fatal_error(err_msg, err_msg) key_line =", "date, secret_access_key, region): \"\"\" Calculate the Signature - https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html \"\"\"", "key_line = key_line.replace(' ', '') # DER encoding TLV (Tag,", "] STUNNEL_GLOBAL_CONFIG = { 'fips': 'no', 'foreground': 'yes', 'socket': [", "create_required_directory(config, state_file_dir) verify_level = int(options.get('verify', DEFAULT_STUNNEL_VERIFY_LEVEL)) ocsp_enabled = is_ocsp_enabled(config, options)", "urlencode try: import botocore.session from botocore.exceptions import ClientError, NoCredentialsError, EndpointConnectionError", "# 'efs' type is a networked file system type. This", "'fips': 'no', 'foreground': 'yes', 'socket': [ 'l:SO_REUSEADDR=yes', 'a:SO_BINDTODEVICE=lo', ], }", "name %s or retention in days %s is specified incorrectly,", "e: exception = e.response['Error']['Code'] if exception == 'InvalidSequenceTokenException': logging.debug('The sequence", "-out %s' % (private_key, public_key) subprocess_call(cmd, 'Failed to create public", "== 'InvalidParameterException': logging.debug('One of the parameter to put log events", "sys.stdout.write('%s Version: %s\\n' % (args[0], VERSION)) sys.exit(0) def parse_arguments(config, args=None):", "requests to update the same log group %s were in", "e) return False return True def cloudwatch_put_retention_policy_helper(cloudwatchlog_client, log_group_name, retention_days): cloudwatchlog_client.put_retention_policy(", "mountpoint, tls_port): return '%s.%s.%d' % (fs_id, os.path.abspath(mountpoint).replace(os.sep, '.').lstrip('.'), tls_port) def", "path = subprocess.check_output(['which', command]) except subprocess.CalledProcessError as e: fatal_error('Failed to", "VERSION, options) global CLOUDWATCHLOG_AGENT CLOUDWATCHLOG_AGENT = bootstrap_cloudwatch_logging(config, fs_id) check_unsupported_options(options) check_options_validity(options)", "'[ v3_ca ]\\nsubjectKeyIdentifier = hash' if ap_id: ca_extension_str += '\\n1.3.6.1.4.1.4843.7.1", "options['wsize'] = '1048576' if 'soft' not in options and 'hard'", "configparser import ConfigParser, NoOptionError, NoSectionError try: from urllib.parse import quote_plus", "'Please refer to the EFS documentation for mounting with DNS", "mountpoint, options): if 'tls' in options: mount_path = '127.0.0.1:%s' %", "= {} for o in options.split(','): if '=' in o:", "SKIP_NO_LIBWRAP_RELEASES): efs_config['libwrap'] = 'no' stunnel_config = '\\n'.join(serialize_stunnel_config(global_config) + serialize_stunnel_config(efs_config, 'efs'))", "e: logging.info('ValueError parsing \"%s\" into json: %s. Returning response body.'", "System Type] [Options] [Dump] [Pass] # # Add an entry", "awsprofile=None, aws_creds_uri=None): \"\"\" Lookup AWS security credentials (access key ID", "creds = resp \\ .get('AssumeRoleWithWebIdentityResponse', {}) \\ .get('AssumeRoleWithWebIdentityResult', {}) \\", "% (directory, private_key, common_name, ca_extension_body, efs_client_auth_body, efs_client_info_body) with open(config_path, 'w')", "log_stream_name, e.response)) return False elif exception == 'ResourceNotFoundException': logging.error('Log group", "to obtain the target region. This functionality should only be", "(dns_name, 'https://docs.aws.amazon.com/console/efs/mount-dns-name'), 'Failed to resolve \"%s\"' % dns_name) return dns_name", "key id is found under [default] section in current file", "resolve \"%s\" - check that your file system ID is", "get_botocore_client(config, service): if not BOTOCORE_PRESENT: logging.error('Failed to import botocore, please", "% public_key fatal_error(err_msg, err_msg) key_line = key_line.replace(' ', '') #", "%s.' % security_creds_lookup_url url_error_msg = 'Unable to reach %s to", "log stream name %s is specified incorrectly, %s' % (log_group_name,", "error_message): \"\"\"Helper method to run shell openssl command and to", "log group %s' % (log_stream_name, log_group_name)) def create_cloudwatch_log_stream(cloudwatchlog_client, log_group_name, log_stream_name):", "def serialize_stunnel_config(config, header=None): lines = [] if header: lines.append('[%s]' %", "awsprofile if is_fatal: log_message = 'AWS security credentials not found", "access key id is found under [default] section in current", "on EKS) if WEB_IDENTITY_ROLE_ARN_ENV in os.environ and WEB_IDENTITY_TOKEN_FILE_ENV in os.environ:", "'log_group_name') retention_days = DEFAULT_RETENTION_DAYS if config.has_option(CLOUDWATCH_LOG_SECTION, 'retention_in_days'): retention_days = config.get(CLOUDWATCH_LOG_SECTION,", "certificate_signing_request, certificate) subprocess_call(cmd, 'Failed to create self-signed client-side certificate') return", "\"%s\" did not resolve to an EFS mount target' %", "$dir/database/serial private_key = %s cert = $dir/certificate.pem new_certs_dir = $dir/certs", "get_version_specific_stunnel_options() tls_controls_message = 'WARNING: Your client lacks sufficient controls to", "with \"awscredsuri\"') if 'awscredsuri' in options and 'awsprofile' in options:", "%s cert = $dir/certificate.pem new_certs_dir = $dir/certs default_md = sha256", "%s' % e) return None except EndpointConnectionError as e: logging.warning('Could", "in ecs_security_dict for k in CREDENTIALS_KEYS): return ecs_security_dict, 'ecs:' +", "urlopen(req, timeout=1) return get_resp_obj(request_resp, url, unsuccessful_resp) err_msg = 'Unable to", "exist, %s' % (log_group_name, e.response)) return True elif exception ==", "+= get_credential_scope(date, region) + '\\n' sha256 = hashlib.sha256() sha256.update(canonical_request.encode()) string_to_sign", "method to run shell openssl command and to handle response", "\"%s\"', ' '.join(command)) proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) out,", "specified incorrectly, %s' % (log_group_name, e.response)) return False else: handle_general_botocore_exceptions(e)", "client lacks sufficient controls to properly enforce TLS. Please upgrade", "['/sbin/mount.nfs4', mount_path, mountpoint, '-o', get_nfs_mount_options(options)] if 'netns' in options: command", "import urlencode try: import botocore.session from botocore.exceptions import ClientError, NoCredentialsError,", "in log group %s, %s' % (log_stream_name, log_group_name, e.response)) return", "change these options, update the man page as well at", "to a file. Unfortunately this does not conform to Python's", "tls_port, dns_name, verify_level, ocsp_enabled, options, log_dir=LOG_DIR, cert_details=None): \"\"\" Serializes stunnel", "with open(OS_RELEASE_PATH) as f: for line in f: if 'PRETTY_NAME'", "continue return awsprofile def url_request_helper(url, unsuccessful_resp, url_error_msg, headers={}, retry_with_new_header_token=False): try:", "if not level: # delay logging error about malformed log", "file system can be mounted with: # # sudo mount", "tls_paths['database_dir'], tls_paths['certs_dir']) ca_supporting_files_check(tls_paths['index'], tls_paths['index_attr'], tls_paths['serial'], tls_paths['rand']) private_key = check_and_create_private_key(base_path) if", "log_message=None, exit_code=1): if log_message is None: log_message = user_message sys.stderr.write('%s\\n'", "for hostname in hostnames: efs_fqdn_match = EFS_FQDN_RE.match(hostname) if efs_fqdn_match: fs_id", "to pull out the actual key material by looking for", "state_file), 'w') as f: json.dump(state, f) return state_file def test_tunnel_process(tunnel_proc,", "client-side certificate') return current_time.strftime(CERT_DATETIME_FORMAT) def get_private_key_path(): \"\"\"Wrapped for mocking purposes", "if credentials cannot be fetched from the given awsprofile if", "output and 'nfs' in str(output) def mount_tls(config, init_system, dns_name, path,", "the credentials URI the ECS agent generated if aws_creds_uri: return", "purposes in unit tests\"\"\" return PRIVATE_KEY_FILE def check_and_create_private_key(base_path=STATE_FILE_DIR): # Creating", "log_stream_name): cloudwatchlog_client.create_log_stream( logGroupName=log_group_name, logStreamName=log_stream_name ) logging.info('Created cloudwatch log stream %s", "[%s] section found in config file %s', awsprofile, file_path) return", "Access Key ID and Secret Access Key are not found", "0 prim: NULL # 19:d=1 hl=4 l= 399 prim: BIT", "get_credential_scope(date, region)) request = HTTP_REQUEST_METHOD + '\\n' request += CANONICAL_URI", "network on non-systemd init systems') return check_network_target(fs_id) def start_watchdog(init_system): if", "+ session_token return efs_client_auth_str def efs_client_info_builder(client_info): efs_client_info_str = '[ efs_client_info", "= None if 'timeo' not in options: options['timeo'] = '600'", "(log_stream_name, log_group_name)) def create_cloudwatch_log_stream(cloudwatchlog_client, log_group_name, log_stream_name): try: cloudwatch_create_log_stream_helper(cloudwatchlog_client, log_group_name, log_stream_name)", "remaining 127 bits are used to encode the number of", "{ 'client': 'yes', 'accept': '127.0.0.1:%s', 'connect': '%s:2049', 'sslVersion': 'TLSv1.2', 'renegotiation':", "line in output.splitlines(): if 'BIT STRING' in line.decode('utf-8'): key_line =", "entry like this: # # fs-deadbeef /mount_point efs _netdev 0", "= options.get('awsprofile') if not awsprofile and use_iam: for file_path in", "public_key_path = os.path.join(directory, 'publicKey.pem') ca_extension_body = ca_extension_builder(ap_id, security_credentials, fs_id, client_info)", "octets are the \"value\" aka content # # For a", "headers={'Accept': 'application/json'}) if resp: creds = resp \\ .get('AssumeRoleWithWebIdentityResponse', {})", "proc.returncode) def usage(out, exit_code=1): out.write('Usage: mount.efs [--version] [-h|--help] <fsname> <mountpoint>", "\"awsprofile\" options are mutually exclusive') def bootstrap_cloudwatch_logging(config, fs_id=None): if not", "instance_identity[property] except KeyError as e: logging.warning('%s not present in %s:", "not yet available, add \"_netdev\" to your mount options' %", "not awsprofile and use_iam: for file_path in [AWS_CREDENTIALS_FILE, AWS_CONFIG_FILE]: aws_credentials_configs", "Example: # 0:d=0 hl=4 l= 418 cons: SEQUENCE # 4:d=1", "'logging_file_count') handler = RotatingFileHandler(os.path.join(log_dir, LOG_FILE), maxBytes=max_bytes, backupCount=file_count) handler.setFormatter(logging.Formatter(fmt='%(asctime)s - %(levelname)s", "Cloudwatchlog agent dict includes cloudwatchlog botocore client, cloudwatchlog group name,", "= proc.communicate() stunnel_output = err.splitlines() check_host_supported = is_stunnel_option_supported(stunnel_output, b'checkHost') ocsp_aia_supported", "get_client_info(config) if use_iam: aws_creds_uri = options.get('awscredsuri') if aws_creds_uri: kwargs =", "mode_str, CONFIG_FILE) except NoOptionError: pass try: os.makedirs(directory, mode) except OSError", "!= expected_ct or format_str.count('}') != expected_ct: raise ValueError('DNS name format", "the specific language governing permissions and limitations under # the", "v) for k, v in sorted(canonical_query_params.items())]) def create_string_to_sign(canonical_request, date, region):", "try: opener = build_opener(HTTPHandler) request = Request(INSTANCE_METADATA_TOKEN_URL) request.add_header('X-aws-ec2-metadata-token-ttl-seconds', 21600) request.get_method", "to instance # through IAM role name security credentials lookup", "as e: # For instance enable with IMDSv2, Unauthorized 401", "% (fs_id, os.path.abspath(mountpoint).replace(os.sep, '.').lstrip('.'), tls_port) def serialize_stunnel_config(config, header=None): lines =", "mount_name, 'database/index.txt'), 'index_attr': os.path.join(base_path, mount_name, 'database/index.txt.attr'), 'serial': os.path.join(base_path, mount_name, 'database/serial'),", "tlsport to X. options['tlsport'] = tls_port use_iam = 'iam' in", "not start %s, unrecognized init system \"%s\"' % (WATCHDOG_SERVICE, init_system)", "assets due to lack of multi-threading support in openssl 'database_dir':", "Type] [Options] [Dump] [Pass] # # Add an entry like", "efs_config = dict(STUNNEL_EFS_CONFIG) efs_config['accept'] = efs_config['accept'] % tls_port efs_config['connect'] =", "directory, private_key, date, region, fs_id, security_credentials, ap_id, client_info): \"\"\"Populate ca/req", "CONFIG_SECTION = 'mount' CLIENT_INFO_SECTION = 'client-info' CLIENT_SOURCE_STR_LEN_LIMIT = 100 CLOUDWATCH_LOG_SECTION", "iam_role_unsuccessful_resp = 'Unsuccessful retrieval of IAM role name at %s.'", "'request.csr') certificate = os.path.join(tls_paths['mount_dir'], 'certificate.pem') ca_dirs_check(config, tls_paths['database_dir'], tls_paths['certs_dir']) ca_supporting_files_check(tls_paths['index'], tls_paths['index_attr'],", "Create a Canonical Request - https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html \"\"\" formatted_datetime = date.strftime(SIGV4_DATETIME_FORMAT)", "+ '\\n' string_to_sign += get_credential_scope(date, region) + '\\n' sha256 =", "int(key_line.split(':')[0]) key = key[offset:] num_length_octets = key[1] & 0b01111111 #", "check_host_supported, ocsp_aia_supported = get_version_specific_stunnel_options() tls_controls_message = 'WARNING: Your client lacks", "{fs_id}') format_args = {'fs_id': fs_id} expected_replacement_field_ct = 1 if '{region}'", "stream name %s is specified incorrectly, %s' % (cloudwatchlog_agent.get('log_group_name'), cloudwatchlog_agent.get('log_stream_name'),", "False elif exception == 'ResourceNotFoundException': logging.error('Either log group %s or", "is incorrectly formatted' % public_key fatal_error(err_msg, err_msg) key_line = key_line.replace('", "'iam' in options ap_id = options.get('accesspoint') cert_details = {} security_credentials", "aws_creds_uri ecs_unsuccessful_resp = 'Unsuccessful retrieval of AWS security credentials at", "not valid, %s' % e.response) return False elif exception ==", "= %s' % (k, v)) return lines def add_stunnel_ca_options(efs_config, config,", "non-systemd init systems') return check_network_target(fs_id) def start_watchdog(init_system): if init_system ==", "close_fds=True) status, _ = proc.communicate() if 'stop' in status: with", "= line.decode('utf-8') if not key_line: err_msg = 'Public key file,", "index_attr_path, serial_path, rand_path): \"\"\"Recreate all supporting openssl ca and req", "init_system == 'systemd': rc = subprocess.call(['systemctl', 'is-active', '--quiet', WATCHDOG_SERVICE], close_fds=True)", "/etc/fstab. The syntax of an fstab entry is: # #", "NoOptionError as e: if 'aws_access_key_id' in str(e) or 'aws_secret_access_key' in", "octets # - the remaining octets are the \"value\" aka", "key[offset:] num_length_octets = key[1] & 0b01111111 # Exclude the tag", "hl=2 l= 0 prim: NULL # 19:d=1 hl=4 l= 399", "return None, None def get_aws_security_credentials_from_instance_metadata(iam_role_name): security_creds_lookup_url = INSTANCE_IAM_URL + iam_role_name", "os.path.join(base_path, mount_name), # every mount will have its own ca", "required when mounting via \"iam\"') if 'awsprofile' in options and", "Exception as e: logging.warning('Unknown error, %s' % e) return None", "stderr=devnull, close_fds=True) elif 'start' in status: logging.debug('%s is already running',", "'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL", "options: stunnel_cafile = options['cafile'] else: try: stunnel_cafile = config.get(CONFIG_SECTION, 'stunnel_cafile')", "systemd # (Amazon Linux 2, CentOS 7, RHEL 7, Debian", "| os.O_DSYNC | os.O_EXCL | os.O_RDWR) try: lock_file_contents = 'PID:", "return config.getboolean(CLOUDWATCH_LOG_SECTION, 'enabled') return False def cloudwatch_create_log_group_helper(cloudwatchlog_client, log_group_name): cloudwatchlog_client.create_log_group( logGroupName=log_group_name", "language governing permissions and limitations under # the License. #", "parse public key file, %s, correctly' % public_key) key_line =", "Choose a random midpoint, and then try ports in-order from", "- mount.log' return log_stream_name def check_if_cloudwatch_log_enabled(config): if config.has_option(CLOUDWATCH_LOG_SECTION, 'enabled'): return", "See %s for more info.' % \\ (INSTANCE_IAM_URL, SECURITY_CREDS_IAM_ROLE_HELP_URL) iam_role_name", "cloudwatchlog_config = get_cloudwatchlog_config(config, fs_id) log_group_name = cloudwatchlog_config.get('log_group_name') log_stream_name = cloudwatchlog_config.get('log_stream_name')", "- %(message)s')) logger = logging.getLogger() logger.setLevel(level) logger.addHandler(handler) if level_error: logging.error('Malformed", "try: from urllib2 import URLError, HTTPError, build_opener, urlopen, Request, HTTPHandler", "err_msg = 'Public key file, %s, is incorrectly formatted' %", "t.daemon = True t.start() mount_nfs(dns_name, path, mountpoint, options) mount_completed.set() t.join()", "= date.strftime(SIGV4_DATETIME_FORMAT) credential = quote_plus(access_key + '/' + get_credential_scope(date, region))" ]