file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
gobuild.go
false return false } if !dep.Compiled && (dep.Type == godata.LOCAL_PACKAGE || dep.Type == godata.UNKNOWN_PACKAGE && dep.Files.Len() > 0) { if !compile(dep) { pack.HasErrors = true pack.InProgress = false return false } } } // cgo files (the ones which import "C") can't be compiled // at the moment. They need to be compiled by hand into .a files. if pack.HasCGOFiles() { if pack.HasExistingAFile() { pack.Compiled = true pack.InProgress = false return true } else { logger.Error("Can't compile cgo files. Please manually compile them.\n") os.Exit(1) } } // check if this package has any files (if not -> error) if pack.Files.Len() == 0 && pack.Type == godata.LOCAL_PACKAGE { logger.Error("No files found for package %s.\n", pack.Name) os.Exit(1) } // if the outputDirPrefix points to something, subdirectories // need to be created if they don't already exist outputFile := objDir + pack.OutputFile if strings.Index(outputFile, "/") != -1 { path := outputFile[0:strings.LastIndex(outputFile, "/")] dir, err := os.Stat(path) if err != nil { err = os.MkdirAll(path, rootPathPerm) if err != nil { logger.Error("Could not create output path %s: %s\n", path, err) os.Exit(1) } } else if !dir.IsDirectory() { logger.Error("File found in %s instead of a directory.\n", path) os.Exit(1) } } // before compiling, remove any .a file // this is done because the compiler/linker looks for .a files // before it looks for .[568] files if !*flagKeepAFiles { if err := os.Remove(outputFile + ".a"); err == nil { logger.Debug("Removed file %s.a.\n", outputFile) } } // construct compiler command line arguments if pack.Name != "main" { logger.Info("Compiling %s...\n", pack.Name) } else { logger.Info("Compiling %s (%s)...\n", pack.Name, pack.OutputFile) } argc = pack.Files.Len() + 3 if *flagIncludePaths != "" { argc += 2 * (strings.Count(*flagIncludePaths, ",") + 1) } if pack.NeedsLocalSearchPath() || objDir != "" { argc += 2 } if pack.Name == "main" { argc += 2 } argv = make([]string, argc*2) argv[argvFilled] = compilerBin argvFilled++ argv[argvFilled] = "-o" argvFilled++ argv[argvFilled] = outputFile + objExt argvFilled++ if *flagIncludePaths != "" { for _, includePath := range strings.Split(*flagIncludePaths, ",", -1) { argv[argvFilled] = "-I" argvFilled++ argv[argvFilled] = includePath argvFilled++ } } // for _, arg := range argv { // logger.Info(arg) // logger.Info(" ") // } // logger.Info("\n") if pack.NeedsLocalSearchPath() || objDir != "" { argv[argvFilled] = "-I" argvFilled++ if objDir != "" { argv[argvFilled] = objDir } else { argv[argvFilled] = "." } argvFilled++ } if pack.Name == "main" { argv[argvFilled] = "-I" argvFilled++ argv[argvFilled] = "." argvFilled++ } for i := 0; i < pack.Files.Len(); i++ { gf := pack.Files.At(i).(*godata.GoFile) argv[argvFilled] = gf.Filename argvFilled++ } logger.Info(" %s\n", getCommandline(argv[0:argvFilled])) cmd, err := exec.Run(compilerBin, argv[0:argvFilled], os.Environ(), rootPath, exec.DevNull, exec.PassThrough, exec.PassThrough) if err != nil { logger.Error("%s\n", err) os.Exit(1) } waitmsg, err := cmd.Wait(0) if err != nil { logger.Error("Compiler execution error (%s), aborting compilation.\n", err) os.Exit(1) } if waitmsg.ExitStatus() != 0 { pack.HasErrors = true pack.InProgress = false return false } // it should now be compiled pack.Compiled = true pack.InProgress = false return true } /* Calls the linker for the main file, which should be called "main.(5|6|8)". */ func link(pack *godata.GoPackage) bool { var argc int var argv []string var argvFilled int var objDir string = "" //outputDirPrefix + getObjDir(); // build the command line for the linker argc = 4 if *flagIncludePaths != "" { argc += 2 } if pack.NeedsLocalSearchPath() { argc += 2 } if pack.Name == "main" { argc += 2 } argv = make([]string, argc*3) argv[argvFilled] = linkerBin argvFilled++ argv[argvFilled] = "-o" argvFilled++ argv[argvFilled] = outputDirPrefix + pack.OutputFile argvFilled++ if *flagIncludePaths != "" { for _, v := range strings.Split(*flagIncludePaths, ",", -1) { argv[argvFilled] = "-L" argvFilled++ argv[argvFilled] = v argvFilled++ } } // if pack.NeedsLocalSearchPath() { // argv[argvFilled] = "-L" // argvFilled++ // if objDir != "" { // argv[argvFilled] = objDir // } else { // argv[argvFilled] = "." // } // argvFilled++ // } if pack.Name == "main" { argv[argvFilled] = "-L" argvFilled++ argv[argvFilled] = "." argvFilled++ } argv[argvFilled] = objDir + pack.OutputFile + objExt argvFilled++ logger.Info("Linking %s...\n", argv[2]) logger.Info(" %s\n\n", getCommandline(argv)) cmd, err := exec.Run(linkerBin, argv[0:argvFilled], os.Environ(), rootPath, exec.DevNull, exec.PassThrough, exec.PassThrough) if err != nil { logger.Error("%s\n", err) os.Exit(1) } waitmsg, err := cmd.Wait(0) if err != nil { logger.Error("Linker execution error (%s), aborting compilation.\n", err) os.Exit(1) } if waitmsg.ExitStatus() != 0 { logger.Error("Linker returned with errors, aborting.\n") return false } return true } /* Executes goyacc for a single .y file. The new .go files is prefixed with an underscore and returned as a string for further use. */ func goyacc(filepath string) string { // construct output file path var outFilepath string l_idx := strings.LastIndex(filepath, "/") if l_idx >= 0 { outFilepath = filepath[0:l_idx+1] + "_" + filepath[l_idx+1:len(filepath)-1] + "go" } else { outFilepath = "_" + filepath[0:len(filepath)-1] + "go" } goyaccPath, err := exec.LookPath("goyacc") if err != nil { logger.Error("%s\n", err) os.Exit(1) } logger.Info("Parsing goyacc file %s.\n", filepath) argv := []string{goyaccPath, "-o", outFilepath, filepath} logger.Debug("%s\n", argv) cmd, err := exec.Run(argv[0], argv, os.Environ(), rootPath, exec.PassThrough, exec.PassThrough, exec.PassThrough) if err != nil { logger.Error("%s\n", err) os.Exit(1) } waitmsg, err := cmd.Wait(0) if err != nil { logger.Error("Executing goyacc failed: %s.\n", err) os.Exit(1) } if waitmsg.ExitStatus() != 0 { os.Exit(waitmsg.ExitStatus()) } return outFilepath } /* Executes something. Used for the -run command line option. */ func
runExec
identifier_name
sa_collection.py
raw_cookie_file = "../config/raw_cookie.txt" user_agent = {'User-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2)' + ' AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'} add_article = ("INSERT INTO articles" "(articleID, ticker_symbol, published_date, author_name, title, text, num_likes, includes_symbols)" "VALUES (%(articleID)s, %(ticker_symbol)s, %(published_date)s, %(author_name)s, %(title)s, %(text)s," " %(num_likes)s, %(includes_symbols)s)") add_comment = ("INSERT INTO comments" "(articleID, commentID, userID, comment_date, content, parentID, discussionID)" "VALUES (%(articleID)s, %(commentID)s, %(userID)s, %(comment_date)s, %(content)s, %(parentID)s," "%(discussionID)s)") ################################## # # # DATA CLASSES # # # ################################## class Article: def __init__(self, _id, a_cookie, a_user_agent): """ Initializes all fields with default values then parses the information from the url. """ self._id = _id self.ticker = '' self.pub_date = '0001-01-01' self.author = '' self.title = '' self.text = '' self.includes = '' self.comments = [] self.valid = True self._parse_article(a_cookie, a_user_agent) def _parse_article(self, a_cookie, a_ua): """ Parses article info from the given url. """ url = "https://seekingalpha.com/article/%s" % self._id r = safe_request(url, {}) r_login = safe_request(url, a_cookie) soup_log = BeautifulSoup(r_login.text, 'html.parser') # Stops process if article invalid primary_about = soup_log.find_all("a", href=True, sasource="article_primary_about") if len(primary_about) != 1: # Excludes non-single-ticker articles print("Invalid Article") self.valid = False return else: self.ticker = primary_about[0].text.split()[-1][1:-1] # Gets all includes and author about = soup_log.find_all("a", href=True) for a in about: if 'sasource' in a.attrs: if a.attrs['sasource'] == "article_about": self.includes += a.text + "," elif a.attrs['sasource'] == "auth_header_name": self.author += a.text + "," self.includes = self.includes[:-1] self.author = self.author[:-1] self.title = soup_log.find_all('h1')[0].text self.pub_date = soup_log.find_all('time', itemprop="datePublished")[0]['content'][:10] # Get Full Article Text name_box = BeautifulSoup(r.text, 'html.parser').find_all('p') print(name_box) try: disc_idx = list(filter(lambda i: 'id' in name_box[i].attrs and name_box[i]['id'] == 'a-disclosure', range(len(name_box))))[0] except IndexError: disc_idx = len(name_box) self.text = ''.join(map(lambda x: x.text + "\n", name_box[:disc_idx])) def json(self): """ Returns json representation of an article (for writing to the database). """ if self.valid: return { 'articleID': self._id, 'ticker_symbol': self.ticker, 'published_date': self.pub_date, 'author_name': self.author, 'title': self.title, 'text': self.text, 'num_likes': 0, 'includes_symbols': self.includes } return {} class Comment: def __init__(self, article_id, comment): self.articleID = article_id self.commentID = comment['id'] self.userID = comment['user_id'] self.date = comment['created_on'][:10] self.text = comment['content'] self.parentID = comment['parent_id'] self.discussionID = comment['discussion_id'] self.children_ids = comment['children'] def get_children(self): """ Recursively returns an array of all the children of the comment. """ children = [] for i in self.children_ids: child = Comment(self.articleID, self.children_ids[i]) children.append(child) children.extend(child.get_children()) return children def json(self): return { 'articleID': self.articleID,
'comment_date': self.date, 'content': self.text.encode('ascii', errors='ignore').decode(), 'parentID': self.parentID, 'discussionID': self.discussionID } ################################## # # # FILE FUNCTIONS # # # ################################## def read_json_file(filename): """ Reads a json formatted file. """ with open(filename) as f: try: data = json.loads(f.read()) except: data = {} return data def write_json_file(json_data, filename): """ Writes a json to a file. """ try: str_data = json.dumps(json_data) with open(filename, "w") as f: f.write(str_data) return True except MemoryError: return False def browser_cookie(rawcookie): cookie = SimpleCookie() cookie.load(rawcookie) # reference: https://stackoverflow.com/questions/32281041/converting-cookie-string-into-python-dict # Even though SimpleCookie is dictionary-like, it internally uses a Morsel object # which is incompatible with requests. Manually construct a dictionary instead. cookies = {} for key, morsel in cookie.items(): cookies[key] = morsel.value return cookies def default_cookie(): """ Gets cookie from the raw cookie file. """ with open(raw_cookie_file) as f: rc = "".join(f.readlines()) return browser_cookie(rc) def default_db_config(): """ Gets default database configuration. """ return read_json_file(db_config_file) def safe_request(url, cookie): """ Continues trying to make a request until a certain amount of tries have failed. """ count = 0 r = "" # Adjust this number if a certain amount of failed attempts # is acceptable while count < 1: try: r = requests.get(url, cookies=cookie, headers=user_agent) if r.status_code != 200: print(r.status_code, "blocked") count += 1 else: break except requests.exceptions.ConnectionError: print("timeout", url) time.sleep(1) return r def get_comment_jsons(article_id, cookie): """ Returns all comments for the given article as array of jsons. """ url = "https://seekingalpha.com/account/ajax_get_comments?id=%s&type=Article&commentType=" % article_id r = safe_request(url, cookie) comments = [] if r.status_code != 404: res = json.loads(r.text) for comment in res['comments'].values(): c = Comment(article_id, comment) comments.append(c.json()) comments.extend(map(lambda x: x.json(), c.get_children())) return comments def try_add_comment(com_jsons, cursor, article_id): """ Given array of comment jsons, adds comments to database. """ if not com_jsons: print("\t No comments found for " + article_id) for c in com_jsons: try: cursor.execute(add_comment, c) except mysql.connector.DatabaseError as err: if not err.errno == 1062: print("Wrong Comment Format: " + c["id"]) def try_add_article(art_json, cursor): """ Given an article json, tries to write that article to database. """ try: cursor.execute(add_article, art_json) except mysql.connector.errors.IntegrityError: print("Duplicate Article") def try_add_db(art_json, com_jsons, cursor, article_id): try_add_article(art_json, cursor) try_add_comment(com_jsons, cursor, article_id) def gather_mysql_data(article_fn, start=0, stop=None, comments_only=False): """ Given a file with Seeking Alpha article ids separated by commas, iterates through the article ids in the article and records the article and comment data in the mysql database. """ config = default_db_config() cookie = default_cookie() cnx = mysql.connector.connect(**config) cursor = cnx.cursor() with open(article_fn) as f: articles = f.read().split(",") i, total = start+1, float(len(articles)) for a in articles[start: stop]: if comments_only: com_jsons = get_comment_jsons(a, cookie) try_add_comment(com_jsons, cursor, a) else: art_json
'commentID': self.commentID, 'userID': self.userID,
random_line_split
sa_collection.py
raw_cookie_file = "../config/raw_cookie.txt" user_agent = {'User-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2)' + ' AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'} add_article = ("INSERT INTO articles" "(articleID, ticker_symbol, published_date, author_name, title, text, num_likes, includes_symbols)" "VALUES (%(articleID)s, %(ticker_symbol)s, %(published_date)s, %(author_name)s, %(title)s, %(text)s," " %(num_likes)s, %(includes_symbols)s)") add_comment = ("INSERT INTO comments" "(articleID, commentID, userID, comment_date, content, parentID, discussionID)" "VALUES (%(articleID)s, %(commentID)s, %(userID)s, %(comment_date)s, %(content)s, %(parentID)s," "%(discussionID)s)") ################################## # # # DATA CLASSES # # # ################################## class Article: def __init__(self, _id, a_cookie, a_user_agent): """ Initializes all fields with default values then parses the information from the url. """ self._id = _id self.ticker = '' self.pub_date = '0001-01-01' self.author = '' self.title = '' self.text = '' self.includes = '' self.comments = [] self.valid = True self._parse_article(a_cookie, a_user_agent) def _parse_article(self, a_cookie, a_ua): """ Parses article info from the given url. """ url = "https://seekingalpha.com/article/%s" % self._id r = safe_request(url, {}) r_login = safe_request(url, a_cookie) soup_log = BeautifulSoup(r_login.text, 'html.parser') # Stops process if article invalid primary_about = soup_log.find_all("a", href=True, sasource="article_primary_about") if len(primary_about) != 1: # Excludes non-single-ticker articles print("Invalid Article") self.valid = False return else: self.ticker = primary_about[0].text.split()[-1][1:-1] # Gets all includes and author about = soup_log.find_all("a", href=True) for a in about: if 'sasource' in a.attrs: if a.attrs['sasource'] == "article_about": self.includes += a.text + "," elif a.attrs['sasource'] == "auth_header_name": self.author += a.text + "," self.includes = self.includes[:-1] self.author = self.author[:-1] self.title = soup_log.find_all('h1')[0].text self.pub_date = soup_log.find_all('time', itemprop="datePublished")[0]['content'][:10] # Get Full Article Text name_box = BeautifulSoup(r.text, 'html.parser').find_all('p') print(name_box) try: disc_idx = list(filter(lambda i: 'id' in name_box[i].attrs and name_box[i]['id'] == 'a-disclosure', range(len(name_box))))[0] except IndexError: disc_idx = len(name_box) self.text = ''.join(map(lambda x: x.text + "\n", name_box[:disc_idx])) def
(self): """ Returns json representation of an article (for writing to the database). """ if self.valid: return { 'articleID': self._id, 'ticker_symbol': self.ticker, 'published_date': self.pub_date, 'author_name': self.author, 'title': self.title, 'text': self.text, 'num_likes': 0, 'includes_symbols': self.includes } return {} class Comment: def __init__(self, article_id, comment): self.articleID = article_id self.commentID = comment['id'] self.userID = comment['user_id'] self.date = comment['created_on'][:10] self.text = comment['content'] self.parentID = comment['parent_id'] self.discussionID = comment['discussion_id'] self.children_ids = comment['children'] def get_children(self): """ Recursively returns an array of all the children of the comment. """ children = [] for i in self.children_ids: child = Comment(self.articleID, self.children_ids[i]) children.append(child) children.extend(child.get_children()) return children def json(self): return { 'articleID': self.articleID, 'commentID': self.commentID, 'userID': self.userID, 'comment_date': self.date, 'content': self.text.encode('ascii', errors='ignore').decode(), 'parentID': self.parentID, 'discussionID': self.discussionID } ################################## # # # FILE FUNCTIONS # # # ################################## def read_json_file(filename): """ Reads a json formatted file. """ with open(filename) as f: try: data = json.loads(f.read()) except: data = {} return data def write_json_file(json_data, filename): """ Writes a json to a file. """ try: str_data = json.dumps(json_data) with open(filename, "w") as f: f.write(str_data) return True except MemoryError: return False def browser_cookie(rawcookie): cookie = SimpleCookie() cookie.load(rawcookie) # reference: https://stackoverflow.com/questions/32281041/converting-cookie-string-into-python-dict # Even though SimpleCookie is dictionary-like, it internally uses a Morsel object # which is incompatible with requests. Manually construct a dictionary instead. cookies = {} for key, morsel in cookie.items(): cookies[key] = morsel.value return cookies def default_cookie(): """ Gets cookie from the raw cookie file. """ with open(raw_cookie_file) as f: rc = "".join(f.readlines()) return browser_cookie(rc) def default_db_config(): """ Gets default database configuration. """ return read_json_file(db_config_file) def safe_request(url, cookie): """ Continues trying to make a request until a certain amount of tries have failed. """ count = 0 r = "" # Adjust this number if a certain amount of failed attempts # is acceptable while count < 1: try: r = requests.get(url, cookies=cookie, headers=user_agent) if r.status_code != 200: print(r.status_code, "blocked") count += 1 else: break except requests.exceptions.ConnectionError: print("timeout", url) time.sleep(1) return r def get_comment_jsons(article_id, cookie): """ Returns all comments for the given article as array of jsons. """ url = "https://seekingalpha.com/account/ajax_get_comments?id=%s&type=Article&commentType=" % article_id r = safe_request(url, cookie) comments = [] if r.status_code != 404: res = json.loads(r.text) for comment in res['comments'].values(): c = Comment(article_id, comment) comments.append(c.json()) comments.extend(map(lambda x: x.json(), c.get_children())) return comments def try_add_comment(com_jsons, cursor, article_id): """ Given array of comment jsons, adds comments to database. """ if not com_jsons: print("\t No comments found for " + article_id) for c in com_jsons: try: cursor.execute(add_comment, c) except mysql.connector.DatabaseError as err: if not err.errno == 1062: print("Wrong Comment Format: " + c["id"]) def try_add_article(art_json, cursor): """ Given an article json, tries to write that article to database. """ try: cursor.execute(add_article, art_json) except mysql.connector.errors.IntegrityError: print("Duplicate Article") def try_add_db(art_json, com_jsons, cursor, article_id): try_add_article(art_json, cursor) try_add_comment(com_jsons, cursor, article_id) def gather_mysql_data(article_fn, start=0, stop=None, comments_only=False): """ Given a file with Seeking Alpha article ids separated by commas, iterates through the article ids in the article and records the article and comment data in the mysql database. """ config = default_db_config() cookie = default_cookie() cnx = mysql.connector.connect(**config) cursor = cnx.cursor() with open(article_fn) as f: articles = f.read().split(",") i, total = start+1, float(len(articles)) for a in articles[start: stop]: if comments_only: com_jsons = get_comment_jsons(a, cookie) try_add_comment(com_jsons, cursor, a) else: art
json
identifier_name
sa_collection.py
raw_cookie_file = "../config/raw_cookie.txt" user_agent = {'User-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2)' + ' AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'} add_article = ("INSERT INTO articles" "(articleID, ticker_symbol, published_date, author_name, title, text, num_likes, includes_symbols)" "VALUES (%(articleID)s, %(ticker_symbol)s, %(published_date)s, %(author_name)s, %(title)s, %(text)s," " %(num_likes)s, %(includes_symbols)s)") add_comment = ("INSERT INTO comments" "(articleID, commentID, userID, comment_date, content, parentID, discussionID)" "VALUES (%(articleID)s, %(commentID)s, %(userID)s, %(comment_date)s, %(content)s, %(parentID)s," "%(discussionID)s)") ################################## # # # DATA CLASSES # # # ################################## class Article: def __init__(self, _id, a_cookie, a_user_agent): """ Initializes all fields with default values then parses the information from the url. """ self._id = _id self.ticker = '' self.pub_date = '0001-01-01' self.author = '' self.title = '' self.text = '' self.includes = '' self.comments = [] self.valid = True self._parse_article(a_cookie, a_user_agent) def _parse_article(self, a_cookie, a_ua): """ Parses article info from the given url. """ url = "https://seekingalpha.com/article/%s" % self._id r = safe_request(url, {}) r_login = safe_request(url, a_cookie) soup_log = BeautifulSoup(r_login.text, 'html.parser') # Stops process if article invalid primary_about = soup_log.find_all("a", href=True, sasource="article_primary_about") if len(primary_about) != 1: # Excludes non-single-ticker articles print("Invalid Article") self.valid = False return else: self.ticker = primary_about[0].text.split()[-1][1:-1] # Gets all includes and author about = soup_log.find_all("a", href=True) for a in about: if 'sasource' in a.attrs: if a.attrs['sasource'] == "article_about": self.includes += a.text + "," elif a.attrs['sasource'] == "auth_header_name": self.author += a.text + "," self.includes = self.includes[:-1] self.author = self.author[:-1] self.title = soup_log.find_all('h1')[0].text self.pub_date = soup_log.find_all('time', itemprop="datePublished")[0]['content'][:10] # Get Full Article Text name_box = BeautifulSoup(r.text, 'html.parser').find_all('p') print(name_box) try: disc_idx = list(filter(lambda i: 'id' in name_box[i].attrs and name_box[i]['id'] == 'a-disclosure', range(len(name_box))))[0] except IndexError: disc_idx = len(name_box) self.text = ''.join(map(lambda x: x.text + "\n", name_box[:disc_idx])) def json(self): """ Returns json representation of an article (for writing to the database). """ if self.valid: return { 'articleID': self._id, 'ticker_symbol': self.ticker, 'published_date': self.pub_date, 'author_name': self.author, 'title': self.title, 'text': self.text, 'num_likes': 0, 'includes_symbols': self.includes } return {} class Comment: def __init__(self, article_id, comment): self.articleID = article_id self.commentID = comment['id'] self.userID = comment['user_id'] self.date = comment['created_on'][:10] self.text = comment['content'] self.parentID = comment['parent_id'] self.discussionID = comment['discussion_id'] self.children_ids = comment['children'] def get_children(self): """ Recursively returns an array of all the children of the comment. """ children = [] for i in self.children_ids: child = Comment(self.articleID, self.children_ids[i]) children.append(child) children.extend(child.get_children()) return children def json(self): return { 'articleID': self.articleID, 'commentID': self.commentID, 'userID': self.userID, 'comment_date': self.date, 'content': self.text.encode('ascii', errors='ignore').decode(), 'parentID': self.parentID, 'discussionID': self.discussionID } ################################## # # # FILE FUNCTIONS # # # ################################## def read_json_file(filename): """ Reads a json formatted file. """ with open(filename) as f: try: data = json.loads(f.read()) except: data = {} return data def write_json_file(json_data, filename): """ Writes a json to a file. """ try: str_data = json.dumps(json_data) with open(filename, "w") as f: f.write(str_data) return True except MemoryError: return False def browser_cookie(rawcookie): cookie = SimpleCookie() cookie.load(rawcookie) # reference: https://stackoverflow.com/questions/32281041/converting-cookie-string-into-python-dict # Even though SimpleCookie is dictionary-like, it internally uses a Morsel object # which is incompatible with requests. Manually construct a dictionary instead. cookies = {} for key, morsel in cookie.items(): cookies[key] = morsel.value return cookies def default_cookie(): """ Gets cookie from the raw cookie file. """ with open(raw_cookie_file) as f: rc = "".join(f.readlines()) return browser_cookie(rc) def default_db_config(): """ Gets default database configuration. """ return read_json_file(db_config_file) def safe_request(url, cookie): """ Continues trying to make a request until a certain amount of tries have failed. """ count = 0 r = "" # Adjust this number if a certain amount of failed attempts # is acceptable while count < 1: try: r = requests.get(url, cookies=cookie, headers=user_agent) if r.status_code != 200: print(r.status_code, "blocked") count += 1 else: break except requests.exceptions.ConnectionError: print("timeout", url) time.sleep(1) return r def get_comment_jsons(article_id, cookie): """ Returns all comments for the given article as array of jsons. """ url = "https://seekingalpha.com/account/ajax_get_comments?id=%s&type=Article&commentType=" % article_id r = safe_request(url, cookie) comments = [] if r.status_code != 404: res = json.loads(r.text) for comment in res['comments'].values(): c = Comment(article_id, comment) comments.append(c.json()) comments.extend(map(lambda x: x.json(), c.get_children())) return comments def try_add_comment(com_jsons, cursor, article_id):
def try_add_article(art_json, cursor): """ Given an article json, tries to write that article to database. """ try: cursor.execute(add_article, art_json) except mysql.connector.errors.IntegrityError: print("Duplicate Article") def try_add_db(art_json, com_jsons, cursor, article_id): try_add_article(art_json, cursor) try_add_comment(com_jsons, cursor, article_id) def gather_mysql_data(article_fn, start=0, stop=None, comments_only=False): """ Given a file with Seeking Alpha article ids separated by commas, iterates through the article ids in the article and records the article and comment data in the mysql database. """ config = default_db_config() cookie = default_cookie() cnx = mysql.connector.connect(**config) cursor = cnx.cursor() with open(article_fn) as f: articles = f.read().split(",") i, total = start+1, float(len(articles)) for a in articles[start: stop]: if comments_only: com_jsons = get_comment_jsons(a, cookie) try_add_comment(com_jsons, cursor, a) else: art_json
""" Given array of comment jsons, adds comments to database. """ if not com_jsons: print("\t No comments found for " + article_id) for c in com_jsons: try: cursor.execute(add_comment, c) except mysql.connector.DatabaseError as err: if not err.errno == 1062: print("Wrong Comment Format: " + c["id"])
identifier_body
sa_collection.py
raw_cookie_file = "../config/raw_cookie.txt" user_agent = {'User-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2)' + ' AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'} add_article = ("INSERT INTO articles" "(articleID, ticker_symbol, published_date, author_name, title, text, num_likes, includes_symbols)" "VALUES (%(articleID)s, %(ticker_symbol)s, %(published_date)s, %(author_name)s, %(title)s, %(text)s," " %(num_likes)s, %(includes_symbols)s)") add_comment = ("INSERT INTO comments" "(articleID, commentID, userID, comment_date, content, parentID, discussionID)" "VALUES (%(articleID)s, %(commentID)s, %(userID)s, %(comment_date)s, %(content)s, %(parentID)s," "%(discussionID)s)") ################################## # # # DATA CLASSES # # # ################################## class Article: def __init__(self, _id, a_cookie, a_user_agent): """ Initializes all fields with default values then parses the information from the url. """ self._id = _id self.ticker = '' self.pub_date = '0001-01-01' self.author = '' self.title = '' self.text = '' self.includes = '' self.comments = [] self.valid = True self._parse_article(a_cookie, a_user_agent) def _parse_article(self, a_cookie, a_ua): """ Parses article info from the given url. """ url = "https://seekingalpha.com/article/%s" % self._id r = safe_request(url, {}) r_login = safe_request(url, a_cookie) soup_log = BeautifulSoup(r_login.text, 'html.parser') # Stops process if article invalid primary_about = soup_log.find_all("a", href=True, sasource="article_primary_about") if len(primary_about) != 1: # Excludes non-single-ticker articles print("Invalid Article") self.valid = False return else: self.ticker = primary_about[0].text.split()[-1][1:-1] # Gets all includes and author about = soup_log.find_all("a", href=True) for a in about: if 'sasource' in a.attrs: if a.attrs['sasource'] == "article_about": self.includes += a.text + "," elif a.attrs['sasource'] == "auth_header_name": self.author += a.text + "," self.includes = self.includes[:-1] self.author = self.author[:-1] self.title = soup_log.find_all('h1')[0].text self.pub_date = soup_log.find_all('time', itemprop="datePublished")[0]['content'][:10] # Get Full Article Text name_box = BeautifulSoup(r.text, 'html.parser').find_all('p') print(name_box) try: disc_idx = list(filter(lambda i: 'id' in name_box[i].attrs and name_box[i]['id'] == 'a-disclosure', range(len(name_box))))[0] except IndexError: disc_idx = len(name_box) self.text = ''.join(map(lambda x: x.text + "\n", name_box[:disc_idx])) def json(self): """ Returns json representation of an article (for writing to the database). """ if self.valid: return { 'articleID': self._id, 'ticker_symbol': self.ticker, 'published_date': self.pub_date, 'author_name': self.author, 'title': self.title, 'text': self.text, 'num_likes': 0, 'includes_symbols': self.includes } return {} class Comment: def __init__(self, article_id, comment): self.articleID = article_id self.commentID = comment['id'] self.userID = comment['user_id'] self.date = comment['created_on'][:10] self.text = comment['content'] self.parentID = comment['parent_id'] self.discussionID = comment['discussion_id'] self.children_ids = comment['children'] def get_children(self): """ Recursively returns an array of all the children of the comment. """ children = [] for i in self.children_ids: child = Comment(self.articleID, self.children_ids[i]) children.append(child) children.extend(child.get_children()) return children def json(self): return { 'articleID': self.articleID, 'commentID': self.commentID, 'userID': self.userID, 'comment_date': self.date, 'content': self.text.encode('ascii', errors='ignore').decode(), 'parentID': self.parentID, 'discussionID': self.discussionID } ################################## # # # FILE FUNCTIONS # # # ################################## def read_json_file(filename): """ Reads a json formatted file. """ with open(filename) as f: try: data = json.loads(f.read()) except: data = {} return data def write_json_file(json_data, filename): """ Writes a json to a file. """ try: str_data = json.dumps(json_data) with open(filename, "w") as f: f.write(str_data) return True except MemoryError: return False def browser_cookie(rawcookie): cookie = SimpleCookie() cookie.load(rawcookie) # reference: https://stackoverflow.com/questions/32281041/converting-cookie-string-into-python-dict # Even though SimpleCookie is dictionary-like, it internally uses a Morsel object # which is incompatible with requests. Manually construct a dictionary instead. cookies = {} for key, morsel in cookie.items(): cookies[key] = morsel.value return cookies def default_cookie(): """ Gets cookie from the raw cookie file. """ with open(raw_cookie_file) as f: rc = "".join(f.readlines()) return browser_cookie(rc) def default_db_config(): """ Gets default database configuration. """ return read_json_file(db_config_file) def safe_request(url, cookie): """ Continues trying to make a request until a certain amount of tries have failed. """ count = 0 r = "" # Adjust this number if a certain amount of failed attempts # is acceptable while count < 1:
return r def get_comment_jsons(article_id, cookie): """ Returns all comments for the given article as array of jsons. """ url = "https://seekingalpha.com/account/ajax_get_comments?id=%s&type=Article&commentType=" % article_id r = safe_request(url, cookie) comments = [] if r.status_code != 404: res = json.loads(r.text) for comment in res['comments'].values(): c = Comment(article_id, comment) comments.append(c.json()) comments.extend(map(lambda x: x.json(), c.get_children())) return comments def try_add_comment(com_jsons, cursor, article_id): """ Given array of comment jsons, adds comments to database. """ if not com_jsons: print("\t No comments found for " + article_id) for c in com_jsons: try: cursor.execute(add_comment, c) except mysql.connector.DatabaseError as err: if not err.errno == 1062: print("Wrong Comment Format: " + c["id"]) def try_add_article(art_json, cursor): """ Given an article json, tries to write that article to database. """ try: cursor.execute(add_article, art_json) except mysql.connector.errors.IntegrityError: print("Duplicate Article") def try_add_db(art_json, com_jsons, cursor, article_id): try_add_article(art_json, cursor) try_add_comment(com_jsons, cursor, article_id) def gather_mysql_data(article_fn, start=0, stop=None, comments_only=False): """ Given a file with Seeking Alpha article ids separated by commas, iterates through the article ids in the article and records the article and comment data in the mysql database. """ config = default_db_config() cookie = default_cookie() cnx = mysql.connector.connect(**config) cursor = cnx.cursor() with open(article_fn) as f: articles = f.read().split(",") i, total = start+1, float(len(articles)) for a in articles[start: stop]: if comments_only: com_jsons = get_comment_jsons(a, cookie) try_add_comment(com_jsons, cursor, a) else: art
try: r = requests.get(url, cookies=cookie, headers=user_agent) if r.status_code != 200: print(r.status_code, "blocked") count += 1 else: break except requests.exceptions.ConnectionError: print("timeout", url) time.sleep(1)
conditional_block
set.js
Charm"), Necrogenesis: require("./Necrogenesis"), Necroplasm: require("./Necroplasm"), NevinyrralsDisk: require("./NevinyrralsDisk"), NomadOutpost: require("./NomadOutpost"), OathofDruids: require("./OathofDruids"), Oblation: require("./Oblation"), OpalPalace: require("./OpalPalace"), OpentheVaults: require("./OpentheVaults"), OpulentPalace: require("./OpulentPalace"), OrderChaos: require("./OrderChaos"), OrzhovAdvokist: require("./OrzhovAdvokist"), OrzhovBasilica: require("./OrzhovBasilica"), OrzhovSignet: require("./OrzhovSignet"), PartingThoughts: require("./PartingThoughts"), PastinFlames: require("./PastinFlames"), PhyrexianRebirth: require("./PhyrexianRebirth"), Plains: require("./Plains"), PrimevalProtector: require("./PrimevalProtector"), PrismaticGeoscope: require("./PrismaticGeoscope"), ProgenitorMimic: require("./ProgenitorMimic"), Propaganda: require("./Propaganda"), PsychosisCrawler: require("./PsychosisCrawler"), Putrefy: require("./Putrefy"), QuirionExplorer: require("./QuirionExplorer"), RakdosCarnarium: require("./RakdosCarnarium"), RakdosCharm: require("./RakdosCharm"), RakdosSignet: require("./RakdosSignet"), RampantGrowth: require("./RampantGrowth"), RavosSoultender: require("./RavosSoultender"), ReadtheRunes: require("./ReadtheRunes"), RealmSeekers: require("./RealmSeekers"), ReforgetheSoul: require("./ReforgetheSoul"), ReinsofPower: require("./ReinsofPower"), ReliquaryTower: require("./ReliquaryTower"), Reveillark: require("./Reveillark"), ReversetheSands: require("./ReversetheSands"), ReyhanLastoftheAbzan: require("./ReyhanLastoftheAbzan"), RitesofFlourishing: require("./RitesofFlourishing"), RootboundCrag: require("./RootboundCrag"), Rubblehulk: require("./Rubblehulk"), RuggedHighlands: require("./RuggedHighlands"), RunehornHellkite: require("./RunehornHellkite"), RuptureSpire: require("./RuptureSpire"), SakuraTribeElder: require("./SakuraTribeElder"), SanctumGargoyle: require("./SanctumGargoyle"), SandsteppeCitadel: require("./SandsteppeCitadel"), Sangromancer: require("./Sangromancer"), SaskiatheUnyielding: require("./SaskiatheUnyielding"), SatyrWayfinder: require("./SatyrWayfinder"), SavageLands: require("./SavageLands"), ScavengingOoze: require("./ScavengingOoze"), SeasideCitadel: require("./SeasideCitadel"), SeatoftheSynod: require("./SeatoftheSynod"), SeedsofRenewal: require("./SeedsofRenewal"), SelesnyaGuildmage: require("./SelesnyaGuildmage"), SelesnyaSanctuary: require("./SelesnyaSanctuary"), SelflessSquire: require("./SelflessSquire"), SelvalaExplorerReturned: require("./SelvalaExplorerReturned"), ShadowbloodRidge: require("./ShadowbloodRidge"), ShamanicRevelation: require("./ShamanicRevelation"), SharuumtheHegemon: require("./SharuumtheHegemon"), ShimmerMyr: require("./ShimmerMyr"), SidarKondoofJamuraa: require("./SidarKondoofJamuraa"), SilasRennSeekerAdept: require("./SilasRennSeekerAdept"), SimicGrowthChamber: require("./SimicGrowthChamber"), SimicSignet: require("./SimicSignet"), Skullclamp: require("./Skullclamp"), SlobadGoblinTinkerer: require("./SlobadGoblinTinkerer"), SolemnSimulacrum: require("./SolemnSimulacrum"), SolidarityofHeroes: require("./SolidarityofHeroes"), SolRing: require("./SolRing"), SoulofNewPhyrexia: require("./SoulofNewPhyrexia"), SpellheartChimera: require("./SpellheartChimera"), Spelltwine: require("./Spelltwine"), SphereofSafety: require("./SphereofSafety"), SphinxSummoner: require("./SphinxSummoner"), SpinerockKnoll: require("./SpinerockKnoll"), SpittingImage: require("./SpittingImage"), StalkingVengeance: require("./StalkingVengeance"), StonehoofChieftain: require("./StonehoofChieftain"), SublimeExhalation: require("./SublimeExhalation"), Sunforger: require("./Sunforger"), SungrassPrairie: require("./SungrassPrairie"), SunpetalGrove: require("./SunpetalGrove"), Swamp: require("./Swamp"), SwanSong: require("./SwanSong"), SwiftfootBoots: require("./SwiftfootBoots"), SwiftwaterCliffs: require("./SwiftwaterCliffs"), SwordstoPlowshares: require("./SwordstoPlowshares"), SydriGalvanicGenius: require("./SydriGalvanicGenius"), SylvanReclamation: require("./SylvanReclamation"), SylvokExplorer: require("./SylvokExplorer"), TanatheBloodsower: require("./TanatheBloodsower"), TaureanMauler: require("./TaureanMauler"), TempleBell: require("./TempleBell"), TempleoftheFalseGod: require("./TempleoftheFalseGod"), TemptwithDiscovery: require("./TemptwithDiscovery"), Terminate: require("./Terminate"), TerramorphicExpanse: require("./TerramorphicExpanse"), TezzeretsGambit: require("./TezzeretsGambit"), TheloniteHermit: require("./TheloniteHermit"), ThopterFoundry: require("./ThopterFoundry"), ThornwoodFalls: require("./ThornwoodFalls"), ThrasiosTritonHero: require("./ThrasiosTritonHero"), Thrummingbird: require("./Thrummingbird"), ThunderfootBaloth: require("./ThunderfootBaloth"), TradingPost: require("./TradingPost"), TransguildPromenade: require("./TransguildPromenade"), TrashforTreasure: require("./TrashforTreasure"), TreacherousTerrain: require("./TreacherousTerrain"), TreasureCruise: require("./TreasureCruise"), TrialError: require("./TrialError"), TrinketMage: require("./TrinketMage"), TuskguardCaptain: require("./TuskguardCaptain"), TymnatheWeaver: require("./TymnatheWeaver"), UndergroundRiver: require("./UndergroundRiver"), UtterEnd: require("./UtterEnd"), VedalkenEngineer: require("./VedalkenEngineer"), VensersJournal: require("./VensersJournal"), VeteranExplorer: require("./VeteranExplorer"), VialSmashertheFierce: require("./VialSmashertheFierce"), VolcanicVision: require("./VolcanicVision"), VoreloftheHullClade: require("./VoreloftheHullClade"), VulturousZombie: require("./VulturousZombie"), WallofBlossoms: require("./WallofBlossoms"), WasteNot: require("./WasteNot"), WaveofReckoning: require("./WaveofReckoning"), WheelofFate: require("./WheelofFate"), WhimsoftheFates: require("./WhimsoftheFates"), Whipflare: require("./Whipflare"), WhisperingMadness: require("./WhisperingMadness"), WhispersilkCloak: require("./WhispersilkCloak"), WightofPrecinctSix: require("./WightofPrecinctSix"), WildBeastmaster: require("./WildBeastmaster"), WildernessElemental: require("./WildernessElemental"), WindbornMuse: require("./WindbornMuse"), WindbriskHeights: require("./WindbriskHeights"), Windfall: require("./Windfall"), WormHarvest: require("./WormHarvest"), YidrisMaelstromWielder: require("./YidrisMaelstromWielder"), ZedruutheGreathearted: require("./ZedruutheGreathearted"), ZhurTaaDruid: require("./ZhurTaaDruid") }; if (window) {if (!window.mtgSets)
{ window.mtgSets = {}; }
conditional_block
set.js
ment: require("./EverlastingTorment"), EvolutionaryEscalation: require("./EvolutionaryEscalation"), EvolvingWilds: require("./EvolvingWilds"), ExecutionersCapsule: require("./ExecutionersCapsule"), ExoticOrchard: require("./ExoticOrchard"), FaerieArtisans: require("./FaerieArtisans"), Farseek: require("./Farseek"), FarWanderings: require("./FarWanderings"), FathomMage: require("./FathomMage"), FellwarStone: require("./FellwarStone"), Festercreep: require("./Festercreep"), FiligreeAngel: require("./FiligreeAngel"), ForbiddenOrchard: require("./ForbiddenOrchard"), Forest: require("./Forest"), ForgottenAncient: require("./ForgottenAncient"), FrenziedFugue: require("./FrenziedFugue"), FrontierBivouac: require("./FrontierBivouac"), Gamekeeper: require("./Gamekeeper"), GhastlyConscription: require("./GhastlyConscription"), GhaveGuruofSpores: require("./GhaveGuruofSpores"), GhostlyPrison: require("./GhostlyPrison"), GlintEyeNephilim: require("./GlintEyeNephilim"), GoblinSpymaster: require("./GoblinSpymaster"), GodoBanditWarlord: require("./GodoBanditWarlord"), GolgariRotFarm: require("./GolgariRotFarm"), GolgariSignet: require("./GolgariSignet"), GrabtheReins: require("./GrabtheReins"), GrandColiseum: require("./GrandColiseum"), GraveUpheaval: require("./GraveUpheaval"), GripofPhyresis: require("./GripofPhyresis"), GruulSignet: require("./GruulSignet"), GruulTurf: require("./GruulTurf"), Guiltfeeder: require("./Guiltfeeder"), GwafaHazidProfiteer: require("./GwafaHazidProfiteer"), HannaShipsNavigator: require("./HannaShipsNavigator"), HardenedScales: require("./HardenedScales"), HellkiteIgniter: require("./HellkiteIgniter"), HellkiteTyrant: require("./HellkiteTyrant"), HomewardPath: require("./HomewardPath"), HoofprintsoftheStag: require("./HoofprintsoftheStag"), HorizonChimera: require("./HorizonChimera"), HowlingMine: require("./HowlingMine"), HumbleDefector: require("./HumbleDefector"), HushwingGryff: require("./HushwingGryff"), IchorWellspring: require("./IchorWellspring"), IkraShidiqitheUsurper: require("./IkraShidiqitheUsurper"), InGarruksWake: require("./InGarruksWake"), InspiringCall: require("./InspiringCall"), IroasGodofVictory: require("./IroasGodofVictory"), IshaiOjutaiDragonspeaker: require("./IshaiOjutaiDragonspeaker"), Island: require("./Island"), IzzetBoilerworks: require("./IzzetBoilerworks"), JorKadeenthePrevailer: require("./JorKadeenthePrevailer"), JungleHollow: require("./JungleHollow"), JungleShrine: require("./JungleShrine"), JuniperOrderRanger: require("./JuniperOrderRanger"), KalonianHydra: require("./KalonianHydra"), KarplusanForest: require("./KarplusanForest"), KazuulTyrantoftheCliffs: require("./KazuulTyrantoftheCliffs"), KeeningStone: require("./KeeningStone"), KodamasReach: require("./KodamasReach"), KorozdaGuildmage: require("./KorozdaGuildmage"), KraumLudevicsOpus: require("./KraumLudevicsOpus"), KrosanVerge: require("./KrosanVerge"), KydeleChosenofKruphix: require("./KydeleChosenofKruphix"), KynaiosandTiroofMeletis: require("./KynaiosandTiroofMeletis"), Languish: require("./Languish"), Lavalanche: require("./Lavalanche"), LightningGreaves: require("./LightningGreaves"), LoxodonWarhammer: require("./LoxodonWarhammer"), LudevicNecroAlchemist: require("./LudevicNecroAlchemist"), LurkingPredators: require("./LurkingPredators"), MagusoftheWill: require("./MagusoftheWill"), ManagorgerHydra: require("./ManagorgerHydra"), ManifoldInsights: require("./ManifoldInsights"), MasterBiomancer: require("./MasterBiomancer"), MasterofEtherium: require("./MasterofEtherium"), MentoroftheMeek: require("./MentoroftheMeek"), MercilessEviction: require("./MercilessEviction"), MigratoryRoute: require("./MigratoryRoute"), MindsAglow: require("./MindsAglow"), MirrorEntity: require("./MirrorEntity"), Mirrorweave: require("./Mirrorweave"), Mortify: require("./Mortify"), MosswortBridge: require("./MosswortBridge"), Mountain: require("./Mountain"), MurmuringBosk: require("./MurmuringBosk"), Mycoloth: require("./Mycoloth"), MycosynthWellspring: require("./MycosynthWellspring"), MyrBattlesphere: require("./MyrBattlesphere"), MyriadLandscape: require("./MyriadLandscape"), MyrRetriever: require("./MyrRetriever"), MysticMonastery: require("./MysticMonastery"), NathoftheGiltLeaf: require("./NathoftheGiltLeaf"), NayaCharm: require("./NayaCharm"), Necrogenesis: require("./Necrogenesis"), Necroplasm: require("./Necroplasm"), NevinyrralsDisk: require("./NevinyrralsDisk"), NomadOutpost: require("./NomadOutpost"), OathofDruids: require("./OathofDruids"), Oblation: require("./Oblation"), OpalPalace: require("./OpalPalace"), OpentheVaults: require("./OpentheVaults"), OpulentPalace: require("./OpulentPalace"), OrderChaos: require("./OrderChaos"), OrzhovAdvokist: require("./OrzhovAdvokist"), OrzhovBasilica: require("./OrzhovBasilica"), OrzhovSignet: require("./OrzhovSignet"), PartingThoughts: require("./PartingThoughts"), PastinFlames: require("./PastinFlames"), PhyrexianRebirth: require("./PhyrexianRebirth"), Plains: require("./Plains"), PrimevalProtector: require("./PrimevalProtector"), PrismaticGeoscope: require("./PrismaticGeoscope"), ProgenitorMimic: require("./ProgenitorMimic"), Propaganda: require("./Propaganda"), PsychosisCrawler: require("./PsychosisCrawler"), Putrefy: require("./Putrefy"), QuirionExplorer: require("./QuirionExplorer"), RakdosCarnarium: require("./RakdosCarnarium"), RakdosCharm: require("./RakdosCharm"), RakdosSignet: require("./RakdosSignet"), RampantGrowth: require("./RampantGrowth"), RavosSoultender: require("./RavosSoultender"), ReadtheRunes: require("./ReadtheRunes"), RealmSeekers: require("./RealmSeekers"), ReforgetheSoul: require("./ReforgetheSoul"), ReinsofPower: require("./ReinsofPower"), ReliquaryTower: require("./ReliquaryTower"), Reveillark: require("./Reveillark"), ReversetheSands: require("./ReversetheSands"), ReyhanLastoftheAbzan: require("./ReyhanLastoftheAbzan"), RitesofFlourishing: require("./RitesofFlourishing"), RootboundCrag: require("./RootboundCrag"), Rubblehulk: require("./Rubblehulk"), RuggedHighlands: require("./RuggedHighlands"), RunehornHellkite: require("./RunehornHellkite"), RuptureSpire: require("./RuptureSpire"), SakuraTribeElder: require("./SakuraTribeElder"), SanctumGargoyle: require("./SanctumGargoyle"),
SandsteppeCitadel: require("./SandsteppeCitadel"), Sangromancer: require("./Sangromancer"),
random_line_split
utils.rs
.y; } } #[no_mangle] pub extern "C" fn get_hex_coord( map: Option<&MaybeInvalid<Map>>, hex_x: u16, hex_y: u16, end_x: &mut u16, end_y: &mut u16, angle: f32, dist: u32, ) { if let Some(map) = map.and_then(MaybeInvalid::validate) { let end_hex = get_hex_in_path( map, Hex { x: hex_x, y: hex_y }, Hex { x: *end_x, y: *end_y, }, angle, dist, ); *end_x = end_hex.x; *end_y = end_hex.y; } } /* #[no_mangle] pub extern "C" fn test_hex_flags( map: Option<&MaybeInvalid<Map>>, hex_x: u16, hex_y: u16, raked: bool, passed: bool, ) { if let Some(map) = map.and_then(MaybeInvalid::validate) { let hex = Hex { x: hex_x, y: hex_y }; let flags = map.get_hex_flags_with_proto(hex); let mut wrong = false; if raked != map.is_hex_raked(hex) { wrong = true; print!("Raked - should be {}, but {}; ", raked, !raked); } if passed != map.is_hex_passed(hex) { wrong = true; print!("Passed - should be {}, but {}; ", passed, !passed); } if wrong { println!("Hex: {:?}, flags: {:016b}", hex, flags); } } } */ macro_rules! validate { ($this:expr, $default:expr) => { match $this.and_then(MaybeInvalid::validate) { Some(this) => this, None => return $default, } }; } /* #[no_mangle] pub extern "C" fn is_gM(Critter& player)
{ if( !player.IsPlayer() ) return false; if( !isLoadedGMs ) LoadGMs( player, 0, 0, 0 ); if( player.StatBase[ ST_ACCESS_LEVEL ] < ACCESS_MODER && ( player.GetAccess() >= ACCESS_MODER || isPocketGM( player.Id ) ) ) player.StatBase[ ST_ACCESS_LEVEL ] = ACCESS_MODER; return player.StatBase[ ST_ACCESS_LEVEL ] >= ACCESS_MODER && ( checkVision ? player.ParamBase[ QST_VISION ] > 0 : true ); }*/ #[no_mangle] pub extern "C" fn check_look( map: Option<&MaybeInvalid<Map>>, cr: Option<&MaybeInvalid<Critter>>, opponent: Option<&MaybeInvalid<Critter>>, ) -> bool { // Consider remove this let map = validate!(map, false); let cr = validate!(cr, false); let opponent = validate!(opponent, false); let config = &config().check_look; let smart = check_look_smart(config, map, cr, opponent); /*let old = check_look_old(config, map, cr, opponent); if old != smart { println!("old != smart: {:?} != {:?}", old, smart); }*/ /*let mut config_default = CheckLook::default(); config_default.npc_fast.enable = config.npc_fast.enable; let smart_default = check_look_smart(&config_default, map, cr, opponent); if smart != smart_default { println!("smart != smart_default: {:?} != {:?}", smart, smart_default); }*/ smart } fn check_look_smart(config: &CheckLook, map: &Map, cr: &Critter, opponent: &Critter) -> bool { if map.proto_id() == config.map_utility_start && opponent.is_player() && cr.is_player() && !cr.have_gm_vision() { return false; } let cr_hex = cr.hex(); let opp_hex = opponent.hex(); let dist = cr_hex.get_distance(opp_hex); use tnf_common::{defines::CritterParam, defines_fo4rp::param::Param}; let cr_vision = cr.uparam(Param::QST_VISION); let opp_invis = opponent.uparam(Param::QST_INVIS); if cr_vision >= dist && opp_invis <= dist { return true; } if opp_invis != 0 && (opp_invis - 1) < dist { // && ( !( cr.IsPlayer() ) || cr.IsPlayer() && !isGM( cr ) ) ) return false; } if opp_invis > dist || cr_vision >= dist { return true; } let cr_perception = param_getters::getParam_Perception(cr, 0) as u32; assert!(cr_perception >= 1 && cr_perception <= 10); fn basic_dist(rates: &CritterRates, perception: u32) -> u32 { rates.basic_bonus + perception * rates.basic_perception_rate } let self_is_npc = cr.is_npc(); if self_is_npc { if cr.is_dead() { return false; } let npc_fast = &config.npc_fast; if npc_fast.enable && cr.ProtoId >= npc_fast.fast_from && cr.ProtoId <= npc_fast.fast_to { return basic_dist(&config.senses[npc_fast.sense_index].npc, cr_perception) >= dist; } } let start_dir = cr_hex.get_direction(opp_hex); let mut look_dir = i8::abs(start_dir as i8 - cr.Dir as i8); //Направление if look_dir > 3 { look_dir = 6 - look_dir } assert!(look_dir >= 0 && look_dir <= 3); fn moving_rate(cr: &Critter, rates: &MovingRates) -> f32 { if cr.IsRuning { rates.running //} else if cr.is_walking() { // rates.walking } else { rates.still } } fn sense_mul(rates: &SenseRates, cr: &Critter, opponent: &Critter, look_dir: i8) -> f32 { rates.dir_rate[look_dir as usize] * moving_rate(cr, &rates.self_moving) * moving_rate(opponent, &rates.target_moving) } let senses: Vec<(f32, f32)> = config .senses .iter() .map(|sense| { let critter_rates = if self_is_npc { &sense.npc } else { &sense.player }; let basic_dist = basic_dist(critter_rates, cr_perception); let sense_mul = sense_mul(sense, cr, opponent, look_dir); let wall_mul = sense.wall_rate[cr_perception as usize - 1]; let clear_dist = basic_dist as f32 * sense_mul; //dbg!(clear_dist, wall_mul); (clear_dist, wall_mul) }) .collect(); let max_dist = senses .iter() .map(|(dist, _wall_mul)| *dist as u32) .max() .expect("At least one sense"); //dbg!(dist, max_dist); if dist > max_dist { return false; } let end_hex = get_hex_in_path(map, cr_hex, opp_hex, 0.0, dist); if dist > cr_hex.get_distance(end_hex) { for (basic_dist, wall_mull) in senses { //dbg!(basic_dist * wall_mull, dist); if (basic_dist * wall_mull) as u32 >= dist { return true; } } false } else { true } } fn _check_look_old(config: &CheckLook, map: &Map, cr: &Critter, opponent: &Critter) -> bool { if map.proto_id() == config.map_utility_start && opponent.is_player() && cr.is_player() && !cr.have_gm_vision() { return false; } let cr_hex = cr.hex(); let opp_hex = opponent.hex(); let dist = cr_hex.get_distance(opp_hex); use tnf_common::{defines::CritterParam, defines_fo4rp::param::Param}; let cr_vision = cr.uparam(Param::QST_VISION); let cr_perception = param_getters::getParam_Perception(cr, 0) as u32; //cr.uparam(Param::ST_PERCEPTION); let opp_invis = opponent.uparam(Param::QST_INVIS); if cr_vision >= dist && opp_invis <= dist { return true; } if opp_invis != 0 && (opp_invis - 1) < dist { // && ( !( cr.IsPlayer() ) || cr.IsPlayer() && !isGM( cr ) ) ) return false; } if opp_invis > dist || cr_vision >= dist { return true; } if cr.is_npc() { // упрощенный расчет для нпц, учитывает только дистанцию
random_line_split
utils.rs
; } } #[no_mangle] pub extern "C" fn get_hex_coord( map: Option<&MaybeInvalid<Map>>, hex_x: u16, hex_y: u16, end_x: &mut u16, end_y: &mut u16, angle: f32, dist: u32, ) { if let Some(map) = map.and_then(MaybeInvalid::validate) { let end_hex = get_hex_in_path( map, Hex { x: hex_x, y: hex_y }, Hex { x: *end_x, y: *end_y, }, angle, dist, ); *end_x = end_hex.x; *end_y = end_hex.y; } } /* #[no_mangle] pub extern "C" fn test_hex_flags( map: Option<&MaybeInvalid<Map>>, hex_x: u16, hex_y: u16, raked: bool, passed: bool, ) { if let Some(map) = map.and_then(MaybeInvalid::validate) { let hex = Hex { x: hex_x, y: hex_y }; let flags = map.get_hex_flags_with_proto(hex); let mut wrong = false; if raked != map.is_hex_raked(hex) { wrong = true; print!("Raked - should be {}, but {}; ", raked, !raked); } if passed != map.is_hex_passed(hex) { wrong = true; print!("Passed - should be {}, but {}; ", passed, !passed); } if wrong { println!("Hex: {:?}, flags: {:016b}", hex, flags); } } } */ macro_rules! validate { ($this:expr, $default:expr) => { match $this.and_then(MaybeInvalid::validate) { Some(this) => this, None => return $default, } }; } /* #[no_mangle] pub extern "C" fn is_gM(Critter& player) { if( !player.IsPlayer() ) return false; if( !isLoadedGMs ) LoadGMs( player, 0, 0, 0 ); if( player.StatBase[ ST_ACCESS_LEVEL ] < ACCESS_MODER && ( player.GetAccess() >= ACCESS_MODER || isPocketGM( player.Id ) ) ) player.StatBase[ ST_ACCESS_LEVEL ] = ACCESS_MODER; return player.StatBase[ ST_ACCESS_LEVEL ] >= ACCESS_MODER && ( checkVision ? player.ParamBase[ QST_VISION ] > 0 : true ); }*/ #[no_mangle] pub extern "C" fn check_look( map: Option<&MaybeInvalid<Map>>, cr: Option<&MaybeInvalid<Critter>>, opponent: Option<&MaybeInvalid<Critter>>, ) -> bool { // Consider remove this let map = validate!(map, false); let cr = validate!(cr, false); let opponent = validate!(opponent, false); let config = &config().check_look; let smart = check_look_smart(config, map, cr, opponent); /*let old = check_look_old(config, map, cr, opponent); if old != smart { println!("old != smart: {:?} != {:?}", old, smart); }*/ /*let mut config_default = CheckLook::default(); config_default.npc_fast.enable = config.npc_fast.enable; let smart_default = check_look_smart(&config_default, map, cr, opponent); if smart != smart_default { println!("smart != smart_default: {:?} != {:?}", smart, smart_default); }*/ smart } fn check_look_smart(config: &CheckLook, map: &Map, cr: &Critter, opponent: &Critter) -> bool { if map.proto_id() == config.map_utility_start && opponent.is_player() && cr.is_player() && !cr.have_gm_vision() { return false; } let cr_hex = cr.hex(); let opp_hex = opponent.hex(); let dist = cr_hex.get_distance(opp_hex); use tnf_common::{defines::CritterParam, defines_fo4rp::param::Param}; let cr_vision = cr.uparam(Param::QST_VISION); let opp_invis = opponent.uparam(Param::QST_INVIS); if cr_vision >= dist && opp_invis <= dist { return true; } if opp_invis != 0 && (opp_invis - 1) < dist { // && ( !( cr.IsPlayer() ) || cr.IsPlayer() && !isGM( cr ) ) ) return false; } if opp_invis > dist || cr_vision >= dist { return true; } let cr_perception = param_getters::getParam_Perception(cr, 0) as u32; assert!(cr_perception >= 1 && cr_perception <= 10); fn basic_dist(rates: &CritterRates, perception: u32) -> u32 { rates.basic_bonus + perception * rates.basic_perception_rate } let self_is_npc = cr.is_npc(); if self_is_npc { if cr.is_dead() { return false; } let npc_fast = &config.npc_fast; if npc_fast.enable && cr.ProtoId >= npc_fast.fast_from && cr.ProtoId <= npc_fast.fast_to { return basic_dist(&config.senses[npc_fast.sense_index].npc, cr_perception) >= dist; } } let start_dir = cr_hex.get_direction(opp_hex); let mut look_dir = i8::abs(start_dir as i8 - cr.Dir as i8); //Направление if look_dir > 3 { look_dir = 6 - look_dir } assert!(look_dir >= 0 && look_dir <= 3); fn moving_rate
er, rates: &MovingRates) -> f32 { if cr.IsRuning { rates.running //} else if cr.is_walking() { // rates.walking } else { rates.still } } fn sense_mul(rates: &SenseRates, cr: &Critter, opponent: &Critter, look_dir: i8) -> f32 { rates.dir_rate[look_dir as usize] * moving_rate(cr, &rates.self_moving) * moving_rate(opponent, &rates.target_moving) } let senses: Vec<(f32, f32)> = config .senses .iter() .map(|sense| { let critter_rates = if self_is_npc { &sense.npc } else { &sense.player }; let basic_dist = basic_dist(critter_rates, cr_perception); let sense_mul = sense_mul(sense, cr, opponent, look_dir); let wall_mul = sense.wall_rate[cr_perception as usize - 1]; let clear_dist = basic_dist as f32 * sense_mul; //dbg!(clear_dist, wall_mul); (clear_dist, wall_mul) }) .collect(); let max_dist = senses .iter() .map(|(dist, _wall_mul)| *dist as u32) .max() .expect("At least one sense"); //dbg!(dist, max_dist); if dist > max_dist { return false; } let end_hex = get_hex_in_path(map, cr_hex, opp_hex, 0.0, dist); if dist > cr_hex.get_distance(end_hex) { for (basic_dist, wall_mull) in senses { //dbg!(basic_dist * wall_mull, dist); if (basic_dist * wall_mull) as u32 >= dist { return true; } } false } else { true } } fn _check_look_old(config: &CheckLook, map: &Map, cr: &Critter, opponent: &Critter) -> bool { if map.proto_id() == config.map_utility_start && opponent.is_player() && cr.is_player() && !cr.have_gm_vision() { return false; } let cr_hex = cr.hex(); let opp_hex = opponent.hex(); let dist = cr_hex.get_distance(opp_hex); use tnf_common::{defines::CritterParam, defines_fo4rp::param::Param}; let cr_vision = cr.uparam(Param::QST_VISION); let cr_perception = param_getters::getParam_Perception(cr, 0) as u32; //cr.uparam(Param::ST_PERCEPTION); let opp_invis = opponent.uparam(Param::QST_INVIS); if cr_vision >= dist && opp_invis <= dist { return true; } if opp_invis != 0 && (opp_invis - 1) < dist { // && ( !( cr.IsPlayer() ) || cr.IsPlayer() && !isGM( cr ) ) ) return false; } if opp_invis > dist || cr_vision >= dist { return true; } if cr.is_npc() { // упрощенный расчет для нпц, учитывает только дистанцию
(cr: &Critt
identifier_name
utils.rs
; } } #[no_mangle] pub extern "C" fn get_hex_coord( map: Option<&MaybeInvalid<Map>>, hex_x: u16, hex_y: u16, end_x: &mut u16, end_y: &mut u16, angle: f32, dist: u32, ) { if let Some(map) = map.and_then(MaybeInvalid::validate) { let end_hex = get_hex_in_path( map, Hex { x: hex_x, y: hex_y }, Hex { x: *end_x, y: *end_y, }, angle, dist, ); *end_x = end_hex.x; *end_y = end_hex.y; } } /* #[no_mangle] pub extern "C" fn test_hex_flags( map: Option<&MaybeInvalid<Map>>, hex_x: u16, hex_y: u16, raked: bool, passed: bool, ) { if let Some(map) = map.and_then(MaybeInvalid::validate) { let hex = Hex { x: hex_x, y: hex_y }; let flags = map.get_hex_flags_with_proto(hex); let mut wrong = false; if raked != map.is_hex_raked(hex) { wrong = true; print!("Raked - should be {}, but {}; ", raked, !raked); } if passed != map.is_hex_passed(hex) { wrong = true; print!("Passed - should be {}, but {}; ", passed, !passed); } if wrong { println!("Hex: {:?}, flags: {:016b}", hex, flags); } } } */ macro_rules! validate { ($this:expr, $default:expr) => { match $this.and_then(MaybeInvalid::validate) { Some(this) => this, None => return $default, } }; } /* #[no_mangle] pub extern "C" fn is_gM(Critter& player) { if( !player.IsPlayer() ) return false; if( !isLoadedGMs ) LoadGMs( player, 0, 0, 0 ); if( player.StatBase[ ST_ACCESS_LEVEL ] < ACCESS_MODER && ( player.GetAccess() >= ACCESS_MODER || isPocketGM( player.Id ) ) ) player.StatBase[ ST_ACCESS_LEVEL ] = ACCESS_MODER; return player.StatBase[ ST_ACCESS_LEVEL ] >= ACCESS_MODER && ( checkVision ? player.ParamBase[ QST_VISION ] > 0 : true ); }*/ #[no_mangle] pub extern "C" fn check_look( map: Option<&MaybeInvalid<Map>>, cr: Option<&MaybeInvalid<Critter>>, opponent: Option<&MaybeInvalid<Critter>>, ) -> bool { // Consider remove this let map = validate!(map, false); let cr = validate!(cr, false); let opponent = validate!(opponent, false); let config = &config().check_look; let smart = check_look_smart(config, map, cr, opponent); /*let old = check_look_old(config, map, cr, opponent); if old != smart { println!("old != smart: {:?} != {:?}", old, smart); }*/ /*let mut config_default = CheckLook::default(); config_default.npc_fast.enable = config.npc_fast.enable; let smart_default = check_look_smart(&config_default, map, cr, opponent); if smart != smart_default { println!("smart != smart_default: {:?} != {:?}", smart, smart_default); }*/ smart } fn check_look_smart(config: &CheckLook, map: &Map, cr: &Critter, opponent: &Critter) -> bool { if map.proto_id() == config.map_utility_start && opponent.is_player() && cr.is_player() && !cr.have_gm_vision() { return false; } let cr_hex = cr.hex(); let opp_hex = opponent.hex(); let dist = cr_hex.get_distance(opp_hex); use tnf_common::{defines::CritterParam, defines_fo4rp::param::Param}; let cr_vision = cr.uparam(Param::QST_VISION); let opp_invis = opponent.uparam(Param::QST_INVIS); if cr_vision >= dist && opp_invis <= dist { return true; } if opp_invis != 0 && (opp_invis - 1) < dist { // && ( !( cr.IsPlayer() ) || cr.IsPlayer() && !isGM( cr ) ) ) return false; } if opp_invis > dist || cr_vision >= dist { return true; } let cr_perception = param_getters::getParam_Perception(cr, 0) as u32; assert!(cr_perception >= 1 && cr_perception <= 10); fn basic_dist(rates: &CritterRates, perception: u32) -> u32 { rates.basic_bonus + perception * rates.basic_perception_rate } let self_is_npc = cr.is_npc(); if self_is_npc { if cr.is_dead() { return false; } let npc_fast = &config.npc_fast; if npc_fast.enable && cr.ProtoId >= npc_fast.fast_from && cr.ProtoId <= npc_fast.fast_to { return basic_dist(&config.senses[npc_fast.sense_index].npc, cr_perception) >= dist; } } let start_dir = cr_hex.get_direction(opp_hex); let mut look_dir = i8::abs(start_dir as i8 - cr.Dir as i8); //Направление if look_dir > 3 { look_dir = 6 - look_dir } assert!(look_dir >= 0 && look_dir <= 3); fn moving_rate(cr: &Critter, rates: &MovingRates) -> f32 { if cr.IsRuning { rates.running //} else if cr.is_walking() { // rates.walking } else { rates.still } } fn sense_mul(rates: &SenseRates, cr: &Critter, opponent: &Critter, look_dir: i8) -> f32 { r
enses: Vec<(f32, f32)> = config .senses .iter() .map(|sense| { let critter_rates = if self_is_npc { &sense.npc } else { &sense.player }; let basic_dist = basic_dist(critter_rates, cr_perception); let sense_mul = sense_mul(sense, cr, opponent, look_dir); let wall_mul = sense.wall_rate[cr_perception as usize - 1]; let clear_dist = basic_dist as f32 * sense_mul; //dbg!(clear_dist, wall_mul); (clear_dist, wall_mul) }) .collect(); let max_dist = senses .iter() .map(|(dist, _wall_mul)| *dist as u32) .max() .expect("At least one sense"); //dbg!(dist, max_dist); if dist > max_dist { return false; } let end_hex = get_hex_in_path(map, cr_hex, opp_hex, 0.0, dist); if dist > cr_hex.get_distance(end_hex) { for (basic_dist, wall_mull) in senses { //dbg!(basic_dist * wall_mull, dist); if (basic_dist * wall_mull) as u32 >= dist { return true; } } false } else { true } } fn _check_look_old(config: &CheckLook, map: &Map, cr: &Critter, opponent: &Critter) -> bool { if map.proto_id() == config.map_utility_start && opponent.is_player() && cr.is_player() && !cr.have_gm_vision() { return false; } let cr_hex = cr.hex(); let opp_hex = opponent.hex(); let dist = cr_hex.get_distance(opp_hex); use tnf_common::{defines::CritterParam, defines_fo4rp::param::Param}; let cr_vision = cr.uparam(Param::QST_VISION); let cr_perception = param_getters::getParam_Perception(cr, 0) as u32; //cr.uparam(Param::ST_PERCEPTION); let opp_invis = opponent.uparam(Param::QST_INVIS); if cr_vision >= dist && opp_invis <= dist { return true; } if opp_invis != 0 && (opp_invis - 1) < dist { // && ( !( cr.IsPlayer() ) || cr.IsPlayer() && !isGM( cr ) ) ) return false; } if opp_invis > dist || cr_vision >= dist { return true; } if cr.is_npc() { // упрощенный расчет для нпц, учитывает только дистанцию
ates.dir_rate[look_dir as usize] * moving_rate(cr, &rates.self_moving) * moving_rate(opponent, &rates.target_moving) } let s
identifier_body
utils.rs
pub extern "C" fn is_gM(Critter& player) { if( !player.IsPlayer() ) return false; if( !isLoadedGMs ) LoadGMs( player, 0, 0, 0 ); if( player.StatBase[ ST_ACCESS_LEVEL ] < ACCESS_MODER && ( player.GetAccess() >= ACCESS_MODER || isPocketGM( player.Id ) ) ) player.StatBase[ ST_ACCESS_LEVEL ] = ACCESS_MODER; return player.StatBase[ ST_ACCESS_LEVEL ] >= ACCESS_MODER && ( checkVision ? player.ParamBase[ QST_VISION ] > 0 : true ); }*/ #[no_mangle] pub extern "C" fn check_look( map: Option<&MaybeInvalid<Map>>, cr: Option<&MaybeInvalid<Critter>>, opponent: Option<&MaybeInvalid<Critter>>, ) -> bool { // Consider remove this let map = validate!(map, false); let cr = validate!(cr, false); let opponent = validate!(opponent, false); let config = &config().check_look; let smart = check_look_smart(config, map, cr, opponent); /*let old = check_look_old(config, map, cr, opponent); if old != smart { println!("old != smart: {:?} != {:?}", old, smart); }*/ /*let mut config_default = CheckLook::default(); config_default.npc_fast.enable = config.npc_fast.enable; let smart_default = check_look_smart(&config_default, map, cr, opponent); if smart != smart_default { println!("smart != smart_default: {:?} != {:?}", smart, smart_default); }*/ smart } fn check_look_smart(config: &CheckLook, map: &Map, cr: &Critter, opponent: &Critter) -> bool { if map.proto_id() == config.map_utility_start && opponent.is_player() && cr.is_player() && !cr.have_gm_vision() { return false; } let cr_hex = cr.hex(); let opp_hex = opponent.hex(); let dist = cr_hex.get_distance(opp_hex); use tnf_common::{defines::CritterParam, defines_fo4rp::param::Param}; let cr_vision = cr.uparam(Param::QST_VISION); let opp_invis = opponent.uparam(Param::QST_INVIS); if cr_vision >= dist && opp_invis <= dist { return true; } if opp_invis != 0 && (opp_invis - 1) < dist { // && ( !( cr.IsPlayer() ) || cr.IsPlayer() && !isGM( cr ) ) ) return false; } if opp_invis > dist || cr_vision >= dist { return true; } let cr_perception = param_getters::getParam_Perception(cr, 0) as u32; assert!(cr_perception >= 1 && cr_perception <= 10); fn basic_dist(rates: &CritterRates, perception: u32) -> u32 { rates.basic_bonus + perception * rates.basic_perception_rate } let self_is_npc = cr.is_npc(); if self_is_npc { if cr.is_dead() { return false; } let npc_fast = &config.npc_fast; if npc_fast.enable && cr.ProtoId >= npc_fast.fast_from && cr.ProtoId <= npc_fast.fast_to { return basic_dist(&config.senses[npc_fast.sense_index].npc, cr_perception) >= dist; } } let start_dir = cr_hex.get_direction(opp_hex); let mut look_dir = i8::abs(start_dir as i8 - cr.Dir as i8); //Направление if look_dir > 3 { look_dir = 6 - look_dir } assert!(look_dir >= 0 && look_dir <= 3); fn moving_rate(cr: &Critter, rates: &MovingRates) -> f32 { if cr.IsRuning { rates.running //} else if cr.is_walking() { // rates.walking } else { rates.still } } fn sense_mul(rates: &SenseRates, cr: &Critter, opponent: &Critter, look_dir: i8) -> f32 { rates.dir_rate[look_dir as usize] * moving_rate(cr, &rates.self_moving) * moving_rate(opponent, &rates.target_moving) } let senses: Vec<(f32, f32)> = config .senses .iter() .map(|sense| { let critter_rates = if self_is_npc { &sense.npc } else { &sense.player }; let basic_dist = basic_dist(critter_rates, cr_perception); let sense_mul = sense_mul(sense, cr, opponent, look_dir); let wall_mul = sense.wall_rate[cr_perception as usize - 1]; let clear_dist = basic_dist as f32 * sense_mul; //dbg!(clear_dist, wall_mul); (clear_dist, wall_mul) }) .collect(); let max_dist = senses .iter() .map(|(dist, _wall_mul)| *dist as u32) .max() .expect("At least one sense"); //dbg!(dist, max_dist); if dist > max_dist { return false; } let end_hex = get_hex_in_path(map, cr_hex, opp_hex, 0.0, dist); if dist > cr_hex.get_distance(end_hex) { for (basic_dist, wall_mull) in senses { //dbg!(basic_dist * wall_mull, dist); if (basic_dist * wall_mull) as u32 >= dist { return true; } } false } else { true } } fn _check_look_old(config: &CheckLook, map: &Map, cr: &Critter, opponent: &Critter) -> bool { if map.proto_id() == config.map_utility_start && opponent.is_player() && cr.is_player() && !cr.have_gm_vision() { return false; } let cr_hex = cr.hex(); let opp_hex = opponent.hex(); let dist = cr_hex.get_distance(opp_hex); use tnf_common::{defines::CritterParam, defines_fo4rp::param::Param}; let cr_vision = cr.uparam(Param::QST_VISION); let cr_perception = param_getters::getParam_Perception(cr, 0) as u32; //cr.uparam(Param::ST_PERCEPTION); let opp_invis = opponent.uparam(Param::QST_INVIS); if cr_vision >= dist && opp_invis <= dist { return true; } if opp_invis != 0 && (opp_invis - 1) < dist { // && ( !( cr.IsPlayer() ) || cr.IsPlayer() && !isGM( cr ) ) ) return false; } if opp_invis > dist || cr_vision >= dist { return true; } if cr.is_npc() { // упрощенный расчет для нпц, учитывает только дистанцию if cr.is_dead() { return false; } let cfg_npc = &config.npc_fast; if cfg_npc.enable && cr.ProtoId >= cfg_npc.fast_from && cr.ProtoId <= cfg_npc.fast_to { return (10 + cr_perception * 5) >= dist; } } let max_view = 10 + cr_perception * 5; let mut max_hear = 5 + cr_perception * 2; if cr.is_npc() { max_hear += 20; } let mut is_view = true; let mut is_hear = true; let start_dir = cr_hex.get_direction(opp_hex); let mut look_dir = i8::abs(start_dir as i8 - cr.Dir as i8); //Направление if look_dir > 3 { look_dir = 6 - look_dir } let (view_mul, mut hear_mul) = match look_dir { 0 => (1.0, 0.8), 1 => (0.8, 1.0), 2 => (0.5, 0.8), 3 => (0.4, 0.8), _ => unreachable!(), }; if opponent.IsRuning { hear_mul *= 3.0; } if cr.IsRuning { hear_mul *= 0.8; } let max_view = (max_view as f32 * view_mul) as u32; let tmp_max_hear = (max_hear as f32 * hear_mul) as u32; //dbg!(dist, max_view, tmp_max_hear); // new optimization: return early if distance larger than max_view and max_hear if dist > max_view && dist > tmp_max_hear { return false; } let end_hex = get_hex_in_path(map
, cr_hex, opp_hex, 0.0, dist)
conditional_block
token_flow.go
audience, err := url.Parse(caURL) if err != nil { return "", errs.InvalidFlagValue(ctx, "ca-url", caURL, "") } switch strings.ToLower(audience.Scheme) { case "https", "": var path string switch tokType { // default case SignType, SSHUserSignType, SSHHostSignType: path = "/1.0/sign" // revocation token case RevokeType: path = "/1.0/revoke" default: return "", errors.Errorf("unexpected token type: %d", tokType) } audience.Scheme = "https" audience = audience.ResolveReference(&url.URL{Path: path}) return audience.String(), nil default: return "", errs.InvalidFlagValue(ctx, "ca-url", caURL, "") } } // ErrACMEToken is the error type returned when the user attempts a Token Flow // while using an ACME provisioner. type ErrACMEToken struct { Name string } // Error implements the error interface. func (e *ErrACMEToken) Error() string { return "step ACME provisioners do not support token auth flows" } // NewTokenFlow implements the common flow used to generate a token func NewTokenFlow(ctx *cli.Context, typ int, subject string, sans []string, caURL, root string, notBefore, notAfter time.Time, certNotBefore, certNotAfter provisioner.TimeDuration) (string, error) { // Get audience from ca-url audience, err := parseAudience(ctx, typ) if err != nil { return "", err } provisioners, err := pki.GetProvisioners(caURL, root) if err != nil { return "", err } p, err := provisionerPrompt(ctx, provisioners) if err != nil { return "", err } switch p := p.(type) { case *provisioner.OIDC: // Run step oauth args := []string{"oauth", "--oidc", "--bare", "--provider", p.ConfigurationEndpoint, "--client-id", p.ClientID, "--client-secret", p.ClientSecret} if ctx.Bool("console") { args = append(args, "--console") } if p.ListenAddress != "" { args = append(args, "--listen", p.ListenAddress) } out, err := exec.Step(args...) if err != nil { return "", err } return strings.TrimSpace(string(out)), nil case *provisioner.GCP: // Do the identity request to get the token sharedContext.DisableCustomSANs = p.DisableCustomSANs return p.GetIdentityToken(subject, caURL) case *provisioner.AWS: // Do the identity request to get the token sharedContext.DisableCustomSANs = p.DisableCustomSANs return p.GetIdentityToken(subject, caURL) case *provisioner.Azure: // Do the identity request to get the token sharedContext.DisableCustomSANs = p.DisableCustomSANs return p.GetIdentityToken(subject, caURL) case *provisioner.ACME: // Return an error with the provisioner ID return "", &ErrACMEToken{p.GetName()} } // JWK provisioner prov, ok := p.(*provisioner.JWK) if !ok { return "", errors.Errorf("unknown provisioner type %T", p) } kid := prov.Key.KeyID issuer := prov.Name var opts []jose.Option if passwordFile := ctx.String("password-file"); len(passwordFile) != 0 { opts = append(opts, jose.WithPasswordFile(passwordFile)) } var jwk *jose.JSONWebKey if keyFile := ctx.String("key"); len(keyFile) == 0 { // Get private key from CA encrypted, err := pki.GetProvisionerKey(caURL, root, kid) if err != nil { return "", err } // Add template with check mark opts = append(opts, jose.WithUIOptions( ui.WithPromptTemplates(ui.PromptTemplates()), )) decrypted, err := jose.Decrypt("Please enter the password to decrypt the provisioner key", []byte(encrypted), opts...) if err != nil { return "", err } jwk = new(jose.JSONWebKey) if err := json.Unmarshal(decrypted, jwk); err != nil { return "", errors.Wrap(err, "error unmarshalling provisioning key") } } else { // Get private key from given key file jwk, err = jose.ParseKey(keyFile, opts...) if err != nil { return "", err } } // Generate token tokenGen := NewTokenGenerator(kid, issuer, audience, root, notBefore, notAfter, jwk) switch typ { case SignType: return tokenGen.SignToken(subject, sans) case RevokeType: return tokenGen.RevokeToken(subject) case SSHUserSignType: return tokenGen.SignSSHToken(subject, provisioner.SSHUserCert, sans, certNotBefore, certNotAfter) case SSHHostSignType: return tokenGen.SignSSHToken(subject, provisioner.SSHHostCert, sans, certNotBefore, certNotAfter) default: return tokenGen.Token(subject) } } // OfflineTokenFlow generates a provisioning token using either // 1. static configuration from ca.json (created with `step ca init`) // 2. input from command line flags // These two options are mutually exclusive and priority is given to ca.json. func OfflineTokenFlow(ctx *cli.Context, typ int, subject string, sans []string, notBefore, notAfter time.Time, certNotBefore, certNotAfter provisioner.TimeDuration) (string, error) { caConfig := ctx.String("ca-config") if caConfig == "" { return "", errs.InvalidFlagValue(ctx, "ca-config", "", "") } // Using the offline CA if utils.FileExists(caConfig) { offlineCA, err := NewOfflineCA(caConfig) if err != nil { return "", err } return offlineCA.GenerateToken(ctx, typ, subject, sans, notBefore, notAfter, certNotBefore, certNotAfter) } kid := ctx.String("kid") issuer := ctx.String("issuer") keyFile := ctx.String("key") passwordFile := ctx.String("password-file") // Require issuer and keyFile if ca.json does not exists. // kid can be passed or created using jwk.Thumbprint. switch { case len(issuer) == 0: return "", errs.RequiredWithFlag(ctx, "offline", "issuer") case len(keyFile) == 0: return "", errs.RequiredWithFlag(ctx, "offline", "key") } // Get audience from ca-url audience, err := parseAudience(ctx, typ) if err != nil { return "", err } // Get root from argument or default location root := ctx.String("root") if len(root) == 0 { root = pki.GetRootCAPath() if utils.FileExists(root) { return "", errs.RequiredFlag(ctx, "root") } } // Parse key var opts []jose.Option if len(passwordFile) != 0 { opts = append(opts, jose.WithPasswordFile(passwordFile)) } jwk, err := jose.ParseKey(keyFile, opts...) if err != nil { return "", err } // Get the kid if it's not passed as an argument if len(kid) == 0 { hash, err := jwk.Thumbprint(crypto.SHA256) if err != nil { return "", errors.Wrap(err, "error generating JWK thumbprint") } kid = base64.RawURLEncoding.EncodeToString(hash) } // Generate token tokenGen := NewTokenGenerator(kid, issuer, audience, root, notBefore, notAfter, jwk) switch typ { case SignType: return tokenGen.SignToken(subject, sans) case RevokeType: return tokenGen.RevokeToken(subject) case SSHUserSignType: return tokenGen.SignSSHToken(subject, provisioner.SSHUserCert, sans, certNotBefore, certNotAfter) case SSHHostSignType: return tokenGen.SignSSHToken(subject, provisioner.SSHHostCert, sans, certNotBefore, certNotAfter) default: return tokenGen.Token(subject) } } func provisionerPrompt(ctx *cli.Context, provisioners provisioner.List) (provisioner.Interface, error) { // Filter by type provisioners = provisionerFilter(provisioners, func(p provisioner.Interface) bool { switch p.GetType() { case provisioner.TypeJWK, provisioner.TypeOIDC, provisioner.TypeACME: return true case provisioner.TypeGCP, provisioner.TypeAWS, provisioner.TypeAzure: return true default: return false } }) if len(provisioners) == 0 { return nil, errors.New("cannot create a new token: the CA does not have any provisioner configured") } // Filter by kid if kid := ctx.String("kid"); len
}
random_line_split
token_flow.go
return "", &ErrACMEToken{p.GetName()} } // JWK provisioner prov, ok := p.(*provisioner.JWK) if !ok { return "", errors.Errorf("unknown provisioner type %T", p) } kid := prov.Key.KeyID issuer := prov.Name var opts []jose.Option if passwordFile := ctx.String("password-file"); len(passwordFile) != 0 { opts = append(opts, jose.WithPasswordFile(passwordFile)) } var jwk *jose.JSONWebKey if keyFile := ctx.String("key"); len(keyFile) == 0 { // Get private key from CA encrypted, err := pki.GetProvisionerKey(caURL, root, kid) if err != nil { return "", err } // Add template with check mark opts = append(opts, jose.WithUIOptions( ui.WithPromptTemplates(ui.PromptTemplates()), )) decrypted, err := jose.Decrypt("Please enter the password to decrypt the provisioner key", []byte(encrypted), opts...) if err != nil { return "", err } jwk = new(jose.JSONWebKey) if err := json.Unmarshal(decrypted, jwk); err != nil { return "", errors.Wrap(err, "error unmarshalling provisioning key") } } else { // Get private key from given key file jwk, err = jose.ParseKey(keyFile, opts...) if err != nil { return "", err } } // Generate token tokenGen := NewTokenGenerator(kid, issuer, audience, root, notBefore, notAfter, jwk) switch typ { case SignType: return tokenGen.SignToken(subject, sans) case RevokeType: return tokenGen.RevokeToken(subject) case SSHUserSignType: return tokenGen.SignSSHToken(subject, provisioner.SSHUserCert, sans, certNotBefore, certNotAfter) case SSHHostSignType: return tokenGen.SignSSHToken(subject, provisioner.SSHHostCert, sans, certNotBefore, certNotAfter) default: return tokenGen.Token(subject) } } // OfflineTokenFlow generates a provisioning token using either // 1. static configuration from ca.json (created with `step ca init`) // 2. input from command line flags // These two options are mutually exclusive and priority is given to ca.json. func OfflineTokenFlow(ctx *cli.Context, typ int, subject string, sans []string, notBefore, notAfter time.Time, certNotBefore, certNotAfter provisioner.TimeDuration) (string, error) { caConfig := ctx.String("ca-config") if caConfig == "" { return "", errs.InvalidFlagValue(ctx, "ca-config", "", "") } // Using the offline CA if utils.FileExists(caConfig) { offlineCA, err := NewOfflineCA(caConfig) if err != nil { return "", err } return offlineCA.GenerateToken(ctx, typ, subject, sans, notBefore, notAfter, certNotBefore, certNotAfter) } kid := ctx.String("kid") issuer := ctx.String("issuer") keyFile := ctx.String("key") passwordFile := ctx.String("password-file") // Require issuer and keyFile if ca.json does not exists. // kid can be passed or created using jwk.Thumbprint. switch { case len(issuer) == 0: return "", errs.RequiredWithFlag(ctx, "offline", "issuer") case len(keyFile) == 0: return "", errs.RequiredWithFlag(ctx, "offline", "key") } // Get audience from ca-url audience, err := parseAudience(ctx, typ) if err != nil { return "", err } // Get root from argument or default location root := ctx.String("root") if len(root) == 0 { root = pki.GetRootCAPath() if utils.FileExists(root) { return "", errs.RequiredFlag(ctx, "root") } } // Parse key var opts []jose.Option if len(passwordFile) != 0 { opts = append(opts, jose.WithPasswordFile(passwordFile)) } jwk, err := jose.ParseKey(keyFile, opts...) if err != nil { return "", err } // Get the kid if it's not passed as an argument if len(kid) == 0 { hash, err := jwk.Thumbprint(crypto.SHA256) if err != nil { return "", errors.Wrap(err, "error generating JWK thumbprint") } kid = base64.RawURLEncoding.EncodeToString(hash) } // Generate token tokenGen := NewTokenGenerator(kid, issuer, audience, root, notBefore, notAfter, jwk) switch typ { case SignType: return tokenGen.SignToken(subject, sans) case RevokeType: return tokenGen.RevokeToken(subject) case SSHUserSignType: return tokenGen.SignSSHToken(subject, provisioner.SSHUserCert, sans, certNotBefore, certNotAfter) case SSHHostSignType: return tokenGen.SignSSHToken(subject, provisioner.SSHHostCert, sans, certNotBefore, certNotAfter) default: return tokenGen.Token(subject) } } func provisionerPrompt(ctx *cli.Context, provisioners provisioner.List) (provisioner.Interface, error) { // Filter by type provisioners = provisionerFilter(provisioners, func(p provisioner.Interface) bool { switch p.GetType() { case provisioner.TypeJWK, provisioner.TypeOIDC, provisioner.TypeACME: return true case provisioner.TypeGCP, provisioner.TypeAWS, provisioner.TypeAzure: return true default: return false } }) if len(provisioners) == 0 { return nil, errors.New("cannot create a new token: the CA does not have any provisioner configured") } // Filter by kid if kid := ctx.String("kid"); len(kid) != 0 { provisioners = provisionerFilter(provisioners, func(p provisioner.Interface) bool { switch p := p.(type) { case *provisioner.JWK: return p.Key.KeyID == kid case *provisioner.OIDC: return p.ClientID == kid default: return false } }) if len(provisioners) == 0 { return nil, errs.InvalidFlagValue(ctx, "kid", kid, "") } } // Filter by issuer (provisioner name) if issuer := ctx.String("issuer"); len(issuer) != 0 { provisioners = provisionerFilter(provisioners, func(p provisioner.Interface) bool { return p.GetName() == issuer }) if len(provisioners) == 0 { return nil, errs.InvalidFlagValue(ctx, "issuer", issuer, "") } } // Select provisioner var items []*provisionersSelect for _, prov := range provisioners { switch p := prov.(type) { case *provisioner.JWK: items = append(items, &provisionersSelect{ Name: fmt.Sprintf("%s (%s) [kid: %s]", p.Name, p.GetType(), p.Key.KeyID), Provisioner: p, }) case *provisioner.OIDC: items = append(items, &provisionersSelect{ Name: fmt.Sprintf("%s (%s) [client: %s]", p.Name, p.GetType(), p.ClientID), Provisioner: p, }) case *provisioner.GCP: items = append(items, &provisionersSelect{ Name: fmt.Sprintf("%s (%s)", p.Name, p.GetType()), Provisioner: p, }) case *provisioner.AWS: items = append(items, &provisionersSelect{ Name: fmt.Sprintf("%s (%s)", p.Name, p.GetType()), Provisioner: p, }) case *provisioner.Azure: items = append(items, &provisionersSelect{ Name: fmt.Sprintf("%s (%s) [tenant: %s]", p.Name, p.GetType(), p.TenantID), Provisioner: p, }) case *provisioner.ACME: items = append(items, &provisionersSelect{ Name: fmt.Sprintf("%s (%s)", p.Name, p.GetType()), Provisioner: p, }) default: continue } } if len(items) == 1 { if err := ui.PrintSelected("Provisioner", items[0].Name); err != nil { return nil, err } return items[0].Provisioner, nil } i, _, err := ui.Select("What provisioner key do you want to use?", items, ui.WithSelectTemplates(ui.NamedSelectTemplates("Provisioner"))) if err != nil { return nil, err } return items[i].Provisioner, nil } // provisionerFilter returns a slice of provisioners that pass the given filter. func
provisionerFilter
identifier_name
token_flow.go
, SSHUserSignType, SSHHostSignType: path = "/1.0/sign" // revocation token case RevokeType: path = "/1.0/revoke" default: return "", errors.Errorf("unexpected token type: %d", tokType) } audience.Scheme = "https" audience = audience.ResolveReference(&url.URL{Path: path}) return audience.String(), nil default: return "", errs.InvalidFlagValue(ctx, "ca-url", caURL, "") } } // ErrACMEToken is the error type returned when the user attempts a Token Flow // while using an ACME provisioner. type ErrACMEToken struct { Name string } // Error implements the error interface. func (e *ErrACMEToken) Error() string { return "step ACME provisioners do not support token auth flows" } // NewTokenFlow implements the common flow used to generate a token func NewTokenFlow(ctx *cli.Context, typ int, subject string, sans []string, caURL, root string, notBefore, notAfter time.Time, certNotBefore, certNotAfter provisioner.TimeDuration) (string, error) { // Get audience from ca-url audience, err := parseAudience(ctx, typ) if err != nil { return "", err } provisioners, err := pki.GetProvisioners(caURL, root) if err != nil { return "", err } p, err := provisionerPrompt(ctx, provisioners) if err != nil { return "", err } switch p := p.(type) { case *provisioner.OIDC: // Run step oauth args := []string{"oauth", "--oidc", "--bare", "--provider", p.ConfigurationEndpoint, "--client-id", p.ClientID, "--client-secret", p.ClientSecret} if ctx.Bool("console") { args = append(args, "--console") } if p.ListenAddress != ""
out, err := exec.Step(args...) if err != nil { return "", err } return strings.TrimSpace(string(out)), nil case *provisioner.GCP: // Do the identity request to get the token sharedContext.DisableCustomSANs = p.DisableCustomSANs return p.GetIdentityToken(subject, caURL) case *provisioner.AWS: // Do the identity request to get the token sharedContext.DisableCustomSANs = p.DisableCustomSANs return p.GetIdentityToken(subject, caURL) case *provisioner.Azure: // Do the identity request to get the token sharedContext.DisableCustomSANs = p.DisableCustomSANs return p.GetIdentityToken(subject, caURL) case *provisioner.ACME: // Return an error with the provisioner ID return "", &ErrACMEToken{p.GetName()} } // JWK provisioner prov, ok := p.(*provisioner.JWK) if !ok { return "", errors.Errorf("unknown provisioner type %T", p) } kid := prov.Key.KeyID issuer := prov.Name var opts []jose.Option if passwordFile := ctx.String("password-file"); len(passwordFile) != 0 { opts = append(opts, jose.WithPasswordFile(passwordFile)) } var jwk *jose.JSONWebKey if keyFile := ctx.String("key"); len(keyFile) == 0 { // Get private key from CA encrypted, err := pki.GetProvisionerKey(caURL, root, kid) if err != nil { return "", err } // Add template with check mark opts = append(opts, jose.WithUIOptions( ui.WithPromptTemplates(ui.PromptTemplates()), )) decrypted, err := jose.Decrypt("Please enter the password to decrypt the provisioner key", []byte(encrypted), opts...) if err != nil { return "", err } jwk = new(jose.JSONWebKey) if err := json.Unmarshal(decrypted, jwk); err != nil { return "", errors.Wrap(err, "error unmarshalling provisioning key") } } else { // Get private key from given key file jwk, err = jose.ParseKey(keyFile, opts...) if err != nil { return "", err } } // Generate token tokenGen := NewTokenGenerator(kid, issuer, audience, root, notBefore, notAfter, jwk) switch typ { case SignType: return tokenGen.SignToken(subject, sans) case RevokeType: return tokenGen.RevokeToken(subject) case SSHUserSignType: return tokenGen.SignSSHToken(subject, provisioner.SSHUserCert, sans, certNotBefore, certNotAfter) case SSHHostSignType: return tokenGen.SignSSHToken(subject, provisioner.SSHHostCert, sans, certNotBefore, certNotAfter) default: return tokenGen.Token(subject) } } // OfflineTokenFlow generates a provisioning token using either // 1. static configuration from ca.json (created with `step ca init`) // 2. input from command line flags // These two options are mutually exclusive and priority is given to ca.json. func OfflineTokenFlow(ctx *cli.Context, typ int, subject string, sans []string, notBefore, notAfter time.Time, certNotBefore, certNotAfter provisioner.TimeDuration) (string, error) { caConfig := ctx.String("ca-config") if caConfig == "" { return "", errs.InvalidFlagValue(ctx, "ca-config", "", "") } // Using the offline CA if utils.FileExists(caConfig) { offlineCA, err := NewOfflineCA(caConfig) if err != nil { return "", err } return offlineCA.GenerateToken(ctx, typ, subject, sans, notBefore, notAfter, certNotBefore, certNotAfter) } kid := ctx.String("kid") issuer := ctx.String("issuer") keyFile := ctx.String("key") passwordFile := ctx.String("password-file") // Require issuer and keyFile if ca.json does not exists. // kid can be passed or created using jwk.Thumbprint. switch { case len(issuer) == 0: return "", errs.RequiredWithFlag(ctx, "offline", "issuer") case len(keyFile) == 0: return "", errs.RequiredWithFlag(ctx, "offline", "key") } // Get audience from ca-url audience, err := parseAudience(ctx, typ) if err != nil { return "", err } // Get root from argument or default location root := ctx.String("root") if len(root) == 0 { root = pki.GetRootCAPath() if utils.FileExists(root) { return "", errs.RequiredFlag(ctx, "root") } } // Parse key var opts []jose.Option if len(passwordFile) != 0 { opts = append(opts, jose.WithPasswordFile(passwordFile)) } jwk, err := jose.ParseKey(keyFile, opts...) if err != nil { return "", err } // Get the kid if it's not passed as an argument if len(kid) == 0 { hash, err := jwk.Thumbprint(crypto.SHA256) if err != nil { return "", errors.Wrap(err, "error generating JWK thumbprint") } kid = base64.RawURLEncoding.EncodeToString(hash) } // Generate token tokenGen := NewTokenGenerator(kid, issuer, audience, root, notBefore, notAfter, jwk) switch typ { case SignType: return tokenGen.SignToken(subject, sans) case RevokeType: return tokenGen.RevokeToken(subject) case SSHUserSignType: return tokenGen.SignSSHToken(subject, provisioner.SSHUserCert, sans, certNotBefore, certNotAfter) case SSHHostSignType: return tokenGen.SignSSHToken(subject, provisioner.SSHHostCert, sans, certNotBefore, certNotAfter) default: return tokenGen.Token(subject) } } func provisionerPrompt(ctx *cli.Context, provisioners provisioner.List) (provisioner.Interface, error) { // Filter by type provisioners = provisionerFilter(provisioners, func(p provisioner.Interface) bool { switch p.GetType() { case provisioner.TypeJWK, provisioner.TypeOIDC, provisioner.TypeACME: return true case provisioner.TypeGCP, provisioner.TypeAWS, provisioner.TypeAzure: return true default: return false } }) if len(provisioners) == 0 { return nil, errors.New("cannot create a new token: the CA does not have any provisioner configured") } // Filter by kid if kid := ctx.String("kid"); len(kid) != 0 { provisioners = provisionerFilter(provisioners, func(p provisioner.Interface) bool { switch p := p.(type) { case *provisioner.JWK: return p.Key.KeyID == kid case *provisioner.OIDC: return p
{ args = append(args, "--listen", p.ListenAddress) }
conditional_block
token_flow.go
, SSHUserSignType, SSHHostSignType: path = "/1.0/sign" // revocation token case RevokeType: path = "/1.0/revoke" default: return "", errors.Errorf("unexpected token type: %d", tokType) } audience.Scheme = "https" audience = audience.ResolveReference(&url.URL{Path: path}) return audience.String(), nil default: return "", errs.InvalidFlagValue(ctx, "ca-url", caURL, "") } } // ErrACMEToken is the error type returned when the user attempts a Token Flow // while using an ACME provisioner. type ErrACMEToken struct { Name string } // Error implements the error interface. func (e *ErrACMEToken) Error() string { return "step ACME provisioners do not support token auth flows" } // NewTokenFlow implements the common flow used to generate a token func NewTokenFlow(ctx *cli.Context, typ int, subject string, sans []string, caURL, root string, notBefore, notAfter time.Time, certNotBefore, certNotAfter provisioner.TimeDuration) (string, error) { // Get audience from ca-url audience, err := parseAudience(ctx, typ) if err != nil { return "", err } provisioners, err := pki.GetProvisioners(caURL, root) if err != nil { return "", err } p, err := provisionerPrompt(ctx, provisioners) if err != nil { return "", err } switch p := p.(type) { case *provisioner.OIDC: // Run step oauth args := []string{"oauth", "--oidc", "--bare", "--provider", p.ConfigurationEndpoint, "--client-id", p.ClientID, "--client-secret", p.ClientSecret} if ctx.Bool("console") { args = append(args, "--console") } if p.ListenAddress != "" { args = append(args, "--listen", p.ListenAddress) } out, err := exec.Step(args...) if err != nil { return "", err } return strings.TrimSpace(string(out)), nil case *provisioner.GCP: // Do the identity request to get the token sharedContext.DisableCustomSANs = p.DisableCustomSANs return p.GetIdentityToken(subject, caURL) case *provisioner.AWS: // Do the identity request to get the token sharedContext.DisableCustomSANs = p.DisableCustomSANs return p.GetIdentityToken(subject, caURL) case *provisioner.Azure: // Do the identity request to get the token sharedContext.DisableCustomSANs = p.DisableCustomSANs return p.GetIdentityToken(subject, caURL) case *provisioner.ACME: // Return an error with the provisioner ID return "", &ErrACMEToken{p.GetName()} } // JWK provisioner prov, ok := p.(*provisioner.JWK) if !ok { return "", errors.Errorf("unknown provisioner type %T", p) } kid := prov.Key.KeyID issuer := prov.Name var opts []jose.Option if passwordFile := ctx.String("password-file"); len(passwordFile) != 0 { opts = append(opts, jose.WithPasswordFile(passwordFile)) } var jwk *jose.JSONWebKey if keyFile := ctx.String("key"); len(keyFile) == 0 { // Get private key from CA encrypted, err := pki.GetProvisionerKey(caURL, root, kid) if err != nil { return "", err } // Add template with check mark opts = append(opts, jose.WithUIOptions( ui.WithPromptTemplates(ui.PromptTemplates()), )) decrypted, err := jose.Decrypt("Please enter the password to decrypt the provisioner key", []byte(encrypted), opts...) if err != nil { return "", err } jwk = new(jose.JSONWebKey) if err := json.Unmarshal(decrypted, jwk); err != nil { return "", errors.Wrap(err, "error unmarshalling provisioning key") } } else { // Get private key from given key file jwk, err = jose.ParseKey(keyFile, opts...) if err != nil { return "", err } } // Generate token tokenGen := NewTokenGenerator(kid, issuer, audience, root, notBefore, notAfter, jwk) switch typ { case SignType: return tokenGen.SignToken(subject, sans) case RevokeType: return tokenGen.RevokeToken(subject) case SSHUserSignType: return tokenGen.SignSSHToken(subject, provisioner.SSHUserCert, sans, certNotBefore, certNotAfter) case SSHHostSignType: return tokenGen.SignSSHToken(subject, provisioner.SSHHostCert, sans, certNotBefore, certNotAfter) default: return tokenGen.Token(subject) } } // OfflineTokenFlow generates a provisioning token using either // 1. static configuration from ca.json (created with `step ca init`) // 2. input from command line flags // These two options are mutually exclusive and priority is given to ca.json. func OfflineTokenFlow(ctx *cli.Context, typ int, subject string, sans []string, notBefore, notAfter time.Time, certNotBefore, certNotAfter provisioner.TimeDuration) (string, error) { caConfig := ctx.String("ca-config") if caConfig == "" { return "", errs.InvalidFlagValue(ctx, "ca-config", "", "") } // Using the offline CA if utils.FileExists(caConfig) { offlineCA, err := NewOfflineCA(caConfig) if err != nil { return "", err } return offlineCA.GenerateToken(ctx, typ, subject, sans, notBefore, notAfter, certNotBefore, certNotAfter) } kid := ctx.String("kid") issuer := ctx.String("issuer") keyFile := ctx.String("key") passwordFile := ctx.String("password-file") // Require issuer and keyFile if ca.json does not exists. // kid can be passed or created using jwk.Thumbprint. switch { case len(issuer) == 0: return "", errs.RequiredWithFlag(ctx, "offline", "issuer") case len(keyFile) == 0: return "", errs.RequiredWithFlag(ctx, "offline", "key") } // Get audience from ca-url audience, err := parseAudience(ctx, typ) if err != nil { return "", err } // Get root from argument or default location root := ctx.String("root") if len(root) == 0 { root = pki.GetRootCAPath() if utils.FileExists(root) { return "", errs.RequiredFlag(ctx, "root") } } // Parse key var opts []jose.Option if len(passwordFile) != 0 { opts = append(opts, jose.WithPasswordFile(passwordFile)) } jwk, err := jose.ParseKey(keyFile, opts...) if err != nil { return "", err } // Get the kid if it's not passed as an argument if len(kid) == 0 { hash, err := jwk.Thumbprint(crypto.SHA256) if err != nil { return "", errors.Wrap(err, "error generating JWK thumbprint") } kid = base64.RawURLEncoding.EncodeToString(hash) } // Generate token tokenGen := NewTokenGenerator(kid, issuer, audience, root, notBefore, notAfter, jwk) switch typ { case SignType: return tokenGen.SignToken(subject, sans) case RevokeType: return tokenGen.RevokeToken(subject) case SSHUserSignType: return tokenGen.SignSSHToken(subject, provisioner.SSHUserCert, sans, certNotBefore, certNotAfter) case SSHHostSignType: return tokenGen.SignSSHToken(subject, provisioner.SSHHostCert, sans, certNotBefore, certNotAfter) default: return tokenGen.Token(subject) } } func provisionerPrompt(ctx *cli.Context, provisioners provisioner.List) (provisioner.Interface, error)
switch p := p.(type) { case *provisioner.JWK: return p.Key.KeyID == kid case *provisioner.OIDC: return p.Client
{ // Filter by type provisioners = provisionerFilter(provisioners, func(p provisioner.Interface) bool { switch p.GetType() { case provisioner.TypeJWK, provisioner.TypeOIDC, provisioner.TypeACME: return true case provisioner.TypeGCP, provisioner.TypeAWS, provisioner.TypeAzure: return true default: return false } }) if len(provisioners) == 0 { return nil, errors.New("cannot create a new token: the CA does not have any provisioner configured") } // Filter by kid if kid := ctx.String("kid"); len(kid) != 0 { provisioners = provisionerFilter(provisioners, func(p provisioner.Interface) bool {
identifier_body
recorder.go
", 99.999}, {"-p99.99", 99.99}, {"-p99.9", 99.9}, {"-p99", 99}, {"-p90", 90}, {"-p75", 75}, {"-p50", 50}, } // storeMetrics is the minimum interface of the storage.Store object needed by // MetricsRecorder to provide status summaries. This is used instead of Store // directly in order to simplify testing. type storeMetrics interface { StoreID() roachpb.StoreID Descriptor() (*roachpb.StoreDescriptor, error) MVCCStats() engine.MVCCStats Registry() *metric.Registry } // MetricsRecorder is used to periodically record the information in a number of // metric registries. // // Two types of registries are maintained: "node-level" registries, provided by // node-level systems, and "store-level" registries which are provided by each // store hosted by the node. There are slight differences in the way these are // recorded, and they are thus kept separate. type MetricsRecorder struct { // nodeRegistry contains, as subregistries, the multiple component-specific // registries which are recorded as "node level" metrics. nodeRegistry *metric.Registry // Fields below are locked by this mutex. mu struct { sync.Mutex // storeRegistries contains a registry for each store on the node. These // are not stored as subregistries, but rather are treated as wholly // independent. storeRegistries map[roachpb.StoreID]*metric.Registry nodeID roachpb.NodeID clock *hlc.Clock // Counts to help optimize slice allocation. lastDataCount int lastSummaryCount int // TODO(mrtracy): These are stored to support the current structure of // status summaries. These should be removed as part of #4465. startedAt int64 desc roachpb.NodeDescriptor stores map[roachpb.StoreID]storeMetrics } } // NewMetricsRecorder initializes a new MetricsRecorder object that uses the // given clock. func NewMetricsRecorder(clock *hlc.Clock) *MetricsRecorder { mr := &MetricsRecorder{ nodeRegistry: metric.NewRegistry(), } mr.mu.storeRegistries = make(map[roachpb.StoreID]*metric.Registry) mr.mu.stores = make(map[roachpb.StoreID]storeMetrics) mr.mu.clock = clock return mr } // AddNodeRegistry adds a node-level registry to this recorder. Each node-level // registry has a 'prefix format' which is used to add a prefix to the name of // all metrics in that registry while recording (see the metric.Registry object // for more information on prefix format strings). func (mr *MetricsRecorder) AddNodeRegistry(prefixFmt string, registry *metric.Registry) { mr.nodeRegistry.MustAdd(prefixFmt, registry) } // AddStore adds the Registry from the provided store as a store-level registry // in this recoder. A reference to the store is kept for the purpose of // gathering some additional information which is present in store status // summaries. // Stores should only be added to the registry after they have been started. // TODO(mrtracy): Store references should not be necessary after #4465. func (mr *MetricsRecorder) AddStore(store storeMetrics) { mr.mu.Lock() defer mr.mu.Unlock() storeID := store.StoreID() mr.mu.storeRegistries[storeID] = store.Registry() mr.mu.stores[storeID] = store } // NodeStarted should be called on the recorder once the associated node has // received its Node ID; this indicates that it is appropriate to begin // recording statistics for this node. func (mr *MetricsRecorder) NodeStarted(desc roachpb.NodeDescriptor, startedAt int64) { mr.mu.Lock() defer mr.mu.Unlock() mr.mu.desc = desc mr.mu.nodeID = desc.NodeID mr.mu.startedAt = startedAt } // MarshalJSON returns an appropriate JSON representation of the current values // of the metrics being tracked by this recorder. func (mr *MetricsRecorder) MarshalJSON() ([]byte, error) { mr.mu.Lock() defer mr.mu.Unlock() if mr.mu.nodeID == 0 { // We haven't yet processed initialization information; return an empty // JSON object. if log.V(1) { log.Warning("MetricsRecorder.MarshalJSON() called before NodeID allocation") } return []byte("{}"), nil } topLevel := map[string]interface{}{ fmt.Sprintf("node.%d", mr.mu.nodeID): mr.nodeRegistry, } // Add collection of stores to top level. JSON requires that keys be strings, // so we must convert the store ID to a string. storeLevel := make(map[string]interface{}) for id, reg := range mr.mu.storeRegistries { storeLevel[strconv.Itoa(int(id))] = reg } topLevel["stores"] = storeLevel return json.Marshal(topLevel) } // GetTimeSeriesData serializes registered metrics for consumption by // CockroachDB's time series system. func (mr *MetricsRecorder) GetTimeSeriesData() []ts.TimeSeriesData { mr.mu.Lock() defer mr.mu.Unlock() if mr.mu.desc.NodeID == 0 { // We haven't yet processed initialization information; do nothing. if log.V(1) { log.Warning("MetricsRecorder.GetTimeSeriesData() called before NodeID allocation") } return nil } data := make([]ts.TimeSeriesData, 0, mr.mu.lastDataCount) // Record time series from node-level registries. now := mr.mu.clock.PhysicalNow() recorder := registryRecorder{ registry: mr.nodeRegistry, format: nodeTimeSeriesPrefix, source: strconv.FormatInt(int64(mr.mu.nodeID), 10), timestampNanos: now, } recorder.record(&data) // Record time series from store-level registries. for storeID, r := range mr.mu.storeRegistries { storeRecorder := registryRecorder{ registry: r, format: storeTimeSeriesPrefix, source: strconv.FormatInt(int64(storeID), 10), timestampNanos: now, } storeRecorder.record(&data) } mr.mu.lastDataCount = len(data) return data } // GetStatusSummaries returns a status summary messages for the node, along with // a status summary for every individual store within the node. // TODO(mrtracy): The status summaries deserve a near-term, significant // overhaul. Their primary usage is as an indicator of the most recent metrics // of a node or store - they are essentially a "vertical" query of several // time series for a single node or store, returning only the most recent value // of each series. The structure should be modified to reflect that: there is no // reason for them to have a strict schema of fields. (Github Issue #4465) func (mr *MetricsRecorder) GetStatusSummaries() (*NodeStatus, []storage.StoreStatus) { mr.mu.Lock() defer mr.mu.Unlock() if mr.mu.nodeID == 0 { // We haven't yet processed initialization information; do nothing. if log.V(1) { log.Warning("MetricsRecorder.GetStatusSummaries called before NodeID allocation.") } return nil, nil } now := mr.mu.clock.PhysicalNow() // Generate an node status with no store data. nodeStat := &NodeStatus{ Desc: mr.mu.desc, UpdatedAt: now, StartedAt: mr.mu.startedAt, StoreIDs: make([]roachpb.StoreID, 0, mr.mu.lastSummaryCount), } storeStats := make([]storage.StoreStatus, 0, mr.mu.lastSummaryCount) // Generate status summaries for stores, while accumulating data into the // NodeStatus. for storeID, r := range mr.mu.storeRegistries { nodeStat.StoreIDs = append(nodeStat.StoreIDs, storeID) // Gather MVCCStats from the store directly. stats := mr.mu.stores[storeID].MVCCStats() // Gather updates from a few specific gauges. // TODO(mrtracy): This is the worst hack present in supporting the // current status summary format. It will be removed as part of #4465. rangeCounter := r.GetCounter("ranges") if rangeCounter == nil { log.Errorf("Could not record status summaries: Store %d did not have 'ranges' counter in registry.", storeID) return nil, nil } gaugeNames := []string{"ranges.leader", "ranges.replicated", "ranges.available"} gauges := make(map[string]*metric.Gauge) for _, name := range gaugeNames
{ gauge := r.GetGauge(name) if gauge == nil { log.Errorf("Could not record status summaries: Store %d did not have '%s' gauge in registry.", storeID, name) return nil, nil } gauges[name] = gauge }
conditional_block
recorder.go
Prefix = "cr.node.%s" // runtimeStatTimeSeriesFmt is the current format for time series keys which // record runtime system stats on a node. runtimeStatTimeSeriesNameFmt = "cr.node.sys.%s" ) type quantile struct { suffix string quantile float64 } var recordHistogramQuantiles = []quantile{ {"-max", 100}, {"-p99.999", 99.999}, {"-p99.99", 99.99}, {"-p99.9", 99.9}, {"-p99", 99}, {"-p90", 90}, {"-p75", 75}, {"-p50", 50}, } // storeMetrics is the minimum interface of the storage.Store object needed by // MetricsRecorder to provide status summaries. This is used instead of Store // directly in order to simplify testing. type storeMetrics interface { StoreID() roachpb.StoreID Descriptor() (*roachpb.StoreDescriptor, error) MVCCStats() engine.MVCCStats Registry() *metric.Registry } // MetricsRecorder is used to periodically record the information in a number of // metric registries. // // Two types of registries are maintained: "node-level" registries, provided by // node-level systems, and "store-level" registries which are provided by each // store hosted by the node. There are slight differences in the way these are // recorded, and they are thus kept separate. type MetricsRecorder struct { // nodeRegistry contains, as subregistries, the multiple component-specific // registries which are recorded as "node level" metrics. nodeRegistry *metric.Registry // Fields below are locked by this mutex. mu struct { sync.Mutex // storeRegistries contains a registry for each store on the node. These // are not stored as subregistries, but rather are treated as wholly // independent. storeRegistries map[roachpb.StoreID]*metric.Registry nodeID roachpb.NodeID clock *hlc.Clock // Counts to help optimize slice allocation. lastDataCount int lastSummaryCount int // TODO(mrtracy): These are stored to support the current structure of // status summaries. These should be removed as part of #4465. startedAt int64 desc roachpb.NodeDescriptor stores map[roachpb.StoreID]storeMetrics } } // NewMetricsRecorder initializes a new MetricsRecorder object that uses the // given clock. func NewMetricsRecorder(clock *hlc.Clock) *MetricsRecorder { mr := &MetricsRecorder{ nodeRegistry: metric.NewRegistry(), } mr.mu.storeRegistries = make(map[roachpb.StoreID]*metric.Registry) mr.mu.stores = make(map[roachpb.StoreID]storeMetrics) mr.mu.clock = clock return mr } // AddNodeRegistry adds a node-level registry to this recorder. Each node-level // registry has a 'prefix format' which is used to add a prefix to the name of // all metrics in that registry while recording (see the metric.Registry object // for more information on prefix format strings). func (mr *MetricsRecorder) AddNodeRegistry(prefixFmt string, registry *metric.Registry) { mr.nodeRegistry.MustAdd(prefixFmt, registry) } // AddStore adds the Registry from the provided store as a store-level registry // in this recoder. A reference to the store is kept for the purpose of // gathering some additional information which is present in store status // summaries. // Stores should only be added to the registry after they have been started. // TODO(mrtracy): Store references should not be necessary after #4465. func (mr *MetricsRecorder) AddStore(store storeMetrics) { mr.mu.Lock() defer mr.mu.Unlock() storeID := store.StoreID() mr.mu.storeRegistries[storeID] = store.Registry() mr.mu.stores[storeID] = store } // NodeStarted should be called on the recorder once the associated node has // received its Node ID; this indicates that it is appropriate to begin // recording statistics for this node. func (mr *MetricsRecorder) NodeStarted(desc roachpb.NodeDescriptor, startedAt int64) { mr.mu.Lock() defer mr.mu.Unlock() mr.mu.desc = desc mr.mu.nodeID = desc.NodeID mr.mu.startedAt = startedAt } // MarshalJSON returns an appropriate JSON representation of the current values // of the metrics being tracked by this recorder. func (mr *MetricsRecorder) MarshalJSON() ([]byte, error) { mr.mu.Lock() defer mr.mu.Unlock() if mr.mu.nodeID == 0 { // We haven't yet processed initialization information; return an empty // JSON object. if log.V(1) { log.Warning("MetricsRecorder.MarshalJSON() called before NodeID allocation") } return []byte("{}"), nil } topLevel := map[string]interface{}{ fmt.Sprintf("node.%d", mr.mu.nodeID): mr.nodeRegistry, } // Add collection of stores to top level. JSON requires that keys be strings, // so we must convert the store ID to a string. storeLevel := make(map[string]interface{}) for id, reg := range mr.mu.storeRegistries { storeLevel[strconv.Itoa(int(id))] = reg } topLevel["stores"] = storeLevel return json.Marshal(topLevel) } // GetTimeSeriesData serializes registered metrics for consumption by // CockroachDB's time series system. func (mr *MetricsRecorder) GetTimeSeriesData() []ts.TimeSeriesData
timestampNanos: now, } recorder.record(&data) // Record time series from store-level registries. for storeID, r := range mr.mu.storeRegistries { storeRecorder := registryRecorder{ registry: r, format: storeTimeSeriesPrefix, source: strconv.FormatInt(int64(storeID), 10), timestampNanos: now, } storeRecorder.record(&data) } mr.mu.lastDataCount = len(data) return data } // GetStatusSummaries returns a status summary messages for the node, along with // a status summary for every individual store within the node. // TODO(mrtracy): The status summaries deserve a near-term, significant // overhaul. Their primary usage is as an indicator of the most recent metrics // of a node or store - they are essentially a "vertical" query of several // time series for a single node or store, returning only the most recent value // of each series. The structure should be modified to reflect that: there is no // reason for them to have a strict schema of fields. (Github Issue #4465) func (mr *MetricsRecorder) GetStatusSummaries() (*NodeStatus, []storage.StoreStatus) { mr.mu.Lock() defer mr.mu.Unlock() if mr.mu.nodeID == 0 { // We haven't yet processed initialization information; do nothing. if log.V(1) { log.Warning("MetricsRecorder.GetStatusSummaries called before NodeID allocation.") } return nil, nil } now := mr.mu.clock.PhysicalNow() // Generate an node status with no store data. nodeStat := &NodeStatus{ Desc: mr.mu.desc, UpdatedAt: now, StartedAt: mr.mu.startedAt, StoreIDs: make([]roachpb.StoreID, 0, mr.mu.lastSummaryCount), } storeStats := make([]storage.StoreStatus, 0, mr.mu.lastSummaryCount) // Generate status summaries for stores, while accumulating data into the // NodeStatus. for storeID, r := range mr.mu.storeRegistries { nodeStat.StoreIDs = append(nodeStat.StoreIDs, storeID) // Gather MVCCStats from the store directly. stats := mr.mu.stores[storeID].MVCCStats() // Gather updates from a few specific gauges. // TODO(mrtracy): This is the worst hack present in supporting the // current status summary format. It will be removed as part of #4465. rangeCounter := r.GetCounter("ranges") if rangeCounter == nil { log.Errorf("Could not record status summaries: Store %d did not have 'ranges' counter in registry.", storeID) return nil, nil } gaugeNames := []string{"ranges
{ mr.mu.Lock() defer mr.mu.Unlock() if mr.mu.desc.NodeID == 0 { // We haven't yet processed initialization information; do nothing. if log.V(1) { log.Warning("MetricsRecorder.GetTimeSeriesData() called before NodeID allocation") } return nil } data := make([]ts.TimeSeriesData, 0, mr.mu.lastDataCount) // Record time series from node-level registries. now := mr.mu.clock.PhysicalNow() recorder := registryRecorder{ registry: mr.nodeRegistry, format: nodeTimeSeriesPrefix, source: strconv.FormatInt(int64(mr.mu.nodeID), 10),
identifier_body
recorder.go
Prefix = "cr.node.%s" // runtimeStatTimeSeriesFmt is the current format for time series keys which // record runtime system stats on a node. runtimeStatTimeSeriesNameFmt = "cr.node.sys.%s" ) type quantile struct { suffix string quantile float64 } var recordHistogramQuantiles = []quantile{ {"-max", 100}, {"-p99.999", 99.999}, {"-p99.99", 99.99}, {"-p99.9", 99.9}, {"-p99", 99}, {"-p90", 90}, {"-p75", 75}, {"-p50", 50}, } // storeMetrics is the minimum interface of the storage.Store object needed by // MetricsRecorder to provide status summaries. This is used instead of Store // directly in order to simplify testing. type storeMetrics interface { StoreID() roachpb.StoreID Descriptor() (*roachpb.StoreDescriptor, error) MVCCStats() engine.MVCCStats Registry() *metric.Registry } // MetricsRecorder is used to periodically record the information in a number of // metric registries. // // Two types of registries are maintained: "node-level" registries, provided by // node-level systems, and "store-level" registries which are provided by each // store hosted by the node. There are slight differences in the way these are // recorded, and they are thus kept separate. type MetricsRecorder struct { // nodeRegistry contains, as subregistries, the multiple component-specific // registries which are recorded as "node level" metrics. nodeRegistry *metric.Registry // Fields below are locked by this mutex. mu struct { sync.Mutex // storeRegistries contains a registry for each store on the node. These // are not stored as subregistries, but rather are treated as wholly // independent. storeRegistries map[roachpb.StoreID]*metric.Registry nodeID roachpb.NodeID clock *hlc.Clock // Counts to help optimize slice allocation. lastDataCount int lastSummaryCount int // TODO(mrtracy): These are stored to support the current structure of // status summaries. These should be removed as part of #4465. startedAt int64 desc roachpb.NodeDescriptor stores map[roachpb.StoreID]storeMetrics } } // NewMetricsRecorder initializes a new MetricsRecorder object that uses the // given clock. func NewMetricsRecorder(clock *hlc.Clock) *MetricsRecorder { mr := &MetricsRecorder{ nodeRegistry: metric.NewRegistry(), } mr.mu.storeRegistries = make(map[roachpb.StoreID]*metric.Registry) mr.mu.stores = make(map[roachpb.StoreID]storeMetrics) mr.mu.clock = clock return mr } // AddNodeRegistry adds a node-level registry to this recorder. Each node-level // registry has a 'prefix format' which is used to add a prefix to the name of // all metrics in that registry while recording (see the metric.Registry object // for more information on prefix format strings). func (mr *MetricsRecorder) AddNodeRegistry(prefixFmt string, registry *metric.Registry) { mr.nodeRegistry.MustAdd(prefixFmt, registry) } // AddStore adds the Registry from the provided store as a store-level registry // in this recoder. A reference to the store is kept for the purpose of // gathering some additional information which is present in store status // summaries. // Stores should only be added to the registry after they have been started. // TODO(mrtracy): Store references should not be necessary after #4465. func (mr *MetricsRecorder) AddStore(store storeMetrics) { mr.mu.Lock() defer mr.mu.Unlock() storeID := store.StoreID() mr.mu.storeRegistries[storeID] = store.Registry() mr.mu.stores[storeID] = store } // NodeStarted should be called on the recorder once the associated node has // received its Node ID; this indicates that it is appropriate to begin // recording statistics for this node. func (mr *MetricsRecorder) NodeStarted(desc roachpb.NodeDescriptor, startedAt int64) { mr.mu.Lock() defer mr.mu.Unlock() mr.mu.desc = desc mr.mu.nodeID = desc.NodeID mr.mu.startedAt = startedAt } // MarshalJSON returns an appropriate JSON representation of the current values // of the metrics being tracked by this recorder. func (mr *MetricsRecorder) MarshalJSON() ([]byte, error) { mr.mu.Lock() defer mr.mu.Unlock() if mr.mu.nodeID == 0 { // We haven't yet processed initialization information; return an empty // JSON object. if log.V(1) { log.Warning("MetricsRecorder.MarshalJSON() called before NodeID allocation") } return []byte("{}"), nil } topLevel := map[string]interface{}{ fmt.Sprintf("node.%d", mr.mu.nodeID): mr.nodeRegistry, } // Add collection of stores to top level. JSON requires that keys be strings, // so we must convert the store ID to a string. storeLevel := make(map[string]interface{})
storeLevel[strconv.Itoa(int(id))] = reg } topLevel["stores"] = storeLevel return json.Marshal(topLevel) } // GetTimeSeriesData serializes registered metrics for consumption by // CockroachDB's time series system. func (mr *MetricsRecorder) GetTimeSeriesData() []ts.TimeSeriesData { mr.mu.Lock() defer mr.mu.Unlock() if mr.mu.desc.NodeID == 0 { // We haven't yet processed initialization information; do nothing. if log.V(1) { log.Warning("MetricsRecorder.GetTimeSeriesData() called before NodeID allocation") } return nil } data := make([]ts.TimeSeriesData, 0, mr.mu.lastDataCount) // Record time series from node-level registries. now := mr.mu.clock.PhysicalNow() recorder := registryRecorder{ registry: mr.nodeRegistry, format: nodeTimeSeriesPrefix, source: strconv.FormatInt(int64(mr.mu.nodeID), 10), timestampNanos: now, } recorder.record(&data) // Record time series from store-level registries. for storeID, r := range mr.mu.storeRegistries { storeRecorder := registryRecorder{ registry: r, format: storeTimeSeriesPrefix, source: strconv.FormatInt(int64(storeID), 10), timestampNanos: now, } storeRecorder.record(&data) } mr.mu.lastDataCount = len(data) return data } // GetStatusSummaries returns a status summary messages for the node, along with // a status summary for every individual store within the node. // TODO(mrtracy): The status summaries deserve a near-term, significant // overhaul. Their primary usage is as an indicator of the most recent metrics // of a node or store - they are essentially a "vertical" query of several // time series for a single node or store, returning only the most recent value // of each series. The structure should be modified to reflect that: there is no // reason for them to have a strict schema of fields. (Github Issue #4465) func (mr *MetricsRecorder) GetStatusSummaries() (*NodeStatus, []storage.StoreStatus) { mr.mu.Lock() defer mr.mu.Unlock() if mr.mu.nodeID == 0 { // We haven't yet processed initialization information; do nothing. if log.V(1) { log.Warning("MetricsRecorder.GetStatusSummaries called before NodeID allocation.") } return nil, nil } now := mr.mu.clock.PhysicalNow() // Generate an node status with no store data. nodeStat := &NodeStatus{ Desc: mr.mu.desc, UpdatedAt: now, StartedAt: mr.mu.startedAt, StoreIDs: make([]roachpb.StoreID, 0, mr.mu.lastSummaryCount), } storeStats := make([]storage.StoreStatus, 0, mr.mu.lastSummaryCount) // Generate status summaries for stores, while accumulating data into the // NodeStatus. for storeID, r := range mr.mu.storeRegistries { nodeStat.StoreIDs = append(nodeStat.StoreIDs, storeID) // Gather MVCCStats from the store directly. stats := mr.mu.stores[storeID].MVCCStats() // Gather updates from a few specific gauges. // TODO(mrtracy): This is the worst hack present in supporting the // current status summary format. It will be removed as part of #4465. rangeCounter := r.GetCounter("ranges") if rangeCounter == nil { log.Errorf("Could not record status summaries: Store %d did not have 'ranges' counter in registry.", storeID) return nil, nil } gaugeNames := []string{"ranges.le
for id, reg := range mr.mu.storeRegistries {
random_line_split
recorder.go
Prefix = "cr.node.%s" // runtimeStatTimeSeriesFmt is the current format for time series keys which // record runtime system stats on a node. runtimeStatTimeSeriesNameFmt = "cr.node.sys.%s" ) type quantile struct { suffix string quantile float64 } var recordHistogramQuantiles = []quantile{ {"-max", 100}, {"-p99.999", 99.999}, {"-p99.99", 99.99}, {"-p99.9", 99.9}, {"-p99", 99}, {"-p90", 90}, {"-p75", 75}, {"-p50", 50}, } // storeMetrics is the minimum interface of the storage.Store object needed by // MetricsRecorder to provide status summaries. This is used instead of Store // directly in order to simplify testing. type storeMetrics interface { StoreID() roachpb.StoreID Descriptor() (*roachpb.StoreDescriptor, error) MVCCStats() engine.MVCCStats Registry() *metric.Registry } // MetricsRecorder is used to periodically record the information in a number of // metric registries. // // Two types of registries are maintained: "node-level" registries, provided by // node-level systems, and "store-level" registries which are provided by each // store hosted by the node. There are slight differences in the way these are // recorded, and they are thus kept separate. type MetricsRecorder struct { // nodeRegistry contains, as subregistries, the multiple component-specific // registries which are recorded as "node level" metrics. nodeRegistry *metric.Registry // Fields below are locked by this mutex. mu struct { sync.Mutex // storeRegistries contains a registry for each store on the node. These // are not stored as subregistries, but rather are treated as wholly // independent. storeRegistries map[roachpb.StoreID]*metric.Registry nodeID roachpb.NodeID clock *hlc.Clock // Counts to help optimize slice allocation. lastDataCount int lastSummaryCount int // TODO(mrtracy): These are stored to support the current structure of // status summaries. These should be removed as part of #4465. startedAt int64 desc roachpb.NodeDescriptor stores map[roachpb.StoreID]storeMetrics } } // NewMetricsRecorder initializes a new MetricsRecorder object that uses the // given clock. func NewMetricsRecorder(clock *hlc.Clock) *MetricsRecorder { mr := &MetricsRecorder{ nodeRegistry: metric.NewRegistry(), } mr.mu.storeRegistries = make(map[roachpb.StoreID]*metric.Registry) mr.mu.stores = make(map[roachpb.StoreID]storeMetrics) mr.mu.clock = clock return mr } // AddNodeRegistry adds a node-level registry to this recorder. Each node-level // registry has a 'prefix format' which is used to add a prefix to the name of // all metrics in that registry while recording (see the metric.Registry object // for more information on prefix format strings). func (mr *MetricsRecorder)
(prefixFmt string, registry *metric.Registry) { mr.nodeRegistry.MustAdd(prefixFmt, registry) } // AddStore adds the Registry from the provided store as a store-level registry // in this recoder. A reference to the store is kept for the purpose of // gathering some additional information which is present in store status // summaries. // Stores should only be added to the registry after they have been started. // TODO(mrtracy): Store references should not be necessary after #4465. func (mr *MetricsRecorder) AddStore(store storeMetrics) { mr.mu.Lock() defer mr.mu.Unlock() storeID := store.StoreID() mr.mu.storeRegistries[storeID] = store.Registry() mr.mu.stores[storeID] = store } // NodeStarted should be called on the recorder once the associated node has // received its Node ID; this indicates that it is appropriate to begin // recording statistics for this node. func (mr *MetricsRecorder) NodeStarted(desc roachpb.NodeDescriptor, startedAt int64) { mr.mu.Lock() defer mr.mu.Unlock() mr.mu.desc = desc mr.mu.nodeID = desc.NodeID mr.mu.startedAt = startedAt } // MarshalJSON returns an appropriate JSON representation of the current values // of the metrics being tracked by this recorder. func (mr *MetricsRecorder) MarshalJSON() ([]byte, error) { mr.mu.Lock() defer mr.mu.Unlock() if mr.mu.nodeID == 0 { // We haven't yet processed initialization information; return an empty // JSON object. if log.V(1) { log.Warning("MetricsRecorder.MarshalJSON() called before NodeID allocation") } return []byte("{}"), nil } topLevel := map[string]interface{}{ fmt.Sprintf("node.%d", mr.mu.nodeID): mr.nodeRegistry, } // Add collection of stores to top level. JSON requires that keys be strings, // so we must convert the store ID to a string. storeLevel := make(map[string]interface{}) for id, reg := range mr.mu.storeRegistries { storeLevel[strconv.Itoa(int(id))] = reg } topLevel["stores"] = storeLevel return json.Marshal(topLevel) } // GetTimeSeriesData serializes registered metrics for consumption by // CockroachDB's time series system. func (mr *MetricsRecorder) GetTimeSeriesData() []ts.TimeSeriesData { mr.mu.Lock() defer mr.mu.Unlock() if mr.mu.desc.NodeID == 0 { // We haven't yet processed initialization information; do nothing. if log.V(1) { log.Warning("MetricsRecorder.GetTimeSeriesData() called before NodeID allocation") } return nil } data := make([]ts.TimeSeriesData, 0, mr.mu.lastDataCount) // Record time series from node-level registries. now := mr.mu.clock.PhysicalNow() recorder := registryRecorder{ registry: mr.nodeRegistry, format: nodeTimeSeriesPrefix, source: strconv.FormatInt(int64(mr.mu.nodeID), 10), timestampNanos: now, } recorder.record(&data) // Record time series from store-level registries. for storeID, r := range mr.mu.storeRegistries { storeRecorder := registryRecorder{ registry: r, format: storeTimeSeriesPrefix, source: strconv.FormatInt(int64(storeID), 10), timestampNanos: now, } storeRecorder.record(&data) } mr.mu.lastDataCount = len(data) return data } // GetStatusSummaries returns a status summary messages for the node, along with // a status summary for every individual store within the node. // TODO(mrtracy): The status summaries deserve a near-term, significant // overhaul. Their primary usage is as an indicator of the most recent metrics // of a node or store - they are essentially a "vertical" query of several // time series for a single node or store, returning only the most recent value // of each series. The structure should be modified to reflect that: there is no // reason for them to have a strict schema of fields. (Github Issue #4465) func (mr *MetricsRecorder) GetStatusSummaries() (*NodeStatus, []storage.StoreStatus) { mr.mu.Lock() defer mr.mu.Unlock() if mr.mu.nodeID == 0 { // We haven't yet processed initialization information; do nothing. if log.V(1) { log.Warning("MetricsRecorder.GetStatusSummaries called before NodeID allocation.") } return nil, nil } now := mr.mu.clock.PhysicalNow() // Generate an node status with no store data. nodeStat := &NodeStatus{ Desc: mr.mu.desc, UpdatedAt: now, StartedAt: mr.mu.startedAt, StoreIDs: make([]roachpb.StoreID, 0, mr.mu.lastSummaryCount), } storeStats := make([]storage.StoreStatus, 0, mr.mu.lastSummaryCount) // Generate status summaries for stores, while accumulating data into the // NodeStatus. for storeID, r := range mr.mu.storeRegistries { nodeStat.StoreIDs = append(nodeStat.StoreIDs, storeID) // Gather MVCCStats from the store directly. stats := mr.mu.stores[storeID].MVCCStats() // Gather updates from a few specific gauges. // TODO(mrtracy): This is the worst hack present in supporting the // current status summary format. It will be removed as part of #4465. rangeCounter := r.GetCounter("ranges") if rangeCounter == nil { log.Errorf("Could not record status summaries: Store %d did not have 'ranges' counter in registry.", storeID) return nil, nil } gaugeNames := []string{"ranges
AddNodeRegistry
identifier_name
sdkcallback.go
} xylog.DebugNoId("forward request to %s", subj) reply, err = nats_service.Request(subj, data, time.Duration(DefConfig.NatsTimeout)*time.Second) if err != nil { xylog.ErrorNoId("<%s> Error: %s", subj, err.Error()) return } else { if reply != nil { resp = reply.Data } else { err = errors.New("no reply data") } } return } const ( CallParameter_UUid = "uuid" // sdk唯一id CallParameter_OrderId = "order_id" // sdk 订单号 CallParameter_AppOrderId = "app_order_id" // 游戏订单号 CallParameter_EXT = "app_callback_ext" //扩展参数,保存商品id CallParameter_UserUID = "app_player_id" // 游戏uid CallParameter_Amount = "pay_amount" // 充值数量 CallParameter_PayTime = "pay_time" CallParameter_Sandbox = "sandbox" // 是否测试 CallParameter_Sign = "sign" // 签名校验值 CallParameter_ZoneId = "app_zone_id" CallParameter_Time = "time" CallParameter_UserID = "app_user_id" // 账号id ) func constructCallBackMsg(r *http.Request) (message proto.Message, err error) { var ( goodsId uint64 sandbox, payAmount int parameterSlice ParameterSlice = make([]ParameterStruct, 0) ) r.ParseForm() parameterSlice.Add(CallParameter_Sign, r.PostFormValue(CallParameter_Sign)) parameterSlice.Add(CallParameter_ZoneId, r.PostFormValue(CallParameter_ZoneId)) parameterSlice.Add(CallParameter_Time, r.PostFormValue(CallParameter_Time)) parameterSlice.Add(CallParameter_UserID, r.PostFormValue(CallParameter_UserID)) parameterSlice.Add(CallParameter_UUid, r.PostFormValue(CallParameter_UUid)) parameterSlice.Add(CallParameter_AppOrderId, r.PostFormValue(CallParameter_AppOrderId)) req := &battery.SDKAddOrderRequest{} v := r.PostFormValue(CallParameter_UserUID) if v == "" { xylog.ErrorNoId("get uid from parameter failed") return nil, xyerror.ErrBadInputData } req.Uid = proto.String(v) parameterSlice.Add(CallParameter_UserUID, v) v = r.PostFormValue(CallParameter_OrderId) if v == "" { xylog.ErrorNoId("get orderid from parameter fail") return nil, xyerror.ErrBadInputData } req.OrderId = proto.String(v) parameterSlice.Add(CallParameter_OrderId, v) v = r.PostFormValue(CallParameter_EXT) if v == "" { xylog.ErrorNoId("get goodsid from parameter fail") return nil, xyerror.ErrBadInputData } parameterSlice.Add(CallParameter_EXT, v) goodsId, err = strconv.ParseUint(v, 10, 64) if err != xyerror.ErrOK { xylog.WarningNoId("strconv.ParseUint for uid failed : %v", err) err = xyerror.ErrOK } else { req.GoodsId = proto.Uint64(goodsId) } v = r.PostFormValue(CallParameter_Sandbox) if v == "" { xylog.ErrorNoId("get sandbox from parameterfail") return nil, xyerror.ErrBadInputData } parameterSlice.Add(CallParameter_Sandbox, v) sandbox, err = strconv.Atoi(v) if err != xyerror.ErrOK { xylog.WarningNoId("strconv.Atoi for uid failed : %v", err) err = xyerror.ErrOK } else { req.Sandbox = proto.Int32(int32(sandbox)) } v = r.PostFormValue(CallParameter_Amount) if v == "" { xylog.DebugNoId("get paytime from parameter fail") } else { parameterSlice.Add(CallParameter_Amount, v) payAmount, err = strconv.Atoi(v) if err != xyerror.ErrOK { xylog.WarningNoId("strconv.Atoi for uid failed : %v", err) err = xyerror.ErrOK } else { req.PayAmount = proto.Int32(int32(payAmount)) } } v = r.PostFormValue(CallParameter_PayTime) if v == "" { xylog.WarningNoId("get paytime from parameter fail") } else { parameterSlice.Add(CallParameter_PayTime, v) req.PayTime = proto.String(v) } // 数据验证 var key string key = batteryapi.DefConfigCache.Configs().AppSecretkey if !SDKVerification(parameterSlice, key) { xylog.ErrorNoId("verify error,invalid sig") err = xyerror.ErrBadInputData return } message = req return } func getCallBackResp(respData []byte) (resp string) { respData, err := crypto.Decrypt(respData) if err != nil { resp = "decrypt false" return } respone := &battery.SDKAddOrderResponse{} err = proto.Unmarshal(respData, respone) if err != nil { resp = "unmarshal false" return } if respone.Error.GetCode() != battery.ErrorCode_NoError { resp = "add order fail" return } resp = "ok" return } // 被坑,get请求使用 // func GetCallBackMsg(parameterSlice ParameterSlice) (message proto.Message, err error) { // var ( // goodsId uint64 // sandbox, payAmount int // ) // req := &battery.SDKAddOrderRequest{} // v, result := parameterSlice.Get(CallParameter_UserUID) // if !result { // xylog.ErrorNoId("get uid from parameter failed") // return nil, xyerror.ErrBadInputData // } // req.Uid = proto.String(v) // v, result = parameterSlice.Get(CallParameter_OrderId) // if !result { // xylog.ErrorNoId("get orderid from parameter fail") // return nil, xyerror.ErrBadInputData // } // req.OrderId = proto.String(v) // v, result = parameterSlice.Get(CallParameter_EXT) // if !result { // xylog.ErrorNoId("get goodsid from parameter fail") // return nil, xyerror.ErrBadInputData // } // goodsId, err = strconv.ParseUint(v, 10, 64) // if err != xyerror.ErrOK { // xylog.WarningNoId("strconv.ParseUint for uid failed : %v", err) // err = xyerror.ErrOK // } else { // req.GoodsId = proto.Uint64(goodsId) // } // v, result = parameterSlice.Get(CallParameter_Sandbox) // if !result { // xylog.ErrorNoId("get sandbox from parameterfail") // return nil, xyerror.ErrBadInputData // } // sandbox, err = strconv.Atoi(v) // if err != xyerror.ErrOK { // xylog.WarningNoId("strconv.Atoi for uid failed : %v", err) // err = xyerror.ErrOK // } else { // req.Sandbox = proto.Int32(int32(sandbox)) // } // v, result = parameterSlice.Get(CallParameter_Amount) // if !result { // xylog.DebugNoId("get paytime from parameter fail") // } else { // payAmount, err = strconv.Atoi(v) // if err != xyerror.ErrOK { // xylog.WarningNoId("strconv.Atoi for uid failed : %v", err) // err = xyerror.ErrOK // } else { // req.PayAmount = proto.Int32(int32(payAmount)) // } // } // v, result = parameterSlice.Get(CallParameter_PayTime) // if !result { // xylog.WarningNoId("get paytime from parameter fail") // } else { // req.PayTime = proto.String(v) // } // message = req // return // } // SDK数据验证 func SDKVerification(parameterslice ParameterSlice, key string) bool { var ( uriStr string verifyStr string ) keys := make([]string, 0, len(parameterslice)) for k := range pa
rameterslice { if parameterslice[k].key != "sign" { keys = append(keys, parameterslice[k].key) } } sort.Strings(keys) // 参数升序排序 for index, arg := range keys { v, result := parameterslice.Get(arg) if result { uriStr = fmt.Sprintf("%s%s=%s", uriStr, arg, v) if index != len(keys)-1 { uriStr = fmt.Sprintf("%s&", uriStr) } } } xylog.InfoNoId("uriStr:%s", uriStr) // 参数升序url编码 verifyStr = url.QueryEscape(uriStr)
identifier_body
sdkcallback.go
) xylog.DebugNoId("req url :%v", r.RequestURI) status = http.StatusOK // uri, token = ProcessUri(uri) // xylog.DebugNoId("uri=%s, token=%s, user agent=%s", uri, token, r.UserAgent()) // respData, err = ProcessHttpMsg(token, r) respData, err = ProcessCallBackMsg(uri, r) if err != xyerror.ErrOK { xylog.ErrorNoId("[%s] failed: %s", uri, err.Error()) status = http.StatusInternalServerError //处理失败,返回服务端错误 } else { resp = getCallBackResp(respData) xylog.DebugNoId("response.content : %s", resp) } return } func ProcessCallBackMsg(uri string, r *http.Request) (resp []byte, err error) { var ( req proto.Message route *HttpPostToNatsRoute subj string reply *nats.Msg data []byte ) req, err = constructCallBackMsg(r) if err != xyerror.ErrOK { xylog.ErrorNoId("ConstructPbMsg failed : %v", err) return } xylog.DebugNoId("PbMsg : %v", req) //进行编码 data, err = xyencoder.PbEncode(req) if err != xyerror.ErrOK { xylog.ErrorNoId("xyencoder.PbEncode failed : %v", err) return } //进行加密 data, err = crypto.Encrypt(data) if err != xyerror.ErrOK { xylog.ErrorNoId("crypto.Encrypt failed : %v", err) return } route = DefHttpPostTable.GetRoutePath(uri) xylog.DebugNoId("route:%v,item:%v", route, uri) if route == nil { err = errors.New("No route for item :" + uri) return } subj = route.GetNatsSubject() if subj == "" { err = errors.New("No subject for uri:" + uri) return } xylog.DebugNoId("forward request to %s", subj) reply, err = nats_service.Request(subj, data, time.Duration(DefConfig.NatsTimeout)*time.Second) if err != nil { xylog.ErrorNoId("<%s> Error: %s", subj, err.Error()) return } else { if reply != nil { resp = reply.Data } else { err = errors.New("no reply data") } } return } const ( CallParameter_UUid = "uuid" // sdk唯一id CallParameter_OrderId = "order_id" // sdk 订单号 CallParameter_AppOrderId = "app_order_id" // 游戏订单号 CallParameter_EXT = "app_callback_ext" //扩展参数,保存商品id CallParameter_UserUID = "app_player_id" // 游戏uid CallParameter_Amount = "pay_amount" // 充值数量 CallParameter_PayTime = "pay_time" CallParameter_Sandbox = "sandbox" // 是否测试 CallParameter_Sign = "sign" // 签名校验值 CallParameter_ZoneId = "app_zone_id" CallParameter_Time = "time" CallParameter_UserID = "app_user_id" // 账号id ) func constructCallBackMsg(r *http.Request) (message proto.Message, err error) { var ( goodsId uint64 sandbox, payAmount int parameterSlice ParameterSlice = make([]ParameterStruct, 0) ) r.ParseForm() parameterSlice.Add(CallParameter_Sign, r.PostFormValue(CallParameter_Sign)) parameterSlice.Add(CallParameter_ZoneId, r.PostFormValue(CallParameter_ZoneId)) parameterSlice.Add(CallParameter_Time, r.PostFormValue(CallParameter_Time)) parameterSlice.Add(CallParameter_UserID, r.PostFormValue(CallParameter_UserID)) parameterSlice.Add(CallParameter_UUid, r.PostFormValue(CallParameter_UUid)) parameterSlice.Add(CallParameter_AppOrderId, r.PostFormValue(CallParameter_AppOrderId)) req := &battery.SDKAddOrderRequest{} v := r.PostFormValue(CallParameter_UserUID) if v == "" { xylog.ErrorNoId("get uid from parameter failed") return nil, xyerror.ErrBadInputData } req.Uid = proto.String(v) parameterSlice.Add(CallParameter_UserUID, v) v = r.PostFormValue(CallParameter_OrderId) if v == "" { xylog.ErrorNoId("get orderid from parameter fail") return nil, xyerror.ErrBadInputData } req.OrderId = proto.String(v) parameterSlice.Add(CallParameter_OrderId, v) v = r.PostFormValue(CallParameter_EXT) if v == "" { xylog.ErrorNoId("get goodsid from parameter fail") return nil, xyerror.ErrBadInputData }
error.ErrOK { xylog.WarningNoId("strconv.ParseUint for uid failed : %v", err) err = xyerror.ErrOK } else { req.GoodsId = proto.Uint64(goodsId) } v = r.PostFormValue(CallParameter_Sandbox) if v == "" { xylog.ErrorNoId("get sandbox from parameterfail") return nil, xyerror.ErrBadInputData } parameterSlice.Add(CallParameter_Sandbox, v) sandbox, err = strconv.Atoi(v) if err != xyerror.ErrOK { xylog.WarningNoId("strconv.Atoi for uid failed : %v", err) err = xyerror.ErrOK } else { req.Sandbox = proto.Int32(int32(sandbox)) } v = r.PostFormValue(CallParameter_Amount) if v == "" { xylog.DebugNoId("get paytime from parameter fail") } else { parameterSlice.Add(CallParameter_Amount, v) payAmount, err = strconv.Atoi(v) if err != xyerror.ErrOK { xylog.WarningNoId("strconv.Atoi for uid failed : %v", err) err = xyerror.ErrOK } else { req.PayAmount = proto.Int32(int32(payAmount)) } } v = r.PostFormValue(CallParameter_PayTime) if v == "" { xylog.WarningNoId("get paytime from parameter fail") } else { parameterSlice.Add(CallParameter_PayTime, v) req.PayTime = proto.String(v) } // 数据验证 var key string key = batteryapi.DefConfigCache.Configs().AppSecretkey if !SDKVerification(parameterSlice, key) { xylog.ErrorNoId("verify error,invalid sig") err = xyerror.ErrBadInputData return } message = req return } func getCallBackResp(respData []byte) (resp string) { respData, err := crypto.Decrypt(respData) if err != nil { resp = "decrypt false" return } respone := &battery.SDKAddOrderResponse{} err = proto.Unmarshal(respData, respone) if err != nil { resp = "unmarshal false" return } if respone.Error.GetCode() != battery.ErrorCode_NoError { resp = "add order fail" return } resp = "ok" return } // 被坑,get请求使用 // func GetCallBackMsg(parameterSlice ParameterSlice) (message proto.Message, err error) { // var ( // goodsId uint64 // sandbox, payAmount int // ) // req := &battery.SDKAddOrderRequest{} // v, result := parameterSlice.Get(CallParameter_UserUID) // if !result { // xylog.ErrorNoId("get uid from parameter failed") // return nil, xyerror.ErrBadInputData // } // req.Uid = proto.String(v) // v, result = parameterSlice.Get(CallParameter_OrderId) // if !result { // xylog.ErrorNoId("get orderid from parameter fail") // return nil, xyerror.ErrBadInputData // } // req.OrderId = proto.String(v) // v, result = parameterSlice.Get(CallParameter_EXT) // if !result { // xylog.ErrorNoId("get goodsid from parameter fail") // return nil, xyerror.ErrBadInputData // } // goodsId, err = strconv.ParseUint(v, 10, 64) // if err != xyerror.ErrOK { // xylog.WarningNoId("strconv.ParseUint for uid failed : %v", err) // err = xyerror.ErrOK // } else { // req.GoodsId = proto.Uint64(goodsId) // } // v, result = parameterSlice.Get(CallParameter_Sandbox) // if !result { // xylog.ErrorNoId("get sandbox from parameterfail") // return
parameterSlice.Add(CallParameter_EXT, v) goodsId, err = strconv.ParseUint(v, 10, 64) if err != xy
conditional_block
sdkcallback.go
) xylog.DebugNoId("req url :%v", r.RequestURI) status = http.StatusOK // uri, token = ProcessUri(uri) // xylog.DebugNoId("uri=%s, token=%s, user agent=%s", uri, token, r.UserAgent()) // respData, err = ProcessHttpMsg(token, r) respData, err = ProcessCallBackMsg(uri, r) if err != xyerror.ErrOK { xylog.ErrorNoId("[%s] failed: %s", uri, err.Error()) status = http.StatusInternalServerError //处理失败,返回服务端错误 } else { resp = getCallBackResp(respData) xylog.DebugNoId("response.content : %s", resp) } return } func ProcessCallBackMsg(uri string, r *http.Request) (resp []byte, err error) { var ( req proto.Message route *HttpPostToNatsRoute subj string reply *nats.Msg data []byte ) req, err = constructCallBackMsg(r) if err != xyerror.ErrOK { xylog.ErrorNoId("ConstructPbMsg failed : %v", err) return } xylog.DebugNoId("PbMsg : %v", req) //进行编码 data, err = xyencoder.PbEncode(req) if err != xyerror.ErrOK { xylog.ErrorNoId("xyencoder.PbEncode failed : %v", err) return } //进行加密 data, err = crypto.Encrypt(data) if err != xyerror.ErrOK { xylog.ErrorNoId("crypto.Encrypt failed : %v", err) return } route = DefHttpPostTable.GetRoutePath(uri) xylog.DebugNoId("route:%v,item:%v", route, uri) if route == nil { err = errors.New("No route for item :" + uri) return } subj = route.GetNatsSubject() if subj == "" { err = errors.New("No subject for uri:" + uri) return } xylog.DebugNoId("forward request to %s", subj) reply, err = nats_service.Request(subj, data, time.Duration(DefConfig.NatsTimeout)*time.Second) if err != nil { xylog.ErrorNoId("<%s> Error: %s", subj, err.Error()) return } else { if reply != nil { resp = reply.Data } else { err = errors.New("no reply data") } } return } const ( CallParameter_UUid = "uuid" // sdk唯一id CallParameter_OrderId = "order_id" // sdk 订单号 CallParameter_AppOrderId = "app_order_id" // 游戏订单号 CallParameter_EXT = "app_callback_ext" //扩展参数,保存商品id CallParameter_UserUID = "app_player_id" // 游戏uid CallParameter_Amount = "pay_amount" // 充值数量 CallParameter_PayTime = "pay_time" CallParameter_Sandbox = "sandbox" // 是否测试 CallParameter_Sign = "sign" // 签名校验值 CallParameter_ZoneId = "app_zone_id" CallParameter_Time = "time" CallParameter_UserID = "app_user_id" // 账号id ) func constructCallBackMsg(r *http.Request) (message proto.Message, err error) { var ( goodsId uint64 sandbox, payAmount int parameterSlice ParameterSlice = make([]ParameterStruct, 0) ) r.ParseForm() parameterSlice.Add(CallParameter_Sign, r.PostFormValue(CallParameter_Sign)) parameterSlice.Add(CallParameter_ZoneId, r.PostFormValue(CallParameter_ZoneId)) parameterSlice.Add(CallParameter_Time, r.PostFormValue(CallParameter_Time)) parameterSlice.Add(CallParameter_UserID, r.PostFormValue(CallParameter_UserID)) parameterSlice.Add(CallParameter_UUid, r.PostFormValue(CallParameter_UUid)) parameterSlice.Add(CallParameter_AppOrderId, r.PostFormValue(CallParameter_AppOrderId)) req := &battery.SDKAddOrderRequest{} v := r.PostFormValue(CallParameter_UserUID) if v == "" { xylog.ErrorNoId("get uid from parameter failed") return nil, xyerror.ErrBadInputData } req.Uid = proto.String(v) parameterSlice.Add(CallParameter_UserUID, v) v = r.PostFormValue(CallParameter_OrderId) if v == "" { xylog.ErrorNoId("get orderid from parameter fail") return nil, xyerror.ErrBadInputData } req.OrderId = proto.String(v) parameterSlice.Add(CallParameter_OrderId, v) v = r.PostFormValue(CallParameter_EXT) if v == "" { xylog.ErrorNoId("get goodsid from parameter fail") return nil, xyerror.ErrBadInputData } parameterSlice.Add(CallParameter_EXT, v) goodsId, err = strconv.ParseUint(v, 10, 64) if err != xyerror.ErrOK { xylog.WarningNoId("strconv.ParseUint for uid failed : %v", err) err = xyerror.ErrOK } else { req.GoodsId = proto.Uint64(goodsId) } v = r.PostFormValue(CallParameter_Sandbox) if v == "" { xylog.ErrorNoId("get sandbox from parameterfail") return nil, xyerror.ErrBadInputData } parameterSlice.Add(CallParameter_Sandbox, v) sandbox, err = strconv.Atoi(v) if err != xyerror.ErrOK { xylog.WarningNoId("strconv.Atoi for uid failed : %v", err) err = xyerror.ErrOK } else { req.Sandbox = proto.Int32(int32(sandbox)) } v = r.PostFormValue(CallParameter_Amount) if v == "" { xylog.DebugNoId("get paytime from parameter fail") } else { parameterSlice.Add(CallParameter_Amount, v) payAmount, err = strconv.Atoi(v) if err != xyerror.ErrOK { xylog.WarningNoId("strconv.Atoi for uid failed : %v", err) err = xyerror.ErrOK } else { req.PayAmount = proto.Int32(int32(payAmount)) } } v = r.PostFormValue(CallParameter_PayTime) if v == "" { xylog.WarningNoId("get paytime from parameter fail") } else { parameterSlice.Add(CallParameter_PayTime, v) req.PayTime = proto.String(v) } // 数据验证 var key string key = batteryapi.DefConfigCache.Configs().AppSecretkey if !SDKVerification(parameterSlice, key) { xylog.ErrorNoId("verify error,invalid sig") err = xyerror.ErrBadInputData return } message = req return } func getCallBackResp(respData []byte) (resp string) { respData, err := crypto.Decrypt(respData) if err != nil { resp = "decrypt false" return
} respone := &battery.SDKAddOrderResponse{} err = proto.Unmarshal(respData, respone) if err != nil { resp = "unmarshal false" return } if respone.Error.GetCode() != battery.ErrorCode_NoError { resp = "add order fail" return } resp = "ok" return } // 被坑,get请求使用 // func GetCallBackMsg(parameterSlice ParameterSlice) (message proto.Message, err error) { // var ( // goodsId uint64 // sandbox, payAmount int // ) // req := &battery.SDKAddOrderRequest{} // v, result := parameterSlice.Get(CallParameter_UserUID) // if !result { // xylog.ErrorNoId("get uid from parameter failed") // return nil, xyerror.ErrBadInputData // } // req.Uid = proto.String(v) // v, result = parameterSlice.Get(CallParameter_OrderId) // if !result { // xylog.ErrorNoId("get orderid from parameter fail") // return nil, xyerror.ErrBadInputData // } // req.OrderId = proto.String(v) // v, result = parameterSlice.Get(CallParameter_EXT) // if !result { // xylog.ErrorNoId("get goodsid from parameter fail") // return nil, xyerror.ErrBadInputData // } // goodsId, err = strconv.ParseUint(v, 10, 64) // if err != xyerror.ErrOK { // xylog.WarningNoId("strconv.ParseUint for uid failed : %v", err) // err = xyerror.ErrOK // } else { // req.GoodsId = proto.Uint64(goodsId) // } // v, result = parameterSlice.Get(CallParameter_Sandbox) // if !result { // xylog.ErrorNoId("get sandbox from parameterfail") // return nil,
random_line_split
sdkcallback.go
error.ErrOK { xylog.ErrorNoId("xyencoder.PbEncode failed : %v", err) return } //进行加密 data, err = crypto.Encrypt(data) if err != xyerror.ErrOK { xylog.ErrorNoId("crypto.Encrypt failed : %v", err) return } route = DefHttpPostTable.GetRoutePath(uri) xylog.DebugNoId("route:%v,item:%v", route, uri) if route == nil { err = errors.New("No route for item :" + uri) return } subj = route.GetNatsSubject() if subj == "" { err = errors.New("No subject for uri:" + uri) return } xylog.DebugNoId("forward request to %s", subj) reply, err = nats_service.Request(subj, data, time.Duration(DefConfig.NatsTimeout)*time.Second) if err != nil { xylog.ErrorNoId("<%s> Error: %s", subj, err.Error()) return } else { if reply != nil { resp = reply.Data } else { err = errors.New("no reply data") } } return } const ( CallParameter_UUid = "uuid" // sdk唯一id CallParameter_OrderId = "order_id" // sdk 订单号 CallParameter_AppOrderId = "app_order_id" // 游戏订单号 CallParameter_EXT = "app_callback_ext" //扩展参数,保存商品id CallParameter_UserUID = "app_player_id" // 游戏uid CallParameter_Amount = "pay_amount" // 充值数量 CallParameter_PayTime = "pay_time" CallParameter_Sandbox = "sandbox" // 是否测试 CallParameter_Sign = "sign" // 签名校验值 CallParameter_ZoneId = "app_zone_id" CallParameter_Time = "time" CallParameter_UserID = "app_user_id" // 账号id ) func constructCallBackMsg(r *http.Request) (message proto.Message, err error) { var ( goodsId uint64 sandbox, payAmount int parameterSlice ParameterSlice = make([]ParameterStruct, 0) ) r.ParseForm() parameterSlice.Add(CallParameter_Sign, r.PostFormValue(CallParameter_Sign)) parameterSlice.Add(CallParameter_ZoneId, r.PostFormValue(CallParameter_ZoneId)) parameterSlice.Add(CallParameter_Time, r.PostFormValue(CallParameter_Time)) parameterSlice.Add(CallParameter_UserID, r.PostFormValue(CallParameter_UserID)) parameterSlice.Add(CallParameter_UUid, r.PostFormValue(CallParameter_UUid)) parameterSlice.Add(CallParameter_AppOrderId, r.PostFormValue(CallParameter_AppOrderId)) req := &battery.SDKAddOrderRequest{} v := r.PostFormValue(CallParameter_UserUID) if v == "" { xylog.ErrorNoId("get uid from parameter failed") return nil, xyerror.ErrBadInputData } req.Uid = proto.String(v) parameterSlice.Add(CallParameter_UserUID, v) v = r.PostFormValue(CallParameter_OrderId) if v == "" { xylog.ErrorNoId("get orderid from parameter fail") return nil, xyerror.ErrBadInputData } req.OrderId = proto.String(v) parameterSlice.Add(CallParameter_OrderId, v) v = r.PostFormValue(CallParameter_EXT) if v == "" { xylog.ErrorNoId("get goodsid from parameter fail") return nil, xyerror.ErrBadInputData } parameterSlice.Add(CallParameter_EXT, v) goodsId, err = strconv.ParseUint(v, 10, 64) if err != xyerror.ErrOK { xylog.WarningNoId("strconv.ParseUint for uid failed : %v", err) err = xyerror.ErrOK } else { req.GoodsId = proto.Uint64(goodsId) } v = r.PostFormValue(CallParameter_Sandbox) if v == "" { xylog.ErrorNoId("get sandbox from parameterfail") return nil, xyerror.ErrBadInputData } parameterSlice.Add(CallParameter_Sandbox, v) sandbox, err = strconv.Atoi(v) if err != xyerror.ErrOK { xylog.WarningNoId("strconv.Atoi for uid failed : %v", err) err = xyerror.ErrOK } else { req.Sandbox = proto.Int32(int32(sandbox)) } v = r.PostFormValue(CallParameter_Amount) if v == "" { xylog.DebugNoId("get paytime from parameter fail") } else { parameterSlice.Add(CallParameter_Amount, v) payAmount, err = strconv.Atoi(v) if err != xyerror.ErrOK { xylog.WarningNoId("strconv.Atoi for uid failed : %v", err) err = xyerror.ErrOK } else { req.PayAmount = proto.Int32(int32(payAmount)) } } v = r.PostFormValue(CallParameter_PayTime) if v == "" { xylog.WarningNoId("get paytime from parameter fail") } else { parameterSlice.Add(CallParameter_PayTime, v) req.PayTime = proto.String(v) } // 数据验证 var key string key = batteryapi.DefConfigCache.Configs().AppSecretkey if !SDKVerification(parameterSlice, key) { xylog.ErrorNoId("verify error,invalid sig") err = xyerror.ErrBadInputData return } message = req return } func getCallBackResp(respData []byte) (resp string) { respData, err := crypto.Decrypt(respData) if err != nil { resp = "decrypt false" return } respone := &battery.SDKAddOrderResponse{} err = proto.Unmarshal(respData, respone) if err != nil { resp = "unmarshal false" return } if respone.Error.GetCode() != battery.ErrorCode_NoError { resp = "add order fail" return } resp = "ok" return } // 被坑,get请求使用 // func GetCallBackMsg(parameterSlice ParameterSlice) (message proto.Message, err error) { // var ( // goodsId uint64 // sandbox, payAmount int // ) // req := &battery.SDKAddOrderRequest{} // v, result := parameterSlice.Get(CallParameter_UserUID) // if !result { // xylog.ErrorNoId("get uid from parameter failed") // return nil, xyerror.ErrBadInputData // } // req.Uid = proto.String(v) // v, result = parameterSlice.Get(CallParameter_OrderId) // if !result { // xylog.ErrorNoId("get orderid from parameter fail") // return nil, xyerror.ErrBadInputData // } // req.OrderId = proto.String(v) // v, result = parameterSlice.Get(CallParameter_EXT) // if !result { // xylog.ErrorNoId("get goodsid from parameter fail") // return nil, xyerror.ErrBadInputData // } // goodsId, err = strconv.ParseUint(v, 10, 64) // if err != xyerror.ErrOK { // xylog.WarningNoId("strconv.ParseUint for uid failed : %v", err) // err = xyerror.ErrOK // } else { // req.GoodsId = proto.Uint64(goodsId) // } // v, result = parameterSlice.Get(CallParameter_Sandbox) // if !result { // xylog.ErrorNoId("get sandbox from parameterfail") // return nil, xyerror.ErrBadInputData // } // sandbox, err = strconv.Atoi(v) // if err != xyerror.ErrOK { // xylog.WarningNoId("strconv.Atoi for uid failed : %v", err) // err = xyerror.ErrOK // } else { // req.Sandbox = proto.Int32(int32(sandbox)) // } // v, result = parameterSlice.Get(CallParameter_Amount) // if !result { // xylog.DebugNoId("get paytime from parameter fail") // } else { // payAmount, err = strconv.Atoi(v) // if err != xyerror.ErrOK { // xylog.WarningNoId("strconv.Atoi for uid failed : %v", err) // err = xyerror.ErrOK // } else { // req.PayAmount = proto.Int32(int32(payAmount)) // } // } // v, result = parameterSlice.Get(CallParameter_PayTime) // if !result { // xylog.WarningNoId("get paytime from parameter fail") // } else { // req.PayTime = proto.String(v) // } // message = req // return // } // SDK数据验证 func SDKVerification(parameterslice ParameterSlice, key string) bool { var ( uriStr string verifyStr string ) keys
:= make([]stri
identifier_name
vjAnnotListTableView.js
"); var checkedTbl = _mainControl_.checkedTable; var objAdded = _mainControl_.objAdded; for (var i=0; i<checkedTbl.selectedCnt; ++i) { var curNode = checkedTbl.selectedNodes[i]; if (objAdded[curNode.seqID]) { var curObj = objAdded[curNode.seqID]; if (curObj[curNode.ranges]) { delete curObj[curNode.ranges]; --_mainControl_.rowsCnt; } } if (objAdded[curNode.seqID] && !Object.keys(objAdded[curNode.seqID]).length) { delete objAdded[curNode.seqID]; } } var url = "static://" + _mainControl_.constructPreviewTableUrl(_mainControl_.objAdded); _mainControl_.checkTypeDS.reload(url,true); checkedTbl.selectedCnt=0; checkedTbl.selectedNodes=[]; _mainControl_.updateInfoForSubmitPanel(); if (_mainControl_.removeCallback) { funcLink(_mainControl_.removeCallback, _mainControl_, objNode); } } _mainControl_.reload = function () { if (this.annotObjList.length){ var ionList = this.annotObjList.join(","); var refList = this.referenceObjList.join(";"); this.annotTypeDS.url = urlExchangeParameter(this.defaultAnnotUrl, "ionObjs", ionList); this.annotTypeDS.url = urlExchangeParameter(this.annotTypeDS.url, "refGenomeList", refList); this.annotTypeDS.reload(0,true); } } _mainControl_.updateInfoForSubmitPanel = function () { var infoNode = this.anotSubmitPanel.tree.findByName("info"); if (this.rowsCnt<=0){ this.rowsCnt =0; infoNode.value = 'Select range(s) to add'; } else { infoNode.value = ''+ this.rowsCnt +' range(s) added'; } this.anotSubmitPanel.refresh(); } // contruction Panel function openManualPanel (panel, treeNode, objNode){ //var aa=0; var mPanel = _mainControl_.manualPanel; if (!treeNode.value) { treeNode.value = 1; mPanel.hidden = false; } else { treeNode.value =0; mPanel.hidden = true; } mPanel.render(); } _mainControl_.constructPanel = function () { var anotPanel = new vjBasicPanelView({ data:["dsVoid",this.annotTypeDS.name], rows:[ {name:'refresh', title: 'Refresh' ,order:-1, icon:'refresh' , description: 'refresh the content of the control to retrieve up to date information' , url: "javascript:vjDS['$(dataname)'].reload(null,true);"}, {name:'pager', icon:'page' , title:'per page',order:2, description: 'page up/down or show selected number of objects in the control' , type:'pager', counters: [10,20,50,100,1000,'all']}, { name: 'search', align: 'right', type: ' search', prefix:"Search Id: ",order:10, isSubmitable: true, title: 'Search', description: 'search id',order:'1', url: "?cmd=objFile&ids=$(ids)" }, { name: 'searchType', title:"search type", prefix:"Search Type: ", align: 'right', type: ' text',isSubmitable: true, description: 'search type',order:'1',path:"/search/searchType", hidden: this.searchTypeButton.hidden}, { name : 'ionObjs', type:"text", align: 'left' , order : 1, prefix: this.annotationButton.name, isSubmitable: true, hidden: this.annotationButton.hidden}, { name : 'manualInput', align: 'right' , order : -1, icon:"arrow_sort_down_highlighted.gif",title: "Insert Ranges",showTitle:true, description:"Manual Input",url: openManualPanel, iconSize:18, value:0} ], parentObjCls: main_objCls, formObject:this.formObject }); var manualPanel = new vjPanelView( { data:["dsVoid"], rows: [ { name: 'seqID', align: 'left', type: 'text', prefix:"Sequence Id: ",order:1, title: 'Sequence Id', description: 'Sequence Identifier',order:'1', size: '8' }, { name: 'start', align: 'left', type: 'text', prefix:"Start Position: ",order:2, title: 'Start Position', description: 'Start Position',order:'2',size: '8' }, { name: 'end', align: 'left', type: 'text', prefix:"End Position: ",order:3, title: 'End Position', description: 'End Position',order:'3',size: '8' }, { name : 'add', title:'Add', icon:"plus.gif", iconSize:"18" ,showTitle:true ,align: 'left' , order : 4, url: accumulateRows } ], parentObjCls: main_objCls, hidden:true, myName: "manualPanel", formObject:this.formObject }); this.anotPanel = anotPanel; this.manualPanel = manualPanel; this.viewersArr.push(this.anotPanel); } // contruction Table _mainControl_.constructTable = function () { // annotation table var anotTable = new vjTableView({ data: this.annotTypeDS.name ,formObject:this.formObject ,parentObjCls: main_objCls ,bgColors: this.bgColors ,defaultEmptyText: this.defaultEmptyText ,maxTxtLen: this.maxTxtLen ,treeColumn: "start" ,checkable:true //,selectCallback: this.selectCallback , appendCols : [{header:{name:"path",title:'Annotation', type:"treenode",order:1,maxTxtLen:32},cell:""}] ,cols : [{ name: 'seqID', hidden:true }] ,treeColumn: "path" ,precompute: "node.name=node.seqID+'['+node.start + ':'+node.end+']';node.path='/'+node.name; \ if(this.viewer.dicPaths[node.path]){if (node.type.trim()=='strand'){this.viewer.dicPaths[node.path]= (node.id.trim()=='+') ? 1 : -1; };node.path+='/'+node.type+':'+node.id.replace(/\\//g,'.');} \ else {this.viewer.dicPaths[node.path]=1;if (node.type.trim()=='strand'){this.viewer.dicPaths[node.path]= (node.id.trim()=='+') ? 1 : -1; };} \ " ,postcompute:"if(node.treenode && node.treenode.depth>=2){node.styleNoCheckmark=true;node.name='';node.start='';node.end='';}" ,dicPaths: {} ,checkCallback: accumulateRows ,myName:"mainTable" }); // checked elements table var checkElementTable = new vjTableView({ data: this.checkTypeDS.name ,formObject:this.formObject ,parentObjCls: main_objCls ,bgColors: this.bgColors ,defaultEmptyText: this.defaultEmptyText ,maxTxtLen: this.maxTxtLen ,hidden:true ,myName:"checkTable" }); this.anotTable = anotTable; this.checkedTable = checkElementTable; this.viewersArr.push(this.anotTable, this.checkedTable); } // construct the submit panel at the bottom _mainControl_.constructSubmitPanel = function () { var rows=[{ name : 'info', type : 'text', title : 'Select range(s) to add', value : 'Select range(s) to add', align:'right', readonly:true, size:40, prefix:'Selected range(s): ', order : 1}, { name : 'submit', type : 'button', value: this.submitButton['name'], align: 'right' , order : 2, url: returnRowsChecked, hidden: this.submitButton['hidden']}, { name : 'showChecked', type : 'button', value:'Preview Checked Elements', align: 'left' , order : 1, url: previewCheckedElement}, { name : 'removeSelected', type : 'button', value:'remove selected Elements', align: 'left' , hidden: true ,order : 2, url: removeSelectedElement}, { name : 'clear', type : 'button', value:'Clear', align: 'right' , order : 3, url: onClearAll } ]; var anotPanel = new vjPanelView({ data:["dsVoid"], rows: rows, formObject: this.formObject, parentObjCls: main_objCls, myName: "submitPanel", isok: true } ); this.anotSubmitPanel = anotPanel;
this.viewersArr.push(this.anotSubmitPanel); }
random_line_split
vjAnnotListTableView.js
ObjList) this.referenceObjList = []; if (!this.annotObjList) this.annotObjList = []; var dsname = "dsAnnotList_table"; //this.annotTypeDS = this.vjDS.add("infrastructure: Folders Help", dsname, this.defaultAnnotUrl,0,"seqID,start,end,type,id\n"); this.annotTypeDS = this.vjDS.add("Loading annotation ", dsname, "static://",0,"seqID,start,end,type,id\n"); this.checkTypeDS = this.vjDS.add("Loading results", dsname+"-checked", "static://"); // function var _mainControl_ = this; function checkDirection (dicPath, curPath) { var myArr = Object.keys(dicPath); for (var ia=0; ia<myArr.length; ++ia) { if (curPath.indexOf(myArr[ia])!=-1)
} return 1; } function accumulateRows (viewer, node, ir,ic) { var objAdded = _mainControl_.objAdded; var range = "", seqID ="", type = "", id= "",strand = "+", checked = true; if (viewer.myName && viewer.myName=="manualPanel") { seqID = viewer.tree.findByName("seqID").value; var curStart = viewer.tree.findByName("start").value; curStart = isNaN(curStart) ? (-2) : curStart; var curEnd = viewer.tree.findByName("end").value; curEnd = isNaN(curEnd) ? (-2) : curEnd; if (curStart==-2 || curEnd==-2) { range= "not_valid"; } else { range = curStart + "-" + curEnd; } viewer.render(); } else { range = node.start + "-" + node.end; seqID = node.seqID; type = node.type; id = node.id; strand = checkDirection(viewer.dicPaths, node.path); checked = node.checked; } if ( range != "not_valid") { if (!checked && objAdded[seqID]) { // remove if (objAdded[seqID][range]) { // exist => remove from the array delete objAdded[seqID][range]; _mainControl_.rowsCnt-=1; } } else { if (!objAdded[seqID]) { objAdded[seqID] ={}; } // not exit =>push to the dict objAdded[seqID][range]= {"defLine":type + ":" + id, "strand": strand}; _mainControl_.rowsCnt+=1; } _mainControl_.updateInfoForSubmitPanel(); if (_mainControl_.checkCallback) { funcLink(_mainControl_.checkCallback, _mainControl_, viewer); } } if (viewer.myName && viewer.myName=="manualPanel") { var url = "static://" + _mainControl_.constructPreviewTableUrl(_mainControl_.objAdded); _mainControl_.checkTypeDS.reload(url,true); } } function returnRowsChecked (submitPanel,treeNode,objNode) { _mainControl_.retValue = _mainControl_.constructPreviewTableUrl(_mainControl_.objAdded,true); if (_mainControl_.callbackSubmit){ funcLink(_mainControl_.callbackSubmit, _mainControl_, objNode); } // Reset the preview button and the datasource _mainControl_.anotTable.checkedCnt=0; _mainControl_.anotTable.checkedNodes=[]; _mainControl_.anotTable.hidden = false; _mainControl_.annotTypeDS.reload(0,true); _mainControl_.checkedTable.hidden = true; _mainControl_.checkedTable.render(); _mainControl_.manualPanel.hidden = true; _mainControl_.manualPanel.render(); submitPanel.tree.findByName("showChecked").value = "Preview Checked Elements"; submitPanel.tree.findByName("removeSelected").hidden = true; submitPanel.refresh(); // clear every thing after submit onClearAll(submitPanel); _mainControl_.retValue0 = _mainControl_.retValue; _mainControl_.retValue = "" ; } function onClearAll (submitPanel,treeNode,objNode) { _mainControl_.rowsCnt =0; _mainControl_.objAdded ={}; // clear panel var infoNode = _mainControl_.anotSubmitPanel.tree.findByName("info"); infoNode.value = 'Select range(s) to add'; _mainControl_.anotSubmitPanel.refresh(); // clear check rows _mainControl_.checkTypeDS.reload("static://",true); var checkedNodes = _mainControl_.anotTable.checkedNodes; for (var i=0; i<checkedNodes.length; ++i) { var curNode = checkedNodes[i]; _mainControl_.anotTable.mimicCheckmarkSelected(curNode.irow,false); _mainControl_.anotTable.onCheckmarkSelected(_mainControl_.anotTable.container,0,curNode.irow); } if (_mainControl_.clearCallback) { funcLink(_mainControl_.clearCallback, _mainControl_, submitPanel); } } _mainControl_.constructPreviewTableUrl = function (obj, isOutput) { // obj = {seqID: {start1-end1: type1-id1, start2-end2: type2-id2}} var t = "seqID,ranges\n"; var len = t.length; if (isOutput){ t ="index,seqID,start,end,direction,defLine\n"; len=t.length; // 0: forward, 1: reverse, 2: complement, 3:reverse complement } var objKeyArr = Object.keys(obj); var iCnt=0; for (var i=0; i< objKeyArr.length; ++i) { // looping through seqID var curObj = obj[objKeyArr[i]]; for (var range in curObj) { if (isOutput) { if (curObj[range]["strand"]>0) { // strand = "+" t += "" + iCnt + "," + objKeyArr[i] + "," + range.split("-")[0] + "," + range.split("-")[1] + "," + ( 0 ) + "," + curObj[range]["defLine"] +"\n"; ++iCnt; /*t += "" + iCnt + "," + objKeyArr[i] + "," + range.split("-")[0] + "," + range.split("-")[1] + "," + ( 1 ) + "," + curObj[range]["defLine"] +"\n"; ++iCnt;*/ } else { // strand = "-" t += "" + iCnt + "," + objKeyArr[i] + "," + range.split("-")[0] + "," + range.split("-")[1] + "," + ( 1 ) + "," + curObj[range]["defLine"] +"\n"; ++iCnt; /*t += "" + iCnt + "," + objKeyArr[i] + "," + range.split("-")[0] + "," + range.split("-")[1] + "," + ( 2 ) + "," + curObj[range]["defLine"] +"\n"; ++iCnt; t += "" + iCnt + "," + objKeyArr[i] + "," + range.split("-")[0] + "," + range.split("-")[1] + "," + ( 3 ) + "," + curObj[range]["defLine"] +"\n"; ++iCnt;*/ } } else { t += "" + objKeyArr[i] + "," + range + "\n"; } } } return (t.length > len) ? t: ""; } function previewCheckedElement(submitPanel,treeNode,objNode) { var showCheckedNode = submitPanel.tree.findByName("showChecked"); var removeNode = submitPanel.tree.findByName("removeSelected"); if (showCheckedNode.value.indexOf("Back")==-1) { // when select preview _mainControl_.anotTable.hidden=true; _mainControl_.anotTable.render(); var url = "static://" + _mainControl_.constructPreviewTableUrl(_mainControl_.objAdded); _mainControl_.checkedTable.hidden=false; _mainControl_.checkTypeDS.reload(url,true); showCheckedNode.value = "Back"; removeNode.hidden = false; submitPanel.refresh(); } else { // when select back _mainControl_.anotTable.checkedCnt=0; _mainControl_.anotTable.checkedNodes=[]; _mainControl_.anotTable.hidden = false; _mainControl_.annotTypeDS.reload(0,true); _mainControl_.checkedTable.hidden = true; _mainControl_.checkedTable.render(); showCheckedNode.value = "Preview Checked Elements"; removeNode.hidden = true; submitPanel.refresh(); } } function removeSelectedElement(submitPanel,treeNode,objNode) { console.log("removing selected element"); var checkedTbl = _mainControl_.
{ return dicPath[myArr[ia]]; }
conditional_block
vjAnnotListTableView.js
0; ia<myArr.length; ++ia) { if (curPath.indexOf(myArr[ia])!=-1) { return dicPath[myArr[ia]]; } } return 1; } function accumulateRows (viewer, node, ir,ic) { var objAdded = _mainControl_.objAdded; var range = "", seqID ="", type = "", id= "",strand = "+", checked = true; if (viewer.myName && viewer.myName=="manualPanel") { seqID = viewer.tree.findByName("seqID").value; var curStart = viewer.tree.findByName("start").value; curStart = isNaN(curStart) ? (-2) : curStart; var curEnd = viewer.tree.findByName("end").value; curEnd = isNaN(curEnd) ? (-2) : curEnd; if (curStart==-2 || curEnd==-2) { range= "not_valid"; } else { range = curStart + "-" + curEnd; } viewer.render(); } else { range = node.start + "-" + node.end; seqID = node.seqID; type = node.type; id = node.id; strand = checkDirection(viewer.dicPaths, node.path); checked = node.checked; } if ( range != "not_valid") { if (!checked && objAdded[seqID]) { // remove if (objAdded[seqID][range]) { // exist => remove from the array delete objAdded[seqID][range]; _mainControl_.rowsCnt-=1; } } else { if (!objAdded[seqID]) { objAdded[seqID] ={}; } // not exit =>push to the dict objAdded[seqID][range]= {"defLine":type + ":" + id, "strand": strand}; _mainControl_.rowsCnt+=1; } _mainControl_.updateInfoForSubmitPanel(); if (_mainControl_.checkCallback) { funcLink(_mainControl_.checkCallback, _mainControl_, viewer); } } if (viewer.myName && viewer.myName=="manualPanel") { var url = "static://" + _mainControl_.constructPreviewTableUrl(_mainControl_.objAdded); _mainControl_.checkTypeDS.reload(url,true); } } function returnRowsChecked (submitPanel,treeNode,objNode) { _mainControl_.retValue = _mainControl_.constructPreviewTableUrl(_mainControl_.objAdded,true); if (_mainControl_.callbackSubmit){ funcLink(_mainControl_.callbackSubmit, _mainControl_, objNode); } // Reset the preview button and the datasource _mainControl_.anotTable.checkedCnt=0; _mainControl_.anotTable.checkedNodes=[]; _mainControl_.anotTable.hidden = false; _mainControl_.annotTypeDS.reload(0,true); _mainControl_.checkedTable.hidden = true; _mainControl_.checkedTable.render(); _mainControl_.manualPanel.hidden = true; _mainControl_.manualPanel.render(); submitPanel.tree.findByName("showChecked").value = "Preview Checked Elements"; submitPanel.tree.findByName("removeSelected").hidden = true; submitPanel.refresh(); // clear every thing after submit onClearAll(submitPanel); _mainControl_.retValue0 = _mainControl_.retValue; _mainControl_.retValue = "" ; } function onClearAll (submitPanel,treeNode,objNode) { _mainControl_.rowsCnt =0; _mainControl_.objAdded ={}; // clear panel var infoNode = _mainControl_.anotSubmitPanel.tree.findByName("info"); infoNode.value = 'Select range(s) to add'; _mainControl_.anotSubmitPanel.refresh(); // clear check rows _mainControl_.checkTypeDS.reload("static://",true); var checkedNodes = _mainControl_.anotTable.checkedNodes; for (var i=0; i<checkedNodes.length; ++i) { var curNode = checkedNodes[i]; _mainControl_.anotTable.mimicCheckmarkSelected(curNode.irow,false); _mainControl_.anotTable.onCheckmarkSelected(_mainControl_.anotTable.container,0,curNode.irow); } if (_mainControl_.clearCallback) { funcLink(_mainControl_.clearCallback, _mainControl_, submitPanel); } } _mainControl_.constructPreviewTableUrl = function (obj, isOutput) { // obj = {seqID: {start1-end1: type1-id1, start2-end2: type2-id2}} var t = "seqID,ranges\n"; var len = t.length; if (isOutput){ t ="index,seqID,start,end,direction,defLine\n"; len=t.length; // 0: forward, 1: reverse, 2: complement, 3:reverse complement } var objKeyArr = Object.keys(obj); var iCnt=0; for (var i=0; i< objKeyArr.length; ++i) { // looping through seqID var curObj = obj[objKeyArr[i]]; for (var range in curObj) { if (isOutput) { if (curObj[range]["strand"]>0) { // strand = "+" t += "" + iCnt + "," + objKeyArr[i] + "," + range.split("-")[0] + "," + range.split("-")[1] + "," + ( 0 ) + "," + curObj[range]["defLine"] +"\n"; ++iCnt; /*t += "" + iCnt + "," + objKeyArr[i] + "," + range.split("-")[0] + "," + range.split("-")[1] + "," + ( 1 ) + "," + curObj[range]["defLine"] +"\n"; ++iCnt;*/ } else { // strand = "-" t += "" + iCnt + "," + objKeyArr[i] + "," + range.split("-")[0] + "," + range.split("-")[1] + "," + ( 1 ) + "," + curObj[range]["defLine"] +"\n"; ++iCnt; /*t += "" + iCnt + "," + objKeyArr[i] + "," + range.split("-")[0] + "," + range.split("-")[1] + "," + ( 2 ) + "," + curObj[range]["defLine"] +"\n"; ++iCnt; t += "" + iCnt + "," + objKeyArr[i] + "," + range.split("-")[0] + "," + range.split("-")[1] + "," + ( 3 ) + "," + curObj[range]["defLine"] +"\n"; ++iCnt;*/ } } else { t += "" + objKeyArr[i] + "," + range + "\n"; } } } return (t.length > len) ? t: ""; } function previewCheckedElement(submitPanel,treeNode,objNode) { var showCheckedNode = submitPanel.tree.findByName("showChecked"); var removeNode = submitPanel.tree.findByName("removeSelected"); if (showCheckedNode.value.indexOf("Back")==-1) { // when select preview _mainControl_.anotTable.hidden=true; _mainControl_.anotTable.render(); var url = "static://" + _mainControl_.constructPreviewTableUrl(_mainControl_.objAdded); _mainControl_.checkedTable.hidden=false; _mainControl_.checkTypeDS.reload(url,true); showCheckedNode.value = "Back"; removeNode.hidden = false; submitPanel.refresh(); } else { // when select back _mainControl_.anotTable.checkedCnt=0; _mainControl_.anotTable.checkedNodes=[]; _mainControl_.anotTable.hidden = false; _mainControl_.annotTypeDS.reload(0,true); _mainControl_.checkedTable.hidden = true; _mainControl_.checkedTable.render(); showCheckedNode.value = "Preview Checked Elements"; removeNode.hidden = true; submitPanel.refresh(); } } function removeSelectedElement(submitPanel,treeNode,objNode)
{ console.log("removing selected element"); var checkedTbl = _mainControl_.checkedTable; var objAdded = _mainControl_.objAdded; for (var i=0; i<checkedTbl.selectedCnt; ++i) { var curNode = checkedTbl.selectedNodes[i]; if (objAdded[curNode.seqID]) { var curObj = objAdded[curNode.seqID]; if (curObj[curNode.ranges]) { delete curObj[curNode.ranges]; --_mainControl_.rowsCnt; } } if (objAdded[curNode.seqID] && !Object.keys(objAdded[curNode.seqID]).length) { delete objAdded[curNode.seqID]; } } var url = "static://" + _mainControl_.constructPreviewTableUrl(_mainControl_.objAdded); _mainControl_.checkTypeDS.reload(url,true);
identifier_body
vjAnnotListTableView.js
ObjList) this.referenceObjList = []; if (!this.annotObjList) this.annotObjList = []; var dsname = "dsAnnotList_table"; //this.annotTypeDS = this.vjDS.add("infrastructure: Folders Help", dsname, this.defaultAnnotUrl,0,"seqID,start,end,type,id\n"); this.annotTypeDS = this.vjDS.add("Loading annotation ", dsname, "static://",0,"seqID,start,end,type,id\n"); this.checkTypeDS = this.vjDS.add("Loading results", dsname+"-checked", "static://"); // function var _mainControl_ = this; function
(dicPath, curPath) { var myArr = Object.keys(dicPath); for (var ia=0; ia<myArr.length; ++ia) { if (curPath.indexOf(myArr[ia])!=-1) { return dicPath[myArr[ia]]; } } return 1; } function accumulateRows (viewer, node, ir,ic) { var objAdded = _mainControl_.objAdded; var range = "", seqID ="", type = "", id= "",strand = "+", checked = true; if (viewer.myName && viewer.myName=="manualPanel") { seqID = viewer.tree.findByName("seqID").value; var curStart = viewer.tree.findByName("start").value; curStart = isNaN(curStart) ? (-2) : curStart; var curEnd = viewer.tree.findByName("end").value; curEnd = isNaN(curEnd) ? (-2) : curEnd; if (curStart==-2 || curEnd==-2) { range= "not_valid"; } else { range = curStart + "-" + curEnd; } viewer.render(); } else { range = node.start + "-" + node.end; seqID = node.seqID; type = node.type; id = node.id; strand = checkDirection(viewer.dicPaths, node.path); checked = node.checked; } if ( range != "not_valid") { if (!checked && objAdded[seqID]) { // remove if (objAdded[seqID][range]) { // exist => remove from the array delete objAdded[seqID][range]; _mainControl_.rowsCnt-=1; } } else { if (!objAdded[seqID]) { objAdded[seqID] ={}; } // not exit =>push to the dict objAdded[seqID][range]= {"defLine":type + ":" + id, "strand": strand}; _mainControl_.rowsCnt+=1; } _mainControl_.updateInfoForSubmitPanel(); if (_mainControl_.checkCallback) { funcLink(_mainControl_.checkCallback, _mainControl_, viewer); } } if (viewer.myName && viewer.myName=="manualPanel") { var url = "static://" + _mainControl_.constructPreviewTableUrl(_mainControl_.objAdded); _mainControl_.checkTypeDS.reload(url,true); } } function returnRowsChecked (submitPanel,treeNode,objNode) { _mainControl_.retValue = _mainControl_.constructPreviewTableUrl(_mainControl_.objAdded,true); if (_mainControl_.callbackSubmit){ funcLink(_mainControl_.callbackSubmit, _mainControl_, objNode); } // Reset the preview button and the datasource _mainControl_.anotTable.checkedCnt=0; _mainControl_.anotTable.checkedNodes=[]; _mainControl_.anotTable.hidden = false; _mainControl_.annotTypeDS.reload(0,true); _mainControl_.checkedTable.hidden = true; _mainControl_.checkedTable.render(); _mainControl_.manualPanel.hidden = true; _mainControl_.manualPanel.render(); submitPanel.tree.findByName("showChecked").value = "Preview Checked Elements"; submitPanel.tree.findByName("removeSelected").hidden = true; submitPanel.refresh(); // clear every thing after submit onClearAll(submitPanel); _mainControl_.retValue0 = _mainControl_.retValue; _mainControl_.retValue = "" ; } function onClearAll (submitPanel,treeNode,objNode) { _mainControl_.rowsCnt =0; _mainControl_.objAdded ={}; // clear panel var infoNode = _mainControl_.anotSubmitPanel.tree.findByName("info"); infoNode.value = 'Select range(s) to add'; _mainControl_.anotSubmitPanel.refresh(); // clear check rows _mainControl_.checkTypeDS.reload("static://",true); var checkedNodes = _mainControl_.anotTable.checkedNodes; for (var i=0; i<checkedNodes.length; ++i) { var curNode = checkedNodes[i]; _mainControl_.anotTable.mimicCheckmarkSelected(curNode.irow,false); _mainControl_.anotTable.onCheckmarkSelected(_mainControl_.anotTable.container,0,curNode.irow); } if (_mainControl_.clearCallback) { funcLink(_mainControl_.clearCallback, _mainControl_, submitPanel); } } _mainControl_.constructPreviewTableUrl = function (obj, isOutput) { // obj = {seqID: {start1-end1: type1-id1, start2-end2: type2-id2}} var t = "seqID,ranges\n"; var len = t.length; if (isOutput){ t ="index,seqID,start,end,direction,defLine\n"; len=t.length; // 0: forward, 1: reverse, 2: complement, 3:reverse complement } var objKeyArr = Object.keys(obj); var iCnt=0; for (var i=0; i< objKeyArr.length; ++i) { // looping through seqID var curObj = obj[objKeyArr[i]]; for (var range in curObj) { if (isOutput) { if (curObj[range]["strand"]>0) { // strand = "+" t += "" + iCnt + "," + objKeyArr[i] + "," + range.split("-")[0] + "," + range.split("-")[1] + "," + ( 0 ) + "," + curObj[range]["defLine"] +"\n"; ++iCnt; /*t += "" + iCnt + "," + objKeyArr[i] + "," + range.split("-")[0] + "," + range.split("-")[1] + "," + ( 1 ) + "," + curObj[range]["defLine"] +"\n"; ++iCnt;*/ } else { // strand = "-" t += "" + iCnt + "," + objKeyArr[i] + "," + range.split("-")[0] + "," + range.split("-")[1] + "," + ( 1 ) + "," + curObj[range]["defLine"] +"\n"; ++iCnt; /*t += "" + iCnt + "," + objKeyArr[i] + "," + range.split("-")[0] + "," + range.split("-")[1] + "," + ( 2 ) + "," + curObj[range]["defLine"] +"\n"; ++iCnt; t += "" + iCnt + "," + objKeyArr[i] + "," + range.split("-")[0] + "," + range.split("-")[1] + "," + ( 3 ) + "," + curObj[range]["defLine"] +"\n"; ++iCnt;*/ } } else { t += "" + objKeyArr[i] + "," + range + "\n"; } } } return (t.length > len) ? t: ""; } function previewCheckedElement(submitPanel,treeNode,objNode) { var showCheckedNode = submitPanel.tree.findByName("showChecked"); var removeNode = submitPanel.tree.findByName("removeSelected"); if (showCheckedNode.value.indexOf("Back")==-1) { // when select preview _mainControl_.anotTable.hidden=true; _mainControl_.anotTable.render(); var url = "static://" + _mainControl_.constructPreviewTableUrl(_mainControl_.objAdded); _mainControl_.checkedTable.hidden=false; _mainControl_.checkTypeDS.reload(url,true); showCheckedNode.value = "Back"; removeNode.hidden = false; submitPanel.refresh(); } else { // when select back _mainControl_.anotTable.checkedCnt=0; _mainControl_.anotTable.checkedNodes=[]; _mainControl_.anotTable.hidden = false; _mainControl_.annotTypeDS.reload(0,true); _mainControl_.checkedTable.hidden = true; _mainControl_.checkedTable.render(); showCheckedNode.value = "Preview Checked Elements"; removeNode.hidden = true; submitPanel.refresh(); } } function removeSelectedElement(submitPanel,treeNode,objNode) { console.log("removing selected element"); var checkedTbl = _mainControl_.checked
checkDirection
identifier_name
fifo.rs
00 dataset. We will use these joinable keys for understanding // incremental execution. const TEST_JOIN_RATIO: f64 = 0.01; fn create_fifo_file(tmp_dir: &TempDir, file_name: &str) -> Result<PathBuf> { let file_path = tmp_dir.path().join(file_name); // Simulate an infinite environment via a FIFO file if let Err(e) = unistd::mkfifo(&file_path, stat::Mode::S_IRWXU) { Err(DataFusionError::Execution(e.to_string())) } else { Ok(file_path) } } fn write_to_fifo( mut file: &File, line: &str, ref_time: Instant, broken_pipe_timeout: Duration, ) -> Result<()> { // We need to handle broken pipe error until the reader is ready. This // is why we use a timeout to limit the wait duration for the reader. // If the error is different than broken pipe, we fail immediately. while let Err(e) = file.write_all(line.as_bytes()) { if e.raw_os_error().unwrap() == 32 { let interval = Instant::now().duration_since(ref_time); if interval < broken_pipe_timeout { thread::sleep(Duration::from_millis(100)); continue; } } return Err(DataFusionError::Execution(e.to_string())); } Ok(()) } // This test provides a relatively realistic end-to-end scenario where // we swap join sides to accommodate a FIFO source. #[rstest] #[timeout(std::time::Duration::from_secs(30))] #[tokio::test(flavor = "multi_thread", worker_threads = 8)] async fn
( #[values(true, false)] unbounded_file: bool, ) -> Result<()> { // Create session context let config = SessionConfig::new() .with_batch_size(TEST_BATCH_SIZE) .with_collect_statistics(false) .with_target_partitions(1); let ctx = SessionContext::with_config(config); // To make unbounded deterministic let waiting = Arc::new(AtomicBool::new(unbounded_file)); // Create a new temporary FIFO file let tmp_dir = TempDir::new()?; let fifo_path = create_fifo_file(&tmp_dir, &format!("fifo_{unbounded_file:?}.csv"))?; // Execution can calculated at least one RecordBatch after the number of // "joinable_lines_length" lines are read. let joinable_lines_length = (TEST_DATA_SIZE as f64 * TEST_JOIN_RATIO).round() as usize; // The row including "a" is joinable with aggregate_test_100.c1 let joinable_iterator = (0..joinable_lines_length).map(|_| "a".to_string()); let second_joinable_iterator = (0..joinable_lines_length).map(|_| "a".to_string()); // The row including "zzz" is not joinable with aggregate_test_100.c1 let non_joinable_iterator = (0..(TEST_DATA_SIZE - joinable_lines_length)).map(|_| "zzz".to_string()); let lines = joinable_iterator .chain(non_joinable_iterator) .chain(second_joinable_iterator) .zip(0..TEST_DATA_SIZE) .map(|(a1, a2)| format!("{a1},{a2}\n")) .collect::<Vec<_>>(); // Create writing threads for the left and right FIFO files let task = create_writing_thread( fifo_path.clone(), "a1,a2\n".to_owned(), lines, waiting.clone(), joinable_lines_length, ); // Data Schema let schema = Arc::new(Schema::new(vec![ Field::new("a1", DataType::Utf8, false), Field::new("a2", DataType::UInt32, false), ])); // Create a file with bounded or unbounded flag. ctx.register_csv( "left", fifo_path.as_os_str().to_str().unwrap(), CsvReadOptions::new() .schema(schema.as_ref()) .mark_infinite(unbounded_file), ) .await?; // Register right table let schema = aggr_test_schema(); let test_data = arrow_test_data(); ctx.register_csv( "right", &format!("{test_data}/csv/aggregate_test_100.csv"), CsvReadOptions::new().schema(schema.as_ref()), ) .await?; // Execute the query let df = ctx.sql("SELECT t1.a2, t2.c1, t2.c4, t2.c5 FROM left as t1 JOIN right as t2 ON t1.a1 = t2.c1").await?; let mut stream = df.execute_stream().await?; while (stream.next().await).is_some() { waiting.store(false, Ordering::SeqCst); } task.join().unwrap(); Ok(()) } #[derive(Debug, PartialEq)] enum JoinOperation { LeftUnmatched, RightUnmatched, Equal, } fn create_writing_thread( file_path: PathBuf, header: String, lines: Vec<String>, waiting_lock: Arc<AtomicBool>, wait_until: usize, ) -> JoinHandle<()> { // Timeout for a long period of BrokenPipe error let broken_pipe_timeout = Duration::from_secs(10); // Spawn a new thread to write to the FIFO file thread::spawn(move || { let file = OpenOptions::new().write(true).open(file_path).unwrap(); // Reference time to use when deciding to fail the test let execution_start = Instant::now(); write_to_fifo(&file, &header, execution_start, broken_pipe_timeout).unwrap(); for (cnt, line) in enumerate(lines) { while waiting_lock.load(Ordering::SeqCst) && cnt > wait_until { thread::sleep(Duration::from_millis(50)); } write_to_fifo(&file, &line, execution_start, broken_pipe_timeout) .unwrap(); } drop(file); }) } // This test provides a relatively realistic end-to-end scenario where // we change the join into a [SymmetricHashJoin] to accommodate two // unbounded (FIFO) sources. #[rstest] #[timeout(std::time::Duration::from_secs(30))] #[tokio::test(flavor = "multi_thread")] #[ignore] async fn unbounded_file_with_symmetric_join() -> Result<()> { // Create session context let config = SessionConfig::new() .with_batch_size(TEST_BATCH_SIZE) .set_bool("datafusion.execution.coalesce_batches", false) .with_target_partitions(1); let ctx = SessionContext::with_config(config); // Tasks let mut tasks: Vec<JoinHandle<()>> = vec![]; // Join filter let a1_iter = 0..TEST_DATA_SIZE; // Join key let a2_iter = (0..TEST_DATA_SIZE).map(|x| x % 10); let lines = a1_iter .zip(a2_iter) .map(|(a1, a2)| format!("{a1},{a2}\n")) .collect::<Vec<_>>(); // Create a new temporary FIFO file let tmp_dir = TempDir::new()?; // Create a FIFO file for the left input source. let left_fifo = create_fifo_file(&tmp_dir, "left.csv")?; // Create a FIFO file for the right input source. let right_fifo = create_fifo_file(&tmp_dir, "right.csv")?; // Create a mutex for tracking if the right input source is waiting for data. let waiting = Arc::new(AtomicBool::new(true)); // Create writing threads for the left and right FIFO files tasks.push(create_writing_thread( left_fifo.clone(), "a1,a2\n".to_owned(), lines.clone(), waiting.clone(), TEST_BATCH_SIZE, )); tasks.push(create_writing_thread( right_fifo.clone(), "a1,a2\n".to_owned(), lines.clone(), waiting.clone(), TEST_BATCH_SIZE, )); // Create schema let schema = Arc::new(Schema::new(vec![ Field::new("a1", DataType::UInt32, false), Field::new("a2", DataType::UInt32, false), ])); // Specify the ordering: let file_sort_order = vec![[datafusion_expr::col("a1")] .into_iter() .map(|e| { let ascending = true; let nulls_first = false; e.sort(ascending, nulls_first) }) .collect::<Vec<_>>()]; // Set unbounded sorted files read configuration register_unbounded_file_with_ordering( &ctx, schema.clone(), &left_fifo, "left", file_sort_order.clone(), true, ) .await?; register_unbounded_file_with_ordering( &ctx, schema, &right_fifo, "right", file_sort_order, true, ) .await?; // Execute the query, with no matching rows. (since key is modulus
unbounded_file_with_swapped_join
identifier_name
fifo.rs
) = file.write_all(line.as_bytes()) { if e.raw_os_error().unwrap() == 32 { let interval = Instant::now().duration_since(ref_time); if interval < broken_pipe_timeout { thread::sleep(Duration::from_millis(100)); continue; } } return Err(DataFusionError::Execution(e.to_string())); } Ok(()) } // This test provides a relatively realistic end-to-end scenario where // we swap join sides to accommodate a FIFO source. #[rstest] #[timeout(std::time::Duration::from_secs(30))] #[tokio::test(flavor = "multi_thread", worker_threads = 8)] async fn unbounded_file_with_swapped_join( #[values(true, false)] unbounded_file: bool, ) -> Result<()> { // Create session context let config = SessionConfig::new() .with_batch_size(TEST_BATCH_SIZE) .with_collect_statistics(false) .with_target_partitions(1); let ctx = SessionContext::with_config(config); // To make unbounded deterministic let waiting = Arc::new(AtomicBool::new(unbounded_file)); // Create a new temporary FIFO file let tmp_dir = TempDir::new()?; let fifo_path = create_fifo_file(&tmp_dir, &format!("fifo_{unbounded_file:?}.csv"))?; // Execution can calculated at least one RecordBatch after the number of // "joinable_lines_length" lines are read. let joinable_lines_length = (TEST_DATA_SIZE as f64 * TEST_JOIN_RATIO).round() as usize; // The row including "a" is joinable with aggregate_test_100.c1 let joinable_iterator = (0..joinable_lines_length).map(|_| "a".to_string()); let second_joinable_iterator = (0..joinable_lines_length).map(|_| "a".to_string()); // The row including "zzz" is not joinable with aggregate_test_100.c1 let non_joinable_iterator = (0..(TEST_DATA_SIZE - joinable_lines_length)).map(|_| "zzz".to_string()); let lines = joinable_iterator .chain(non_joinable_iterator) .chain(second_joinable_iterator) .zip(0..TEST_DATA_SIZE) .map(|(a1, a2)| format!("{a1},{a2}\n")) .collect::<Vec<_>>(); // Create writing threads for the left and right FIFO files let task = create_writing_thread( fifo_path.clone(), "a1,a2\n".to_owned(), lines, waiting.clone(), joinable_lines_length, ); // Data Schema let schema = Arc::new(Schema::new(vec![ Field::new("a1", DataType::Utf8, false), Field::new("a2", DataType::UInt32, false), ])); // Create a file with bounded or unbounded flag. ctx.register_csv( "left", fifo_path.as_os_str().to_str().unwrap(), CsvReadOptions::new() .schema(schema.as_ref()) .mark_infinite(unbounded_file), ) .await?; // Register right table let schema = aggr_test_schema(); let test_data = arrow_test_data(); ctx.register_csv( "right", &format!("{test_data}/csv/aggregate_test_100.csv"), CsvReadOptions::new().schema(schema.as_ref()), ) .await?; // Execute the query let df = ctx.sql("SELECT t1.a2, t2.c1, t2.c4, t2.c5 FROM left as t1 JOIN right as t2 ON t1.a1 = t2.c1").await?; let mut stream = df.execute_stream().await?; while (stream.next().await).is_some() { waiting.store(false, Ordering::SeqCst); } task.join().unwrap(); Ok(()) } #[derive(Debug, PartialEq)] enum JoinOperation { LeftUnmatched, RightUnmatched, Equal, } fn create_writing_thread( file_path: PathBuf, header: String, lines: Vec<String>, waiting_lock: Arc<AtomicBool>, wait_until: usize, ) -> JoinHandle<()> { // Timeout for a long period of BrokenPipe error let broken_pipe_timeout = Duration::from_secs(10); // Spawn a new thread to write to the FIFO file thread::spawn(move || { let file = OpenOptions::new().write(true).open(file_path).unwrap(); // Reference time to use when deciding to fail the test let execution_start = Instant::now(); write_to_fifo(&file, &header, execution_start, broken_pipe_timeout).unwrap(); for (cnt, line) in enumerate(lines) { while waiting_lock.load(Ordering::SeqCst) && cnt > wait_until { thread::sleep(Duration::from_millis(50)); } write_to_fifo(&file, &line, execution_start, broken_pipe_timeout) .unwrap(); } drop(file); }) } // This test provides a relatively realistic end-to-end scenario where // we change the join into a [SymmetricHashJoin] to accommodate two // unbounded (FIFO) sources. #[rstest] #[timeout(std::time::Duration::from_secs(30))] #[tokio::test(flavor = "multi_thread")] #[ignore] async fn unbounded_file_with_symmetric_join() -> Result<()> { // Create session context let config = SessionConfig::new() .with_batch_size(TEST_BATCH_SIZE) .set_bool("datafusion.execution.coalesce_batches", false) .with_target_partitions(1); let ctx = SessionContext::with_config(config); // Tasks let mut tasks: Vec<JoinHandle<()>> = vec![]; // Join filter let a1_iter = 0..TEST_DATA_SIZE; // Join key let a2_iter = (0..TEST_DATA_SIZE).map(|x| x % 10); let lines = a1_iter .zip(a2_iter) .map(|(a1, a2)| format!("{a1},{a2}\n")) .collect::<Vec<_>>(); // Create a new temporary FIFO file let tmp_dir = TempDir::new()?; // Create a FIFO file for the left input source. let left_fifo = create_fifo_file(&tmp_dir, "left.csv")?; // Create a FIFO file for the right input source. let right_fifo = create_fifo_file(&tmp_dir, "right.csv")?; // Create a mutex for tracking if the right input source is waiting for data. let waiting = Arc::new(AtomicBool::new(true)); // Create writing threads for the left and right FIFO files tasks.push(create_writing_thread( left_fifo.clone(), "a1,a2\n".to_owned(), lines.clone(), waiting.clone(), TEST_BATCH_SIZE, )); tasks.push(create_writing_thread( right_fifo.clone(), "a1,a2\n".to_owned(), lines.clone(), waiting.clone(), TEST_BATCH_SIZE, )); // Create schema let schema = Arc::new(Schema::new(vec![ Field::new("a1", DataType::UInt32, false), Field::new("a2", DataType::UInt32, false), ])); // Specify the ordering: let file_sort_order = vec![[datafusion_expr::col("a1")] .into_iter() .map(|e| { let ascending = true; let nulls_first = false; e.sort(ascending, nulls_first) }) .collect::<Vec<_>>()]; // Set unbounded sorted files read configuration register_unbounded_file_with_ordering( &ctx, schema.clone(), &left_fifo, "left", file_sort_order.clone(), true, ) .await?; register_unbounded_file_with_ordering( &ctx, schema, &right_fifo, "right", file_sort_order, true, ) .await?; // Execute the query, with no matching rows. (since key is modulus 10) let df = ctx .sql( "SELECT t1.a1, t1.a2, t2.a1, t2.a2 FROM left as t1 FULL JOIN right as t2 ON t1.a2 = t2.a2 AND t1.a1 > t2.a1 + 4 AND t1.a1 < t2.a1 + 9", ) .await?; let mut stream = df.execute_stream().await?; let mut operations = vec![]; // Partial. while let Some(Ok(batch)) = stream.next().await { waiting.store(false, Ordering::SeqCst); let left_unmatched = batch.column(2).null_count(); let right_unmatched = batch.column(0).null_count(); let op = if left_unmatched == 0 && right_unmatched == 0 { JoinOperation::Equal } else if right_unmatched > left_unmatched
{ JoinOperation::RightUnmatched }
conditional_block
fifo.rs
00 dataset. We will use these joinable keys for understanding // incremental execution. const TEST_JOIN_RATIO: f64 = 0.01; fn create_fifo_file(tmp_dir: &TempDir, file_name: &str) -> Result<PathBuf> { let file_path = tmp_dir.path().join(file_name); // Simulate an infinite environment via a FIFO file if let Err(e) = unistd::mkfifo(&file_path, stat::Mode::S_IRWXU) { Err(DataFusionError::Execution(e.to_string())) } else { Ok(file_path) } } fn write_to_fifo( mut file: &File, line: &str, ref_time: Instant, broken_pipe_timeout: Duration, ) -> Result<()> { // We need to handle broken pipe error until the reader is ready. This // is why we use a timeout to limit the wait duration for the reader. // If the error is different than broken pipe, we fail immediately. while let Err(e) = file.write_all(line.as_bytes()) { if e.raw_os_error().unwrap() == 32 { let interval = Instant::now().duration_since(ref_time); if interval < broken_pipe_timeout { thread::sleep(Duration::from_millis(100)); continue;
} // This test provides a relatively realistic end-to-end scenario where // we swap join sides to accommodate a FIFO source. #[rstest] #[timeout(std::time::Duration::from_secs(30))] #[tokio::test(flavor = "multi_thread", worker_threads = 8)] async fn unbounded_file_with_swapped_join( #[values(true, false)] unbounded_file: bool, ) -> Result<()> { // Create session context let config = SessionConfig::new() .with_batch_size(TEST_BATCH_SIZE) .with_collect_statistics(false) .with_target_partitions(1); let ctx = SessionContext::with_config(config); // To make unbounded deterministic let waiting = Arc::new(AtomicBool::new(unbounded_file)); // Create a new temporary FIFO file let tmp_dir = TempDir::new()?; let fifo_path = create_fifo_file(&tmp_dir, &format!("fifo_{unbounded_file:?}.csv"))?; // Execution can calculated at least one RecordBatch after the number of // "joinable_lines_length" lines are read. let joinable_lines_length = (TEST_DATA_SIZE as f64 * TEST_JOIN_RATIO).round() as usize; // The row including "a" is joinable with aggregate_test_100.c1 let joinable_iterator = (0..joinable_lines_length).map(|_| "a".to_string()); let second_joinable_iterator = (0..joinable_lines_length).map(|_| "a".to_string()); // The row including "zzz" is not joinable with aggregate_test_100.c1 let non_joinable_iterator = (0..(TEST_DATA_SIZE - joinable_lines_length)).map(|_| "zzz".to_string()); let lines = joinable_iterator .chain(non_joinable_iterator) .chain(second_joinable_iterator) .zip(0..TEST_DATA_SIZE) .map(|(a1, a2)| format!("{a1},{a2}\n")) .collect::<Vec<_>>(); // Create writing threads for the left and right FIFO files let task = create_writing_thread( fifo_path.clone(), "a1,a2\n".to_owned(), lines, waiting.clone(), joinable_lines_length, ); // Data Schema let schema = Arc::new(Schema::new(vec![ Field::new("a1", DataType::Utf8, false), Field::new("a2", DataType::UInt32, false), ])); // Create a file with bounded or unbounded flag. ctx.register_csv( "left", fifo_path.as_os_str().to_str().unwrap(), CsvReadOptions::new() .schema(schema.as_ref()) .mark_infinite(unbounded_file), ) .await?; // Register right table let schema = aggr_test_schema(); let test_data = arrow_test_data(); ctx.register_csv( "right", &format!("{test_data}/csv/aggregate_test_100.csv"), CsvReadOptions::new().schema(schema.as_ref()), ) .await?; // Execute the query let df = ctx.sql("SELECT t1.a2, t2.c1, t2.c4, t2.c5 FROM left as t1 JOIN right as t2 ON t1.a1 = t2.c1").await?; let mut stream = df.execute_stream().await?; while (stream.next().await).is_some() { waiting.store(false, Ordering::SeqCst); } task.join().unwrap(); Ok(()) } #[derive(Debug, PartialEq)] enum JoinOperation { LeftUnmatched, RightUnmatched, Equal, } fn create_writing_thread( file_path: PathBuf, header: String, lines: Vec<String>, waiting_lock: Arc<AtomicBool>, wait_until: usize, ) -> JoinHandle<()> { // Timeout for a long period of BrokenPipe error let broken_pipe_timeout = Duration::from_secs(10); // Spawn a new thread to write to the FIFO file thread::spawn(move || { let file = OpenOptions::new().write(true).open(file_path).unwrap(); // Reference time to use when deciding to fail the test let execution_start = Instant::now(); write_to_fifo(&file, &header, execution_start, broken_pipe_timeout).unwrap(); for (cnt, line) in enumerate(lines) { while waiting_lock.load(Ordering::SeqCst) && cnt > wait_until { thread::sleep(Duration::from_millis(50)); } write_to_fifo(&file, &line, execution_start, broken_pipe_timeout) .unwrap(); } drop(file); }) } // This test provides a relatively realistic end-to-end scenario where // we change the join into a [SymmetricHashJoin] to accommodate two // unbounded (FIFO) sources. #[rstest] #[timeout(std::time::Duration::from_secs(30))] #[tokio::test(flavor = "multi_thread")] #[ignore] async fn unbounded_file_with_symmetric_join() -> Result<()> { // Create session context let config = SessionConfig::new() .with_batch_size(TEST_BATCH_SIZE) .set_bool("datafusion.execution.coalesce_batches", false) .with_target_partitions(1); let ctx = SessionContext::with_config(config); // Tasks let mut tasks: Vec<JoinHandle<()>> = vec![]; // Join filter let a1_iter = 0..TEST_DATA_SIZE; // Join key let a2_iter = (0..TEST_DATA_SIZE).map(|x| x % 10); let lines = a1_iter .zip(a2_iter) .map(|(a1, a2)| format!("{a1},{a2}\n")) .collect::<Vec<_>>(); // Create a new temporary FIFO file let tmp_dir = TempDir::new()?; // Create a FIFO file for the left input source. let left_fifo = create_fifo_file(&tmp_dir, "left.csv")?; // Create a FIFO file for the right input source. let right_fifo = create_fifo_file(&tmp_dir, "right.csv")?; // Create a mutex for tracking if the right input source is waiting for data. let waiting = Arc::new(AtomicBool::new(true)); // Create writing threads for the left and right FIFO files tasks.push(create_writing_thread( left_fifo.clone(), "a1,a2\n".to_owned(), lines.clone(), waiting.clone(), TEST_BATCH_SIZE, )); tasks.push(create_writing_thread( right_fifo.clone(), "a1,a2\n".to_owned(), lines.clone(), waiting.clone(), TEST_BATCH_SIZE, )); // Create schema let schema = Arc::new(Schema::new(vec![ Field::new("a1", DataType::UInt32, false), Field::new("a2", DataType::UInt32, false), ])); // Specify the ordering: let file_sort_order = vec![[datafusion_expr::col("a1")] .into_iter() .map(|e| { let ascending = true; let nulls_first = false; e.sort(ascending, nulls_first) }) .collect::<Vec<_>>()]; // Set unbounded sorted files read configuration register_unbounded_file_with_ordering( &ctx, schema.clone(), &left_fifo, "left", file_sort_order.clone(), true, ) .await?; register_unbounded_file_with_ordering( &ctx, schema, &right_fifo, "right", file_sort_order, true, ) .await?; // Execute the query, with no matching rows. (since key is modulus
} } return Err(DataFusionError::Execution(e.to_string())); } Ok(())
random_line_split
gpt.go
return p, nil } func MustParseGUID(guid string) GUID { p, err := ParseGUID(guid) if err != nil { panic(err) } return p } func (p GUID) String() string { return fmt.Sprintf("%X-%X-%X-%X-%X", endian.Read32be(p[0:]), endian.Read32be(p[4:]), endian.Read32be(p[6:]), endian.Read32be(p[8:]), endian.Read48be(p[10:]), ) } var Parts = []struct { Name string Desc string GUID GUID }{ {"unused", "Unused entry", MustParseGUID("00000000-0000-0000-0000-000000000000")}, {"mbr", "MBR", MustParseGUID("024DEE41-33E7-11D3-9D69-0008C781F39F")}, {"efi", "EFI System", MustParseGUID("C12A7328-F81F-11D2-BA4B-00A0C93EC93B")}, {"bios", "BIOS Boot", MustParseGUID("21686148-6449-6E6F-744E-656564454649")}, {"iffs", "Intel Fast Flash", MustParseGUID("D3BFE2DE-3DAF-11DF-BA40-E3A556D89593")}, {"sony", "Sony boot", MustParseGUID("F4019732-066E-4E12-8273-346C5641494F")}, {"lenovo", "Lenovo boot", MustParseGUID("BFBFAFE7-A34F-448A-9A5B-6213EB736C22")}, {"msr", "Microsoft Reserved", MustParseGUID("E3C9E316-0B5C-4DB8-817D-F92DF00215AE")}, {"dos", "Microsoft Basic data", MustParseGUID("EBD0A0A2-B9E5-4433-87C0-68B6B72699C7")}, {"ldmm", "Microsoft Logical Disk Manager metadata", MustParseGUID("5808C8AA-7E8F-42E0-85D2-E1E90434CFB3")}, {"ldmd", "Microsoft Logical Disk Manager data", MustParseGUID("AF9B60A0-1431-4F62-BC68-3311714A69AD")}, {"recovery", "Windows Recovery Environment", MustParseGUID("DE94BBA4-06D1-4D40-A16A-BFD50179D6AC")}, {"gpfs", "IBM General Parallel File System", MustParseGUID("37AFFC90-EF7D-4E96-91C3-2D7AE055B174")}, {"storagespaces", "Storage Spaces", MustParseGUID("E75CAF8F-F680-4CEE-AFA3-B001E56EFC2D")}, {"hpuxdata", "HP-UX Data", MustParseGUID("75894C1E-3AEB-11D3-B7C1-7B03A0000000")}, {"hpuxserv", "HP-UX Service", MustParseGUID("E2A1E728-32E3-11D6-A682-7B03A0000000")}, {"linuxdata", "Linux Data", MustParseGUID("0FC63DAF-8483-4772-8E79-3D69D8477DE4")}, {"linuxraid", "Linux RAID", MustParseGUID("A19D880F-05FC-4D3B-A006-743F0F84911E")}, {"linuxrootx86", "Linux Root (x86)", MustParseGUID("44479540-F297-41B2-9AF7-D131D5F0458A")}, {"linuxrootx86_64", "Linux Root (x86-64)", MustParseGUID("4F68BCE3-E8CD-4DB1-96E7-FBCAF984B709")}, {"linuxrootarm", "Linux Root (ARM)", MustParseGUID("69DAD710-2CE4-4E3C-B16C-21A1D49ABED3")}, {"linuxrootaarch64", "Linux Root (ARM)", MustParseGUID("B921B045-1DF0-41C3-AF44-4C6F280D3FAE")}, {"linuxswap", "Linux Swap", MustParseGUID("0657FD6D-A4AB-43C4-84E5-0933C84B4F4F")}, {"linuxlvm", "Linux Logical Volume Manager", MustParseGUID("E6D6D379-F507-44C2-A23C-238F2A3DF928")}, {"linuxhome", "Linux /home", MustParseGUID("933AC7E1-2EB4-4F13-B844-0E14E2AEF915")}, {"linuxsrv", "Linux /srv", MustParseGUID("3B8F8425-20E0-4F3B-907F-1A25A76F98E8")}, {"linuxcrypt", "Linux Plain dm-crypt", MustParseGUID("7FFEC5C9-2D00-49B7-8941-3EA10A5586B7")}, {"luks", "LUKS", MustParseGUID("CA7D7CCB-63ED-4C53-861C-1742536059CC")}, {"linuxreserved", "Linux Reserved", MustParseGUID("8DA63339-0007-60C0-C436-083AC8230908")}, {"fbsdboot", "FreeBSD Boot", MustParseGUID("83BD6B9D-7F41-11DC-BE0B-001560B84F0F")}, {"fbsddata", "FreeBSD Data", MustParseGUID("516E7CB4-6ECF-11D6-8FF8-00022D09712B")}, {"fbsdswap", "FreeBSD Swap", MustParseGUID("516E7CB5-6ECF-11D6-8FF8-00022D09712B")}, {"fbsdufs", "FreeBSD Unix File System", MustParseGUID("516E7CB6-6ECF-11D6-8FF8-00022D09712B")}, {"fbsdvvm", "FreeBSD Vinum volume manager", MustParseGUID("516E7CB8-6ECF-11D6-8FF8-00022D09712B")}, {"fbsdzfs", "FreeBSD ZFS", MustParseGUID("516E7CBA-6ECF-11D6-8FF8-00022D09712B")}, {"applehfs", "Apple HFS+", MustParseGUID("48465300
{ var ( a uint32 b, c, d uint16 e uint64 p [16]byte ) n, err := fmt.Sscanf(guid, "%x-%x-%x-%x-%x", &a, &b, &c, &d, &e) if err != nil { return p, err } if n != 5 { return p, errors.New("invalid GUID format") } endian.Put32le(p[0:], a) endian.Put16le(p[4:], b) endian.Put16le(p[6:], c) endian.Put16le(p[8:], d) endian.Put48le(p[10:], e)
identifier_body
gpt.go
if d.MBR.Part[0].Type != 0xee { return ErrHeader } d.Header, err = d.readHeader(int64(d.Sectsz)) if err != nil { return err } d.Entries, err = d.readEntry(int64(d.Sectsz * 2)) if err != nil { return err } return nil } func (d *decoder) readHeader(off int64) (Header, error) { var h Header sr := io.NewSectionReader(d.r, off, math.MaxUint32) err := binary.Read(sr, binary.LittleEndian, &h) if err != nil { return h, err } if string(h.Sig[:]) != "EFI PART" { return h, ErrHeader } return h, nil } func (d *decoder) readEntry(off int64) ([]Entry, error) { var entries []Entry h := &d.Header buf := make([]byte, h.Ent) for i := uint32(0); i < h.Ent; i++ { _, err := d.r.ReadAt(buf, off) if err != nil { return nil, err } var entry Entry rd := bytes.NewReader(buf) err = binary.Read(rd, binary.LittleEndian, &entry) entries = append(entries, entry) } return entries, nil } func ParseGUID(guid string) ([16]byte, error) { var ( a uint32 b, c, d uint16 e uint64 p [16]byte ) n, err := fmt.Sscanf(guid, "%x-%x-%x-%x-%x", &a, &b, &c, &d, &e) if err != nil { return p, err } if n != 5 { return p, errors.New("invalid GUID format") } endian.Put32le(p[0:], a) endian.Put16le(p[4:], b) endian.Put16le(p[6:], c) endian.Put16le(p[8:], d) endian.Put48le(p[10:], e) return p, nil } func MustParseGUID(guid string) GUID { p, err := ParseGUID(guid) if err != nil { panic(err) } return p } func (p GUID) String() string { return fmt.Sprintf("%X-%X-%X-%X-%X", endian.Read32be(p[0:]), endian.Read32be(p[4:]), endian.Read32be(p[6:]), endian.Read32be(p[8:]), endian.Read48be(p[10:]), ) } var Parts = []struct { Name string Desc string GUID GUID }{ {"unused", "Unused entry", MustParseGUID("00000000-0000-0000-0000-000000000000")}, {"mbr", "MBR", MustParseGUID("024DEE41-33E7-11D3-9D69-0008C781F39F")}, {"efi", "EFI System", MustParseGUID("C12A7328-F81F-11D2-BA4B-00A0C93EC93B")}, {"bios", "BIOS Boot", MustParseGUID("21686148-6449-6E6F-744E-656564454649")}, {"iffs", "Intel Fast Flash", MustParseGUID("D3BFE2DE-3DAF-11DF-BA40-E3A556D89593")}, {"sony", "Sony boot", MustParseGUID("F4019732-066E-4E12-8273-346C5641494F")}, {"lenovo", "Lenovo boot", MustParseGUID("BFBFAFE7-A34F-448A-9A5B-6213EB736C22")}, {"msr", "Microsoft Reserved", MustParseGUID("E3C9E316-0B5C-4DB8-817D-F92DF00215AE")}, {"dos", "Microsoft Basic data", MustParseGUID("EBD0A0A2-B9E5-4433-87C0-68B6B72699C7")}, {"ldmm", "Microsoft Logical Disk Manager metadata", MustParseGUID("5808C8AA-7E8F-42E0-85D2-E1E90434CFB3")}, {"ldmd", "Microsoft Logical Disk Manager data", MustParseGUID("AF9B60A0-1431-4F62-BC68-3311714A69AD")}, {"recovery", "Windows Recovery Environment", MustParseGUID("DE94BBA4-06D1-4D40-A16A-BFD50179D6AC")}, {"gpfs", "IBM General Parallel File System", MustParseGUID("37AFFC90-EF7D-4E96-91C3-2D7AE055B174")}, {"storagespaces", "Storage Spaces", MustParseGUID("E75CAF8F-F680-4CEE-AFA3-B001E56EFC2D")}, {"hpuxdata", "HP-UX Data", MustParseGUID("75894C1E-3AEB-11D3-B7C1-7B03A0000000")}, {"hpuxserv", "HP-UX Service", MustParseGUID("E2A1E728-32E3-11D6-A682-7B03A0000000")}, {"linuxdata", "Linux Data", MustParseGUID("0FC63DAF-8483-4772-8E79-3D69D8477DE4")}, {"linuxraid", "Linux RAID", MustParseGUID("A19D880F-05FC-4D3B-A006-743F0F84911E")}, {"linuxrootx86", "Linux Root (x86)", MustParseGUID("44479540-F297-41B2-9AF7-D131D5F0458A")}, {"linuxrootx86_64", "Linux Root (x86-64)", MustParseGUID("4F68BCE3-E8CD-4DB1-96E7-FBCAF984B709")}, {"linuxrootarm", "Linux Root (ARM)", MustParseGUID("69DAD710-2CE4-4E3C-B16C-21A1D49ABED3")}, {"linuxrootaarch64", "Linux Root (ARM)", MustParseGUID("B921B045-1DF0-41C3-AF44-4C6F280D3FAE")}, {"linuxswap", "Linux Swap", MustParseGUID("0657FD6D-A4AB-43C4-84E5-0933C84B4F4F")}, {"linuxlvm", "Linux Logical Volume Manager", MustParseGUID("E6D6D379-F507-44C2-A23C-238F2A3DF928")}, {"linuxhome", "Linux /home", MustParseGUID("933AC7E1-2EB4-4F13-B844-0E14E2AEF915")}, {"linuxsrv", "Linux /srv", MustParseGUID("3B8F8425-20E0-4F3B-907F-1A25A76F98E8")}, {"linuxcrypt", "Linux Plain dm-crypt", MustParseGUID("7FFEC5C9-2D00-49B7-8941-3EA10A5586B7")}, {"luks", "LUKS", MustParseGUID("CA7D7CCB-63ED-4C53-861C-1742536059CC")}, {"linuxreserved", "Linux Reserved", MustParseGUID("8DA63339-0007-60C0-C436-083AC8230908")}, {"fbsdboot
}
random_line_split
gpt.go
() error { var err error d.MBR, err = mbr.Open(d.r) if err != nil { return err } if d.MBR.Part[0].Type != 0xee { return ErrHeader } d.Header, err = d.readHeader(int64(d.Sectsz)) if err != nil { return err } d.Entries, err = d.readEntry(int64(d.Sectsz * 2)) if err != nil { return err } return nil } func (d *decoder) readHeader(off int64) (Header, error) { var h Header sr := io.NewSectionReader(d.r, off, math.MaxUint32) err := binary.Read(sr, binary.LittleEndian, &h) if err != nil { return h, err } if string(h.Sig[:]) != "EFI PART" { return h, ErrHeader } return h, nil } func (d *decoder) readEntry(off int64) ([]Entry, error) { var entries []Entry h := &d.Header buf := make([]byte, h.Ent) for i := uint32(0); i < h.Ent; i++ { _, err := d.r.ReadAt(buf, off) if err != nil { return nil, err } var entry Entry rd := bytes.NewReader(buf) err = binary.Read(rd, binary.LittleEndian, &entry) entries = append(entries, entry) } return entries, nil } func ParseGUID(guid string) ([16]byte, error) { var ( a uint32 b, c, d uint16 e uint64 p [16]byte ) n, err := fmt.Sscanf(guid, "%x-%x-%x-%x-%x", &a, &b, &c, &d, &e) if err != nil { return p, err } if n != 5 { return p, errors.New("invalid GUID format") } endian.Put32le(p[0:], a) endian.Put16le(p[4:], b) endian.Put16le(p[6:], c) endian.Put16le(p[8:], d) endian.Put48le(p[10:], e) return p, nil } func MustParseGUID(guid string) GUID { p, err := ParseGUID(guid) if err != nil { panic(err) } return p } func (p GUID) String() string { return fmt.Sprintf("%X-%X-%X-%X-%X", endian.Read32be(p[0:]), endian.Read32be(p[4:]), endian.Read32be(p[6:]), endian.Read32be(p[8:]), endian.Read48be(p[10:]), ) } var Parts = []struct { Name string Desc string GUID GUID }{ {"unused", "Unused entry", MustParseGUID("00000000-0000-0000-0000-000000000000")}, {"mbr", "MBR", MustParseGUID("024DEE41-33E7-11D3-9D69-0008C781F39F")}, {"efi", "EFI System", MustParseGUID("C12A7328-F81F-11D2-BA4B-00A0C93EC93B")}, {"bios", "BIOS Boot", MustParseGUID("21686148-6449-6E6F-744E-656564454649")}, {"iffs", "Intel Fast Flash", MustParseGUID("D3BFE2DE-3DAF-11DF-BA40-E3A556D89593")}, {"sony", "Sony boot", MustParseGUID("F4019732-066E-4E12-8273-346C5641494F")}, {"lenovo", "Lenovo boot", MustParseGUID("BFBFAFE7-A34F-448A-9A5B-6213EB736C22")}, {"msr", "Microsoft Reserved", MustParseGUID("E3C9E316-0B5C-4DB8-817D-F92DF00215AE")}, {"dos", "Microsoft Basic data", MustParseGUID("EBD0A0A2-B9E5-4433-87C0-68B6B72699C7")}, {"ldmm", "Microsoft Logical Disk Manager metadata", MustParseGUID("5808C8AA-7E8F-42E0-85D2-E1E90434CFB3")}, {"ldmd", "Microsoft Logical Disk Manager data", MustParseGUID("AF9B60A0-1431-4F62-BC68-3311714A69AD")}, {"recovery", "Windows Recovery Environment", MustParseGUID("DE94BBA4-06D1-4D40-A16A-BFD50179D6AC")}, {"gpfs", "IBM General Parallel File System", MustParseGUID("37AFFC90-EF7D-4E96-91C3-2D7AE055B174")}, {"storagespaces", "Storage Spaces", MustParseGUID("E75CAF8F-F680-4CEE-AFA3-B001E56EFC2D")}, {"hpuxdata", "HP-UX Data", MustParseGUID("75894C1E-3AEB-11D3-B7C1-7B03A0000000")}, {"hpuxserv", "HP-UX Service", MustParseGUID("E2A1E728-32E3-11D6-A682-7B03A0000000")}, {"linuxdata", "Linux Data", MustParseGUID("0FC63DAF-8483-4772-8E79-3D69D8477DE4")}, {"linuxraid", "Linux RAID", MustParseGUID("A19D880F-05FC-4D3B-A006-743F0F84911E")}, {"linuxrootx86", "Linux Root (x86)", MustParseGUID("44479540-F297-41B2-9AF7-D131D5F0458A")}, {"linuxrootx86_64", "Linux Root (x86-64)", MustParseGUID("4F68BCE3-E8CD-4DB1-96E7-FBCAF984B709")}, {"linuxrootarm", "Linux Root (ARM)", MustParseGUID("69DAD710-2CE4-4E3C-B16C-21A1D49ABED3")}, {"linuxrootaarch64", "Linux Root (ARM)", MustParseGUID("B921B045-1DF0-41C3-AF44-4C6F280D3FAE")}, {"linuxswap", "Linux Swap", MustParseGUID("0657FD6D-A4AB-43C4-84E5-0933C84B4F4F")}, {"linuxlvm", "Linux Logical Volume Manager", MustParseGUID("E6D6D379-F507-44C2-A23C-238F2A3DF928")}, {"linuxhome", "Linux /home", MustParseGUID("933AC7E1-2EB4-4F13-B844-0E14E2AEF915")}, {"linuxsrv", "Linux /srv", MustParseGUID("3B8F8425-20E0-4F3B-907F-1A25A76F98E8")}, {"linuxcrypt", "Linux Plain dm-crypt", MustParseGUID("7FFEC5C9-2D00-49B7-8941-3EA10A5586B7")}, {"luks", "LUKS", MustParseGUID("CA7D7CCB-63ED-4C53-861C-1742536059CC")}, {"linuxreserved", "Linux Reserved", MustParseGUID("8DA63339-000
decode
identifier_name
gpt.go
d := decoder{ r: r, Table: Table{Sectsz: o.Sectsz}, } err := d.decode() if err != nil { return nil, err } return &d.Table, nil } type decoder struct { Table r io.ReaderAt } func (d *decoder) decode() error { var err error d.MBR, err = mbr.Open(d.r) if err != nil { return err } if d.MBR.Part[0].Type != 0xee { return ErrHeader } d.Header, err = d.readHeader(int64(d.Sectsz)) if err != nil { return err } d.Entries, err = d.readEntry(int64(d.Sectsz * 2)) if err != nil { return err } return nil } func (d *decoder) readHeader(off int64) (Header, error) { var h Header sr := io.NewSectionReader(d.r, off, math.MaxUint32) err := binary.Read(sr, binary.LittleEndian, &h) if err != nil { return h, err } if string(h.Sig[:]) != "EFI PART" { return h, ErrHeader } return h, nil } func (d *decoder) readEntry(off int64) ([]Entry, error) { var entries []Entry h := &d.Header buf := make([]byte, h.Ent) for i := uint32(0); i < h.Ent; i++ { _, err := d.r.ReadAt(buf, off) if err != nil { return nil, err } var entry Entry rd := bytes.NewReader(buf) err = binary.Read(rd, binary.LittleEndian, &entry) entries = append(entries, entry) } return entries, nil } func ParseGUID(guid string) ([16]byte, error) { var ( a uint32 b, c, d uint16 e uint64 p [16]byte ) n, err := fmt.Sscanf(guid, "%x-%x-%x-%x-%x", &a, &b, &c, &d, &e) if err != nil { return p, err } if n != 5 { return p, errors.New("invalid GUID format") } endian.Put32le(p[0:], a) endian.Put16le(p[4:], b) endian.Put16le(p[6:], c) endian.Put16le(p[8:], d) endian.Put48le(p[10:], e) return p, nil } func MustParseGUID(guid string) GUID { p, err := ParseGUID(guid) if err != nil { panic(err) } return p } func (p GUID) String() string { return fmt.Sprintf("%X-%X-%X-%X-%X", endian.Read32be(p[0:]), endian.Read32be(p[4:]), endian.Read32be(p[6:]), endian.Read32be(p[8:]), endian.Read48be(p[10:]), ) } var Parts = []struct { Name string Desc string GUID GUID }{ {"unused", "Unused entry", MustParseGUID("00000000-0000-0000-0000-000000000000")}, {"mbr", "MBR", MustParseGUID("024DEE41-33E7-11D3-9D69-0008C781F39F")}, {"efi", "EFI System", MustParseGUID("C12A7328-F81F-11D2-BA4B-00A0C93EC93B")}, {"bios", "BIOS Boot", MustParseGUID("21686148-6449-6E6F-744E-656564454649")}, {"iffs", "Intel Fast Flash", MustParseGUID("D3BFE2DE-3DAF-11DF-BA40-E3A556D89593")}, {"sony", "Sony boot", MustParseGUID("F4019732-066E-4E12-8273-346C5641494F")}, {"lenovo", "Lenovo boot", MustParseGUID("BFBFAFE7-A34F-448A-9A5B-6213EB736C22")}, {"msr", "Microsoft Reserved", MustParseGUID("E3C9E316-0B5C-4DB8-817D-F92DF00215AE")}, {"dos", "Microsoft Basic data", MustParseGUID("EBD0A0A2-B9E5-4433-87C0-68B6B72699C7")}, {"ldmm", "Microsoft Logical Disk Manager metadata", MustParseGUID("5808C8AA-7E8F-42E0-85D2-E1E90434CFB3")}, {"ldmd", "Microsoft Logical Disk Manager data", MustParseGUID("AF9B60A0-1431-4F62-BC68-3311714A69AD")}, {"recovery", "Windows Recovery Environment", MustParseGUID("DE94BBA4-06D1-4D40-A16A-BFD50179D6AC")}, {"gpfs", "IBM General Parallel File System", MustParseGUID("37AFFC90-EF7D-4E96-91C3-2D7AE055B174")}, {"storagespaces", "Storage Spaces", MustParseGUID("E75CAF8F-F680-4CEE-AFA3-B001E56EFC2D")}, {"hpuxdata", "HP-UX Data", MustParseGUID("75894C1E-3AEB-11D3-B7C1-7B03A0000000")}, {"hpuxserv", "HP-UX Service", MustParseGUID("E2A1E728-32E3-11D6-A682-7B03A0000000")}, {"linuxdata", "Linux Data", MustParseGUID("0FC63DAF-8483-4772-8E79-3D69D8477DE4")}, {"linuxraid", "Linux RAID", MustParseGUID("A19D880F-05FC-4D3B-A006-743F0F84911E")}, {"linuxrootx86", "Linux Root (x86)", MustParseGUID("44479540-F297-41B2-9AF7-D131D5F0458A")}, {"linuxrootx86_64", "Linux Root (x86-64)", MustParseGUID("4F68BCE3-E8CD-4DB1-96E7-FBCAF984B709")}, {"linuxrootarm", "Linux Root (ARM)", MustParseGUID("69DAD710-2CE4-4E3C-B16C-21A1D49ABED3")}, {"linuxrootaarch64", "Linux Root (ARM)", MustParseGUID("B921B045-1DF0-41C3-AF44-4C6F280D3FAE")}, {"linuxswap", "Linux Swap", MustParseGUID("0657FD6D-A4AB-43C4-84E5-0933C84B4F4F")}, {"linuxlvm", "Linux Logical Volume Manager", MustParseGUID("E6D6D379-F507-44C2-A23C-238F2A3DF928")}, {"linuxhome", "Linux /home", MustParseGUID("933AC7E1-2EB4-4F13-B844-0E14E2AEF915")}, {"linuxsrv", "Linux /srv", MustParseGUID("3B8F8425-20E0-4F3B-907F-1A25A76F98E8")}, {"linuxcrypt", "Linux Plain dm-crypt", MustParseGUID("7FFEC5C9-2D00-4
{ o = &Option{Sectsz: 512} }
conditional_block
serving.py
. Examples: .. code-block:: python pid_is_exist(pid=8866) ''' try: os.kill(pid, 0) except: return False else: return True @register(name='hub.serving', description='Start Module Serving or Bert Service for online predicting.') class ServingCommand: name = "serving" module_list = [] def dump_pid_file(self): ''' Write PID info to file. ''' pid = os.getpid() filepath = os.path.join(CONF_HOME, "serving_" + str(self.args.port) + ".json") if os.path.exists(filepath): os.remove(filepath) with open(filepath, "w") as fp: info = {"pid": pid, "module": self.args.modules, "start_time": time.time()} json.dump(info, fp) @staticmethod def load_pid_file(filepath: str, port: int = None): ''' Read PID info from file. ''' if port is None: port = os.path.basename(filepath).split(".")[0].split("_")[1] if not os.path.exists(filepath): log.logger.error( "PaddleHub Serving config file is not exists, please confirm the port [%s] you specified is correct." % port) return False with open(filepath, "r") as fp: info = json.load(fp) return info def stop_serving(self, port: int): ''' Stop PaddleHub-Serving by port. ''' filepath = os.path.join(CONF_HOME, "serving_" + str(port) + ".json") info = self.load_pid_file(filepath, port) if info is False: return pid = info["pid"] module = info["module"] start_time = info["start_time"] CacheUpdater("hub_serving_stop", module=module, addition={"period_time": time.time() - start_time}).start() if os.path.exists(filepath): os.remove(filepath) if not pid_is_exist(pid): log.logger.info("PaddleHub Serving has been stopped.") return log.logger.info("PaddleHub Serving will stop.") if platform.system() == "Windows": os.kill(pid, signal.SIGTERM) else: try: os.killpg(pid, signal.SIGTERM) except ProcessLookupError: os.kill(pid, signal.SIGTERM) @staticmethod def start_bert_serving(args): ''' Start bert serving server. ''' if platform.system() != "Linux": log.logger.error("Error. Bert Service only support linux.") return False if is_port_occupied("127.0.0.1", args.port) is True: log.logger.error("Port %s is occupied, please change it." % args.port) return False from paddle_gpu_serving.run import BertServer bs = BertServer(with_gpu=args.use_gpu) bs.with_model(model_name=args.modules[0]) CacheUpdater("hub_bert_service", module=args.modules[0], version="0.0.0").start() bs.run(gpu_index=args.gpu, port=int(args.port)) def preinstall_modules(self): ''' Install module by PaddleHub and get info of this module. ''' for key, value in self.modules_info.items(): init_args = value["init_args"] CacheUpdater("hub_serving_start", module=key, version=init_args.get("version", "0.0.0")).start() if "directory" not in init_args: init_args.update({"name": key}) m = hub.Module(**init_args) method_name = m.serving_func_name if method_name is None: raise RuntimeError("{} cannot be use for " "predicting".format(key)) exit(1) serving_method = getattr(m, method_name) category = str(m.type).split("/")[0].upper() self.modules_info[key].update({ "method_name": method_name, "version": m.version, "category": category, "module": m, "name": m.name, "serving_method": serving_method }) def start_app_with_args(self): ''' Start one PaddleHub-Serving instance by arguments with gunicorn. ''' module = self.modules_info if module is not None: port = self.args.port if is_port_occupied("127.0.0.1", port) is True: log.logger.error("Port %s is occupied, please change it." % port) return False self.preinstall_modules() options = {"bind": "0.0.0.0:%s" % port, "workers": self.args.workers} self.dump_pid_file() StandaloneApplication(app.create_app(init_flag=False, configs=self.modules_info), options).run() else: log.logger.error("Lack of necessary parameters!") def start_zmq_serving_with_args(self): ''' Start one PaddleHub-Serving instance by arguments with zmq. ''' if self.modules_info is not None: for module, info in self.modules_info.items(): CacheUpdater("hub_serving_start", module=module, version=info['init_args']['version']).start() front_port = self.args.port if is_port_occupied("127.0.0.1", front_port) is True: log.logger.error("Port %s is occupied, please change it." % front_port) return False back_port = int(front_port) + 1 for index in range(100): if not is_port_occupied("127.0.0.1", back_port): break else: back_port = int(back_port) + 1 else: raise RuntimeError( "Port from %s to %s is occupied, please use another port" % (int(front_port) + 1, back_port)) self.dump_pid_file() run_all(self.modules_info, self.args.gpu, front_port, back_port) else: log.logger.error("Lack of necessary parameters!") def start_single_app_with_args(self): ''' Start one PaddleHub-Serving instance by arguments with flask. ''' module = self.modules_info if module is not None: port = self.args.port if is_port_occupied("127.0.0.1", port) is True: log.logger.error("Port %s is occupied, please change it." % port) return False self.preinstall_modules() self.dump_pid_file() app.run(configs=self.modules_info, port=port) else: log.logger.error("Lack of necessary parameters!") def start_serving(self): ''' Start PaddleHub-Serving with flask and gunicorn ''' if self.args.use_gpu:
else: if self.args.use_multiprocess: if platform.system() == "Windows": log.logger.warning( "Warning: Windows cannot use multiprocess working mode, PaddleHub Serving will switch to single process mode" ) self.start_single_app_with_args() else: self.start_app_with_args() else: self.start_single_app_with_args() @staticmethod def show_help(): str = "serving <option>\n" str += "\tManage PaddleHub Serving.\n" str += "sub command:\n" str += "1. start\n" str += "\tStart PaddleHub Serving.\n" str += "2. stop\n" str += "\tStop PaddleHub Serving.\n" str += "3. start bert_service\n" str += "\tStart Bert Service.\n" str += "\n" str += "[start] option:\n" str += "--modules/-m [module1==version, module2==version...]\n" str += "\tPre-install modules via the parameter list.\n" str += "--port/-p XXXX\n" str += "\tUse port XXXX for serving.\n" str += "--use_multiprocess\n" str += "\tChoose multoprocess mode, cannot be use on Windows.\n" str += "--modules_info\n" str += "\tSet module config in PaddleHub Serving." str += "--config/-c file_path\n" str += "\tUse configs in file to start PaddleHub Serving. " str += "Other parameters will be ignored if you specify the parameter.\n" str += "\n" str += "[stop] option:\n" str += "--port/-p XXXX\n" str += "\tStop PaddleHub Serving on port XXXX safely.\n" str += "\n" str += "[start bert_service] option:\n" str += "--modules/-m\n" str += "\tPre-install modules via the parameter.\n" str += "--port/-p XXXX\n" str += "\tUse port XXXX for serving.\n" str += "--use_gpu\n" str += "\tUse gpu for predicting if specifies the parameter.\n" str += "--gpu\n" str += "\tSpecify the GPU devices to use.\n"
if self.args.use_multiprocess: log.logger.warning('`use_multiprocess` will be ignored if specify `use_gpu`.') self.start_zmq_serving_with_args()
conditional_block
serving.py
. Examples: .. code-block:: python pid_is_exist(pid=8866) ''' try: os.kill(pid, 0) except: return False else: return True @register(name='hub.serving', description='Start Module Serving or Bert Service for online predicting.') class ServingCommand: name = "serving" module_list = [] def dump_pid_file(self): ''' Write PID info to file. ''' pid = os.getpid() filepath = os.path.join(CONF_HOME, "serving_" + str(self.args.port) + ".json") if os.path.exists(filepath): os.remove(filepath) with open(filepath, "w") as fp: info = {"pid": pid, "module": self.args.modules, "start_time": time.time()} json.dump(info, fp) @staticmethod def load_pid_file(filepath: str, port: int = None): ''' Read PID info from file. ''' if port is None: port = os.path.basename(filepath).split(".")[0].split("_")[1] if not os.path.exists(filepath): log.logger.error( "PaddleHub Serving config file is not exists, please confirm the port [%s] you specified is correct." % port) return False with open(filepath, "r") as fp: info = json.load(fp) return info def stop_serving(self, port: int): ''' Stop PaddleHub-Serving by port. ''' filepath = os.path.join(CONF_HOME, "serving_" + str(port) + ".json") info = self.load_pid_file(filepath, port) if info is False: return pid = info["pid"] module = info["module"] start_time = info["start_time"] CacheUpdater("hub_serving_stop", module=module, addition={"period_time": time.time() - start_time}).start()
if not pid_is_exist(pid): log.logger.info("PaddleHub Serving has been stopped.") return log.logger.info("PaddleHub Serving will stop.") if platform.system() == "Windows": os.kill(pid, signal.SIGTERM) else: try: os.killpg(pid, signal.SIGTERM) except ProcessLookupError: os.kill(pid, signal.SIGTERM) @staticmethod def start_bert_serving(args): ''' Start bert serving server. ''' if platform.system() != "Linux": log.logger.error("Error. Bert Service only support linux.") return False if is_port_occupied("127.0.0.1", args.port) is True: log.logger.error("Port %s is occupied, please change it." % args.port) return False from paddle_gpu_serving.run import BertServer bs = BertServer(with_gpu=args.use_gpu) bs.with_model(model_name=args.modules[0]) CacheUpdater("hub_bert_service", module=args.modules[0], version="0.0.0").start() bs.run(gpu_index=args.gpu, port=int(args.port)) def preinstall_modules(self): ''' Install module by PaddleHub and get info of this module. ''' for key, value in self.modules_info.items(): init_args = value["init_args"] CacheUpdater("hub_serving_start", module=key, version=init_args.get("version", "0.0.0")).start() if "directory" not in init_args: init_args.update({"name": key}) m = hub.Module(**init_args) method_name = m.serving_func_name if method_name is None: raise RuntimeError("{} cannot be use for " "predicting".format(key)) exit(1) serving_method = getattr(m, method_name) category = str(m.type).split("/")[0].upper() self.modules_info[key].update({ "method_name": method_name, "version": m.version, "category": category, "module": m, "name": m.name, "serving_method": serving_method }) def start_app_with_args(self): ''' Start one PaddleHub-Serving instance by arguments with gunicorn. ''' module = self.modules_info if module is not None: port = self.args.port if is_port_occupied("127.0.0.1", port) is True: log.logger.error("Port %s is occupied, please change it." % port) return False self.preinstall_modules() options = {"bind": "0.0.0.0:%s" % port, "workers": self.args.workers} self.dump_pid_file() StandaloneApplication(app.create_app(init_flag=False, configs=self.modules_info), options).run() else: log.logger.error("Lack of necessary parameters!") def start_zmq_serving_with_args(self): ''' Start one PaddleHub-Serving instance by arguments with zmq. ''' if self.modules_info is not None: for module, info in self.modules_info.items(): CacheUpdater("hub_serving_start", module=module, version=info['init_args']['version']).start() front_port = self.args.port if is_port_occupied("127.0.0.1", front_port) is True: log.logger.error("Port %s is occupied, please change it." % front_port) return False back_port = int(front_port) + 1 for index in range(100): if not is_port_occupied("127.0.0.1", back_port): break else: back_port = int(back_port) + 1 else: raise RuntimeError( "Port from %s to %s is occupied, please use another port" % (int(front_port) + 1, back_port)) self.dump_pid_file() run_all(self.modules_info, self.args.gpu, front_port, back_port) else: log.logger.error("Lack of necessary parameters!") def start_single_app_with_args(self): ''' Start one PaddleHub-Serving instance by arguments with flask. ''' module = self.modules_info if module is not None: port = self.args.port if is_port_occupied("127.0.0.1", port) is True: log.logger.error("Port %s is occupied, please change it." % port) return False self.preinstall_modules() self.dump_pid_file() app.run(configs=self.modules_info, port=port) else: log.logger.error("Lack of necessary parameters!") def start_serving(self): ''' Start PaddleHub-Serving with flask and gunicorn ''' if self.args.use_gpu: if self.args.use_multiprocess: log.logger.warning('`use_multiprocess` will be ignored if specify `use_gpu`.') self.start_zmq_serving_with_args() else: if self.args.use_multiprocess: if platform.system() == "Windows": log.logger.warning( "Warning: Windows cannot use multiprocess working mode, PaddleHub Serving will switch to single process mode" ) self.start_single_app_with_args() else: self.start_app_with_args() else: self.start_single_app_with_args() @staticmethod def show_help(): str = "serving <option>\n" str += "\tManage PaddleHub Serving.\n" str += "sub command:\n" str += "1. start\n" str += "\tStart PaddleHub Serving.\n" str += "2. stop\n" str += "\tStop PaddleHub Serving.\n" str += "3. start bert_service\n" str += "\tStart Bert Service.\n" str += "\n" str += "[start] option:\n" str += "--modules/-m [module1==version, module2==version...]\n" str += "\tPre-install modules via the parameter list.\n" str += "--port/-p XXXX\n" str += "\tUse port XXXX for serving.\n" str += "--use_multiprocess\n" str += "\tChoose multoprocess mode, cannot be use on Windows.\n" str += "--modules_info\n" str += "\tSet module config in PaddleHub Serving." str += "--config/-c file_path\n" str += "\tUse configs in file to start PaddleHub Serving. " str += "Other parameters will be ignored if you specify the parameter.\n" str += "\n" str += "[stop] option:\n" str += "--port/-p XXXX\n" str += "\tStop PaddleHub Serving on port XXXX safely.\n" str += "\n" str += "[start bert_service] option:\n" str += "--modules/-m\n" str += "\tPre-install modules via the parameter.\n" str += "--port/-p XXXX\n" str += "\tUse port XXXX for serving.\n" str += "--use_gpu\n" str += "\tUse gpu for predicting if specifies the parameter.\n" str += "--gpu\n" str += "\tSpecify the GPU devices to use.\n"
if os.path.exists(filepath): os.remove(filepath)
random_line_split
serving.py
. Examples: .. code-block:: python pid_is_exist(pid=8866) ''' try: os.kill(pid, 0) except: return False else: return True @register(name='hub.serving', description='Start Module Serving or Bert Service for online predicting.') class ServingCommand: name = "serving" module_list = [] def dump_pid_file(self): ''' Write PID info to file. ''' pid = os.getpid() filepath = os.path.join(CONF_HOME, "serving_" + str(self.args.port) + ".json") if os.path.exists(filepath): os.remove(filepath) with open(filepath, "w") as fp: info = {"pid": pid, "module": self.args.modules, "start_time": time.time()} json.dump(info, fp) @staticmethod def load_pid_file(filepath: str, port: int = None): ''' Read PID info from file. ''' if port is None: port = os.path.basename(filepath).split(".")[0].split("_")[1] if not os.path.exists(filepath): log.logger.error( "PaddleHub Serving config file is not exists, please confirm the port [%s] you specified is correct." % port) return False with open(filepath, "r") as fp: info = json.load(fp) return info def stop_serving(self, port: int): ''' Stop PaddleHub-Serving by port. ''' filepath = os.path.join(CONF_HOME, "serving_" + str(port) + ".json") info = self.load_pid_file(filepath, port) if info is False: return pid = info["pid"] module = info["module"] start_time = info["start_time"] CacheUpdater("hub_serving_stop", module=module, addition={"period_time": time.time() - start_time}).start() if os.path.exists(filepath): os.remove(filepath) if not pid_is_exist(pid): log.logger.info("PaddleHub Serving has been stopped.") return log.logger.info("PaddleHub Serving will stop.") if platform.system() == "Windows": os.kill(pid, signal.SIGTERM) else: try: os.killpg(pid, signal.SIGTERM) except ProcessLookupError: os.kill(pid, signal.SIGTERM) @staticmethod def start_bert_serving(args): ''' Start bert serving server. ''' if platform.system() != "Linux": log.logger.error("Error. Bert Service only support linux.") return False if is_port_occupied("127.0.0.1", args.port) is True: log.logger.error("Port %s is occupied, please change it." % args.port) return False from paddle_gpu_serving.run import BertServer bs = BertServer(with_gpu=args.use_gpu) bs.with_model(model_name=args.modules[0]) CacheUpdater("hub_bert_service", module=args.modules[0], version="0.0.0").start() bs.run(gpu_index=args.gpu, port=int(args.port)) def preinstall_modules(self): ''' Install module by PaddleHub and get info of this module. ''' for key, value in self.modules_info.items(): init_args = value["init_args"] CacheUpdater("hub_serving_start", module=key, version=init_args.get("version", "0.0.0")).start() if "directory" not in init_args: init_args.update({"name": key}) m = hub.Module(**init_args) method_name = m.serving_func_name if method_name is None: raise RuntimeError("{} cannot be use for " "predicting".format(key)) exit(1) serving_method = getattr(m, method_name) category = str(m.type).split("/")[0].upper() self.modules_info[key].update({ "method_name": method_name, "version": m.version, "category": category, "module": m, "name": m.name, "serving_method": serving_method }) def start_app_with_args(self): ''' Start one PaddleHub-Serving instance by arguments with gunicorn. ''' module = self.modules_info if module is not None: port = self.args.port if is_port_occupied("127.0.0.1", port) is True: log.logger.error("Port %s is occupied, please change it." % port) return False self.preinstall_modules() options = {"bind": "0.0.0.0:%s" % port, "workers": self.args.workers} self.dump_pid_file() StandaloneApplication(app.create_app(init_flag=False, configs=self.modules_info), options).run() else: log.logger.error("Lack of necessary parameters!") def start_zmq_serving_with_args(self): ''' Start one PaddleHub-Serving instance by arguments with zmq. ''' if self.modules_info is not None: for module, info in self.modules_info.items(): CacheUpdater("hub_serving_start", module=module, version=info['init_args']['version']).start() front_port = self.args.port if is_port_occupied("127.0.0.1", front_port) is True: log.logger.error("Port %s is occupied, please change it." % front_port) return False back_port = int(front_port) + 1 for index in range(100): if not is_port_occupied("127.0.0.1", back_port): break else: back_port = int(back_port) + 1 else: raise RuntimeError( "Port from %s to %s is occupied, please use another port" % (int(front_port) + 1, back_port)) self.dump_pid_file() run_all(self.modules_info, self.args.gpu, front_port, back_port) else: log.logger.error("Lack of necessary parameters!") def start_single_app_with_args(self): ''' Start one PaddleHub-Serving instance by arguments with flask. ''' module = self.modules_info if module is not None: port = self.args.port if is_port_occupied("127.0.0.1", port) is True: log.logger.error("Port %s is occupied, please change it." % port) return False self.preinstall_modules() self.dump_pid_file() app.run(configs=self.modules_info, port=port) else: log.logger.error("Lack of necessary parameters!") def start_serving(self):
@staticmethod def show_help(): str = "serving <option>\n" str += "\tManage PaddleHub Serving.\n" str += "sub command:\n" str += "1. start\n" str += "\tStart PaddleHub Serving.\n" str += "2. stop\n" str += "\tStop PaddleHub Serving.\n" str += "3. start bert_service\n" str += "\tStart Bert Service.\n" str += "\n" str += "[start] option:\n" str += "--modules/-m [module1==version, module2==version...]\n" str += "\tPre-install modules via the parameter list.\n" str += "--port/-p XXXX\n" str += "\tUse port XXXX for serving.\n" str += "--use_multiprocess\n" str += "\tChoose multoprocess mode, cannot be use on Windows.\n" str += "--modules_info\n" str += "\tSet module config in PaddleHub Serving." str += "--config/-c file_path\n" str += "\tUse configs in file to start PaddleHub Serving. " str += "Other parameters will be ignored if you specify the parameter.\n" str += "\n" str += "[stop] option:\n" str += "--port/-p XXXX\n" str += "\tStop PaddleHub Serving on port XXXX safely.\n" str += "\n" str += "[start bert_service] option:\n" str += "--modules/-m\n" str += "\tPre-install modules via the parameter.\n" str += "--port/-p XXXX\n" str += "\tUse port XXXX for serving.\n" str += "--use_gpu\n" str += "\tUse gpu for predicting if specifies the parameter.\n" str += "--gpu\n" str += "\tSpecify the GPU devices to use.\n"
''' Start PaddleHub-Serving with flask and gunicorn ''' if self.args.use_gpu: if self.args.use_multiprocess: log.logger.warning('`use_multiprocess` will be ignored if specify `use_gpu`.') self.start_zmq_serving_with_args() else: if self.args.use_multiprocess: if platform.system() == "Windows": log.logger.warning( "Warning: Windows cannot use multiprocess working mode, PaddleHub Serving will switch to single process mode" ) self.start_single_app_with_args() else: self.start_app_with_args() else: self.start_single_app_with_args()
identifier_body
serving.py
. Examples: .. code-block:: python pid_is_exist(pid=8866) ''' try: os.kill(pid, 0) except: return False else: return True @register(name='hub.serving', description='Start Module Serving or Bert Service for online predicting.') class ServingCommand: name = "serving" module_list = [] def dump_pid_file(self): ''' Write PID info to file. ''' pid = os.getpid() filepath = os.path.join(CONF_HOME, "serving_" + str(self.args.port) + ".json") if os.path.exists(filepath): os.remove(filepath) with open(filepath, "w") as fp: info = {"pid": pid, "module": self.args.modules, "start_time": time.time()} json.dump(info, fp) @staticmethod def load_pid_file(filepath: str, port: int = None): ''' Read PID info from file. ''' if port is None: port = os.path.basename(filepath).split(".")[0].split("_")[1] if not os.path.exists(filepath): log.logger.error( "PaddleHub Serving config file is not exists, please confirm the port [%s] you specified is correct." % port) return False with open(filepath, "r") as fp: info = json.load(fp) return info def stop_serving(self, port: int): ''' Stop PaddleHub-Serving by port. ''' filepath = os.path.join(CONF_HOME, "serving_" + str(port) + ".json") info = self.load_pid_file(filepath, port) if info is False: return pid = info["pid"] module = info["module"] start_time = info["start_time"] CacheUpdater("hub_serving_stop", module=module, addition={"period_time": time.time() - start_time}).start() if os.path.exists(filepath): os.remove(filepath) if not pid_is_exist(pid): log.logger.info("PaddleHub Serving has been stopped.") return log.logger.info("PaddleHub Serving will stop.") if platform.system() == "Windows": os.kill(pid, signal.SIGTERM) else: try: os.killpg(pid, signal.SIGTERM) except ProcessLookupError: os.kill(pid, signal.SIGTERM) @staticmethod def
(args): ''' Start bert serving server. ''' if platform.system() != "Linux": log.logger.error("Error. Bert Service only support linux.") return False if is_port_occupied("127.0.0.1", args.port) is True: log.logger.error("Port %s is occupied, please change it." % args.port) return False from paddle_gpu_serving.run import BertServer bs = BertServer(with_gpu=args.use_gpu) bs.with_model(model_name=args.modules[0]) CacheUpdater("hub_bert_service", module=args.modules[0], version="0.0.0").start() bs.run(gpu_index=args.gpu, port=int(args.port)) def preinstall_modules(self): ''' Install module by PaddleHub and get info of this module. ''' for key, value in self.modules_info.items(): init_args = value["init_args"] CacheUpdater("hub_serving_start", module=key, version=init_args.get("version", "0.0.0")).start() if "directory" not in init_args: init_args.update({"name": key}) m = hub.Module(**init_args) method_name = m.serving_func_name if method_name is None: raise RuntimeError("{} cannot be use for " "predicting".format(key)) exit(1) serving_method = getattr(m, method_name) category = str(m.type).split("/")[0].upper() self.modules_info[key].update({ "method_name": method_name, "version": m.version, "category": category, "module": m, "name": m.name, "serving_method": serving_method }) def start_app_with_args(self): ''' Start one PaddleHub-Serving instance by arguments with gunicorn. ''' module = self.modules_info if module is not None: port = self.args.port if is_port_occupied("127.0.0.1", port) is True: log.logger.error("Port %s is occupied, please change it." % port) return False self.preinstall_modules() options = {"bind": "0.0.0.0:%s" % port, "workers": self.args.workers} self.dump_pid_file() StandaloneApplication(app.create_app(init_flag=False, configs=self.modules_info), options).run() else: log.logger.error("Lack of necessary parameters!") def start_zmq_serving_with_args(self): ''' Start one PaddleHub-Serving instance by arguments with zmq. ''' if self.modules_info is not None: for module, info in self.modules_info.items(): CacheUpdater("hub_serving_start", module=module, version=info['init_args']['version']).start() front_port = self.args.port if is_port_occupied("127.0.0.1", front_port) is True: log.logger.error("Port %s is occupied, please change it." % front_port) return False back_port = int(front_port) + 1 for index in range(100): if not is_port_occupied("127.0.0.1", back_port): break else: back_port = int(back_port) + 1 else: raise RuntimeError( "Port from %s to %s is occupied, please use another port" % (int(front_port) + 1, back_port)) self.dump_pid_file() run_all(self.modules_info, self.args.gpu, front_port, back_port) else: log.logger.error("Lack of necessary parameters!") def start_single_app_with_args(self): ''' Start one PaddleHub-Serving instance by arguments with flask. ''' module = self.modules_info if module is not None: port = self.args.port if is_port_occupied("127.0.0.1", port) is True: log.logger.error("Port %s is occupied, please change it." % port) return False self.preinstall_modules() self.dump_pid_file() app.run(configs=self.modules_info, port=port) else: log.logger.error("Lack of necessary parameters!") def start_serving(self): ''' Start PaddleHub-Serving with flask and gunicorn ''' if self.args.use_gpu: if self.args.use_multiprocess: log.logger.warning('`use_multiprocess` will be ignored if specify `use_gpu`.') self.start_zmq_serving_with_args() else: if self.args.use_multiprocess: if platform.system() == "Windows": log.logger.warning( "Warning: Windows cannot use multiprocess working mode, PaddleHub Serving will switch to single process mode" ) self.start_single_app_with_args() else: self.start_app_with_args() else: self.start_single_app_with_args() @staticmethod def show_help(): str = "serving <option>\n" str += "\tManage PaddleHub Serving.\n" str += "sub command:\n" str += "1. start\n" str += "\tStart PaddleHub Serving.\n" str += "2. stop\n" str += "\tStop PaddleHub Serving.\n" str += "3. start bert_service\n" str += "\tStart Bert Service.\n" str += "\n" str += "[start] option:\n" str += "--modules/-m [module1==version, module2==version...]\n" str += "\tPre-install modules via the parameter list.\n" str += "--port/-p XXXX\n" str += "\tUse port XXXX for serving.\n" str += "--use_multiprocess\n" str += "\tChoose multoprocess mode, cannot be use on Windows.\n" str += "--modules_info\n" str += "\tSet module config in PaddleHub Serving." str += "--config/-c file_path\n" str += "\tUse configs in file to start PaddleHub Serving. " str += "Other parameters will be ignored if you specify the parameter.\n" str += "\n" str += "[stop] option:\n" str += "--port/-p XXXX\n" str += "\tStop PaddleHub Serving on port XXXX safely.\n" str += "\n" str += "[start bert_service] option:\n" str += "--modules/-m\n" str += "\tPre-install modules via the parameter.\n" str += "--port/-p XXXX\n" str += "\tUse port XXXX for serving.\n" str += "--use_gpu\n" str += "\tUse gpu for predicting if specifies the parameter.\n" str += "--gpu\n" str += "\tSpecify the GPU devices to use.\n"
start_bert_serving
identifier_name
main.rs
() -> Self { let mut app = App::new("servicemanagement1") .setting(clap::AppSettings::ColoredHelp) .author("Sebastian Thiel <byronimo@gmail.com>") .version("0.1.0-20200619") .about("Google Service Management allows service producers to publish their services on Google Cloud Platform so that they can be discovered and used by service consumers.") .after_help("All documentation details can be found at <TODO figure out URL>") .arg(Arg::with_name("scope") .long("scope") .help("Specify the authentication method should be executed in. Each scope requires the user to grant this application permission to use it. If unset, it defaults to the shortest scope url for a particular method.") .multiple(true) .takes_value(true)) .arg(Arg::with_name("folder") .long("config-dir") .help("A directory into which we will store our persistent data. Defaults to a user-writable directory that we will create during the first invocation." ) .multiple(false) .takes_value(true)) .arg(Arg::with_name("debug") .long("debug") .help("Provide more output to aid with debugging") .multiple(false) .takes_value(false)); let mut operations0 = SubCommand::with_name("operations") .setting(AppSettings::ColoredHelp) .about("methods: get and list"); { let mcmd = SubCommand::with_name("get").about("Gets the latest state of a long-running operation. Clients can use this\nmethod to poll the operation result at intervals as recommended by the API\nservice."); operations0 = operations0.subcommand(mcmd); } { let mcmd = SubCommand::with_name("list") .about("Lists service operations that match the specified filter in the request."); operations0 = operations0.subcommand(mcmd); } let mut services0 = SubCommand::with_name("services") .setting(AppSettings::ColoredHelp) .about("methods: create, delete, disable, enable, generate_config_report, get, get_config, get_iam_policy, list, set_iam_policy, test_iam_permissions and undelete"); { let mcmd = SubCommand::with_name("create").about("Creates a new managed service.\n\nA managed service is immutable, and is subject to mandatory 30-day\ndata retention. You cannot move a service or recreate it within 30 days\nafter deletion.\n\nOne producer project can own no more than 500 services. For security and\nreliability purposes, a production service should be hosted in a\ndedicated producer project.\n\nOperation<response: ManagedService>"); services0 = services0.subcommand(mcmd); } { let mcmd = SubCommand::with_name("delete").about("Deletes a managed service. This method will change the service to the\n`Soft-Delete` state for 30 days. Within this period, service producers may\ncall UndeleteService to restore the service.\nAfter 30 days, the service will be permanently deleted.\n\nOperation<response: google.protobuf.Empty>"); services0 = services0.subcommand(mcmd); } { let mcmd = SubCommand::with_name("disable").about("Disables a service for a project, so it can no longer be\nbe used for the project. It prevents accidental usage that may cause\nunexpected billing charges or security leaks.\n\nOperation<response: DisableServiceResponse>"); services0 = services0.subcommand(mcmd); } { let mcmd = SubCommand::with_name("enable").about("Enables a service for a project, so it can be used\nfor the project. See\n[Cloud Auth Guide](https://cloud.google.com/docs/authentication) for\nmore information.\n\nOperation<response: EnableServiceResponse>"); services0 = services0.subcommand(mcmd); } { let mcmd = SubCommand::with_name("generate_config_report").about("Generates and returns a report (errors, warnings and changes from\nexisting configurations) associated with\nGenerateConfigReportRequest.new_value\n\nIf GenerateConfigReportRequest.old_value is specified,\nGenerateConfigReportRequest will contain a single ChangeReport based on the\ncomparison between GenerateConfigReportRequest.new_value and\nGenerateConfigReportRequest.old_value.\nIf GenerateConfigReportRequest.old_value is not specified, this method\nwill compare GenerateConfigReportRequest.new_value with the last pushed\nservice configuration."); services0 = services0.subcommand(mcmd); } { let mcmd = SubCommand::with_name("get").about( "Gets a managed service. Authentication is required unless the service is\npublic.", ); services0 = services0.subcommand(mcmd); } { let mcmd = SubCommand::with_name("get_config") .about("Gets a service configuration (version) for a managed service."); services0 = services0.subcommand(mcmd); } { let mcmd = SubCommand::with_name("get_iam_policy").about("Gets the access control policy for a resource.\nReturns an empty policy if the resource exists and does not have a policy\nset."); services0 = services0.subcommand(mcmd); } { let mcmd = SubCommand::with_name("list").about("Lists managed services.\n\nReturns all public services. For authenticated users, also returns all\nservices the calling user has \"servicemanagement.services.get\" permission\nfor.\n\n**BETA:** If the caller specifies the `consumer_id`, it returns only the\nservices enabled on the consumer. The `consumer_id` must have the format\nof \"project:{PROJECT-ID}\"."); services0 = services0.subcommand(mcmd); } { let mcmd = SubCommand::with_name("set_iam_policy").about("Sets the access control policy on the specified resource. Replaces any\nexisting policy.\n\nCan return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED` errors."); services0 = services0.subcommand(mcmd); } { let mcmd = SubCommand::with_name("test_iam_permissions").about("Returns permissions that a caller has on the specified resource.\nIf the resource does not exist, this will return an empty set of\npermissions, not a `NOT_FOUND` error.\n\nNote: This operation is designed to be used for building permission-aware\nUIs and command-line tools, not for authorization checking. This operation\nmay \"fail open\" without warning."); services0 = services0.subcommand(mcmd); } { let mcmd = SubCommand::with_name("undelete").about("Revives a previously deleted managed service. The method restores the\nservice using the configuration at the time the service was deleted.\nThe target service must exist and must have been deleted within the\nlast 30 days.\n\nOperation<response: UndeleteServiceResponse>"); services0 = services0.subcommand(mcmd); } let mut configs1 = SubCommand::with_name("configs") .setting(AppSettings::ColoredHelp) .about("methods: create, get, list and submit"); { let mcmd = SubCommand::with_name("create").about("Creates a new service configuration (version) for a managed service.\nThis method only stores the service configuration. To roll out the service\nconfiguration to backend systems please call\nCreateServiceRollout.\n\nOnly the 100 most recent service configurations and ones referenced by\nexisting rollouts are kept for each service. The rest will be deleted\neventually."); configs1 = configs1.subcommand(mcmd); } { let mcmd = SubCommand::with_name("get") .about("Gets a service configuration (version) for a managed service."); configs1 = configs1.subcommand(mcmd); } { let mcmd = SubCommand::with_name("list").about("Lists the history of the service configuration for a managed service,\nfrom the newest to the oldest."); configs1 = configs1.subcommand(mcmd); } { let mcmd = SubCommand::with_name("submit").about("Creates a new service configuration (version) for a managed service based\non\nuser-supplied configuration source files (for example: OpenAPI\nSpecification). This method stores the source configurations as well as the\ngenerated service configuration. To rollout the service configuration to\nother services,\nplease call CreateServiceRollout.\n\nOnly the 100 most recent configuration sources and ones referenced by\nexisting service configurtions are kept for each service. The rest will be\ndeleted eventually.\n\nOperation<response: SubmitConfigSourceResponse>"); configs1 = configs1.subcommand(mcmd); } let mut consumers1 = SubCommand::with_name("consumers") .setting(AppSettings::ColoredHelp) .about("methods: get_iam_policy, set_iam_policy and test_iam_permissions"); { let mcmd = SubCommand::with_name("get_iam_policy").about("Gets the access control policy for a resource.\nReturns an empty policy if the resource exists and does not have a policy\nset."); consumers1 = consumers1.subcommand(mcmd); } { let mcmd = SubCommand::with_name("set_iam_policy").about("Sets the access control policy on the specified resource. Replaces
default
identifier_name
main.rs
, and is subject to mandatory 30-day\ndata retention. You cannot move a service or recreate it within 30 days\nafter deletion.\n\nOne producer project can own no more than 500 services. For security and\nreliability purposes, a production service should be hosted in a\ndedicated producer project.\n\nOperation<response: ManagedService>"); services0 = services0.subcommand(mcmd); } { let mcmd = SubCommand::with_name("delete").about("Deletes a managed service. This method will change the service to the\n`Soft-Delete` state for 30 days. Within this period, service producers may\ncall UndeleteService to restore the service.\nAfter 30 days, the service will be permanently deleted.\n\nOperation<response: google.protobuf.Empty>"); services0 = services0.subcommand(mcmd); } { let mcmd = SubCommand::with_name("disable").about("Disables a service for a project, so it can no longer be\nbe used for the project. It prevents accidental usage that may cause\nunexpected billing charges or security leaks.\n\nOperation<response: DisableServiceResponse>"); services0 = services0.subcommand(mcmd); } { let mcmd = SubCommand::with_name("enable").about("Enables a service for a project, so it can be used\nfor the project. See\n[Cloud Auth Guide](https://cloud.google.com/docs/authentication) for\nmore information.\n\nOperation<response: EnableServiceResponse>"); services0 = services0.subcommand(mcmd); } { let mcmd = SubCommand::with_name("generate_config_report").about("Generates and returns a report (errors, warnings and changes from\nexisting configurations) associated with\nGenerateConfigReportRequest.new_value\n\nIf GenerateConfigReportRequest.old_value is specified,\nGenerateConfigReportRequest will contain a single ChangeReport based on the\ncomparison between GenerateConfigReportRequest.new_value and\nGenerateConfigReportRequest.old_value.\nIf GenerateConfigReportRequest.old_value is not specified, this method\nwill compare GenerateConfigReportRequest.new_value with the last pushed\nservice configuration."); services0 = services0.subcommand(mcmd); } { let mcmd = SubCommand::with_name("get").about( "Gets a managed service. Authentication is required unless the service is\npublic.", ); services0 = services0.subcommand(mcmd); } { let mcmd = SubCommand::with_name("get_config") .about("Gets a service configuration (version) for a managed service."); services0 = services0.subcommand(mcmd); } { let mcmd = SubCommand::with_name("get_iam_policy").about("Gets the access control policy for a resource.\nReturns an empty policy if the resource exists and does not have a policy\nset."); services0 = services0.subcommand(mcmd); } { let mcmd = SubCommand::with_name("list").about("Lists managed services.\n\nReturns all public services. For authenticated users, also returns all\nservices the calling user has \"servicemanagement.services.get\" permission\nfor.\n\n**BETA:** If the caller specifies the `consumer_id`, it returns only the\nservices enabled on the consumer. The `consumer_id` must have the format\nof \"project:{PROJECT-ID}\"."); services0 = services0.subcommand(mcmd); } { let mcmd = SubCommand::with_name("set_iam_policy").about("Sets the access control policy on the specified resource. Replaces any\nexisting policy.\n\nCan return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED` errors."); services0 = services0.subcommand(mcmd); } { let mcmd = SubCommand::with_name("test_iam_permissions").about("Returns permissions that a caller has on the specified resource.\nIf the resource does not exist, this will return an empty set of\npermissions, not a `NOT_FOUND` error.\n\nNote: This operation is designed to be used for building permission-aware\nUIs and command-line tools, not for authorization checking. This operation\nmay \"fail open\" without warning."); services0 = services0.subcommand(mcmd); } { let mcmd = SubCommand::with_name("undelete").about("Revives a previously deleted managed service. The method restores the\nservice using the configuration at the time the service was deleted.\nThe target service must exist and must have been deleted within the\nlast 30 days.\n\nOperation<response: UndeleteServiceResponse>"); services0 = services0.subcommand(mcmd); } let mut configs1 = SubCommand::with_name("configs") .setting(AppSettings::ColoredHelp) .about("methods: create, get, list and submit"); { let mcmd = SubCommand::with_name("create").about("Creates a new service configuration (version) for a managed service.\nThis method only stores the service configuration. To roll out the service\nconfiguration to backend systems please call\nCreateServiceRollout.\n\nOnly the 100 most recent service configurations and ones referenced by\nexisting rollouts are kept for each service. The rest will be deleted\neventually."); configs1 = configs1.subcommand(mcmd); } { let mcmd = SubCommand::with_name("get") .about("Gets a service configuration (version) for a managed service."); configs1 = configs1.subcommand(mcmd); } { let mcmd = SubCommand::with_name("list").about("Lists the history of the service configuration for a managed service,\nfrom the newest to the oldest."); configs1 = configs1.subcommand(mcmd); } { let mcmd = SubCommand::with_name("submit").about("Creates a new service configuration (version) for a managed service based\non\nuser-supplied configuration source files (for example: OpenAPI\nSpecification). This method stores the source configurations as well as the\ngenerated service configuration. To rollout the service configuration to\nother services,\nplease call CreateServiceRollout.\n\nOnly the 100 most recent configuration sources and ones referenced by\nexisting service configurtions are kept for each service. The rest will be\ndeleted eventually.\n\nOperation<response: SubmitConfigSourceResponse>"); configs1 = configs1.subcommand(mcmd); } let mut consumers1 = SubCommand::with_name("consumers") .setting(AppSettings::ColoredHelp) .about("methods: get_iam_policy, set_iam_policy and test_iam_permissions"); { let mcmd = SubCommand::with_name("get_iam_policy").about("Gets the access control policy for a resource.\nReturns an empty policy if the resource exists and does not have a policy\nset."); consumers1 = consumers1.subcommand(mcmd); } { let mcmd = SubCommand::with_name("set_iam_policy").about("Sets the access control policy on the specified resource. Replaces any\nexisting policy.\n\nCan return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED` errors."); consumers1 = consumers1.subcommand(mcmd); } { let mcmd = SubCommand::with_name("test_iam_permissions").about("Returns permissions that a caller has on the specified resource.\nIf the resource does not exist, this will return an empty set of\npermissions, not a `NOT_FOUND` error.\n\nNote: This operation is designed to be used for building permission-aware\nUIs and command-line tools, not for authorization checking. This operation\nmay \"fail open\" without warning."); consumers1 = consumers1.subcommand(mcmd); } let mut rollouts1 = SubCommand::with_name("rollouts") .setting(AppSettings::ColoredHelp) .about("methods: create, get and list"); { let mcmd = SubCommand::with_name("create").about("Creates a new service configuration rollout. Based on rollout, the\nGoogle Service Management will roll out the service configurations to\ndifferent backend services. For example, the logging configuration will be\npushed to Google Cloud Logging.\n\nPlease note that any previous pending and running Rollouts and associated\nOperations will be automatically cancelled so that the latest Rollout will\nnot be blocked by previous Rollouts.\n\nOnly the 100 most recent (in any state) and the last 10 successful (if not\nalready part of the set of 100 most recent) rollouts are kept for each\nservice. The rest will be deleted eventually.\n\nOperation<response: Rollout>"); rollouts1 = rollouts1.subcommand(mcmd); } { let mcmd = SubCommand::with_name("get").about("Gets a service configuration rollout."); rollouts1 = rollouts1.subcommand(mcmd); } { let mcmd = SubCommand::with_name("list").about("Lists the history of the service configuration rollouts for a managed\nservice, from the newest to the oldest."); rollouts1 = rollouts1.subcommand(mcmd); } services0 = services0.subcommand(rollouts1); services0 = services0.subcommand(consumers1); services0 = services0.subcommand(configs1); app = app.subcommand(services0); app = app.subcommand(operations0); Self { app } } }
random_line_split
main.rs
managed service. This method will change the service to the\n`Soft-Delete` state for 30 days. Within this period, service producers may\ncall UndeleteService to restore the service.\nAfter 30 days, the service will be permanently deleted.\n\nOperation<response: google.protobuf.Empty>"); services0 = services0.subcommand(mcmd); } { let mcmd = SubCommand::with_name("disable").about("Disables a service for a project, so it can no longer be\nbe used for the project. It prevents accidental usage that may cause\nunexpected billing charges or security leaks.\n\nOperation<response: DisableServiceResponse>"); services0 = services0.subcommand(mcmd); } { let mcmd = SubCommand::with_name("enable").about("Enables a service for a project, so it can be used\nfor the project. See\n[Cloud Auth Guide](https://cloud.google.com/docs/authentication) for\nmore information.\n\nOperation<response: EnableServiceResponse>"); services0 = services0.subcommand(mcmd); } { let mcmd = SubCommand::with_name("generate_config_report").about("Generates and returns a report (errors, warnings and changes from\nexisting configurations) associated with\nGenerateConfigReportRequest.new_value\n\nIf GenerateConfigReportRequest.old_value is specified,\nGenerateConfigReportRequest will contain a single ChangeReport based on the\ncomparison between GenerateConfigReportRequest.new_value and\nGenerateConfigReportRequest.old_value.\nIf GenerateConfigReportRequest.old_value is not specified, this method\nwill compare GenerateConfigReportRequest.new_value with the last pushed\nservice configuration."); services0 = services0.subcommand(mcmd); } { let mcmd = SubCommand::with_name("get").about( "Gets a managed service. Authentication is required unless the service is\npublic.", ); services0 = services0.subcommand(mcmd); } { let mcmd = SubCommand::with_name("get_config") .about("Gets a service configuration (version) for a managed service."); services0 = services0.subcommand(mcmd); } { let mcmd = SubCommand::with_name("get_iam_policy").about("Gets the access control policy for a resource.\nReturns an empty policy if the resource exists and does not have a policy\nset."); services0 = services0.subcommand(mcmd); } { let mcmd = SubCommand::with_name("list").about("Lists managed services.\n\nReturns all public services. For authenticated users, also returns all\nservices the calling user has \"servicemanagement.services.get\" permission\nfor.\n\n**BETA:** If the caller specifies the `consumer_id`, it returns only the\nservices enabled on the consumer. The `consumer_id` must have the format\nof \"project:{PROJECT-ID}\"."); services0 = services0.subcommand(mcmd); } { let mcmd = SubCommand::with_name("set_iam_policy").about("Sets the access control policy on the specified resource. Replaces any\nexisting policy.\n\nCan return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED` errors."); services0 = services0.subcommand(mcmd); } { let mcmd = SubCommand::with_name("test_iam_permissions").about("Returns permissions that a caller has on the specified resource.\nIf the resource does not exist, this will return an empty set of\npermissions, not a `NOT_FOUND` error.\n\nNote: This operation is designed to be used for building permission-aware\nUIs and command-line tools, not for authorization checking. This operation\nmay \"fail open\" without warning."); services0 = services0.subcommand(mcmd); } { let mcmd = SubCommand::with_name("undelete").about("Revives a previously deleted managed service. The method restores the\nservice using the configuration at the time the service was deleted.\nThe target service must exist and must have been deleted within the\nlast 30 days.\n\nOperation<response: UndeleteServiceResponse>"); services0 = services0.subcommand(mcmd); } let mut configs1 = SubCommand::with_name("configs") .setting(AppSettings::ColoredHelp) .about("methods: create, get, list and submit"); { let mcmd = SubCommand::with_name("create").about("Creates a new service configuration (version) for a managed service.\nThis method only stores the service configuration. To roll out the service\nconfiguration to backend systems please call\nCreateServiceRollout.\n\nOnly the 100 most recent service configurations and ones referenced by\nexisting rollouts are kept for each service. The rest will be deleted\neventually."); configs1 = configs1.subcommand(mcmd); } { let mcmd = SubCommand::with_name("get") .about("Gets a service configuration (version) for a managed service."); configs1 = configs1.subcommand(mcmd); } { let mcmd = SubCommand::with_name("list").about("Lists the history of the service configuration for a managed service,\nfrom the newest to the oldest."); configs1 = configs1.subcommand(mcmd); } { let mcmd = SubCommand::with_name("submit").about("Creates a new service configuration (version) for a managed service based\non\nuser-supplied configuration source files (for example: OpenAPI\nSpecification). This method stores the source configurations as well as the\ngenerated service configuration. To rollout the service configuration to\nother services,\nplease call CreateServiceRollout.\n\nOnly the 100 most recent configuration sources and ones referenced by\nexisting service configurtions are kept for each service. The rest will be\ndeleted eventually.\n\nOperation<response: SubmitConfigSourceResponse>"); configs1 = configs1.subcommand(mcmd); } let mut consumers1 = SubCommand::with_name("consumers") .setting(AppSettings::ColoredHelp) .about("methods: get_iam_policy, set_iam_policy and test_iam_permissions"); { let mcmd = SubCommand::with_name("get_iam_policy").about("Gets the access control policy for a resource.\nReturns an empty policy if the resource exists and does not have a policy\nset."); consumers1 = consumers1.subcommand(mcmd); } { let mcmd = SubCommand::with_name("set_iam_policy").about("Sets the access control policy on the specified resource. Replaces any\nexisting policy.\n\nCan return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED` errors."); consumers1 = consumers1.subcommand(mcmd); } { let mcmd = SubCommand::with_name("test_iam_permissions").about("Returns permissions that a caller has on the specified resource.\nIf the resource does not exist, this will return an empty set of\npermissions, not a `NOT_FOUND` error.\n\nNote: This operation is designed to be used for building permission-aware\nUIs and command-line tools, not for authorization checking. This operation\nmay \"fail open\" without warning."); consumers1 = consumers1.subcommand(mcmd); } let mut rollouts1 = SubCommand::with_name("rollouts") .setting(AppSettings::ColoredHelp) .about("methods: create, get and list"); { let mcmd = SubCommand::with_name("create").about("Creates a new service configuration rollout. Based on rollout, the\nGoogle Service Management will roll out the service configurations to\ndifferent backend services. For example, the logging configuration will be\npushed to Google Cloud Logging.\n\nPlease note that any previous pending and running Rollouts and associated\nOperations will be automatically cancelled so that the latest Rollout will\nnot be blocked by previous Rollouts.\n\nOnly the 100 most recent (in any state) and the last 10 successful (if not\nalready part of the set of 100 most recent) rollouts are kept for each\nservice. The rest will be deleted eventually.\n\nOperation<response: Rollout>"); rollouts1 = rollouts1.subcommand(mcmd); } { let mcmd = SubCommand::with_name("get").about("Gets a service configuration rollout."); rollouts1 = rollouts1.subcommand(mcmd); } { let mcmd = SubCommand::with_name("list").about("Lists the history of the service configuration rollouts for a managed\nservice, from the newest to the oldest."); rollouts1 = rollouts1.subcommand(mcmd); } services0 = services0.subcommand(rollouts1); services0 = services0.subcommand(consumers1); services0 = services0.subcommand(configs1); app = app.subcommand(services0); app = app.subcommand(operations0); Self { app } } } use google_servicemanagement1 as api; fn main()
{ // TODO: set homedir afterwards, once the address is unmovable, or use Pin for the very first time // to allow a self-referential structure :D! let _home_dir = dirs::config_dir() .expect("configuration directory can be obtained") .join("google-service-cli"); let outer = Outer::default_boxed(); let app = outer.inner.app; let _matches = app.get_matches(); }
identifier_body
cert.go
MemCert for more details. type CertKind int // Possible kinds of certificates. const ( CertClient CertKind = iota CertServer ) // TestingKeyPair returns CertInfo object initialized with a test keypair. It's // meant to be used only by tests. func TestingKeyPair() *CertInfo { keypair, err := tls.X509KeyPair(testCertPEMBlock, testKeyPEMBlock) if err != nil { panic(fmt.Sprintf("invalid X509 keypair material: %v", err)) } cert := &CertInfo{ keypair: keypair, } return cert } // TestingAltKeyPair returns CertInfo object initialized with a test keypair // which differs from the one returned by TestCertInfo. It's meant to be used // only by tests. func TestingAltKeyPair() *CertInfo { keypair, err := tls.X509KeyPair(testAltCertPEMBlock, testAltKeyPEMBlock) if err != nil { panic(fmt.Sprintf("invalid X509 keypair material: %v", err)) } cert := &CertInfo{ keypair: keypair, } return cert } /* * Generate a list of names for which the certificate will be valid. * This will include the hostname and ip address. */ func mynames() ([]string, error) { h, err := os.Hostname() if err != nil { return nil, err } ret := []string{h, "127.0.0.1/8", "::1/128"} return ret, nil } // FindOrGenCert generates a keypair if needed. // The type argument is false for server, true for client. func FindOrGenCert(certf string, keyf string, certtype bool, addHosts bool) error { if PathExists(certf) && PathExists(keyf) { return nil } /* If neither stat succeeded, then this is our first run and we * need to generate cert and privkey */ err := GenCert(certf, keyf, certtype, addHosts) if err != nil { return err } return nil } // GenCert will create and populate a certificate file and a key file. func GenCert(certf string, keyf string, certtype bool, addHosts bool) error { /* Create the basenames if needed */ dir := filepath.Dir(certf) err := os.MkdirAll(dir, 0750) if err != nil { return err } dir = filepath.Dir(keyf) err = os.MkdirAll(dir, 0750) if err != nil { return err } certBytes, keyBytes, err := GenerateMemCert(certtype, addHosts) if err != nil { return err } certOut, err := os.Create(certf) if err != nil { return fmt.Errorf("Failed to open %s for writing: %w", certf, err) } _, err = certOut.Write(certBytes) if err != nil { return fmt.Errorf("Failed to write cert file: %w", err) } err = certOut.Close() if err != nil { return fmt.Errorf("Failed to close cert file: %w", err) } keyOut, err := os.OpenFile(keyf, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) if err != nil { return fmt.Errorf("Failed to open %s for writing: %w", keyf, err) } _, err = keyOut.Write(keyBytes) if err != nil { return fmt.Errorf("Failed to write key file: %w", err) } err = keyOut.Close() if err != nil { return fmt.Errorf("Failed to close key file: %w", err) } return nil } // GenerateMemCert creates client or server certificate and key pair, // returning them as byte arrays in memory. func GenerateMemCert(client bool, addHosts bool) ([]byte, []byte, error) { privk, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader) if err != nil { return nil, nil, fmt.Errorf("Failed to generate key: %w", err) } validFrom := time.Now() validTo := validFrom.Add(10 * 365 * 24 * time.Hour) serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) if err != nil { return nil, nil, fmt.Errorf("Failed to generate serial number: %w", err) } userEntry, err := user.Current() var username string if err == nil { username = userEntry.Username if username == "" { username = "UNKNOWN" } } else { username = "UNKNOWN" } hostname, err := os.Hostname() if err != nil { hostname = "UNKNOWN" } template := x509.Certificate{ SerialNumber: serialNumber, Subject: pkix.Name{ Organization: []string{"LXD"}, CommonName: fmt.Sprintf("%s@%s", username, hostname), }, NotBefore: validFrom, NotAfter: validTo, KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, BasicConstraintsValid: true, } if client { template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth} } else { template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth} } if addHosts { hosts, err := mynames() if err != nil { return nil, nil, fmt.Errorf("Failed to get my hostname: %w", err) } for _, h := range hosts { ip, _, err := net.ParseCIDR(h) if err == nil { if !ip.IsLinkLocalUnicast() && !ip.IsLinkLocalMulticast() { template.IPAddresses = append(template.IPAddresses, ip) } } else { template.DNSNames = append(template.DNSNames, h) } } } else if !client { template.DNSNames = []string{"unspecified"} } derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &privk.PublicKey, privk) if err != nil { return nil, nil, fmt.Errorf("Failed to create certificate: %w", err) } data, err := x509.MarshalECPrivateKey(privk) if err != nil { return nil, nil, err } cert := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes}) key := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: data}) return cert, key, nil } func ReadCert(fpath string) (*x509.Certificate, error) { cf, err := os.ReadFile(fpath) if err != nil { return nil, err } certBlock, _ := pem.Decode(cf) if certBlock == nil { return nil, fmt.Errorf("Invalid certificate file") } return x509.ParseCertificate(certBlock.Bytes) } func CertFingerprint(cert *x509.Certificate) string { return fmt.Sprintf("%x", sha256.Sum256(cert.Raw)) } func CertFingerprintStr(c string) (string, error) { pemCertificate, _ := pem.Decode([]byte(c)) if pemCertificate == nil { return "", fmt.Errorf("invalid certificate") } cert, err := x509.ParseCertificate(pemCertificate.Bytes) if err != nil { return "", err } return CertFingerprint(cert), nil } func GetRemoteCertificate(address string, useragent string) (*x509.Certificate, error) { // Setup a permissive TLS config tlsConfig, err := GetTLSConfig("", "", "", nil) if err != nil { return nil, err } tlsConfig.InsecureSkipVerify = true tr := &http.Transport{ TLSClientConfig: tlsConfig, DialContext: RFC3493Dialer, Proxy: ProxyFromEnvironment, ExpectContinueTimeout: time.Second * 30, ResponseHeaderTimeout: time.Second * 3600, TLSHandshakeTimeout: time.Second * 5, } // Connect req, err := http.NewRequest("GET", address, nil) if err != nil { return nil, err } if useragent != "" { req.Header.Set("User-Agent", useragent) } client := &http.Client{Transport: tr} resp, err := client.Do(req) if err != nil { return nil, err } // Retrieve the certificate if resp.TLS == nil || len(resp.TLS.PeerCertificates) == 0 { return nil, fmt.Errorf("Unable to read remote TLS certificate") } return resp.TLS.PeerCertificates[0], nil } // CertificateTokenDecode decodes a base64 and JSON encoded certificate add token. func
CertificateTokenDecode
identifier_name
cert.go
convenience to return the underlying public key as an *x509.Certificate. func (c *CertInfo) PublicKeyX509() (*x509.Certificate, error) { return x509.ParseCertificate(c.KeyPair().Certificate[0]) } // PrivateKey is a convenience to encode the underlying private key. func (c *CertInfo) PrivateKey() []byte { ecKey, ok := c.KeyPair().PrivateKey.(*ecdsa.PrivateKey) if ok { data, err := x509.MarshalECPrivateKey(ecKey) if err != nil { return nil } return pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: data}) } rsaKey, ok := c.KeyPair().PrivateKey.(*rsa.PrivateKey) if ok { data := x509.MarshalPKCS1PrivateKey(rsaKey) return pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: data}) } return nil } // Fingerprint returns the fingerprint of the public key. func (c *CertInfo) Fingerprint() string { fingerprint, err := CertFingerprintStr(string(c.PublicKey())) // Parsing should never fail, since we generated the cert ourselves, // but let's check the error for good measure. if err != nil { panic("invalid public key material") } return fingerprint } // CRL returns the certificate revocation list. func (c *CertInfo) CRL() *pkix.CertificateList { return c.crl } // CertKind defines the kind of certificate to generate from scratch in // KeyPairAndCA when it's not there. // // The two possible kinds are client and server, and they differ in the // ext-key-usage bitmaps. See GenerateMemCert for more details. type CertKind int // Possible kinds of certificates. const ( CertClient CertKind = iota CertServer ) // TestingKeyPair returns CertInfo object initialized with a test keypair. It's // meant to be used only by tests. func TestingKeyPair() *CertInfo { keypair, err := tls.X509KeyPair(testCertPEMBlock, testKeyPEMBlock) if err != nil { panic(fmt.Sprintf("invalid X509 keypair material: %v", err)) } cert := &CertInfo{ keypair: keypair, } return cert } // TestingAltKeyPair returns CertInfo object initialized with a test keypair // which differs from the one returned by TestCertInfo. It's meant to be used // only by tests. func TestingAltKeyPair() *CertInfo { keypair, err := tls.X509KeyPair(testAltCertPEMBlock, testAltKeyPEMBlock) if err != nil { panic(fmt.Sprintf("invalid X509 keypair material: %v", err)) } cert := &CertInfo{ keypair: keypair, } return cert } /* * Generate a list of names for which the certificate will be valid. * This will include the hostname and ip address. */ func mynames() ([]string, error) { h, err := os.Hostname() if err != nil { return nil, err } ret := []string{h, "127.0.0.1/8", "::1/128"} return ret, nil } // FindOrGenCert generates a keypair if needed. // The type argument is false for server, true for client. func FindOrGenCert(certf string, keyf string, certtype bool, addHosts bool) error { if PathExists(certf) && PathExists(keyf) { return nil } /* If neither stat succeeded, then this is our first run and we * need to generate cert and privkey */ err := GenCert(certf, keyf, certtype, addHosts) if err != nil { return err } return nil } // GenCert will create and populate a certificate file and a key file. func GenCert(certf string, keyf string, certtype bool, addHosts bool) error { /* Create the basenames if needed */ dir := filepath.Dir(certf) err := os.MkdirAll(dir, 0750) if err != nil { return err } dir = filepath.Dir(keyf) err = os.MkdirAll(dir, 0750) if err != nil { return err } certBytes, keyBytes, err := GenerateMemCert(certtype, addHosts) if err != nil { return err } certOut, err := os.Create(certf) if err != nil { return fmt.Errorf("Failed to open %s for writing: %w", certf, err) } _, err = certOut.Write(certBytes) if err != nil { return fmt.Errorf("Failed to write cert file: %w", err) } err = certOut.Close() if err != nil { return fmt.Errorf("Failed to close cert file: %w", err) } keyOut, err := os.OpenFile(keyf, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) if err != nil { return fmt.Errorf("Failed to open %s for writing: %w", keyf, err) } _, err = keyOut.Write(keyBytes) if err != nil { return fmt.Errorf("Failed to write key file: %w", err) } err = keyOut.Close() if err != nil { return fmt.Errorf("Failed to close key file: %w", err) } return nil } // GenerateMemCert creates client or server certificate and key pair, // returning them as byte arrays in memory. func GenerateMemCert(client bool, addHosts bool) ([]byte, []byte, error) { privk, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader) if err != nil { return nil, nil, fmt.Errorf("Failed to generate key: %w", err) } validFrom := time.Now() validTo := validFrom.Add(10 * 365 * 24 * time.Hour) serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) if err != nil { return nil, nil, fmt.Errorf("Failed to generate serial number: %w", err) } userEntry, err := user.Current() var username string if err == nil { username = userEntry.Username if username == "" { username = "UNKNOWN" } } else { username = "UNKNOWN" } hostname, err := os.Hostname() if err != nil { hostname = "UNKNOWN" } template := x509.Certificate{ SerialNumber: serialNumber, Subject: pkix.Name{ Organization: []string{"LXD"}, CommonName: fmt.Sprintf("%s@%s", username, hostname), }, NotBefore: validFrom, NotAfter: validTo, KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, BasicConstraintsValid: true, } if client { template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth} } else { template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth} } if addHosts { hosts, err := mynames() if err != nil { return nil, nil, fmt.Errorf("Failed to get my hostname: %w", err) } for _, h := range hosts { ip, _, err := net.ParseCIDR(h) if err == nil { if !ip.IsLinkLocalUnicast() && !ip.IsLinkLocalMulticast() { template.IPAddresses = append(template.IPAddresses, ip) } } else { template.DNSNames = append(template.DNSNames, h) } } } else if !client { template.DNSNames = []string{"unspecified"} } derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &privk.PublicKey, privk) if err != nil { return nil, nil, fmt.Errorf("Failed to create certificate: %w", err) } data, err := x509.MarshalECPrivateKey(privk) if err != nil { return nil, nil, err } cert := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes}) key := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: data}) return cert, key, nil } func ReadCert(fpath string) (*x509.Certificate, error) { cf, err := os.ReadFile(fpath) if err != nil { return nil, err } certBlock, _ := pem.Decode(cf) if certBlock == nil { return nil, fmt.Errorf("Invalid certificate file") } return x509.ParseCertificate(certBlock.Bytes) } func CertFingerprint(cert *x509.Certificate) string
{ return fmt.Sprintf("%x", sha256.Sum256(cert.Raw)) }
identifier_body
cert.go
.Block{Type: "CERTIFICATE", Bytes: data}) } // PublicKeyX509 is a convenience to return the underlying public key as an *x509.Certificate. func (c *CertInfo) PublicKeyX509() (*x509.Certificate, error) { return x509.ParseCertificate(c.KeyPair().Certificate[0]) } // PrivateKey is a convenience to encode the underlying private key. func (c *CertInfo) PrivateKey() []byte { ecKey, ok := c.KeyPair().PrivateKey.(*ecdsa.PrivateKey) if ok { data, err := x509.MarshalECPrivateKey(ecKey) if err != nil { return nil } return pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: data}) } rsaKey, ok := c.KeyPair().PrivateKey.(*rsa.PrivateKey) if ok { data := x509.MarshalPKCS1PrivateKey(rsaKey) return pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: data}) } return nil } // Fingerprint returns the fingerprint of the public key. func (c *CertInfo) Fingerprint() string { fingerprint, err := CertFingerprintStr(string(c.PublicKey())) // Parsing should never fail, since we generated the cert ourselves, // but let's check the error for good measure. if err != nil { panic("invalid public key material") } return fingerprint } // CRL returns the certificate revocation list. func (c *CertInfo) CRL() *pkix.CertificateList { return c.crl } // CertKind defines the kind of certificate to generate from scratch in // KeyPairAndCA when it's not there. // // The two possible kinds are client and server, and they differ in the // ext-key-usage bitmaps. See GenerateMemCert for more details. type CertKind int // Possible kinds of certificates. const ( CertClient CertKind = iota CertServer ) // TestingKeyPair returns CertInfo object initialized with a test keypair. It's // meant to be used only by tests. func TestingKeyPair() *CertInfo { keypair, err := tls.X509KeyPair(testCertPEMBlock, testKeyPEMBlock) if err != nil { panic(fmt.Sprintf("invalid X509 keypair material: %v", err)) } cert := &CertInfo{ keypair: keypair, } return cert } // TestingAltKeyPair returns CertInfo object initialized with a test keypair // which differs from the one returned by TestCertInfo. It's meant to be used // only by tests. func TestingAltKeyPair() *CertInfo { keypair, err := tls.X509KeyPair(testAltCertPEMBlock, testAltKeyPEMBlock) if err != nil { panic(fmt.Sprintf("invalid X509 keypair material: %v", err)) } cert := &CertInfo{ keypair: keypair, } return cert } /* * Generate a list of names for which the certificate will be valid. * This will include the hostname and ip address. */ func mynames() ([]string, error) { h, err := os.Hostname() if err != nil { return nil, err } ret := []string{h, "127.0.0.1/8", "::1/128"} return ret, nil } // FindOrGenCert generates a keypair if needed. // The type argument is false for server, true for client. func FindOrGenCert(certf string, keyf string, certtype bool, addHosts bool) error { if PathExists(certf) && PathExists(keyf) { return nil } /* If neither stat succeeded, then this is our first run and we * need to generate cert and privkey */ err := GenCert(certf, keyf, certtype, addHosts) if err != nil { return err } return nil } // GenCert will create and populate a certificate file and a key file. func GenCert(certf string, keyf string, certtype bool, addHosts bool) error { /* Create the basenames if needed */ dir := filepath.Dir(certf) err := os.MkdirAll(dir, 0750) if err != nil { return err } dir = filepath.Dir(keyf) err = os.MkdirAll(dir, 0750) if err != nil { return err } certBytes, keyBytes, err := GenerateMemCert(certtype, addHosts) if err != nil { return err } certOut, err := os.Create(certf) if err != nil { return fmt.Errorf("Failed to open %s for writing: %w", certf, err) } _, err = certOut.Write(certBytes) if err != nil { return fmt.Errorf("Failed to write cert file: %w", err) } err = certOut.Close() if err != nil { return fmt.Errorf("Failed to close cert file: %w", err) } keyOut, err := os.OpenFile(keyf, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) if err != nil { return fmt.Errorf("Failed to open %s for writing: %w", keyf, err) } _, err = keyOut.Write(keyBytes) if err != nil { return fmt.Errorf("Failed to write key file: %w", err) } err = keyOut.Close() if err != nil { return fmt.Errorf("Failed to close key file: %w", err) } return nil } // GenerateMemCert creates client or server certificate and key pair, // returning them as byte arrays in memory. func GenerateMemCert(client bool, addHosts bool) ([]byte, []byte, error) { privk, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader) if err != nil { return nil, nil, fmt.Errorf("Failed to generate key: %w", err) } validFrom := time.Now() validTo := validFrom.Add(10 * 365 * 24 * time.Hour) serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) if err != nil { return nil, nil, fmt.Errorf("Failed to generate serial number: %w", err) } userEntry, err := user.Current() var username string if err == nil { username = userEntry.Username if username == "" { username = "UNKNOWN" }
if err != nil { hostname = "UNKNOWN" } template := x509.Certificate{ SerialNumber: serialNumber, Subject: pkix.Name{ Organization: []string{"LXD"}, CommonName: fmt.Sprintf("%s@%s", username, hostname), }, NotBefore: validFrom, NotAfter: validTo, KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, BasicConstraintsValid: true, } if client { template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth} } else { template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth} } if addHosts { hosts, err := mynames() if err != nil { return nil, nil, fmt.Errorf("Failed to get my hostname: %w", err) } for _, h := range hosts { ip, _, err := net.ParseCIDR(h) if err == nil { if !ip.IsLinkLocalUnicast() && !ip.IsLinkLocalMulticast() { template.IPAddresses = append(template.IPAddresses, ip) } } else { template.DNSNames = append(template.DNSNames, h) } } } else if !client { template.DNSNames = []string{"unspecified"} } derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &privk.PublicKey, privk) if err != nil { return nil, nil, fmt.Errorf("Failed to create certificate: %w", err) } data, err := x509.MarshalECPrivateKey(privk) if err != nil { return nil, nil, err } cert := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes}) key := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: data}) return cert, key, nil } func ReadCert(fpath string) (*x509.Certificate, error) { cf, err := os.ReadFile(fpath) if err != nil { return nil, err } certBlock, _ := pem.Decode(cf) if certBlock == nil { return nil, fmt.Errorf("Invalid certificate file") } return x509.ParseCertificate(certBlock.Bytes) } func CertFingerprint(cert *x509.Certificate)
} else { username = "UNKNOWN" } hostname, err := os.Hostname()
random_line_split
cert.go
.Block{Type: "CERTIFICATE", Bytes: data}) } // PublicKeyX509 is a convenience to return the underlying public key as an *x509.Certificate. func (c *CertInfo) PublicKeyX509() (*x509.Certificate, error) { return x509.ParseCertificate(c.KeyPair().Certificate[0]) } // PrivateKey is a convenience to encode the underlying private key. func (c *CertInfo) PrivateKey() []byte { ecKey, ok := c.KeyPair().PrivateKey.(*ecdsa.PrivateKey) if ok { data, err := x509.MarshalECPrivateKey(ecKey) if err != nil { return nil } return pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: data}) } rsaKey, ok := c.KeyPair().PrivateKey.(*rsa.PrivateKey) if ok { data := x509.MarshalPKCS1PrivateKey(rsaKey) return pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: data}) } return nil } // Fingerprint returns the fingerprint of the public key. func (c *CertInfo) Fingerprint() string { fingerprint, err := CertFingerprintStr(string(c.PublicKey())) // Parsing should never fail, since we generated the cert ourselves, // but let's check the error for good measure. if err != nil { panic("invalid public key material") } return fingerprint } // CRL returns the certificate revocation list. func (c *CertInfo) CRL() *pkix.CertificateList { return c.crl } // CertKind defines the kind of certificate to generate from scratch in // KeyPairAndCA when it's not there. // // The two possible kinds are client and server, and they differ in the // ext-key-usage bitmaps. See GenerateMemCert for more details. type CertKind int // Possible kinds of certificates. const ( CertClient CertKind = iota CertServer ) // TestingKeyPair returns CertInfo object initialized with a test keypair. It's // meant to be used only by tests. func TestingKeyPair() *CertInfo { keypair, err := tls.X509KeyPair(testCertPEMBlock, testKeyPEMBlock) if err != nil { panic(fmt.Sprintf("invalid X509 keypair material: %v", err)) } cert := &CertInfo{ keypair: keypair, } return cert } // TestingAltKeyPair returns CertInfo object initialized with a test keypair // which differs from the one returned by TestCertInfo. It's meant to be used // only by tests. func TestingAltKeyPair() *CertInfo { keypair, err := tls.X509KeyPair(testAltCertPEMBlock, testAltKeyPEMBlock) if err != nil { panic(fmt.Sprintf("invalid X509 keypair material: %v", err)) } cert := &CertInfo{ keypair: keypair, } return cert } /* * Generate a list of names for which the certificate will be valid. * This will include the hostname and ip address. */ func mynames() ([]string, error) { h, err := os.Hostname() if err != nil { return nil, err } ret := []string{h, "127.0.0.1/8", "::1/128"} return ret, nil } // FindOrGenCert generates a keypair if needed. // The type argument is false for server, true for client. func FindOrGenCert(certf string, keyf string, certtype bool, addHosts bool) error { if PathExists(certf) && PathExists(keyf) { return nil } /* If neither stat succeeded, then this is our first run and we * need to generate cert and privkey */ err := GenCert(certf, keyf, certtype, addHosts) if err != nil { return err } return nil } // GenCert will create and populate a certificate file and a key file. func GenCert(certf string, keyf string, certtype bool, addHosts bool) error { /* Create the basenames if needed */ dir := filepath.Dir(certf) err := os.MkdirAll(dir, 0750) if err != nil
dir = filepath.Dir(keyf) err = os.MkdirAll(dir, 0750) if err != nil { return err } certBytes, keyBytes, err := GenerateMemCert(certtype, addHosts) if err != nil { return err } certOut, err := os.Create(certf) if err != nil { return fmt.Errorf("Failed to open %s for writing: %w", certf, err) } _, err = certOut.Write(certBytes) if err != nil { return fmt.Errorf("Failed to write cert file: %w", err) } err = certOut.Close() if err != nil { return fmt.Errorf("Failed to close cert file: %w", err) } keyOut, err := os.OpenFile(keyf, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) if err != nil { return fmt.Errorf("Failed to open %s for writing: %w", keyf, err) } _, err = keyOut.Write(keyBytes) if err != nil { return fmt.Errorf("Failed to write key file: %w", err) } err = keyOut.Close() if err != nil { return fmt.Errorf("Failed to close key file: %w", err) } return nil } // GenerateMemCert creates client or server certificate and key pair, // returning them as byte arrays in memory. func GenerateMemCert(client bool, addHosts bool) ([]byte, []byte, error) { privk, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader) if err != nil { return nil, nil, fmt.Errorf("Failed to generate key: %w", err) } validFrom := time.Now() validTo := validFrom.Add(10 * 365 * 24 * time.Hour) serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) if err != nil { return nil, nil, fmt.Errorf("Failed to generate serial number: %w", err) } userEntry, err := user.Current() var username string if err == nil { username = userEntry.Username if username == "" { username = "UNKNOWN" } } else { username = "UNKNOWN" } hostname, err := os.Hostname() if err != nil { hostname = "UNKNOWN" } template := x509.Certificate{ SerialNumber: serialNumber, Subject: pkix.Name{ Organization: []string{"LXD"}, CommonName: fmt.Sprintf("%s@%s", username, hostname), }, NotBefore: validFrom, NotAfter: validTo, KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, BasicConstraintsValid: true, } if client { template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth} } else { template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth} } if addHosts { hosts, err := mynames() if err != nil { return nil, nil, fmt.Errorf("Failed to get my hostname: %w", err) } for _, h := range hosts { ip, _, err := net.ParseCIDR(h) if err == nil { if !ip.IsLinkLocalUnicast() && !ip.IsLinkLocalMulticast() { template.IPAddresses = append(template.IPAddresses, ip) } } else { template.DNSNames = append(template.DNSNames, h) } } } else if !client { template.DNSNames = []string{"unspecified"} } derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &privk.PublicKey, privk) if err != nil { return nil, nil, fmt.Errorf("Failed to create certificate: %w", err) } data, err := x509.MarshalECPrivateKey(privk) if err != nil { return nil, nil, err } cert := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes}) key := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: data}) return cert, key, nil } func ReadCert(fpath string) (*x509.Certificate, error) { cf, err := os.ReadFile(fpath) if err != nil { return nil, err } certBlock, _ := pem.Decode(cf) if certBlock == nil { return nil, fmt.Errorf("Invalid certificate file") } return x509.ParseCertificate(certBlock.Bytes) } func CertFingerprint(cert *x509.C
{ return err }
conditional_block
ycsb.rs
bytes of the key matter, the rest are zero. The value is always zero. self.workload.borrow_mut().abc( |tenant, key| { // First 11 bytes on the payload were already pre-populated with the // extension name (3 bytes), and the table id (8 bytes). Just write in the // first 4 bytes of the key. p_get[11..15].copy_from_slice(&key[0..4]); self.sender.send_invoke(tenant, 3, &p_get, curr) }, |tenant, key, _val| { // First 13 bytes on the payload were already pre-populated with the // extension name (3 bytes), the table id (8 bytes), and the key length (2 // bytes). Just write in the first 4 bytes of the key. The value is anyway // always zero. p_put[13..17].copy_from_slice(&key[0..4]); self.sender.send_invoke(tenant, 3, &p_put, curr) }, ); } // Update the time stamp at which the next request should be generated, assuming that // the first request was sent out at self.start. self.sent += 1; self.next = self.start + self.sent * self.rate_inv; } } fn dependencies(&mut self) -> Vec<usize> { vec![] } } /// Receives responses to YCSB requests sent out by YcsbSend. struct YcsbRecv<T> where T: PacketTx + PacketRx + Display + Clone + 'static, { // The network stack required to receives RPC response packets from a network port. receiver: dispatch::Receiver<T>, // The number of response packets to wait for before printing out statistics. responses: u64, // Time stamp in cycles at which measurement started. Required to calculate observed // throughput of the Sandstorm server. start: u64, // The total number of responses received so far. recvd: u64, // Vector of sampled request latencies. Required to calculate distributions once all responses // have been received. latencies: Vec<u64>, // If true, this receiver will make latency measurements. master: bool, // If true, then responses will be considered to correspond to native gets and puts. native: bool, // Time stamp in cycles at which measurement stopped. stop: u64, } // Implementation of methods on YcsbRecv. impl<T> YcsbRecv<T> where T: PacketTx + PacketRx + Display + Clone + 'static, { /// Constructs a YcsbRecv. /// /// # Arguments /// /// * `port` : Network port on which responses will be polled for. /// * `resps`: The number of responses to wait for before calculating statistics. /// * `master`: Boolean indicating if the receiver should make latency measurements. /// * `native`: If true, responses will be considered to correspond to native gets and puts. /// /// # Return /// /// A YCSB response receiver that measures the median latency and throughput of a Sandstorm /// server. fn new(port: T, resps: u64, master: bool, native: bool) -> YcsbRecv<T> { YcsbRecv { receiver: dispatch::Receiver::new(port), responses: resps, start: cycles::rdtsc(), recvd: 0, latencies: Vec::with_capacity(resps as usize), master: master, native: native, stop: 0, } } } // Implementation of the `Drop` trait on YcsbRecv. impl<T> Drop for YcsbRecv<T> where T: PacketTx + PacketRx + Display + Clone + 'static, { fn drop(&mut self) { // Calculate & print the throughput for all client threads. println!( "YCSB Throughput {}", self.recvd as f64 / cycles::to_seconds(self.stop - self.start) ); // Calculate & print median & tail latency only on the master thread. if self.master { self.latencies.sort(); let m; let t = self.latencies[(self.latencies.len() * 99) / 100]; match self.latencies.len() % 2 { 0 => { let n = self.latencies.len(); m = (self.latencies[n / 2] + self.latencies[(n / 2) + 1]) / 2; } _ => m = self.latencies[self.latencies.len() / 2], } println!( ">>> {} {}", cycles::to_seconds(m) * 1e9, cycles::to_seconds(t) * 1e9 ); } } } // Executable trait allowing YcsbRecv to be scheduled by Netbricks. impl<T> Executable for YcsbRecv<T> where T: PacketTx + PacketRx + Display + Clone + 'static, { // Called internally by Netbricks. fn execute(&mut self) { // Don't do anything after all responses have been received. if self.responses <= self.recvd { return; } // Try to receive packets from the network port. // If there are packets, sample the latency of the server. if let Some(mut packets) = self.receiver.recv_res() { while let Some(packet) = packets.pop() { self.recvd += 1; // Measure latency on the master client after the first 2 million requests. // The start timestamp is present on the RPC response header. if self.recvd > 2 * 1000 * 1000 && self.master { let curr = cycles::rdtsc(); match self.native { // The response corresponds to an invoke() RPC. false => { let p = packet.parse_header::<InvokeResponse>(); self.latencies .push(curr - p.get_header().common_header.stamp); p.free_packet(); } // The response corresponds to a get() or put() RPC. // The opcode on the response identifies the RPC type. true => match parse_rpc_opcode(&packet) { OpCode::SandstormGetRpc => { let p = packet.parse_header::<GetResponse>(); self.latencies .push(curr - p.get_header().common_header.stamp); p.free_packet(); } OpCode::SandstormPutRpc => { let p = packet.parse_header::<PutResponse>(); self.latencies .push(curr - p.get_header().common_header.stamp); p.free_packet(); } _ => packet.free_packet(), }, } } else { packet.free_packet(); } } } // The moment all response packets have been received, set the value of the // stop timestamp so that throughput can be estimated later. if self.responses <= self.recvd { self.stop = cycles::rdtsc(); } } fn dependencies(&mut self) -> Vec<usize> { vec![] } } /// Sets up YcsbSend by adding it to a Netbricks scheduler. /// /// # Arguments /// /// * `config`: Network related configuration such as the MAC and IP address. /// * `ports`: Network port on which packets will be sent. /// * `scheduler`: Netbricks scheduler to which YcsbSend will be added. fn setup_send<S>( config: &config::ClientConfig, ports: Vec<CacheAligned<PortQueue>>, scheduler: &mut S, _core: i32, ) where S: Scheduler + Sized, { if ports.len() != 1 { error!("Client should be configured with exactly 1 port!"); std::process::exit(1); } // Add the sender to a netbricks pipeline. match scheduler.add_task(YcsbSend::new( config, ports[0].clone(), config.num_reqs as u64, config.server_udp_ports as u16, )) { Ok(_) => { info!( "Successfully added YcsbSend with tx queue {}.", ports[0].txq() ); } Err(ref err) => { error!("Error while adding to Netbricks pipeline {}", err); std::process::exit(1); } } } /// Sets up YcsbRecv by adding it to a Netbricks scheduler. /// /// # Arguments /// /// * `ports`: Network port on which packets will be sent. /// * `scheduler`: Netbricks scheduler to which YcsbRecv will be added. /// * `master`: If true, the added YcsbRecv will make latency measurements. /// * `native`: If true, the added YcsbRecv will assume that responses correspond to gets /// and puts. fn setup_recv<S>( ports: Vec<CacheAligned<PortQueue>>, scheduler: &mut S, _core: i32, master: bool, native: bool, ) where S: Scheduler + Sized, { if ports.len() != 1
{ error!("Client should be configured with exactly 1 port!"); std::process::exit(1); }
conditional_block
ycsb.rs
out so far. sent: u64, // The inverse of the rate at which requests are to be generated. Basically, the time interval // between two request generations in cycles. rate_inv: u64, // The time stamp at which the workload started generating requests in cycles. start: u64, // The time stamp at which the next request must be issued in cycles. next: u64, // If true, RPC requests corresponding to native get() and put() operations are sent out. If // false, invoke() based RPC requests are sent out. native: bool, // Payload for an invoke() based get operation. Required in order to avoid making intermediate // copies of the extension name, table id, and key. payload_get: RefCell<Vec<u8>>, // Payload for an invoke() based put operation. Required in order to avoid making intermediate // copies of the extension name, table id, key length, key, and value. payload_put: RefCell<Vec<u8>>, } // Implementation of methods on YcsbSend. impl YcsbSend { /// Constructs a YcsbSend. /// /// # Arguments /// /// * `config`: Client configuration with YCSB related (key and value length etc.) as well as /// Network related (Server and Client MAC address etc.) parameters. /// * `port`: Network port over which requests will be sent out. /// * `reqs`: The number of requests to be issued to the server. /// * `dst_ports`: The total number of UDP ports the server is listening on. /// /// # Return /// /// A YCSB request generator. fn new( config: &config::ClientConfig, port: CacheAligned<PortQueue>, reqs: u64, dst_ports: u16, ) -> YcsbSend { // The payload on an invoke() based get request consists of the extensions name ("get"), // the table id to perform the lookup on, and the key to lookup. let payload_len = "get".as_bytes().len() + mem::size_of::<u64>() + config.key_len; let mut payload_get = Vec::with_capacity(payload_len); payload_get.extend_from_slice("get".as_bytes()); payload_get.extend_from_slice(&unsafe { transmute::<u64, [u8; 8]>(1u64.to_le()) }); payload_get.resize(payload_len, 0); // The payload on an invoke() based put request consists of the extensions name ("put"), // the table id to perform the lookup on, the length of the key to lookup, the key, and the // value to be inserted into the database. let payload_len = "put".as_bytes().len() + mem::size_of::<u64>() + mem::size_of::<u16>() + config.key_len + config.value_len; let mut payload_put = Vec::with_capacity(payload_len); payload_put.extend_from_slice("put".as_bytes()); payload_put.extend_from_slice(&unsafe { transmute::<u64, [u8; 8]>(1u64.to_le()) }); payload_put.extend_from_slice(&unsafe { transmute::<u16, [u8; 2]>((config.key_len as u16).to_le()) }); payload_put.resize(payload_len, 0); YcsbSend { workload: RefCell::new(Ycsb::new( config.key_len, config.value_len, config.n_keys, config.put_pct, config.skew, config.num_tenants, config.tenant_skew, )), sender: dispatch::Sender::new(config, port, dst_ports), requests: reqs, sent: 0, rate_inv: cycles::cycles_per_second() / config.req_rate as u64, start: cycles::rdtsc(), next: 0, native: !config.use_invoke, payload_get: RefCell::new(payload_get), payload_put: RefCell::new(payload_put), } } } // The Executable trait allowing YcsbSend to be scheduled by Netbricks. impl Executable for YcsbSend { // Called internally by Netbricks. fn execute(&mut self)
let mut p_get = self.payload_get.borrow_mut(); let mut p_put = self.payload_put.borrow_mut(); // XXX Heavily dependent on how `Ycsb` creates a key. Only the first four // bytes of the key matter, the rest are zero. The value is always zero. self.workload.borrow_mut().abc( |tenant, key| { // First 11 bytes on the payload were already pre-populated with the // extension name (3 bytes), and the table id (8 bytes). Just write in the // first 4 bytes of the key. p_get[11..15].copy_from_slice(&key[0..4]); self.sender.send_invoke(tenant, 3, &p_get, curr) }, |tenant, key, _val| { // First 13 bytes on the payload were already pre-populated with the // extension name (3 bytes), the table id (8 bytes), and the key length (2 // bytes). Just write in the first 4 bytes of the key. The value is anyway // always zero. p_put[13..17].copy_from_slice(&key[0..4]); self.sender.send_invoke(tenant, 3, &p_put, curr) }, ); } // Update the time stamp at which the next request should be generated, assuming that // the first request was sent out at self.start. self.sent += 1; self.next = self.start + self.sent * self.rate_inv; } } fn dependencies(&mut self) -> Vec<usize> { vec![] } } /// Receives responses to YCSB requests sent out by YcsbSend. struct YcsbRecv<T> where T: PacketTx + PacketRx + Display + Clone + 'static, { // The network stack required to receives RPC response packets from a network port. receiver: dispatch::Receiver<T>, // The number of response packets to wait for before printing out statistics. responses: u64, // Time stamp in cycles at which measurement started. Required to calculate observed // throughput of the Sandstorm server. start: u64, // The total number of responses received so far. recvd: u64, // Vector of sampled request latencies. Required to calculate distributions once all responses // have been received. latencies: Vec<u64>, // If true, this receiver will make latency measurements. master: bool, // If true, then responses will be considered to correspond to native gets and puts. native: bool, // Time stamp in cycles at which measurement stopped. stop: u64, } // Implementation of methods on YcsbRecv. impl<T> YcsbRecv<T> where T: PacketTx + PacketRx + Display + Clone + 'static, { /// Constructs a YcsbRecv. /// /// # Arguments /// /// * `port` : Network port on which responses will be polled for. /// * `resps`: The number of responses to wait for before calculating statistics. /// * `master`: Boolean indicating if the receiver should make latency measurements. /// * `native`: If true, responses will be considered to correspond to native gets and puts. /// /// # Return /// /// A YCSB response receiver that measures the median latency and throughput of a Sandstorm /// server. fn new(port: T, resps: u64, master: bool, native: bool) -> YcsbRecv<T> { YcsbRecv { receiver: dispatch::Receiver::new(port), responses: resps, start: cycles::rdtsc(), recvd: 0, latencies: Vec::with_capacity(resps as usize), master: master, native: native, stop: 0, } } } // Implementation of the `Drop` trait on YcsbRecv. impl<T> Drop for YcsbRecv<T> where T: PacketTx + Packet
{ // Return if there are no more requests to generate. if self.requests <= self.sent { return; } // Get the current time stamp so that we can determine if it is time to issue the next RPC. let curr = cycles::rdtsc(); // If it is either time to send out a request, or if a request has never been sent out, // then, do so. if curr >= self.next || self.next == 0 { if self.native == true { // Configured to issue native RPCs, issue a regular get()/put() operation. self.workload.borrow_mut().abc( |tenant, key| self.sender.send_get(tenant, 1, key, curr), |tenant, key, val| self.sender.send_put(tenant, 1, key, val, curr), ); } else { // Configured to issue invoke() RPCs.
identifier_body
ycsb.rs
, &p_put, curr) }, ); } // Update the time stamp at which the next request should be generated, assuming that // the first request was sent out at self.start. self.sent += 1; self.next = self.start + self.sent * self.rate_inv; } } fn dependencies(&mut self) -> Vec<usize> { vec![] } } /// Receives responses to YCSB requests sent out by YcsbSend. struct YcsbRecv<T> where T: PacketTx + PacketRx + Display + Clone + 'static, { // The network stack required to receives RPC response packets from a network port. receiver: dispatch::Receiver<T>, // The number of response packets to wait for before printing out statistics. responses: u64, // Time stamp in cycles at which measurement started. Required to calculate observed // throughput of the Sandstorm server. start: u64, // The total number of responses received so far. recvd: u64, // Vector of sampled request latencies. Required to calculate distributions once all responses // have been received. latencies: Vec<u64>, // If true, this receiver will make latency measurements. master: bool, // If true, then responses will be considered to correspond to native gets and puts. native: bool, // Time stamp in cycles at which measurement stopped. stop: u64, } // Implementation of methods on YcsbRecv. impl<T> YcsbRecv<T> where T: PacketTx + PacketRx + Display + Clone + 'static, { /// Constructs a YcsbRecv. /// /// # Arguments /// /// * `port` : Network port on which responses will be polled for. /// * `resps`: The number of responses to wait for before calculating statistics. /// * `master`: Boolean indicating if the receiver should make latency measurements. /// * `native`: If true, responses will be considered to correspond to native gets and puts. /// /// # Return /// /// A YCSB response receiver that measures the median latency and throughput of a Sandstorm /// server. fn new(port: T, resps: u64, master: bool, native: bool) -> YcsbRecv<T> { YcsbRecv { receiver: dispatch::Receiver::new(port), responses: resps, start: cycles::rdtsc(), recvd: 0, latencies: Vec::with_capacity(resps as usize), master: master, native: native, stop: 0, } } } // Implementation of the `Drop` trait on YcsbRecv. impl<T> Drop for YcsbRecv<T> where T: PacketTx + PacketRx + Display + Clone + 'static, { fn drop(&mut self) { // Calculate & print the throughput for all client threads. println!( "YCSB Throughput {}", self.recvd as f64 / cycles::to_seconds(self.stop - self.start) ); // Calculate & print median & tail latency only on the master thread. if self.master { self.latencies.sort(); let m; let t = self.latencies[(self.latencies.len() * 99) / 100]; match self.latencies.len() % 2 { 0 => { let n = self.latencies.len(); m = (self.latencies[n / 2] + self.latencies[(n / 2) + 1]) / 2; } _ => m = self.latencies[self.latencies.len() / 2], } println!( ">>> {} {}", cycles::to_seconds(m) * 1e9, cycles::to_seconds(t) * 1e9 ); } } } // Executable trait allowing YcsbRecv to be scheduled by Netbricks. impl<T> Executable for YcsbRecv<T> where T: PacketTx + PacketRx + Display + Clone + 'static, { // Called internally by Netbricks. fn execute(&mut self) { // Don't do anything after all responses have been received. if self.responses <= self.recvd { return; } // Try to receive packets from the network port. // If there are packets, sample the latency of the server. if let Some(mut packets) = self.receiver.recv_res() { while let Some(packet) = packets.pop() { self.recvd += 1; // Measure latency on the master client after the first 2 million requests. // The start timestamp is present on the RPC response header. if self.recvd > 2 * 1000 * 1000 && self.master { let curr = cycles::rdtsc(); match self.native { // The response corresponds to an invoke() RPC. false => { let p = packet.parse_header::<InvokeResponse>(); self.latencies .push(curr - p.get_header().common_header.stamp); p.free_packet(); } // The response corresponds to a get() or put() RPC. // The opcode on the response identifies the RPC type. true => match parse_rpc_opcode(&packet) { OpCode::SandstormGetRpc => { let p = packet.parse_header::<GetResponse>(); self.latencies .push(curr - p.get_header().common_header.stamp); p.free_packet(); } OpCode::SandstormPutRpc => { let p = packet.parse_header::<PutResponse>(); self.latencies .push(curr - p.get_header().common_header.stamp); p.free_packet(); } _ => packet.free_packet(), }, } } else { packet.free_packet(); } } } // The moment all response packets have been received, set the value of the // stop timestamp so that throughput can be estimated later. if self.responses <= self.recvd { self.stop = cycles::rdtsc(); } } fn dependencies(&mut self) -> Vec<usize> { vec![] } } /// Sets up YcsbSend by adding it to a Netbricks scheduler. /// /// # Arguments /// /// * `config`: Network related configuration such as the MAC and IP address. /// * `ports`: Network port on which packets will be sent. /// * `scheduler`: Netbricks scheduler to which YcsbSend will be added. fn setup_send<S>( config: &config::ClientConfig, ports: Vec<CacheAligned<PortQueue>>, scheduler: &mut S, _core: i32, ) where S: Scheduler + Sized, { if ports.len() != 1 { error!("Client should be configured with exactly 1 port!"); std::process::exit(1); } // Add the sender to a netbricks pipeline. match scheduler.add_task(YcsbSend::new( config, ports[0].clone(), config.num_reqs as u64, config.server_udp_ports as u16, )) { Ok(_) => { info!( "Successfully added YcsbSend with tx queue {}.", ports[0].txq() ); } Err(ref err) => { error!("Error while adding to Netbricks pipeline {}", err); std::process::exit(1); } } } /// Sets up YcsbRecv by adding it to a Netbricks scheduler. /// /// # Arguments /// /// * `ports`: Network port on which packets will be sent. /// * `scheduler`: Netbricks scheduler to which YcsbRecv will be added. /// * `master`: If true, the added YcsbRecv will make latency measurements. /// * `native`: If true, the added YcsbRecv will assume that responses correspond to gets /// and puts. fn setup_recv<S>( ports: Vec<CacheAligned<PortQueue>>, scheduler: &mut S, _core: i32, master: bool, native: bool, ) where S: Scheduler + Sized, { if ports.len() != 1 { error!("Client should be configured with exactly 1 port!"); std::process::exit(1); } // Add the receiver to a netbricks pipeline. match scheduler.add_task(YcsbRecv::new( ports[0].clone(), 34 * 1000 * 1000 as u64, master, native, )) { Ok(_) => { info!( "Successfully added YcsbRecv with rx queue {}.", ports[0].rxq() ); } Err(ref err) => { error!("Error while adding to Netbricks pipeline {}", err); std::process::exit(1); } } } fn main() { db::env_logger::init().expect("ERROR: failed to initialize logger!"); let config = config::ClientConfig::load(); info!("Starting up Sandstorm client with config {:?}", config); // Based on the supplied client configuration, compute the amount of time it will take to send // out `num_reqs` requests at a rate of `req_rate` requests per second. let exec = config.num_reqs / config.req_rate;
random_line_split
ycsb.rs
out so far. sent: u64, // The inverse of the rate at which requests are to be generated. Basically, the time interval // between two request generations in cycles. rate_inv: u64, // The time stamp at which the workload started generating requests in cycles. start: u64, // The time stamp at which the next request must be issued in cycles. next: u64, // If true, RPC requests corresponding to native get() and put() operations are sent out. If // false, invoke() based RPC requests are sent out. native: bool, // Payload for an invoke() based get operation. Required in order to avoid making intermediate // copies of the extension name, table id, and key. payload_get: RefCell<Vec<u8>>, // Payload for an invoke() based put operation. Required in order to avoid making intermediate // copies of the extension name, table id, key length, key, and value. payload_put: RefCell<Vec<u8>>, } // Implementation of methods on YcsbSend. impl YcsbSend { /// Constructs a YcsbSend. /// /// # Arguments /// /// * `config`: Client configuration with YCSB related (key and value length etc.) as well as /// Network related (Server and Client MAC address etc.) parameters. /// * `port`: Network port over which requests will be sent out. /// * `reqs`: The number of requests to be issued to the server. /// * `dst_ports`: The total number of UDP ports the server is listening on. /// /// # Return /// /// A YCSB request generator. fn new( config: &config::ClientConfig, port: CacheAligned<PortQueue>, reqs: u64, dst_ports: u16, ) -> YcsbSend { // The payload on an invoke() based get request consists of the extensions name ("get"), // the table id to perform the lookup on, and the key to lookup. let payload_len = "get".as_bytes().len() + mem::size_of::<u64>() + config.key_len; let mut payload_get = Vec::with_capacity(payload_len); payload_get.extend_from_slice("get".as_bytes()); payload_get.extend_from_slice(&unsafe { transmute::<u64, [u8; 8]>(1u64.to_le()) }); payload_get.resize(payload_len, 0); // The payload on an invoke() based put request consists of the extensions name ("put"), // the table id to perform the lookup on, the length of the key to lookup, the key, and the // value to be inserted into the database. let payload_len = "put".as_bytes().len() + mem::size_of::<u64>() + mem::size_of::<u16>() + config.key_len + config.value_len; let mut payload_put = Vec::with_capacity(payload_len); payload_put.extend_from_slice("put".as_bytes()); payload_put.extend_from_slice(&unsafe { transmute::<u64, [u8; 8]>(1u64.to_le()) }); payload_put.extend_from_slice(&unsafe { transmute::<u16, [u8; 2]>((config.key_len as u16).to_le()) }); payload_put.resize(payload_len, 0); YcsbSend { workload: RefCell::new(Ycsb::new( config.key_len, config.value_len, config.n_keys, config.put_pct, config.skew, config.num_tenants, config.tenant_skew, )), sender: dispatch::Sender::new(config, port, dst_ports), requests: reqs, sent: 0, rate_inv: cycles::cycles_per_second() / config.req_rate as u64, start: cycles::rdtsc(), next: 0, native: !config.use_invoke, payload_get: RefCell::new(payload_get), payload_put: RefCell::new(payload_put), } } } // The Executable trait allowing YcsbSend to be scheduled by Netbricks. impl Executable for YcsbSend { // Called internally by Netbricks. fn execute(&mut self) { // Return if there are no more requests to generate. if self.requests <= self.sent { return; } // Get the current time stamp so that we can determine if it is time to issue the next RPC. let curr = cycles::rdtsc(); // If it is either time to send out a request, or if a request has never been sent out, // then, do so. if curr >= self.next || self.next == 0 { if self.native == true { // Configured to issue native RPCs, issue a regular get()/put() operation. self.workload.borrow_mut().abc( |tenant, key| self.sender.send_get(tenant, 1, key, curr), |tenant, key, val| self.sender.send_put(tenant, 1, key, val, curr), ); } else { // Configured to issue invoke() RPCs. let mut p_get = self.payload_get.borrow_mut(); let mut p_put = self.payload_put.borrow_mut(); // XXX Heavily dependent on how `Ycsb` creates a key. Only the first four // bytes of the key matter, the rest are zero. The value is always zero. self.workload.borrow_mut().abc( |tenant, key| { // First 11 bytes on the payload were already pre-populated with the // extension name (3 bytes), and the table id (8 bytes). Just write in the // first 4 bytes of the key. p_get[11..15].copy_from_slice(&key[0..4]); self.sender.send_invoke(tenant, 3, &p_get, curr) }, |tenant, key, _val| { // First 13 bytes on the payload were already pre-populated with the // extension name (3 bytes), the table id (8 bytes), and the key length (2 // bytes). Just write in the first 4 bytes of the key. The value is anyway // always zero. p_put[13..17].copy_from_slice(&key[0..4]); self.sender.send_invoke(tenant, 3, &p_put, curr) }, ); } // Update the time stamp at which the next request should be generated, assuming that // the first request was sent out at self.start. self.sent += 1; self.next = self.start + self.sent * self.rate_inv; } } fn dependencies(&mut self) -> Vec<usize> { vec![] } } /// Receives responses to YCSB requests sent out by YcsbSend. struct YcsbRecv<T> where T: PacketTx + PacketRx + Display + Clone + 'static, { // The network stack required to receives RPC response packets from a network port. receiver: dispatch::Receiver<T>, // The number of response packets to wait for before printing out statistics. responses: u64, // Time stamp in cycles at which measurement started. Required to calculate observed // throughput of the Sandstorm server. start: u64, // The total number of responses received so far. recvd: u64, // Vector of sampled request latencies. Required to calculate distributions once all responses // have been received. latencies: Vec<u64>, // If true, this receiver will make latency measurements. master: bool, // If true, then responses will be considered to correspond to native gets and puts. native: bool, // Time stamp in cycles at which measurement stopped. stop: u64, } // Implementation of methods on YcsbRecv. impl<T> YcsbRecv<T> where T: PacketTx + PacketRx + Display + Clone + 'static, { /// Constructs a YcsbRecv. /// /// # Arguments /// /// * `port` : Network port on which responses will be polled for. /// * `resps`: The number of responses to wait for before calculating statistics. /// * `master`: Boolean indicating if the receiver should make latency measurements. /// * `native`: If true, responses will be considered to correspond to native gets and puts. /// /// # Return /// /// A YCSB response receiver that measures the median latency and throughput of a Sandstorm /// server. fn
(port: T, resps: u64, master: bool, native: bool) -> YcsbRecv<T> { YcsbRecv { receiver: dispatch::Receiver::new(port), responses: resps, start: cycles::rdtsc(), recvd: 0, latencies: Vec::with_capacity(resps as usize), master: master, native: native, stop: 0, } } } // Implementation of the `Drop` trait on YcsbRecv. impl<T> Drop for YcsbRecv<T> where T: PacketTx + Packet
new
identifier_name
workspace.rs
&Ellipsis) .field("message_locale", &inner.message_locale) .field("path", &inner.path) .field("unit", &inner.unit) .field("document", &inner.document) .field("span", &inner.span.as_ref().map(|_| Ellipsis)) .field("tokens", &inner.tokens.as_ref().map(|_| Ellipsis)) .field("chunk", &inner.chunk.as_ref().map(|_| Ellipsis)) .field("last_chunk", &inner.last_chunk.as_ref().map(|_| Ellipsis)) .finish() } } impl WorkspaceFile { fn new(shared: &Arc<RwLock<WorkspaceShared>>, pool: &Arc<CpuPool>, source: &Arc<RwLock<Source>>, message_locale: Locale, path: PathBuf) -> WorkspaceFile { WorkspaceFile { inner: Arc::new(RwLock::new(WorkspaceFileInner { workspace: shared.clone(), pool: pool.clone(), cancel_token: CancelToken::new(), source: source.clone(), message_locale: message_locale, path: path, unit: Unit::dummy(), document: None, span: None, tokens: None, chunk: None, last_chunk: None, })), } } fn cancel(&self) { let mut inner = self.inner.write(); inner.cancel_token.cancel(); inner.cancel_token = CancelToken::new(); inner.span = None; inner.tokens = None; inner.chunk = None; // also signal the workspace to cancel jobs inner.workspace.write().cancel(); } #[allow(dead_code)] pub fn path(&self) -> PathBuf { self.inner.read().path.clone() } fn update_document<F, E>(&self, f: F) -> Result<(), E> where F: FnOnce(Option<OpenDocument>) -> Result<Option<OpenDocument>, E> { self.cancel(); let mut inner = self.inner.write(); inner.document = f(inner.document.take())?; Ok(()) } fn ensure_span_with_inner(spare_inner: Inner, inner: &mut InnerWrite) -> IoFuture<Span> { if inner.span.is_none() { let fut = future::lazy(move || -> Result<Span, CancelError<io::Error>> { let mut inner = spare_inner.write(); inner.cancel_token.keep_going()?; let file = if let Some(ref doc) = inner.document { SourceFile::from_u8(inner.path.display().to_string(), doc.last_text.as_bytes().to_owned()) } else { SourceFile::from_file(&inner.path)? }; let span = if inner.unit.is_dummy() { let span = inner.source.write().add(file); inner.unit = span.unit(); span } else { inner.source.write().replace(inner.unit, file).unwrap() }; Ok(span) }); inner.span = Some(inner.pool.spawn(fut).boxed().shared()); } inner.span.as_ref().unwrap().clone() } pub fn ensure_span(&self) -> IoFuture<Span> { let cloned = self.inner.clone(); Self::ensure_span_with_inner(cloned, &mut self.inner.write()) } fn ensure_tokens_with_inner(spare_inner: Inner, inner: &mut InnerWrite) -> ReportFuture<Arc<Vec<NestedToken>>> { if inner.tokens.is_none() { let span_fut = Self::ensure_span_with_inner(spare_inner.clone(), inner); // important: the task has to be spawned outside of the future. // this is because, otherwise for the thread pool of n workers // the future chain of n+1 or more tasks will block as the i-th task // will spawn the (i+1)-th task without removing itself from the pool queue! // chaining the already-spawned future will ensure that // the task body will be only spawned after the last future has been finished. let fut = span_fut.then(move |span_ret| { let inner = spare_inner.read(); match span_ret { Ok(span) => { inner.cancel_token.keep_going()?; let source = inner.source.read(); let path = source.file(span.unit()).map(|f| f.path()); let diags = ReportTree::new(inner.message_locale, path); let report = diags.report(|span| diags::translate_span(span, &source)); let tokens = collect_tokens(&source, *span, &report); Ok((Arc::new(tokens), diags)) }, Err(e) => { Err(e.as_ref().map(|e| { // translate an I/O error into a report let dummy_diag = |msg: &Localize| { protocol::Diagnostic { range: protocol::Range { start: protocol::Position { line: 0, character: 0 }, end: protocol::Position { line: 0, character: 0 }, }, severity: Some(protocol::DiagnosticSeverity::Error), code: None, source: None, message: Localized::new(msg, inner.message_locale).to_string(), } }; let path = inner.path.display().to_string(); let config_path = inner.workspace.read().base.config_path_or_default(); let config_path = config_path.display().to_string(); let diags = ReportTree::new(inner.message_locale, Some(&path)); diags.add_diag(path, dummy_diag(&m::CannotOpenStartPath { error: e })); diags.add_diag(config_path, dummy_diag(&m::RestartRequired {})); diags })) }, } }); inner.tokens = Some(inner.pool.spawn(fut).boxed().shared()); } inner.tokens.as_ref().unwrap().clone() } pub fn ensure_tokens(&self) -> ReportFuture<Arc<Vec<NestedToken>>> { let cloned = self.inner.clone(); Self::ensure_tokens_with_inner(cloned, &mut self.inner.write()) } fn ensure_chunk_with_inner(spare_inner: Inner, inner: &mut InnerWrite) -> ReportFuture<Arc<Chunk>> { if inner.chunk.is_none() { let tokens_fut = Self::ensure_tokens_with_inner(spare_inner.clone(), inner); let fut = tokens_fut.map_err(|e| (*e).clone()).and_then(move |tokens_ret| { let tokens = (*tokens_ret.0).clone(); let parent_diags = tokens_ret.1.clone(); let mut inner = spare_inner.write(); inner.cancel_token.keep_going()?; let diags = ReportTree::new(inner.message_locale, None); diags.add_parent(parent_diags); // in this future source access is only needed for reporting let chunk = { let report = diags.report(|span| { diags::translate_span(span, &inner.source.read()) }); parse_to_chunk(tokens, &report) }; match chunk { Ok(chunk) => { let chunk = Arc::new(chunk); inner.last_chunk = Some(chunk.clone()); Ok((chunk, diags)) }, Err(_) => Err(From::from(diags)), } }); inner.chunk = Some(inner.pool.spawn(fut).boxed().shared()); } inner.chunk.as_ref().unwrap().clone() } pub fn ensure_chunk(&self) -> ReportFuture<Arc<Chunk>> { let cloned = self.inner.clone(); Self::ensure_chunk_with_inner(cloned, &mut self.inner.write()) } pub fn last_chunk(&self) -> Option<Arc<Chunk>> { self.inner.read().last_chunk.clone() } pub fn translate_position(&self, pos: &protocol::Position) -> BoxFuture<Pos, CancelError<()>> { let pos = pos.clone(); let source = self.inner.read().source.clone(); self.ensure_span().then(move |res| { match res { Ok(span) => { let source = source.read(); if let Some(file) = source.file(span.unit()) { Ok(position_to_pos(file, &pos)) } else { Ok(Pos::dummy()) } }, Err(e) => Err(e.as_ref().map(|_| ())) } }).boxed() } pub fn
(&mut self, version: u64, event: protocol::TextDocumentContentChangeEvent) -> WorkspaceResult<()> { // TODO, there are several ambiguities with offsets? if event.range.is_some() || event.rangeLength.is_some() { return Err(WorkspaceError("incremental edits not yet supported")); } self.update_document(move |doc| { if let Some(mut doc) = doc { if doc.last_version >= version { return Err(WorkspaceError("non-increasing version")); } doc.last_version = version; doc.last_text = event.text; Ok(Some(doc)) } else { Err(WorkspaceError("change notification with non-existent or non-open file")) } }) } } #[derive(Clone, Debug)] enum WorkspaceBase { Config(kailua_workspace::Config), Workspace(kailua_workspace::Workspace), } impl WorkspaceBase { fn config_path(&self) -> Option<&Path> { match *self { WorkspaceBase::Config(ref config) => config.config_path(), WorkspaceBase::Workspace(ref ws) => ws.config_path(), } } fn config_path_or_default(&self) -> PathBuf { if let Some(config_path) = self.config_path
apply_change
identifier_name
workspace.rs
)); diags })) }, } }); inner.tokens = Some(inner.pool.spawn(fut).boxed().shared()); } inner.tokens.as_ref().unwrap().clone() } pub fn ensure_tokens(&self) -> ReportFuture<Arc<Vec<NestedToken>>> { let cloned = self.inner.clone(); Self::ensure_tokens_with_inner(cloned, &mut self.inner.write()) } fn ensure_chunk_with_inner(spare_inner: Inner, inner: &mut InnerWrite) -> ReportFuture<Arc<Chunk>> { if inner.chunk.is_none() { let tokens_fut = Self::ensure_tokens_with_inner(spare_inner.clone(), inner); let fut = tokens_fut.map_err(|e| (*e).clone()).and_then(move |tokens_ret| { let tokens = (*tokens_ret.0).clone(); let parent_diags = tokens_ret.1.clone(); let mut inner = spare_inner.write(); inner.cancel_token.keep_going()?; let diags = ReportTree::new(inner.message_locale, None); diags.add_parent(parent_diags); // in this future source access is only needed for reporting let chunk = { let report = diags.report(|span| { diags::translate_span(span, &inner.source.read()) }); parse_to_chunk(tokens, &report) }; match chunk { Ok(chunk) => { let chunk = Arc::new(chunk); inner.last_chunk = Some(chunk.clone()); Ok((chunk, diags)) }, Err(_) => Err(From::from(diags)), } }); inner.chunk = Some(inner.pool.spawn(fut).boxed().shared()); } inner.chunk.as_ref().unwrap().clone() } pub fn ensure_chunk(&self) -> ReportFuture<Arc<Chunk>> { let cloned = self.inner.clone(); Self::ensure_chunk_with_inner(cloned, &mut self.inner.write()) } pub fn last_chunk(&self) -> Option<Arc<Chunk>> { self.inner.read().last_chunk.clone() } pub fn translate_position(&self, pos: &protocol::Position) -> BoxFuture<Pos, CancelError<()>> { let pos = pos.clone(); let source = self.inner.read().source.clone(); self.ensure_span().then(move |res| { match res { Ok(span) => { let source = source.read(); if let Some(file) = source.file(span.unit()) { Ok(position_to_pos(file, &pos)) } else { Ok(Pos::dummy()) } }, Err(e) => Err(e.as_ref().map(|_| ())) } }).boxed() } pub fn apply_change(&mut self, version: u64, event: protocol::TextDocumentContentChangeEvent) -> WorkspaceResult<()> { // TODO, there are several ambiguities with offsets? if event.range.is_some() || event.rangeLength.is_some() { return Err(WorkspaceError("incremental edits not yet supported")); } self.update_document(move |doc| { if let Some(mut doc) = doc { if doc.last_version >= version { return Err(WorkspaceError("non-increasing version")); } doc.last_version = version; doc.last_text = event.text; Ok(Some(doc)) } else { Err(WorkspaceError("change notification with non-existent or non-open file")) } }) } } #[derive(Clone, Debug)] enum WorkspaceBase { Config(kailua_workspace::Config), Workspace(kailua_workspace::Workspace), } impl WorkspaceBase { fn config_path(&self) -> Option<&Path> { match *self { WorkspaceBase::Config(ref config) => config.config_path(), WorkspaceBase::Workspace(ref ws) => ws.config_path(), } } fn config_path_or_default(&self) -> PathBuf { if let Some(config_path) = self.config_path() { config_path.to_owned() } else { // we allow both `kailua.json` or `.vscode/kailua.json`, // for now we will issue an error at the latter self.base_dir().join(".vscode").join("kailua.json") } } fn base_dir(&self) -> &Path { match *self { WorkspaceBase::Config(ref config) => config.base_dir(), WorkspaceBase::Workspace(ref ws) => ws.base_dir(), } } } // a portion of Workspace that should be shared across WorkspaceFile. // this should not be modified in the normal cases (otherwise it can be easily deadlocked), // with an exception of cascading cancellation. struct WorkspaceShared { cancel_token: CancelToken, // used for stopping ongoing checks base: WorkspaceBase, check_outputs: Vec<Option<ReportFuture<Arc<Output>>>>, last_check_outputs: Vec<Option<Arc<Output>>>, } type Shared = Arc<RwLock<WorkspaceShared>>; type SharedWrite<'a> = RwLockWriteGuard<'a, WorkspaceShared>; impl fmt::Debug for WorkspaceShared { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { struct DummyOptionList<'a, T: 'a>(&'a [Option<T>]); impl<'a, T: 'a> fmt::Debug for DummyOptionList<'a, T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_list().entries(self.0.iter().map(|e| e.as_ref().map(|_| Ellipsis))).finish() } } f.debug_struct("WorkspaceShared") .field("base", &self.base) .field("cancel_token", &self.cancel_token) .field("check_outputs", &DummyOptionList(&self.check_outputs)) .field("last_check_outputs", &DummyOptionList(&self.last_check_outputs)) .finish() } } impl WorkspaceShared { fn cancel(&mut self) { self.cancel_token.cancel(); self.cancel_token = CancelToken::new(); for output in &mut self.check_outputs { *output = None; } } } struct WorkspaceFsSourceInner { cancel_token: CancelToken, // will be used independently of WorkspaceShared files: Arc<RwLock<HashMap<PathBuf, WorkspaceFile>>>, source: Arc<RwLock<Source>>, temp_units: Vec<Unit>, // will be gone after checking temp_files: HashMap<PathBuf, Chunk>, message_locale: Locale, root_report: ReportTree, } #[derive(Clone)] struct WorkspaceFsSource { inner: Rc<RefCell<WorkspaceFsSourceInner>>, } impl FsSource for WorkspaceFsSource { fn chunk_from_path(&self, path: Spanned<&Path>, _report: &Report) -> Result<Option<Chunk>, Option<Stop>> { let mut fssource = self.inner.borrow_mut(); fssource.cancel_token.keep_going::<()>().map_err(|_| Stop)?; // try to use the client-maintained text as a source code let files = fssource.files.clone(); let files = files.read(); if let Some(file) = files.get(path.base) { let (chunk, diags) = match file.ensure_chunk().wait() { Ok(res) => { let (ref chunk, ref diags) = *res; (Some((**chunk).clone()), diags.clone()) }, Err(res) => match *res { CancelError::Canceled => return Err(Some(Stop)), CancelError::Error(ref diags) => (None, diags.clone()) }, }; // this can be called multiple times, which ReportTree handles correctly fssource.root_report.add_parent(diags); return Ok(chunk); } drop(files); // avoid prolonged lock // try to use the already-read temporary chunk if let Some(chunk) = fssource.temp_files.get(path.base) { return Ok(Some(chunk.clone())); } // try to read the file (and finally raise an error if it can't be read) let sourcefile = match SourceFile::from_file(path.base) { Ok(f) => f, Err(ref e) if e.kind() == io::ErrorKind::NotFound => return Ok(None), Err(_) => return Err(None), }; let span = fssource.source.write().add(sourcefile); fssource.temp_units.push(span.unit()); let diags = ReportTree::new(fssource.message_locale, path.to_str()); fssource.root_report.add_parent(diags.clone()); let chunk = { let source = fssource.source.read(); let report = diags.report(|span| diags::translate_span(span, &source)); let tokens = collect_tokens(&source, span, &report); parse_to_chunk(tokens, &report) }; match chunk { Ok(chunk) => { fssource.temp_files.insert(path.base.to_owned(), chunk.clone()); Ok(Some(chunk)) }, Err(Stop) => Err(Some(Stop)), // we have already reported parsing errors } } } pub struct Workspace { message_locale: Locale, pool: Arc<CpuPool>, files: Arc<RwLock<HashMap<PathBuf, WorkspaceFile>>>, // conceptually this belongs to shared, but it is frequently updated by futures // unlike all other fields in shared, so getting this out avoids deadlock source: Arc<RwLock<Source>>, shared: Arc<RwLock<WorkspaceShared>>, }
random_line_split
workspace.rs
source: Arc<RwLock<Source>>, temp_units: Vec<Unit>, // will be gone after checking temp_files: HashMap<PathBuf, Chunk>, message_locale: Locale, root_report: ReportTree, } #[derive(Clone)] struct WorkspaceFsSource { inner: Rc<RefCell<WorkspaceFsSourceInner>>, } impl FsSource for WorkspaceFsSource { fn chunk_from_path(&self, path: Spanned<&Path>, _report: &Report) -> Result<Option<Chunk>, Option<Stop>> { let mut fssource = self.inner.borrow_mut(); fssource.cancel_token.keep_going::<()>().map_err(|_| Stop)?; // try to use the client-maintained text as a source code let files = fssource.files.clone(); let files = files.read(); if let Some(file) = files.get(path.base) { let (chunk, diags) = match file.ensure_chunk().wait() { Ok(res) => { let (ref chunk, ref diags) = *res; (Some((**chunk).clone()), diags.clone()) }, Err(res) => match *res { CancelError::Canceled => return Err(Some(Stop)), CancelError::Error(ref diags) => (None, diags.clone()) }, }; // this can be called multiple times, which ReportTree handles correctly fssource.root_report.add_parent(diags); return Ok(chunk); } drop(files); // avoid prolonged lock // try to use the already-read temporary chunk if let Some(chunk) = fssource.temp_files.get(path.base) { return Ok(Some(chunk.clone())); } // try to read the file (and finally raise an error if it can't be read) let sourcefile = match SourceFile::from_file(path.base) { Ok(f) => f, Err(ref e) if e.kind() == io::ErrorKind::NotFound => return Ok(None), Err(_) => return Err(None), }; let span = fssource.source.write().add(sourcefile); fssource.temp_units.push(span.unit()); let diags = ReportTree::new(fssource.message_locale, path.to_str()); fssource.root_report.add_parent(diags.clone()); let chunk = { let source = fssource.source.read(); let report = diags.report(|span| diags::translate_span(span, &source)); let tokens = collect_tokens(&source, span, &report); parse_to_chunk(tokens, &report) }; match chunk { Ok(chunk) => { fssource.temp_files.insert(path.base.to_owned(), chunk.clone()); Ok(Some(chunk)) }, Err(Stop) => Err(Some(Stop)), // we have already reported parsing errors } } } pub struct Workspace { message_locale: Locale, pool: Arc<CpuPool>, files: Arc<RwLock<HashMap<PathBuf, WorkspaceFile>>>, // conceptually this belongs to shared, but it is frequently updated by futures // unlike all other fields in shared, so getting this out avoids deadlock source: Arc<RwLock<Source>>, shared: Arc<RwLock<WorkspaceShared>>, } impl fmt::Debug for Workspace { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("Workspace") .field("message_locale", &self.message_locale) .field("pool", &Ellipsis) .field("files", &self.files) .field("source", &Ellipsis) .field("shared", &self.shared) .finish() } } impl Workspace { pub fn new(base_dir: PathBuf, pool: Arc<CpuPool>, default_locale: Locale) -> Workspace { Workspace { message_locale: default_locale, pool: pool, files: Arc::new(RwLock::new(HashMap::new())), source: Arc::new(RwLock::new(Source::new())), shared: Arc::new(RwLock::new(WorkspaceShared { cancel_token: CancelToken::new(), base: WorkspaceBase::Config(kailua_workspace::Config::from_base_dir(base_dir)), check_outputs: Vec::new(), last_check_outputs: Vec::new(), })), } } pub fn pool(&self) -> &Arc<CpuPool> { &self.pool } pub fn source<'a>(&'a self) -> RwLockReadGuard<'a, Source> { self.source.read() } pub fn has_read_config(&self) -> bool { if let WorkspaceBase::Workspace(_) = self.shared.read().base { true } else { false } } #[allow(dead_code)] pub fn config_path(&self) -> Option<PathBuf> { self.shared.read().base.config_path().map(|p| p.to_owned()) } pub fn config_path_or_default(&self) -> PathBuf { self.shared.read().base.config_path_or_default() } pub fn read_config(&mut self) -> bool { let mut shared = self.shared.write(); let ws = if let WorkspaceBase::Config(ref mut config) = shared.base { config.use_default_config_paths(); if let Some(ws) = kailua_workspace::Workspace::new(config, self.message_locale) { Some(ws) } else { return false; } } else { None }; if let Some(ws) = ws { let noutputs = ws.start_paths().len(); shared.base = WorkspaceBase::Workspace(ws); shared.check_outputs.resize(noutputs, None); shared.last_check_outputs.resize(noutputs, None); } true } pub fn populate_watchlist(&mut self) { let walker = WalkDir::new(self.shared.read().base.base_dir()); for e in walker.follow_links(true) { // we don't care about I/O errors and (in Unix) symlink loops let e = if let Ok(e) = e { e } else { continue }; let ext = e.path().extension(); if ext == Some(OsStr::new("lua")) || ext == Some(OsStr::new("kailua")) { // TODO probably this should be of the lower priority let _ = self.ensure_file(e.path()).ensure_chunk(); } } } pub fn localize<'a, T: Localize + ?Sized + 'a>(&self, msg: &'a T) -> Localized<'a, T> { Localized::new(msg, self.message_locale) } pub fn files<'a>(&'a self) -> RwLockReadGuard<'a, HashMap<PathBuf, WorkspaceFile>> { self.files.read() } pub fn file<'a>(&'a self, uri: &str) -> Option<WorkspaceFile> { match uri_to_path(uri) { Ok(path) => self.files.read().get(&path).cloned(), Err(_) => None, } } fn make_file(&self, path: PathBuf) -> WorkspaceFile { WorkspaceFile::new(&self.shared, &self.pool, &self.source, self.message_locale, path) } fn destroy_file(&self, file: WorkspaceFile) -> bool { file.cancel(); let file = file.inner.read(); let sourcefile = self.source.write().remove(file.unit); file.document.is_some() && sourcefile.is_some() } pub fn open_file(&self, item: protocol::TextDocumentItem) -> WorkspaceResult<()> { let path = uri_to_path(&item.uri)?; let mut files = self.files.write(); let file = files.entry(path.clone()).or_insert_with(|| self.make_file(path)); file.update_document(|doc| { if doc.is_some() { Err(WorkspaceError("open notification with duplicate file")) } else { Ok(Some(OpenDocument::new(item))) } }) } fn ensure_file(&self, path: &Path) -> WorkspaceFile { let mut files = self.files.write(); files.entry(path.to_owned()).or_insert_with(|| self.make_file(path.to_owned())).clone() } pub fn close_file(&self, uri: &str) -> WorkspaceResult<()> { let path = uri_to_path(uri)?; // closing file breaks the synchronization so the file should be re-read from fs let mut files = self.files.write(); let ok = if let hash_map::Entry::Occupied(mut e) = files.entry(path.clone()) { // replace the previous WorkspaceFile by a fresh WorkspaceFile let file = mem::replace(e.get_mut(), self.make_file(path)); self.destroy_file(file) } else { false }; if ok { Ok(()) } else { Err(WorkspaceError("close notification with non-existent or non-open file")) } } pub fn on_file_created(&self, uri: &str) -> Option<WorkspaceFile> { if let Ok(path) = uri_to_path(uri) { let file = self.ensure_file(&path); let _ = file.ensure_chunk(); Some(file) } else { None } } pub fn on_file_changed(&self, uri: &str) -> Option<WorkspaceFile>
{ if let Ok(path) = uri_to_path(uri) { let file = self.ensure_file(&path); file.cancel(); let _ = file.ensure_chunk(); Some(file) } else { None } }
identifier_body
train.py
=0) parser.add_argument('-mg', '--max_grad_norm', type=float, default=5.) parser.add_argument('-m', '--model', type=str, choices=['vae', 'ae'], default='vae') parser.add_argument('-eb', '--embedding_size', type=int, default=300) parser.add_argument('-rnn', '--rnn_type', type=str, choices=['rnn', 'lstm', 'gru'], default='gru') parser.add_argument('-hs', '--hidden_size', type=int, default=512) parser.add_argument('-nl', '--num_layers', type=int, default=1) parser.add_argument('-bi', '--bidirectional', action='store_true') parser.add_argument('-ls', '--latent_size', type=int, default=16) parser.add_argument('-wd', '--word_dropout', type=float, default=0.5) parser.add_argument('-d', '--denoise', action='store_true') parser.add_argument('-pd', '--prob_drop', type=float, default=0.1) parser.add_argument('-ps', '--prob_swap', type=float, default=0.1) parser.add_argument('-af', '--anneal_function', type=str, choices=['logistic', 'linear'], default='logistic') parser.add_argument('-k', '--k', type=float, default=0.0025) parser.add_argument('-x0', '--x0', type=int, default=2500) parser.add_argument('-v', '--print_every', type=int, default=50) parser.add_argument('-tb', '--tensorboard_logging', action='store_true') args = parser.parse_args(arguments) log.basicConfig(format="%(asctime)s: %(message)s", level=log.INFO, datefmt='%m/%d %I:%M:%S %p') if args.log_file: log.getLogger().addHandler(log.FileHandler(args.log_file)) log.info(args) ts = time.strftime('%Y-%b-%d-%H:%M:%S', time.gmtime()) seed = random.randint(1, 10000) if args.seed < 0 else args.seed random.seed(seed) torch.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.set_device(args.gpu_id) torch.cuda.manual_seed_all(seed) splits = ['train', 'valid'] + (['test'] if args.test else []) datasets = OrderedDict() for split in splits: datasets[split] = PTB( data_dir=args.data_dir, split=split, create_data=args.create_data, max_sequence_length=args.max_sequence_length, min_occ=args.min_occ) if args.model == 'vae': model = SentenceVAE(args, datasets['train'].get_w2i(), embedding_size=args.embedding_size, rnn_type=args.rnn_type, hidden_size=args.hidden_size, word_dropout=args.word_dropout, latent_size=args.latent_size, num_layers=args.num_layers, bidirectional=args.bidirectional) elif args.model == 'ae': model = SentenceAE(args, datasets['train'].get_w2i(), embedding_size=args.embedding_size, rnn_type=args.rnn_type, hidden_size=args.hidden_size, word_dropout=args.word_dropout, latent_size=args.latent_size, num_layers=args.num_layers, bidirectional=args.bidirectional) if args.denoise: log.info("DENOISING!") if torch.cuda.is_available(): model = model.cuda() log.info(model) if args.tensorboard_logging: writer = SummaryWriter(os.path.join(args.run_dir, experiment_name(args, ts))) writer.add_text("model", str(model)) writer.add_text("args", str(args)) writer.add_text("ts", ts) save_model_path = args.run_dir if not os.path.exists(save_model_path): os.makedirs(save_model_path) NLL = torch.nn.NLLLoss(size_average=False, ignore_index=datasets['train'].pad_idx) params = model.parameters() if args.optimizer == 'sgd': optimizer = optim.SGD(params, lr=args.learning_rate) elif args.optimizer == 'adam': optimizer = optim.Adam(params, lr=args.learning_rate) scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=args.lr_decay_factor, patience=args.sched_patience, verbose=True) tensor = torch.cuda.FloatTensor if torch.cuda.is_available() else torch.Tensor batch_size = args.batch_size step, stop_training = 0, 0 global_tracker = {'best_epoch': -1, 'best_score': -1, 'history': []} for epoch in range(args.epochs): if stop_training: break for split in splits: tracker = defaultdict(tensor) exs = [ex for ex in datasets[split].data.values()] random.shuffle(exs) n_batches = math.ceil(len(exs) / batch_size) # Enable/Disable Dropout if split == 'train': log.info("***** Epoch %02d *****", epoch) log.info("Training...") model.train() else: log.info("Validating...") model.eval() #for iteration, batch in enumerate(data_loader): for iteration in range(n_batches): raw_batch = exs[iteration*batch_size:(iteration+1)*batch_size] batch = model.prepare_batch([e['input'] for e in raw_batch]) batch['src_length'] = model.tensor(batch['src_length']).long() batch['trg_length'] = model.tensor(batch['trg_length']).long() b_size = batch['input'].size(0) for k, v in batch.items(): if torch.is_tensor(v): batch[k] = to_var(v) # Forward pass logp, mean, logv, z = model(batch['input'], batch['target'], batch['src_length'], batch['trg_length']) # loss calculation nll_loss, kl_loss, kl_weight = model.loss_fn(logp, batch['target'], batch['trg_length'], mean, logv, args.anneal_function, step, args.k, args.x0) loss = (nll_loss + kl_weight * kl_loss) / b_size nll_loss /= b_size kl_loss /= b_size if loss.data[0] != loss.data[0]: # nan detection log.info("***** UH OH NAN DETECTED *****") pdb.set_trace() # backward + optimization if split == 'train': optimizer.zero_grad() loss.backward() if args.max_grad_norm: grad_norm = clip_grad_norm(model.parameters(), args.max_grad_norm) optimizer.step() step += 1 # bookkeeping tracker['ELBO'] = torch.cat((tracker['ELBO'], loss.data)) loss = loss.data[0] if args.model == 'vae': tracker['NLL'] = torch.cat((tracker['NLL'], nll_loss.data)) tracker['KL'] = torch.cat((tracker['NLL'], kl_loss.data)) nll_loss = nll_loss.data[0] kl_loss = kl_loss.data[0] else: tracker['NLL'] = torch.cat((tracker['NLL'], model.tensor([0]))) tracker['KL'] = torch.cat((tracker['KL'], model.tensor([0]))) if args.tensorboard_logging: writer.add_scalar("%s/ELBO"%split.upper(), loss, epoch*n_batches + iteration) writer.add_scalar("%s/NLL Loss"%split.upper(), nll_loss, epoch*n_batches + iteration) writer.add_scalar("%s/KL Loss"%split.upper(), kl_loss, epoch*n_batches + iteration) writer.add_scalar("%s/KL Weight"%split.upper(), kl_weight, epoch*n_batches + iteration) if iteration % args.print_every == 0 or iteration + 1 == n_batches: log.info(" Batch %04d/%i\tLoss %9.4f\tNLL-Loss %9.4f\tKL-Loss %9.4f\tKL-Weight %6.3f", iteration, n_batches-1, loss, nll_loss, kl_loss, kl_weight) if split == 'valid': # store the dev target sentences if 'target_sents' not in tracker: tracker['target_sents'] = list() tracker['target_sents'] += idx2word(batch['target'].data, \ i2w=datasets['train'].get_i2w(), pad_idx=datasets['train'].pad_idx) if args.model == 'vae': tracker['z'] = torch.cat((tracker['z'], z.data), dim=0) log.info(" Mean ELBO %9.4f, NLL: %9.4f", torch.mean(tracker['ELBO']), torch.mean(tracker['NLL'])) if args.tensorboard_logging: writer.add_scalar("%s-Epoch/ELBO" % split.upper(), torch.mean(tracker['ELBO']), epoch) # save a dump of all sentences and the encoded latent space if split == 'valid': loss = torch.mean(tracker['ELBO']) dump = {'target_sents':tracker['target_sents'], 'z':tracker['z'].tolist()} if not os.path.exists(os.path.join('dumps', ts)):
os.makedirs('dumps/' + ts)
conditional_block
train.py
def loss_fn(NLL, logp, target, length, mean, logv, anneal_function, step, k, x0): # cut-off unnecessary padding from target, and flatten target = target[:, :torch.max(length).data[0]].contiguous().view(-1) logp = logp.view(-1, logp.size(2)) # Negative Log Likelihood nll_loss = NLL(logp, target) # KL Divergence kl_loss = -0.5 * torch.sum(1 + logv - mean.pow(2) - logv.exp()) kl_weight = kl_anneal_function(anneal_function, step, k, x0) return nll_loss, kl_loss, kl_weight def main(arguments): parser = argparse.ArgumentParser() parser.add_argument('--seed', help='random seed', type=int, default=19) parser.add_argument('-gpu', '--gpu_id', help='GPU ID', type=int, default=0) parser.add_argument('--run_dir', help='prefix to save ckpts to', type=str, default=SCR_PREFIX + 'ckpts/svae/test/') parser.add_argument('--log_file', help='file to log to', type=str, default='') parser.add_argument('--data_dir', type=str, default='data') parser.add_argument('--create_data', action='store_true') parser.add_argument('--max_sequence_length', type=int, default=40) parser.add_argument('--min_occ', type=int, default=1) parser.add_argument('--max_vocab_size', type=int, default=30000) parser.add_argument('--test', action='store_true') parser.add_argument('-ep', '--epochs', type=int, default=10) parser.add_argument('-bs', '--batch_size', type=int, default=128) parser.add_argument('-o', '--optimizer', type=str, choices=['sgd', 'adam'], default='adam') parser.add_argument('-lr', '--learning_rate', type=float, default=0.001) parser.add_argument('--lr_decay_factor', type=float, default=0.5) parser.add_argument('-p', '--patience', type=int, default=5) parser.add_argument('--sched_patience', type=int, default=0) parser.add_argument('-mg', '--max_grad_norm', type=float, default=5.) parser.add_argument('-m', '--model', type=str, choices=['vae', 'ae'], default='vae') parser.add_argument('-eb', '--embedding_size', type=int, default=300) parser.add_argument('-rnn', '--rnn_type', type=str, choices=['rnn', 'lstm', 'gru'], default='gru') parser.add_argument('-hs', '--hidden_size', type=int, default=512) parser.add_argument('-nl', '--num_layers', type=int, default=1) parser.add_argument('-bi', '--bidirectional', action='store_true') parser.add_argument('-ls', '--latent_size', type=int, default=16) parser.add_argument('-wd', '--word_dropout', type=float, default=0.5) parser.add_argument('-d', '--denoise', action='store_true') parser.add_argument('-pd', '--prob_drop', type=float, default=0.1) parser.add_argument('-ps', '--prob_swap', type=float, default=0.1) parser.add_argument('-af', '--anneal_function', type=str, choices=['logistic', 'linear'], default='logistic') parser.add_argument('-k', '--k', type=float, default=0.0025) parser.add_argument('-x0', '--x0', type=int, default=2500) parser.add_argument('-v', '--print_every', type=int, default=50) parser.add_argument('-tb', '--tensorboard_logging', action='store_true') args = parser.parse_args(arguments) log.basicConfig(format="%(asctime)s: %(message)s", level=log.INFO, datefmt='%m/%d %I:%M:%S %p') if args.log_file: log.getLogger().addHandler(log.FileHandler(args.log_file)) log.info(args) ts = time.strftime('%Y-%b-%d-%H:%M:%S', time.gmtime()) seed = random.randint(1, 10000) if args.seed < 0 else args.seed random.seed(seed) torch.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.set_device(args.gpu_id) torch.cuda.manual_seed_all(seed) splits = ['train', 'valid'] + (['test'] if args.test else []) datasets = OrderedDict() for split in splits: datasets[split] = PTB( data_dir=args.data_dir, split=split, create_data=args.create_data, max_sequence_length=args.max_sequence_length, min_occ=args.min_occ) if args.model == 'vae': model = SentenceVAE(args, datasets['train'].get_w2i(), embedding_size=args.embedding_size, rnn_type=args.rnn_type, hidden_size=args.hidden_size, word_dropout=args.word_dropout, latent_size=args.latent_size, num_layers=args.num_layers, bidirectional=args.bidirectional) elif args.model == 'ae': model = SentenceAE(args, datasets['train'].get_w2i(), embedding_size=args.embedding_size, rnn_type=args.rnn_type, hidden_size=args.hidden_size, word_dropout=args.word_dropout, latent_size=args.latent_size, num_layers=args.num_layers, bidirectional=args.bidirectional) if args.denoise: log.info("DENOISING!") if torch.cuda.is_available(): model = model.cuda() log.info(model) if args.tensorboard_logging: writer = SummaryWriter(os.path.join(args.run_dir, experiment_name(args, ts))) writer.add_text("model", str(model)) writer.add_text("args", str(args)) writer.add_text("ts", ts) save_model_path = args.run_dir if not os.path.exists(save_model_path): os.makedirs(save_model_path) NLL = torch.nn.NLLLoss(size_average=False, ignore_index=datasets['train'].pad_idx) params = model.parameters() if args.optimizer == 'sgd': optimizer = optim.SGD(params, lr=args.learning_rate) elif args.optimizer == 'adam': optimizer = optim.Adam(params, lr=args.learning_rate) scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=args.lr_decay_factor, patience=args.sched_patience, verbose=True) tensor = torch.cuda.FloatTensor if torch.cuda.is_available() else torch.Tensor batch_size = args.batch_size step, stop_training = 0, 0 global_tracker = {'best_epoch': -1, 'best_score': -1, 'history': []} for epoch in range(args.epochs): if stop_training: break for split in splits: tracker = defaultdict(tensor) exs = [ex for ex in datasets[split].data.values()] random.shuffle(exs) n_batches = math.ceil(len(exs) / batch_size) # Enable/Disable Dropout if split == 'train': log.info("***** Epoch %02d *****", epoch) log.info("Training...") model.train() else: log.info("Validating...") model.eval() #for iteration, batch in enumerate(data_loader): for iteration in range(n_batches): raw_batch = exs[iteration*batch_size:(iteration+1)*batch_size] batch = model.prepare_batch([e['input'] for e in raw_batch]) batch['src_length'] = model.tensor(batch['src_length']).long() batch['trg_length'] = model.tensor(batch['trg_length']).long() b_size = batch['input'].size(0) for k, v in batch.items(): if torch.is_tensor(v): batch[k] = to_var(v) # Forward pass logp, mean, logv, z = model(batch['input'], batch['target'], batch['src_length'], batch['trg_length']) # loss calculation nll_loss, kl_loss, kl_weight = model.loss_fn(logp, batch['target'], batch['trg_length'], mean, logv, args.anneal_function, step, args.k, args.x0) loss = (nll_loss + kl_weight * kl_loss) / b_size nll_loss /= b_size kl_loss /= b_size if loss.data[0] != loss.data[0]: # nan detection log.info("***** UH OH NAN DETECTED *****") pdb.set_trace() # backward + optimization if split == 'train': optimizer.zero_grad() loss.backward() if args.max_grad_norm: grad_norm = clip_grad_norm(model.parameters(), args.max_grad_norm) optimizer.step() step += 1 # bookkeeping tracker['ELBO'] = torch.cat((tracker['ELBO'], loss.data)) loss = loss.data[0] if args.model == 'vae':
if anneal_function == 'logistic': return float(1/(1+np.exp(-k*(step-x0)))) elif anneal_function == 'linear': return min(1, step/x0)
identifier_body
train.py
p = logp.view(-1, logp.size(2)) # Negative Log Likelihood nll_loss = NLL(logp, target) # KL Divergence kl_loss = -0.5 * torch.sum(1 + logv - mean.pow(2) - logv.exp()) kl_weight = kl_anneal_function(anneal_function, step, k, x0) return nll_loss, kl_loss, kl_weight
parser = argparse.ArgumentParser() parser.add_argument('--seed', help='random seed', type=int, default=19) parser.add_argument('-gpu', '--gpu_id', help='GPU ID', type=int, default=0) parser.add_argument('--run_dir', help='prefix to save ckpts to', type=str, default=SCR_PREFIX + 'ckpts/svae/test/') parser.add_argument('--log_file', help='file to log to', type=str, default='') parser.add_argument('--data_dir', type=str, default='data') parser.add_argument('--create_data', action='store_true') parser.add_argument('--max_sequence_length', type=int, default=40) parser.add_argument('--min_occ', type=int, default=1) parser.add_argument('--max_vocab_size', type=int, default=30000) parser.add_argument('--test', action='store_true') parser.add_argument('-ep', '--epochs', type=int, default=10) parser.add_argument('-bs', '--batch_size', type=int, default=128) parser.add_argument('-o', '--optimizer', type=str, choices=['sgd', 'adam'], default='adam') parser.add_argument('-lr', '--learning_rate', type=float, default=0.001) parser.add_argument('--lr_decay_factor', type=float, default=0.5) parser.add_argument('-p', '--patience', type=int, default=5) parser.add_argument('--sched_patience', type=int, default=0) parser.add_argument('-mg', '--max_grad_norm', type=float, default=5.) parser.add_argument('-m', '--model', type=str, choices=['vae', 'ae'], default='vae') parser.add_argument('-eb', '--embedding_size', type=int, default=300) parser.add_argument('-rnn', '--rnn_type', type=str, choices=['rnn', 'lstm', 'gru'], default='gru') parser.add_argument('-hs', '--hidden_size', type=int, default=512) parser.add_argument('-nl', '--num_layers', type=int, default=1) parser.add_argument('-bi', '--bidirectional', action='store_true') parser.add_argument('-ls', '--latent_size', type=int, default=16) parser.add_argument('-wd', '--word_dropout', type=float, default=0.5) parser.add_argument('-d', '--denoise', action='store_true') parser.add_argument('-pd', '--prob_drop', type=float, default=0.1) parser.add_argument('-ps', '--prob_swap', type=float, default=0.1) parser.add_argument('-af', '--anneal_function', type=str, choices=['logistic', 'linear'], default='logistic') parser.add_argument('-k', '--k', type=float, default=0.0025) parser.add_argument('-x0', '--x0', type=int, default=2500) parser.add_argument('-v', '--print_every', type=int, default=50) parser.add_argument('-tb', '--tensorboard_logging', action='store_true') args = parser.parse_args(arguments) log.basicConfig(format="%(asctime)s: %(message)s", level=log.INFO, datefmt='%m/%d %I:%M:%S %p') if args.log_file: log.getLogger().addHandler(log.FileHandler(args.log_file)) log.info(args) ts = time.strftime('%Y-%b-%d-%H:%M:%S', time.gmtime()) seed = random.randint(1, 10000) if args.seed < 0 else args.seed random.seed(seed) torch.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.set_device(args.gpu_id) torch.cuda.manual_seed_all(seed) splits = ['train', 'valid'] + (['test'] if args.test else []) datasets = OrderedDict() for split in splits: datasets[split] = PTB( data_dir=args.data_dir, split=split, create_data=args.create_data, max_sequence_length=args.max_sequence_length, min_occ=args.min_occ) if args.model == 'vae': model = SentenceVAE(args, datasets['train'].get_w2i(), embedding_size=args.embedding_size, rnn_type=args.rnn_type, hidden_size=args.hidden_size, word_dropout=args.word_dropout, latent_size=args.latent_size, num_layers=args.num_layers, bidirectional=args.bidirectional) elif args.model == 'ae': model = SentenceAE(args, datasets['train'].get_w2i(), embedding_size=args.embedding_size, rnn_type=args.rnn_type, hidden_size=args.hidden_size, word_dropout=args.word_dropout, latent_size=args.latent_size, num_layers=args.num_layers, bidirectional=args.bidirectional) if args.denoise: log.info("DENOISING!") if torch.cuda.is_available(): model = model.cuda() log.info(model) if args.tensorboard_logging: writer = SummaryWriter(os.path.join(args.run_dir, experiment_name(args, ts))) writer.add_text("model", str(model)) writer.add_text("args", str(args)) writer.add_text("ts", ts) save_model_path = args.run_dir if not os.path.exists(save_model_path): os.makedirs(save_model_path) NLL = torch.nn.NLLLoss(size_average=False, ignore_index=datasets['train'].pad_idx) params = model.parameters() if args.optimizer == 'sgd': optimizer = optim.SGD(params, lr=args.learning_rate) elif args.optimizer == 'adam': optimizer = optim.Adam(params, lr=args.learning_rate) scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=args.lr_decay_factor, patience=args.sched_patience, verbose=True) tensor = torch.cuda.FloatTensor if torch.cuda.is_available() else torch.Tensor batch_size = args.batch_size step, stop_training = 0, 0 global_tracker = {'best_epoch': -1, 'best_score': -1, 'history': []} for epoch in range(args.epochs): if stop_training: break for split in splits: tracker = defaultdict(tensor) exs = [ex for ex in datasets[split].data.values()] random.shuffle(exs) n_batches = math.ceil(len(exs) / batch_size) # Enable/Disable Dropout if split == 'train': log.info("***** Epoch %02d *****", epoch) log.info("Training...") model.train() else: log.info("Validating...") model.eval() #for iteration, batch in enumerate(data_loader): for iteration in range(n_batches): raw_batch = exs[iteration*batch_size:(iteration+1)*batch_size] batch = model.prepare_batch([e['input'] for e in raw_batch]) batch['src_length'] = model.tensor(batch['src_length']).long() batch['trg_length'] = model.tensor(batch['trg_length']).long() b_size = batch['input'].size(0) for k, v in batch.items(): if torch.is_tensor(v): batch[k] = to_var(v) # Forward pass logp, mean, logv, z = model(batch['input'], batch['target'], batch['src_length'], batch['trg_length']) # loss calculation nll_loss, kl_loss, kl_weight = model.loss_fn(logp, batch['target'], batch['trg_length'], mean, logv, args.anneal_function, step, args.k, args.x0) loss = (nll_loss + kl_weight * kl_loss) / b_size nll_loss /= b_size kl_loss /= b_size if loss.data[0] != loss.data[0]: # nan detection log.info("***** UH OH NAN DETECTED *****") pdb.set_trace() # backward + optimization if split == 'train': optimizer.zero_grad() loss.backward() if args.max_grad_norm: grad_norm = clip_grad_norm(model.parameters(), args.max_grad_norm) optimizer.step() step += 1 # bookkeeping tracker['ELBO'] = torch.cat((tracker['ELBO'], loss.data)) loss = loss.data[0] if args.model == 'vae': tracker['NLL'] = torch.cat((tracker['NLL'], nll_loss.data)) tracker['KL'] = torch.cat((tracker['NLL'], kl_loss.data)) nll_loss = nll_loss.data[0] kl_loss = kl_loss.data[0] else: tracker['NLL'] = torch.cat((tracker['NLL'], model.tensor([0]))) tracker['KL'] = torch.cat((tracker['KL'], model.tensor([0]))) if args.tensorboard_logging:
def main(arguments):
random_line_split
train.py
(NLL, logp, target, length, mean, logv, anneal_function, step, k, x0): # cut-off unnecessary padding from target, and flatten target = target[:, :torch.max(length).data[0]].contiguous().view(-1) logp = logp.view(-1, logp.size(2)) # Negative Log Likelihood nll_loss = NLL(logp, target) # KL Divergence kl_loss = -0.5 * torch.sum(1 + logv - mean.pow(2) - logv.exp()) kl_weight = kl_anneal_function(anneal_function, step, k, x0) return nll_loss, kl_loss, kl_weight def main(arguments): parser = argparse.ArgumentParser() parser.add_argument('--seed', help='random seed', type=int, default=19) parser.add_argument('-gpu', '--gpu_id', help='GPU ID', type=int, default=0) parser.add_argument('--run_dir', help='prefix to save ckpts to', type=str, default=SCR_PREFIX + 'ckpts/svae/test/') parser.add_argument('--log_file', help='file to log to', type=str, default='') parser.add_argument('--data_dir', type=str, default='data') parser.add_argument('--create_data', action='store_true') parser.add_argument('--max_sequence_length', type=int, default=40) parser.add_argument('--min_occ', type=int, default=1) parser.add_argument('--max_vocab_size', type=int, default=30000) parser.add_argument('--test', action='store_true') parser.add_argument('-ep', '--epochs', type=int, default=10) parser.add_argument('-bs', '--batch_size', type=int, default=128) parser.add_argument('-o', '--optimizer', type=str, choices=['sgd', 'adam'], default='adam') parser.add_argument('-lr', '--learning_rate', type=float, default=0.001) parser.add_argument('--lr_decay_factor', type=float, default=0.5) parser.add_argument('-p', '--patience', type=int, default=5) parser.add_argument('--sched_patience', type=int, default=0) parser.add_argument('-mg', '--max_grad_norm', type=float, default=5.) parser.add_argument('-m', '--model', type=str, choices=['vae', 'ae'], default='vae') parser.add_argument('-eb', '--embedding_size', type=int, default=300) parser.add_argument('-rnn', '--rnn_type', type=str, choices=['rnn', 'lstm', 'gru'], default='gru') parser.add_argument('-hs', '--hidden_size', type=int, default=512) parser.add_argument('-nl', '--num_layers', type=int, default=1) parser.add_argument('-bi', '--bidirectional', action='store_true') parser.add_argument('-ls', '--latent_size', type=int, default=16) parser.add_argument('-wd', '--word_dropout', type=float, default=0.5) parser.add_argument('-d', '--denoise', action='store_true') parser.add_argument('-pd', '--prob_drop', type=float, default=0.1) parser.add_argument('-ps', '--prob_swap', type=float, default=0.1) parser.add_argument('-af', '--anneal_function', type=str, choices=['logistic', 'linear'], default='logistic') parser.add_argument('-k', '--k', type=float, default=0.0025) parser.add_argument('-x0', '--x0', type=int, default=2500) parser.add_argument('-v', '--print_every', type=int, default=50) parser.add_argument('-tb', '--tensorboard_logging', action='store_true') args = parser.parse_args(arguments) log.basicConfig(format="%(asctime)s: %(message)s", level=log.INFO, datefmt='%m/%d %I:%M:%S %p') if args.log_file: log.getLogger().addHandler(log.FileHandler(args.log_file)) log.info(args) ts = time.strftime('%Y-%b-%d-%H:%M:%S', time.gmtime()) seed = random.randint(1, 10000) if args.seed < 0 else args.seed random.seed(seed) torch.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.set_device(args.gpu_id) torch.cuda.manual_seed_all(seed) splits = ['train', 'valid'] + (['test'] if args.test else []) datasets = OrderedDict() for split in splits: datasets[split] = PTB( data_dir=args.data_dir, split=split, create_data=args.create_data, max_sequence_length=args.max_sequence_length, min_occ=args.min_occ) if args.model == 'vae': model = SentenceVAE(args, datasets['train'].get_w2i(), embedding_size=args.embedding_size, rnn_type=args.rnn_type, hidden_size=args.hidden_size, word_dropout=args.word_dropout, latent_size=args.latent_size, num_layers=args.num_layers, bidirectional=args.bidirectional) elif args.model == 'ae': model = SentenceAE(args, datasets['train'].get_w2i(), embedding_size=args.embedding_size, rnn_type=args.rnn_type, hidden_size=args.hidden_size, word_dropout=args.word_dropout, latent_size=args.latent_size, num_layers=args.num_layers, bidirectional=args.bidirectional) if args.denoise: log.info("DENOISING!") if torch.cuda.is_available(): model = model.cuda() log.info(model) if args.tensorboard_logging: writer = SummaryWriter(os.path.join(args.run_dir, experiment_name(args, ts))) writer.add_text("model", str(model)) writer.add_text("args", str(args)) writer.add_text("ts", ts) save_model_path = args.run_dir if not os.path.exists(save_model_path): os.makedirs(save_model_path) NLL = torch.nn.NLLLoss(size_average=False, ignore_index=datasets['train'].pad_idx) params = model.parameters() if args.optimizer == 'sgd': optimizer = optim.SGD(params, lr=args.learning_rate) elif args.optimizer == 'adam': optimizer = optim.Adam(params, lr=args.learning_rate) scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=args.lr_decay_factor, patience=args.sched_patience, verbose=True) tensor = torch.cuda.FloatTensor if torch.cuda.is_available() else torch.Tensor batch_size = args.batch_size step, stop_training = 0, 0 global_tracker = {'best_epoch': -1, 'best_score': -1, 'history': []} for epoch in range(args.epochs): if stop_training: break for split in splits: tracker = defaultdict(tensor) exs = [ex for ex in datasets[split].data.values()] random.shuffle(exs) n_batches = math.ceil(len(exs) / batch_size) # Enable/Disable Dropout if split == 'train': log.info("***** Epoch %02d *****", epoch) log.info("Training...") model.train() else: log.info("Validating...") model.eval() #for iteration, batch in enumerate(data_loader): for iteration in range(n_batches): raw_batch = exs[iteration*batch_size:(iteration+1)*batch_size] batch = model.prepare_batch([e['input'] for e in raw_batch]) batch['src_length'] = model.tensor(batch['src_length']).long() batch['trg_length'] = model.tensor(batch['trg_length']).long() b_size = batch['input'].size(0) for k, v in batch.items(): if torch.is_tensor(v): batch[k] = to_var(v) # Forward pass logp, mean, logv, z = model(batch['input'], batch['target'], batch['src_length'], batch['trg_length']) # loss calculation nll_loss, kl_loss, kl_weight = model.loss_fn(logp, batch['target'], batch['trg_length'], mean, logv, args.anneal_function, step, args.k, args.x0) loss = (nll_loss + kl_weight * kl_loss) / b_size nll_loss /= b_size kl_loss /= b_size if loss.data[0] != loss.data[0]: # nan detection log.info("***** UH OH NAN DETECTED *****") pdb.set_trace() # backward + optimization if split == 'train': optimizer.zero_grad() loss.backward() if args.max_grad_norm: grad_norm = clip_grad_norm(model.parameters(), args.max_grad_norm) optimizer.step() step += 1 # bookkeeping tracker['ELBO'] = torch.cat((tracker['ELBO'], loss.data)) loss = loss.data[0] if args.model == 'vae': tracker['NLL'] = torch.cat((tracker['NLL'], nll_loss.data)) tracker['KL'] = torch.cat((tracker['NLL'], kl_loss.data)) nll_loss = nll_loss.data
loss_fn
identifier_name
menu.rs
(), cur_language: "en", } } /// Adds the menu to the window - takes XID of window as parameter pub fn add_to_window(&mut self, window_id: u32) { self.window_id = Some(window_id); // todo: notify app menu registrar here println!("registered window!"); } /// Removes the menu pub fn remove_from_window(&mut self) { self.window_id = None; // appmenu unregister window // should also be called on drop println!("unregistered window!"); } /// Removes an item from the menu list. /// Does not error out, but rather returns if the removal was successful pub fn remove_item<S: Into<String>>(item: S) -> bool { let item_id = item.into(); println!("remove_item: {:?}", item_id); false } /// Adds an item to the menu list. /// Does not error out, but rather returns if the add was successful pub fn add_item<S: Into<String>>(item: S) -> bool { let item_id = item.into(); println!("add item: {:?}", item_id); false } /// Actually constructs the window so that it shows the menu now /// Sends the menu over DBus pub fn show() { } } pub enum MenuItem { /// Text menu item, regular. Gets called if clicked TextMenuItem(MenuData<Box<Fn() -> ()>>), /// Checkbox menu item, CheckboxMenuItem(MenuData<Box<Fn(bool) -> ()>>), /// Radio menu item, consisting of multiple menu items. /// Callback gets a string of the currently selected value RadioMenuItem(Vec<MenuData<Box<Fn(String) -> ()>>>), /// Seperator Seperator(), /// Submenu SubMenuItem(String, Box<SubMenu>), } #[derive(Debug)] pub struct MenuData<F> { /// The action to execute, depends on the type of menu item pub action: F, /// Optional image as PNG bytes pub image: Option<Vec<u8>>, /// The label(s) of the menu item, indexed by language identifier /// /// For example: /// /// de - Datei öffnen /// en - Open file pub label: HashMap<String, String>, /// Should the menu entry be activated on hovering pub activate_on_hover: bool, /// Optional shortcuts in the format of a string /// `[["Control", "S"]]` /// `[["Control", "Q"], ["Alt", "X"]]` /// This is only a visual cue (todo: really?) pub shortcut: Option<Vec<ShortcutData>>, } #[derive(Debug, Clone)] pub enum ShortcutData { /// The "Control" in CTRL + S ControlChar(CtrlChar), /// The "S" in CTRL + S Char(String), } /// The four controls registered by dbus #[derive(Debug, Copy, Clone)] pub enum CtrlChar { Ctrl, Alt, Shift, Super, } /* 0 => [ "type" => "standard" | "seperator", "label" => "Hello", "enabled" => true, "visible" => true, "icon-name" => "hello.png", "icon-data" => Vec<u8>, "shortcut" => [["Control", "S"]], "toggle-type" => "checkmark" | "radio", "", "toggle-state" => MenuItemToggleState, "children-display" => "" | "submenu", ], defaults: type = "standard", label = "", enabled = "", visible = "", icon-name = "", icon-data = None, shortcut = None, toggle-type = "", toggle-state = -1 children-display = "", */ #[derive(Debug)] pub enum MenuItemToggleState { On, Off, Invalid, } impl Into<i32> for MenuItemToggleState { fn into(self) -> i32 { match self { MenuItemToggleState::On => 1, MenuItemToggleState::Off => 0, MenuItemToggleState::Invalid => -1, } } } /// Implement the ComCanonicalMenu so we can push it to the server impl ComCanonicalDbusmenu for Menu { type Err = dbus::tree::MethodErr; /// - `parent_id`: The ID of the parent node for the layout. For grabbing the layout from the root node use zero. /// - `recursion_depth`: The amount of levels of recursion to use. This affects the content of the second variant array. /// - -1: deliver all the items under the @a parentId. /// - 0: no recursion, the array will be empty. /// - n: array will contains items up to 'n' level depth. /// - `property_names`: The list of item properties we are interested in. If there are no entries in the list all of the properties will be sent. /// /// ### Outputs /// /// - `revision: i32`: The revision number of the layout. For matching with layoutUpdated signals. /// - `layout: HashMap`: The layout, as a recursive structure. /// fn get_layout(&self, parent_id: i32, recursion_depth: i32, property_names: Vec<&str>) -> Result<(u32, (i32, ::std::collections::HashMap<String, arg::Variant<Box<arg::RefArg>>>, Vec<arg::Variant<Box<arg::RefArg>>>)), Self::Err> { // I have no idea if this will actually work in any way possible // (u, (ia{sv}av)) // Nautilus: 0, 2, [] // Answer: 14 /* try!(m.as_result()); let mut i = m.iter_init(); let revision: u32 = try!(i.read()); let layout: (i32, ::std::collections::HashMap<String, arg::Variant<Box<arg::RefArg>>>, Vec<arg::Variant<Box<arg::RefArg>>>) = try!(i.read()); Ok((revision, layout)) */ use dbus::Message; use dbus::Member; println!("getlayout called!"); let mut m = Message::new_method_call("com.canonical.dbusmenu", "com/canonical/dbusmenu", "com.canonical.dbusmenu", Member::new("com.canonical.dbusmenu".as_bytes()).unwrap()).unwrap(); try!(m.as_result()); let mut i = m.iter_init(); let mut map = HashMap::<String, arg::Variant<Box<arg::RefArg>>>::new(); map.insert("data-hello".into(), arg::Variant::new_refarg(&mut i).unwrap()); *self.revision.borrow_mut() += 1; Ok((1, (*self.revision.borrow(), map, Vec::new()))) } fn get_group_properties(&self, ids: Vec<i32>, property_names: Vec<&str>) -> Result<Vec<(i32, ::std::collections::HashMap<String, arg::Variant<Box<arg::RefArg>>>)>, Self::Err> { // I AM NOT SURE IF THS WORKS! println!("get_group_properties called: {:?}, {:?}", ids, property_names); /* method call time=1510750424.121891 sender=:1.318 -> destination=org.freedesktop.DBus serial=1 path=/org/freedesktop/DBus; interface=org.freedesktop.DBus; member=Hello */ // warning: other method is also called "hello" // If Nautilus is called with [0], returns [(0, {'children-display': 'submenu'})] let mut properties_hashmap = HashMap::<String, arg::Variant<Box<arg::RefArg>>>::new(); properties_hashmap.insert("label".into(), arg::Variant(Box::new("Hello".to_string()))); Ok(vec![(0, properties_hashmap)]) } fn get_property(&self, id: i32, name: &str) -> Result<arg::Variant<Box<arg::RefArg>>, Self::Err> { println!("get property called!"); // Nautilus get_propery(0, 'children-display') -> 'submenu' Ok(arg::Variant(Box::new("everything is OK".to_string()))) } fn event(&self, id: i32, event_id: &str, data: arg::Variant<Box<arg::RefArg>>, timestamp: u32) -> Result<(), Self::Err> { println!("event called!"); if event_id == "clicked" { println!("received clicked event for menu item {:?}", id); } else if event_id == "hovered" { println!("received hovered event for menu item {:?}", id); } Ok(()) } fn about_to_show(&self, id: i32) -> Result<bool, Self::Err> { // ??? "Whether this AboutToShow event should result in the menu being updated." // not sure what this means println!("about_to_show called, id: {:?}", id); Ok(true) } fn get_version(&self) -> Result<u32, Self::Err> {
// ???? println!("about_to_show called!"); Ok(3) }
identifier_body
menu.rs
-> Self { Self { revision: Rc::new(RefCell::new(0)), window_id: None, menu: HashMap::new(), cur_language: "en", } } /// Adds the menu to the window - takes XID of window as parameter pub fn add_to_window(&mut self, window_id: u32) { self.window_id = Some(window_id); // todo: notify app menu registrar here println!("registered window!"); } /// Removes the menu pub fn remove_from_window(&mut self) { self.window_id = None; // appmenu unregister window // should also be called on drop println!("unregistered window!"); } /// Removes an item from the menu list. /// Does not error out, but rather returns if the removal was successful pub fn remove_item<S: Into<String>>(item: S) -> bool { let item_id = item.into(); println!("remove_item: {:?}", item_id); false } /// Adds an item to the menu list. /// Does not error out, but rather returns if the add was successful pub fn add_item<S: Into<String>>(item: S) -> bool { let item_id = item.into(); println!("add item: {:?}", item_id); false } /// Actually constructs the window so that it shows the menu now /// Sends the menu over DBus pub fn show() { } } pub enum MenuItem { /// Text menu item, regular. Gets called if clicked TextMenuItem(MenuData<Box<Fn() -> ()>>), /// Checkbox menu item, CheckboxMenuItem(MenuData<Box<Fn(bool) -> ()>>), /// Radio menu item, consisting of multiple menu items. /// Callback gets a string of the currently selected value RadioMenuItem(Vec<MenuData<Box<Fn(String) -> ()>>>), /// Seperator Seperator(), /// Submenu SubMenuItem(String, Box<SubMenu>), } #[derive(Debug)] pub struct MenuData<F> { /// The action to execute, depends on the type of menu item pub action: F, /// Optional image as PNG bytes pub image: Option<Vec<u8>>, /// The label(s) of the menu item, indexed by language identifier /// /// For example: /// /// de - Datei öffnen /// en - Open file pub label: HashMap<String, String>, /// Should the menu entry be activated on hovering pub activate_on_hover: bool, /// Optional shortcuts in the format of a string /// `[["Control", "S"]]` /// `[["Control", "Q"], ["Alt", "X"]]` /// This is only a visual cue (todo: really?) pub shortcut: Option<Vec<ShortcutData>>, } #[derive(Debug, Clone)] pub enum ShortcutData { /// The "Control" in CTRL + S ControlChar(CtrlChar), /// The "S" in CTRL + S Char(String), } /// The four controls registered by dbus #[derive(Debug, Copy, Clone)] pub enum CtrlChar { Ctrl, Alt, Shift, Super, } /* 0 => [ "type" => "standard" | "seperator", "label" => "Hello", "enabled" => true, "visible" => true, "icon-name" => "hello.png", "icon-data" => Vec<u8>, "shortcut" => [["Control", "S"]], "toggle-type" => "checkmark" | "radio", "", "toggle-state" => MenuItemToggleState, "children-display" => "" | "submenu", ], defaults: type = "standard", label = "", enabled = "", visible = "", icon-name = "", icon-data = None, shortcut = None, toggle-type = "", toggle-state = -1 children-display = "", */ #[derive(Debug)] pub enum MenuItemToggleState { On, Off, Invalid, } impl Into<i32> for MenuItemToggleState { fn into(self) -> i32 { match self { MenuItemToggleState::On => 1, MenuItemToggleState::Off => 0, MenuItemToggleState::Invalid => -1, } } } /// Implement the ComCanonicalMenu so we can push it to the server impl ComCanonicalDbusmenu for Menu { type Err = dbus::tree::MethodErr; /// - `parent_id`: The ID of the parent node for the layout. For grabbing the layout from the root node use zero. /// - `recursion_depth`: The amount of levels of recursion to use. This affects the content of the second variant array. /// - -1: deliver all the items under the @a parentId. /// - 0: no recursion, the array will be empty. /// - n: array will contains items up to 'n' level depth. /// - `property_names`: The list of item properties we are interested in. If there are no entries in the list all of the properties will be sent. /// /// ### Outputs /// /// - `revision: i32`: The revision number of the layout. For matching with layoutUpdated signals. /// - `layout: HashMap`: The layout, as a recursive structure. /// fn get_layout(&self, parent_id: i32, recursion_depth: i32, property_names: Vec<&str>) -> Result<(u32, (i32, ::std::collections::HashMap<String, arg::Variant<Box<arg::RefArg>>>, Vec<arg::Variant<Box<arg::RefArg>>>)), Self::Err> { // I have no idea if this will actually work in any way possible // (u, (ia{sv}av)) // Nautilus: 0, 2, [] // Answer: 14 /* try!(m.as_result()); let mut i = m.iter_init(); let revision: u32 = try!(i.read()); let layout: (i32, ::std::collections::HashMap<String, arg::Variant<Box<arg::RefArg>>>, Vec<arg::Variant<Box<arg::RefArg>>>) = try!(i.read()); Ok((revision, layout)) */ use dbus::Message; use dbus::Member; println!("getlayout called!"); let mut m = Message::new_method_call("com.canonical.dbusmenu", "com/canonical/dbusmenu", "com.canonical.dbusmenu", Member::new("com.canonical.dbusmenu".as_bytes()).unwrap()).unwrap(); try!(m.as_result()); let mut i = m.iter_init(); let mut map = HashMap::<String, arg::Variant<Box<arg::RefArg>>>::new(); map.insert("data-hello".into(), arg::Variant::new_refarg(&mut i).unwrap()); *self.revision.borrow_mut() += 1; Ok((1, (*self.revision.borrow(), map, Vec::new()))) } fn get_group_properties(&self, ids: Vec<i32>, property_names: Vec<&str>) -> Result<Vec<(i32, ::std::collections::HashMap<String, arg::Variant<Box<arg::RefArg>>>)>, Self::Err> { // I AM NOT SURE IF THS WORKS! println!("get_group_properties called: {:?}, {:?}", ids, property_names); /* method call time=1510750424.121891 sender=:1.318 -> destination=org.freedesktop.DBus serial=1 path=/org/freedesktop/DBus; interface=org.freedesktop.DBus; member=Hello */ // warning: other method is also called "hello" // If Nautilus is called with [0], returns [(0, {'children-display': 'submenu'})] let mut properties_hashmap = HashMap::<String, arg::Variant<Box<arg::RefArg>>>::new(); properties_hashmap.insert("label".into(), arg::Variant(Box::new("Hello".to_string()))); Ok(vec![(0, properties_hashmap)]) } fn get_property(&self, id: i32, name: &str) -> Result<arg::Variant<Box<arg::RefArg>>, Self::Err> { println!("get property called!"); // Nautilus get_propery(0, 'children-display') -> 'submenu' Ok(arg::Variant(Box::new("everything is OK".to_string()))) } fn event(&self, id: i32, event_id: &str, data: arg::Variant<Box<arg::RefArg>>, timestamp: u32) -> Result<(), Self::Err> { println!("event called!"); if event_id == "clicked" { println!("received clicked event for menu item {:?}", id); } else if event_id == "hovered" { println!("received hovered event for menu item {:?}", id); } Ok(()) } fn about_to_show(&self, id: i32) -> Result<bool, Self::Err> { // ??? "Whether this AboutToShow event should result in the menu being updated." // not sure what this means println!("about_to_show called, id: {:?}", id); Ok(true) } fn g
et_version(
identifier_name
menu.rs
.window_id = Some(window_id); // todo: notify app menu registrar here println!("registered window!"); } /// Removes the menu pub fn remove_from_window(&mut self) { self.window_id = None; // appmenu unregister window // should also be called on drop println!("unregistered window!"); } /// Removes an item from the menu list. /// Does not error out, but rather returns if the removal was successful pub fn remove_item<S: Into<String>>(item: S) -> bool { let item_id = item.into(); println!("remove_item: {:?}", item_id); false } /// Adds an item to the menu list. /// Does not error out, but rather returns if the add was successful pub fn add_item<S: Into<String>>(item: S) -> bool { let item_id = item.into(); println!("add item: {:?}", item_id); false } /// Actually constructs the window so that it shows the menu now /// Sends the menu over DBus pub fn show() { } } pub enum MenuItem { /// Text menu item, regular. Gets called if clicked TextMenuItem(MenuData<Box<Fn() -> ()>>), /// Checkbox menu item, CheckboxMenuItem(MenuData<Box<Fn(bool) -> ()>>), /// Radio menu item, consisting of multiple menu items. /// Callback gets a string of the currently selected value RadioMenuItem(Vec<MenuData<Box<Fn(String) -> ()>>>), /// Seperator Seperator(), /// Submenu SubMenuItem(String, Box<SubMenu>), } #[derive(Debug)] pub struct MenuData<F> { /// The action to execute, depends on the type of menu item pub action: F, /// Optional image as PNG bytes pub image: Option<Vec<u8>>, /// The label(s) of the menu item, indexed by language identifier /// /// For example: /// /// de - Datei öffnen /// en - Open file pub label: HashMap<String, String>, /// Should the menu entry be activated on hovering pub activate_on_hover: bool, /// Optional shortcuts in the format of a string /// `[["Control", "S"]]` /// `[["Control", "Q"], ["Alt", "X"]]` /// This is only a visual cue (todo: really?) pub shortcut: Option<Vec<ShortcutData>>, } #[derive(Debug, Clone)] pub enum ShortcutData { /// The "Control" in CTRL + S ControlChar(CtrlChar), /// The "S" in CTRL + S Char(String), } /// The four controls registered by dbus #[derive(Debug, Copy, Clone)] pub enum CtrlChar { Ctrl, Alt, Shift, Super, } /* 0 => [ "type" => "standard" | "seperator", "label" => "Hello", "enabled" => true, "visible" => true, "icon-name" => "hello.png", "icon-data" => Vec<u8>, "shortcut" => [["Control", "S"]], "toggle-type" => "checkmark" | "radio", "", "toggle-state" => MenuItemToggleState, "children-display" => "" | "submenu", ], defaults: type = "standard", label = "", enabled = "", visible = "", icon-name = "", icon-data = None, shortcut = None, toggle-type = "", toggle-state = -1 children-display = "", */ #[derive(Debug)] pub enum MenuItemToggleState { On, Off, Invalid, } impl Into<i32> for MenuItemToggleState { fn into(self) -> i32 { match self { MenuItemToggleState::On => 1, MenuItemToggleState::Off => 0, MenuItemToggleState::Invalid => -1, } } } /// Implement the ComCanonicalMenu so we can push it to the server impl ComCanonicalDbusmenu for Menu { type Err = dbus::tree::MethodErr; /// - `parent_id`: The ID of the parent node for the layout. For grabbing the layout from the root node use zero. /// - `recursion_depth`: The amount of levels of recursion to use. This affects the content of the second variant array. /// - -1: deliver all the items under the @a parentId. /// - 0: no recursion, the array will be empty. /// - n: array will contains items up to 'n' level depth. /// - `property_names`: The list of item properties we are interested in. If there are no entries in the list all of the properties will be sent. /// /// ### Outputs /// /// - `revision: i32`: The revision number of the layout. For matching with layoutUpdated signals. /// - `layout: HashMap`: The layout, as a recursive structure. /// fn get_layout(&self, parent_id: i32, recursion_depth: i32, property_names: Vec<&str>) -> Result<(u32, (i32, ::std::collections::HashMap<String, arg::Variant<Box<arg::RefArg>>>, Vec<arg::Variant<Box<arg::RefArg>>>)), Self::Err> { // I have no idea if this will actually work in any way possible // (u, (ia{sv}av)) // Nautilus: 0, 2, [] // Answer: 14 /* try!(m.as_result()); let mut i = m.iter_init(); let revision: u32 = try!(i.read()); let layout: (i32, ::std::collections::HashMap<String, arg::Variant<Box<arg::RefArg>>>, Vec<arg::Variant<Box<arg::RefArg>>>) = try!(i.read()); Ok((revision, layout)) */ use dbus::Message; use dbus::Member; println!("getlayout called!"); let mut m = Message::new_method_call("com.canonical.dbusmenu", "com/canonical/dbusmenu", "com.canonical.dbusmenu", Member::new("com.canonical.dbusmenu".as_bytes()).unwrap()).unwrap(); try!(m.as_result()); let mut i = m.iter_init(); let mut map = HashMap::<String, arg::Variant<Box<arg::RefArg>>>::new(); map.insert("data-hello".into(), arg::Variant::new_refarg(&mut i).unwrap()); *self.revision.borrow_mut() += 1; Ok((1, (*self.revision.borrow(), map, Vec::new()))) } fn get_group_properties(&self, ids: Vec<i32>, property_names: Vec<&str>) -> Result<Vec<(i32, ::std::collections::HashMap<String, arg::Variant<Box<arg::RefArg>>>)>, Self::Err> { // I AM NOT SURE IF THS WORKS! println!("get_group_properties called: {:?}, {:?}", ids, property_names); /* method call time=1510750424.121891 sender=:1.318 -> destination=org.freedesktop.DBus serial=1 path=/org/freedesktop/DBus; interface=org.freedesktop.DBus; member=Hello */ // warning: other method is also called "hello" // If Nautilus is called with [0], returns [(0, {'children-display': 'submenu'})] let mut properties_hashmap = HashMap::<String, arg::Variant<Box<arg::RefArg>>>::new(); properties_hashmap.insert("label".into(), arg::Variant(Box::new("Hello".to_string()))); Ok(vec![(0, properties_hashmap)]) } fn get_property(&self, id: i32, name: &str) -> Result<arg::Variant<Box<arg::RefArg>>, Self::Err> { println!("get property called!"); // Nautilus get_propery(0, 'children-display') -> 'submenu' Ok(arg::Variant(Box::new("everything is OK".to_string()))) } fn event(&self, id: i32, event_id: &str, data: arg::Variant<Box<arg::RefArg>>, timestamp: u32) -> Result<(), Self::Err> { println!("event called!"); if event_id == "clicked" { println!("received clicked event for menu item {:?}", id); } else if event_id == "hovered" { println!("received hovered event for menu item {:?}", id); } Ok(()) } fn about_to_show(&self, id: i32) -> Result<bool, Self::Err> { // ??? "Whether this AboutToShow event should result in the menu being updated." // not sure what this means println!("about_to_show called, id: {:?}", id); Ok(true) } fn get_version(&self) -> Result<u32, Self::Err> { // ???? println!("about_to_show called!"); Ok(3) } fn get_status(&self) -> Result<String, Self::Err> { println!("get_status called!"); // Menus will always be in "normal" state, may change later on Ok("normal".into()) }
random_line_split
poll_evented.rs
@AsyncWrite /// [`mio::Evented`]: trait@mio::Evented /// [`Registration`]: struct@Registration /// [`TcpListener`]: struct@crate::net::TcpListener /// [`clear_read_ready`]: method@Self::clear_read_ready /// [`clear_write_ready`]: method@Self::clear_write_ready /// [`poll_read_ready`]: method@Self::poll_read_ready /// [`poll_write_ready`]: method@Self::poll_write_ready pub(crate) struct PollEvented<E: Evented> { io: Option<E>, registration: Registration, } } // ===== impl PollEvented ===== impl<E> PollEvented<E> where E: Evented, { /// Creates a new `PollEvented` associated with the default reactor. /// /// # Panics /// /// This function panics if thread-local runtime is not set. /// /// The runtime is usually set implicitly when this function is called /// from a future driven by a tokio runtime, otherwise runtime can be set /// explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function. #[cfg_attr(feature = "signal", allow(unused))] pub(crate) fn new(io: E) -> io::Result<Self> { PollEvented::new_with_ready(io, mio::Ready::all()) } /// Creates a new `PollEvented` associated with the default reactor, for specific `mio::Ready` /// state. `new_with_ready` should be used over `new` when you need control over the readiness /// state, such as when a file descriptor only allows reads. This does not add `hup` or `error` /// so if you are interested in those states, you will need to add them to the readiness state /// passed to this function. /// /// An example to listen to read only /// /// ```rust /// ##[cfg(unix)] /// mio::Ready::from_usize( /// mio::Ready::readable().as_usize() /// | mio::unix::UnixReady::error().as_usize() /// | mio::unix::UnixReady::hup().as_usize() /// ); /// ``` /// /// # Panics /// /// This function panics if thread-local runtime is not set. /// /// The runtime is usually set implicitly when this function is called /// from a future driven by a tokio runtime, otherwise runtime can be set /// explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function. #[cfg_attr(feature = "signal", allow(unused))] pub(crate) fn new_with_ready(io: E, ready: mio::Ready) -> io::Result<Self> { Self::new_with_ready_and_handle(io, ready, Handle::current()) } pub(crate) fn new_with_ready_and_handle( io: E, ready: mio::Ready, handle: Handle, ) -> io::Result<Self> { let registration = Registration::new_with_ready_and_handle(&io, ready, handle)?; Ok(Self { io: Some(io), registration, }) } /// Returns a shared reference to the underlying I/O object this readiness /// stream is wrapping. #[cfg(any( feature = "process", feature = "tcp", feature = "udp", feature = "uds", feature = "signal" ))] pub(crate) fn get_ref(&self) -> &E { self.io.as_ref().unwrap() } /// Returns a mutable reference to the underlying I/O object this readiness /// stream is wrapping. pub(crate) fn get_mut(&mut self) -> &mut E { self.io.as_mut().unwrap() } /// Consumes self, returning the inner I/O object /// /// This function will deregister the I/O resource from the reactor before /// returning. If the deregistration operation fails, an error is returned. /// /// Note that deregistering does not guarantee that the I/O resource can be /// registered with a different reactor. Some I/O resource types can only be /// associated with a single reactor instance for their lifetime. #[cfg(any(feature = "tcp", feature = "udp", feature = "uds"))] pub(crate) fn into_inner(mut self) -> io::Result<E> { let io = self.io.take().unwrap(); self.registration.deregister(&io)?; Ok(io) } pub(crate) fn clear_readiness(&self, event: ReadyEvent) { self.registration.clear_readiness(event); } /// Checks the I/O resource's read readiness state. /// /// The mask argument allows specifying what readiness to notify on. This /// can be any value, including platform specific readiness, **except** /// `writable`. HUP is always implicitly included on platforms that support /// it. /// /// If the resource is not ready for a read then `Poll::Pending` is returned /// and the current task is notified once a new event is received. /// /// The I/O resource will remain in a read-ready state until readiness is /// cleared by calling [`clear_read_ready`]. /// /// [`clear_read_ready`]: method@Self::clear_read_ready /// /// # Panics /// /// This function panics if: /// /// * `ready` includes writable. /// * called from outside of a task context. /// /// # Warning /// /// This method may not be called concurrently. It takes `&self` to allow /// calling it concurrently with `poll_write_ready`. pub(crate) fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<ReadyEvent>> { self.registration.poll_readiness(cx, Direction::Read) } /// Checks the I/O resource's write readiness state. /// /// This always checks for writable readiness and also checks for HUP /// readiness on platforms that support it. /// /// If the resource is not ready for a write then `Poll::Pending` is /// returned and the current task is notified once a new event is received. /// /// The I/O resource will remain in a write-ready state until readiness is /// cleared by calling [`clear_write_ready`]. /// /// [`clear_write_ready`]: method@Self::clear_write_ready /// /// # Panics /// /// This function panics if: /// /// * `ready` contains bits besides `writable` and `hup`. /// * called from outside of a task context. /// /// # Warning /// /// This method may not be called concurrently. It takes `&self` to allow /// calling it concurrently with `poll_read_ready`. pub(crate) fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<ReadyEvent>> { self.registration.poll_readiness(cx, Direction::Write) } } cfg_io_readiness! { impl<E> PollEvented<E> where E: Evented, { pub(crate) async fn readiness(&self, interest: mio::Ready) -> io::Result<ReadyEvent> { self.registration.readiness(interest).await } pub(crate) async fn async_io<F, R>(&self, interest: mio::Ready, mut op: F) -> io::Result<R> where F: FnMut(&E) -> io::Result<R>, { loop { let event = self.readiness(interest).await?; match op(self.get_ref()) { Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { self.clear_readiness(event); } x => return x, } } } } } // ===== Read / Write impls ===== impl<E> AsyncRead for PollEvented<E> where E: Evented + Read + Unpin, { fn poll_read( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<io::Result<()>> { loop { let ev = ready!(self.poll_read_ready(cx))?; // We can't assume the `Read` won't look at the read buffer, // so we have to force initialization here. let r = (*self).get_mut().read(buf.initialize_unfilled()); if is_wouldblock(&r) { self.clear_readiness(ev); continue; } return Poll::Ready(r.map(|n| { buf.add_filled(n); })); } } } impl<E> AsyncWrite for PollEvented<E> where E: Evented + Write + Unpin, { fn poll_write( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8], ) -> Poll<io::Result<usize>> { loop { let ev = ready!(self.poll_write_ready(cx))?; let r = (*self).get_mut().write(buf); if is_wouldblock(&r) { self.clear_readiness(ev); continue; } return Poll::Ready(r); } } fn
poll_flush
identifier_name
poll_evented.rs
most two tasks that /// use a `PollEvented` instance concurrently. One for reading and one for /// writing. While violating this requirement is "safe" from a Rust memory /// model point of view, it will result in unexpected behavior in the form /// of lost notifications and tasks hanging. /// /// ## Readiness events /// /// Besides just providing [`AsyncRead`] and [`AsyncWrite`] implementations, /// this type also supports access to the underlying readiness event stream. /// While similar in function to what [`Registration`] provides, the /// semantics are a bit different. /// /// Two functions are provided to access the readiness events: /// [`poll_read_ready`] and [`poll_write_ready`]. These functions return the /// current readiness state of the `PollEvented` instance. If /// [`poll_read_ready`] indicates read readiness, immediately calling /// [`poll_read_ready`] again will also indicate read readiness. /// /// When the operation is attempted and is unable to succeed due to the I/O /// resource not being ready, the caller must call [`clear_read_ready`] or /// [`clear_write_ready`]. This clears the readiness state until a new /// readiness event is received. /// /// This allows the caller to implement additional functions. For example, /// [`TcpListener`] implements poll_accept by using [`poll_read_ready`] and /// [`clear_read_ready`]. /// /// ## Platform-specific events /// /// `PollEvented` also allows receiving platform-specific `mio::Ready` events. /// These events are included as part of the read readiness event stream. The /// write readiness event stream is only for `Ready::writable()` events. /// /// [`std::io::Read`]: trait@std::io::Read /// [`std::io::Write`]: trait@std::io::Write /// [`AsyncRead`]: trait@AsyncRead /// [`AsyncWrite`]: trait@AsyncWrite /// [`mio::Evented`]: trait@mio::Evented /// [`Registration`]: struct@Registration /// [`TcpListener`]: struct@crate::net::TcpListener /// [`clear_read_ready`]: method@Self::clear_read_ready /// [`clear_write_ready`]: method@Self::clear_write_ready /// [`poll_read_ready`]: method@Self::poll_read_ready /// [`poll_write_ready`]: method@Self::poll_write_ready pub(crate) struct PollEvented<E: Evented> { io: Option<E>, registration: Registration, } } // ===== impl PollEvented ===== impl<E> PollEvented<E> where E: Evented, { /// Creates a new `PollEvented` associated with the default reactor. /// /// # Panics /// /// This function panics if thread-local runtime is not set. /// /// The runtime is usually set implicitly when this function is called /// from a future driven by a tokio runtime, otherwise runtime can be set /// explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function. #[cfg_attr(feature = "signal", allow(unused))] pub(crate) fn new(io: E) -> io::Result<Self> { PollEvented::new_with_ready(io, mio::Ready::all()) } /// Creates a new `PollEvented` associated with the default reactor, for specific `mio::Ready` /// state. `new_with_ready` should be used over `new` when you need control over the readiness /// state, such as when a file descriptor only allows reads. This does not add `hup` or `error` /// so if you are interested in those states, you will need to add them to the readiness state /// passed to this function. /// /// An example to listen to read only /// /// ```rust /// ##[cfg(unix)] /// mio::Ready::from_usize( /// mio::Ready::readable().as_usize() /// | mio::unix::UnixReady::error().as_usize() /// | mio::unix::UnixReady::hup().as_usize() /// ); /// ``` /// /// # Panics /// /// This function panics if thread-local runtime is not set. /// /// The runtime is usually set implicitly when this function is called /// from a future driven by a tokio runtime, otherwise runtime can be set /// explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function. #[cfg_attr(feature = "signal", allow(unused))] pub(crate) fn new_with_ready(io: E, ready: mio::Ready) -> io::Result<Self> { Self::new_with_ready_and_handle(io, ready, Handle::current()) } pub(crate) fn new_with_ready_and_handle( io: E, ready: mio::Ready, handle: Handle, ) -> io::Result<Self>
/// Returns a shared reference to the underlying I/O object this readiness /// stream is wrapping. #[cfg(any( feature = "process", feature = "tcp", feature = "udp", feature = "uds", feature = "signal" ))] pub(crate) fn get_ref(&self) -> &E { self.io.as_ref().unwrap() } /// Returns a mutable reference to the underlying I/O object this readiness /// stream is wrapping. pub(crate) fn get_mut(&mut self) -> &mut E { self.io.as_mut().unwrap() } /// Consumes self, returning the inner I/O object /// /// This function will deregister the I/O resource from the reactor before /// returning. If the deregistration operation fails, an error is returned. /// /// Note that deregistering does not guarantee that the I/O resource can be /// registered with a different reactor. Some I/O resource types can only be /// associated with a single reactor instance for their lifetime. #[cfg(any(feature = "tcp", feature = "udp", feature = "uds"))] pub(crate) fn into_inner(mut self) -> io::Result<E> { let io = self.io.take().unwrap(); self.registration.deregister(&io)?; Ok(io) } pub(crate) fn clear_readiness(&self, event: ReadyEvent) { self.registration.clear_readiness(event); } /// Checks the I/O resource's read readiness state. /// /// The mask argument allows specifying what readiness to notify on. This /// can be any value, including platform specific readiness, **except** /// `writable`. HUP is always implicitly included on platforms that support /// it. /// /// If the resource is not ready for a read then `Poll::Pending` is returned /// and the current task is notified once a new event is received. /// /// The I/O resource will remain in a read-ready state until readiness is /// cleared by calling [`clear_read_ready`]. /// /// [`clear_read_ready`]: method@Self::clear_read_ready /// /// # Panics /// /// This function panics if: /// /// * `ready` includes writable. /// * called from outside of a task context. /// /// # Warning /// /// This method may not be called concurrently. It takes `&self` to allow /// calling it concurrently with `poll_write_ready`. pub(crate) fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<ReadyEvent>> { self.registration.poll_readiness(cx, Direction::Read) } /// Checks the I/O resource's write readiness state. /// /// This always checks for writable readiness and also checks for HUP /// readiness on platforms that support it. /// /// If the resource is not ready for a write then `Poll::Pending` is /// returned and the current task is notified once a new event is received. /// /// The I/O resource will remain in a write-ready state until readiness is /// cleared by calling [`clear_write_ready`]. /// /// [`clear_write_ready`]: method@Self::clear_write_ready /// /// # Panics /// /// This function panics if: /// /// * `ready` contains bits besides `writable` and `hup`. /// * called from outside of a task context. /// /// # Warning /// /// This method may not be called concurrently. It takes `&self` to allow /// calling it concurrently with `poll_read_ready`. pub(crate) fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<ReadyEvent>> { self.registration.poll_readiness(cx, Direction::Write) } } cfg_io_readiness! { impl<E> PollEvented<E> where E: Evented, { pub(crate) async fn readiness(&self, interest: mio::Ready) -> io::Result<ReadyEvent> { self.registration.readiness(interest).await
{ let registration = Registration::new_with_ready_and_handle(&io, ready, handle)?; Ok(Self { io: Some(io), registration, }) }
identifier_body
poll_evented.rs
implement additional functions. For example, /// [`TcpListener`] implements poll_accept by using [`poll_read_ready`] and /// [`clear_read_ready`]. /// /// ## Platform-specific events /// /// `PollEvented` also allows receiving platform-specific `mio::Ready` events. /// These events are included as part of the read readiness event stream. The /// write readiness event stream is only for `Ready::writable()` events. /// /// [`std::io::Read`]: trait@std::io::Read /// [`std::io::Write`]: trait@std::io::Write /// [`AsyncRead`]: trait@AsyncRead /// [`AsyncWrite`]: trait@AsyncWrite /// [`mio::Evented`]: trait@mio::Evented /// [`Registration`]: struct@Registration /// [`TcpListener`]: struct@crate::net::TcpListener /// [`clear_read_ready`]: method@Self::clear_read_ready /// [`clear_write_ready`]: method@Self::clear_write_ready /// [`poll_read_ready`]: method@Self::poll_read_ready /// [`poll_write_ready`]: method@Self::poll_write_ready pub(crate) struct PollEvented<E: Evented> { io: Option<E>, registration: Registration, } } // ===== impl PollEvented ===== impl<E> PollEvented<E> where E: Evented, { /// Creates a new `PollEvented` associated with the default reactor. /// /// # Panics /// /// This function panics if thread-local runtime is not set. /// /// The runtime is usually set implicitly when this function is called /// from a future driven by a tokio runtime, otherwise runtime can be set /// explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function. #[cfg_attr(feature = "signal", allow(unused))] pub(crate) fn new(io: E) -> io::Result<Self> { PollEvented::new_with_ready(io, mio::Ready::all()) } /// Creates a new `PollEvented` associated with the default reactor, for specific `mio::Ready` /// state. `new_with_ready` should be used over `new` when you need control over the readiness /// state, such as when a file descriptor only allows reads. This does not add `hup` or `error` /// so if you are interested in those states, you will need to add them to the readiness state /// passed to this function. /// /// An example to listen to read only /// /// ```rust /// ##[cfg(unix)] /// mio::Ready::from_usize( /// mio::Ready::readable().as_usize() /// | mio::unix::UnixReady::error().as_usize() /// | mio::unix::UnixReady::hup().as_usize() /// ); /// ``` /// /// # Panics /// /// This function panics if thread-local runtime is not set. /// /// The runtime is usually set implicitly when this function is called /// from a future driven by a tokio runtime, otherwise runtime can be set /// explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function. #[cfg_attr(feature = "signal", allow(unused))] pub(crate) fn new_with_ready(io: E, ready: mio::Ready) -> io::Result<Self> { Self::new_with_ready_and_handle(io, ready, Handle::current()) } pub(crate) fn new_with_ready_and_handle( io: E, ready: mio::Ready, handle: Handle, ) -> io::Result<Self> { let registration = Registration::new_with_ready_and_handle(&io, ready, handle)?; Ok(Self { io: Some(io), registration, }) } /// Returns a shared reference to the underlying I/O object this readiness /// stream is wrapping. #[cfg(any( feature = "process", feature = "tcp", feature = "udp", feature = "uds", feature = "signal" ))] pub(crate) fn get_ref(&self) -> &E { self.io.as_ref().unwrap() } /// Returns a mutable reference to the underlying I/O object this readiness /// stream is wrapping. pub(crate) fn get_mut(&mut self) -> &mut E { self.io.as_mut().unwrap() } /// Consumes self, returning the inner I/O object /// /// This function will deregister the I/O resource from the reactor before /// returning. If the deregistration operation fails, an error is returned. /// /// Note that deregistering does not guarantee that the I/O resource can be /// registered with a different reactor. Some I/O resource types can only be /// associated with a single reactor instance for their lifetime. #[cfg(any(feature = "tcp", feature = "udp", feature = "uds"))] pub(crate) fn into_inner(mut self) -> io::Result<E> { let io = self.io.take().unwrap(); self.registration.deregister(&io)?; Ok(io) } pub(crate) fn clear_readiness(&self, event: ReadyEvent) { self.registration.clear_readiness(event); } /// Checks the I/O resource's read readiness state. /// /// The mask argument allows specifying what readiness to notify on. This /// can be any value, including platform specific readiness, **except** /// `writable`. HUP is always implicitly included on platforms that support /// it. /// /// If the resource is not ready for a read then `Poll::Pending` is returned /// and the current task is notified once a new event is received. /// /// The I/O resource will remain in a read-ready state until readiness is /// cleared by calling [`clear_read_ready`]. /// /// [`clear_read_ready`]: method@Self::clear_read_ready /// /// # Panics /// /// This function panics if: /// /// * `ready` includes writable. /// * called from outside of a task context. /// /// # Warning /// /// This method may not be called concurrently. It takes `&self` to allow /// calling it concurrently with `poll_write_ready`. pub(crate) fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<ReadyEvent>> { self.registration.poll_readiness(cx, Direction::Read) } /// Checks the I/O resource's write readiness state. /// /// This always checks for writable readiness and also checks for HUP /// readiness on platforms that support it. /// /// If the resource is not ready for a write then `Poll::Pending` is /// returned and the current task is notified once a new event is received. /// /// The I/O resource will remain in a write-ready state until readiness is /// cleared by calling [`clear_write_ready`]. /// /// [`clear_write_ready`]: method@Self::clear_write_ready /// /// # Panics /// /// This function panics if: /// /// * `ready` contains bits besides `writable` and `hup`. /// * called from outside of a task context. /// /// # Warning /// /// This method may not be called concurrently. It takes `&self` to allow /// calling it concurrently with `poll_read_ready`. pub(crate) fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<ReadyEvent>> { self.registration.poll_readiness(cx, Direction::Write) } } cfg_io_readiness! { impl<E> PollEvented<E> where E: Evented, { pub(crate) async fn readiness(&self, interest: mio::Ready) -> io::Result<ReadyEvent> { self.registration.readiness(interest).await } pub(crate) async fn async_io<F, R>(&self, interest: mio::Ready, mut op: F) -> io::Result<R> where F: FnMut(&E) -> io::Result<R>, { loop { let event = self.readiness(interest).await?; match op(self.get_ref()) { Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { self.clear_readiness(event); } x => return x, } } } } } // ===== Read / Write impls ===== impl<E> AsyncRead for PollEvented<E> where E: Evented + Read + Unpin, { fn poll_read( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<io::Result<()>> { loop { let ev = ready!(self.poll_read_ready(cx))?; // We can't assume the `Read` won't look at the read buffer, // so we have to force initialization here. let r = (*self).get_mut().read(buf.initialize_unfilled()); if is_wouldblock(&r)
{ self.clear_readiness(ev); continue; }
conditional_block
poll_evented.rs
most two tasks that /// use a `PollEvented` instance concurrently. One for reading and one for /// writing. While violating this requirement is "safe" from a Rust memory /// model point of view, it will result in unexpected behavior in the form /// of lost notifications and tasks hanging. /// /// ## Readiness events /// /// Besides just providing [`AsyncRead`] and [`AsyncWrite`] implementations, /// this type also supports access to the underlying readiness event stream. /// While similar in function to what [`Registration`] provides, the /// semantics are a bit different. /// /// Two functions are provided to access the readiness events: /// [`poll_read_ready`] and [`poll_write_ready`]. These functions return the /// current readiness state of the `PollEvented` instance. If /// [`poll_read_ready`] indicates read readiness, immediately calling /// [`poll_read_ready`] again will also indicate read readiness. /// /// When the operation is attempted and is unable to succeed due to the I/O /// resource not being ready, the caller must call [`clear_read_ready`] or /// [`clear_write_ready`]. This clears the readiness state until a new /// readiness event is received. /// /// This allows the caller to implement additional functions. For example, /// [`TcpListener`] implements poll_accept by using [`poll_read_ready`] and /// [`clear_read_ready`]. /// /// ## Platform-specific events /// /// `PollEvented` also allows receiving platform-specific `mio::Ready` events. /// These events are included as part of the read readiness event stream. The /// write readiness event stream is only for `Ready::writable()` events. /// /// [`std::io::Read`]: trait@std::io::Read /// [`std::io::Write`]: trait@std::io::Write /// [`AsyncRead`]: trait@AsyncRead /// [`AsyncWrite`]: trait@AsyncWrite /// [`mio::Evented`]: trait@mio::Evented /// [`Registration`]: struct@Registration /// [`TcpListener`]: struct@crate::net::TcpListener /// [`clear_read_ready`]: method@Self::clear_read_ready /// [`clear_write_ready`]: method@Self::clear_write_ready /// [`poll_read_ready`]: method@Self::poll_read_ready /// [`poll_write_ready`]: method@Self::poll_write_ready pub(crate) struct PollEvented<E: Evented> { io: Option<E>, registration: Registration, } } // ===== impl PollEvented ===== impl<E> PollEvented<E> where E: Evented, { /// Creates a new `PollEvented` associated with the default reactor. /// /// # Panics /// /// This function panics if thread-local runtime is not set. /// /// The runtime is usually set implicitly when this function is called /// from a future driven by a tokio runtime, otherwise runtime can be set /// explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function. #[cfg_attr(feature = "signal", allow(unused))] pub(crate) fn new(io: E) -> io::Result<Self> { PollEvented::new_with_ready(io, mio::Ready::all()) } /// Creates a new `PollEvented` associated with the default reactor, for specific `mio::Ready` /// state. `new_with_ready` should be used over `new` when you need control over the readiness /// state, such as when a file descriptor only allows reads. This does not add `hup` or `error` /// so if you are interested in those states, you will need to add them to the readiness state /// passed to this function. /// /// An example to listen to read only /// /// ```rust /// ##[cfg(unix)] /// mio::Ready::from_usize( /// mio::Ready::readable().as_usize() /// | mio::unix::UnixReady::error().as_usize() /// | mio::unix::UnixReady::hup().as_usize() /// ); /// ``` /// /// # Panics /// /// This function panics if thread-local runtime is not set. /// /// The runtime is usually set implicitly when this function is called /// from a future driven by a tokio runtime, otherwise runtime can be set /// explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function. #[cfg_attr(feature = "signal", allow(unused))] pub(crate) fn new_with_ready(io: E, ready: mio::Ready) -> io::Result<Self> { Self::new_with_ready_and_handle(io, ready, Handle::current()) } pub(crate) fn new_with_ready_and_handle( io: E, ready: mio::Ready, handle: Handle, ) -> io::Result<Self> { let registration = Registration::new_with_ready_and_handle(&io, ready, handle)?; Ok(Self { io: Some(io), registration, }) } /// Returns a shared reference to the underlying I/O object this readiness /// stream is wrapping. #[cfg(any( feature = "process", feature = "tcp", feature = "udp", feature = "uds", feature = "signal" ))] pub(crate) fn get_ref(&self) -> &E { self.io.as_ref().unwrap() } /// Returns a mutable reference to the underlying I/O object this readiness /// stream is wrapping. pub(crate) fn get_mut(&mut self) -> &mut E { self.io.as_mut().unwrap() } /// Consumes self, returning the inner I/O object /// /// This function will deregister the I/O resource from the reactor before /// returning. If the deregistration operation fails, an error is returned. /// /// Note that deregistering does not guarantee that the I/O resource can be /// registered with a different reactor. Some I/O resource types can only be /// associated with a single reactor instance for their lifetime. #[cfg(any(feature = "tcp", feature = "udp", feature = "uds"))] pub(crate) fn into_inner(mut self) -> io::Result<E> { let io = self.io.take().unwrap(); self.registration.deregister(&io)?; Ok(io) } pub(crate) fn clear_readiness(&self, event: ReadyEvent) { self.registration.clear_readiness(event); } /// Checks the I/O resource's read readiness state. /// /// The mask argument allows specifying what readiness to notify on. This /// can be any value, including platform specific readiness, **except** /// `writable`. HUP is always implicitly included on platforms that support /// it. /// /// If the resource is not ready for a read then `Poll::Pending` is returned /// and the current task is notified once a new event is received. /// /// The I/O resource will remain in a read-ready state until readiness is /// cleared by calling [`clear_read_ready`]. /// /// [`clear_read_ready`]: method@Self::clear_read_ready /// /// # Panics ///
/// /// # Warning /// /// This method may not be called concurrently. It takes `&self` to allow /// calling it concurrently with `poll_write_ready`. pub(crate) fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<ReadyEvent>> { self.registration.poll_readiness(cx, Direction::Read) } /// Checks the I/O resource's write readiness state. /// /// This always checks for writable readiness and also checks for HUP /// readiness on platforms that support it. /// /// If the resource is not ready for a write then `Poll::Pending` is /// returned and the current task is notified once a new event is received. /// /// The I/O resource will remain in a write-ready state until readiness is /// cleared by calling [`clear_write_ready`]. /// /// [`clear_write_ready`]: method@Self::clear_write_ready /// /// # Panics /// /// This function panics if: /// /// * `ready` contains bits besides `writable` and `hup`. /// * called from outside of a task context. /// /// # Warning /// /// This method may not be called concurrently. It takes `&self` to allow /// calling it concurrently with `poll_read_ready`. pub(crate) fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<ReadyEvent>> { self.registration.poll_readiness(cx, Direction::Write) } } cfg_io_readiness! { impl<E> PollEvented<E> where E: Evented, { pub(crate) async fn readiness(&self, interest: mio::Ready) -> io::Result<ReadyEvent> { self.registration.readiness(interest).await
/// This function panics if: /// /// * `ready` includes writable. /// * called from outside of a task context.
random_line_split
projects.ts
{ year: 2018, name: {ru: 'Мобильное приложение Emotion Miner', en: 'Emotion Miner mobile app'}, description: {ru: 'Техническая демонстрация мобильного приложения для платформы Emotion Miner. Реализованы ключевые элементы управления приложением, заточенные под мобильные устройства. Проект подготовлен для загрузки на iOS, Android и Windows Phone.', en: 'Technical demonstration of the mobile application for the Emotion Miner platform. Implemented key application control elements designed for mobile devices. The project is prepared for download on iOS, Android and Windows Phone.'}, img: 'emotionminer_m.jpg', links: [ { url: 'https://emotion-miner-ionic-test.herokuapp.com/', name: {ru: 'Тестовый сайт проекта', en: 'Project\'s test website'}, icon: 'cog' } ], feedback: true }, { year: 2017, name: {ru: 'Emotion Miner', en: 'Emotion Miner'}, description: {ru: 'Платформа для сбора датасетов эмоций людей на фрагментах видео из YouTube. На платформу может зайти любой человек, пройти небольшой тест и обучение по разметке эмоций, а после этого начать зарабатывать и выводить деньги за разметку. Внедрена поддержка веб-камеры, записывающей эмоциональное состояние человека, размечающего видео. На платформе зарегистрировано и работает более 50.000 человек.', en: 'The platform for collecting datasets of people\'s emotions at video fragments from YouTube. Any person can sign up to the platform, pass a short test and a training on emotions annotating. And after that he can start working and withdraw money for markup. Implemented support for webcam, recording the emotional state of a person marking a video. There are over 50,000 people registered and working at the platform.'}, img: 'emotionminer.jpg', links: [ { url: 'https://emotionminer.com', name: {ru: 'Сайт проекта', en: 'Project\'s website'}, icon: 'globe' }, { url: 'http://neurodatalab.com', name: {ru: 'Сайт заказчика', en: 'Customer\'s website'}, icon: 'globe' }, { url: 'https://youtu.be/dTLLGIVRFj8', name: {ru: 'Обзор на платформу от филиппинского видеоблоггера', en: 'Overview of the platform from the Filipino videoblogger'}, icon: 'youtube' } ], feedback: true, best: true, forBanner: true }, { year: 2017, name: {ru: 'OYWO', en: 'OYWO'}, description: {ru: 'Оптимальная мотивационная система контроля своего времени и занятости. Разработан список дел и календарь, работающие в связке друг с другом. Есть возможность входить в систему через соцсети.', en: 'Optimal motivational system for controlling personal and working time. There was developed a todo-list working together in conjunction with a calendar. There is an opportunity to sign in to the system through social networks.'}, img: 'oywo.jpg', links: [ { url: 'https://oywo.herokuapp.com/', name: {ru: 'Сайт проекта', en: 'Project\'s website'}, icon: 'globe' }, { url: 'https://vk.com/useoywo', name: {ru: 'Поддержки проекта в группе ВКонтакте', en: 'Project\'s support VK group'}, icon: 'vk' } ], feedback: true, best: true, forBanner: true }, { year: 2017, name: {ru: 'Мой блог', en: 'My blog'}, description: {ru: 'Блог-платформу на движке Jekyll, позволяющие писать статьи на языке Markdown. Внедрил возможность вставлять программный код с подсветкой, а также LaTeX-формулы.', en: 'A blog-platform on the Jekyll engine, which allows writing articles in the Markdown language. Implemented the ability to insert highlighted code, as well as LaTeX-equations.'}, img: 'blog.jpg', links: [ { url: 'https://polyakovin.github.io', name: {ru: 'Сайт проекта', en: 'Project\'s website'}, icon: 'globe' }, { url: 'https://github.com/polyakovin/polyakovin.github.io', name: {ru: 'Рабочий репозиторий проекта', en: 'Project\'s working repository'}, icon: 'github-alt' } ], ohNo: true }, { year: 2017, name: {ru: 'Конструктор документов для заказа', en: 'The document builder for the order'}, description: {ru: 'Упрощено делопроизводство в компании «Бастион», изготавливающей стальные двери. Программа принимает на вход все необоходимые параметры заказа и выдаёт документ, пригодный для печати.', en: 'Оffice work in the producing steel doors company “Bastion” has been simplified. The program accepts all required parameters of the order for input and produces a document suitable for printing.'}, img: 'bastion.jpg', links: [ { url: 'https://polyakovin.github.io/bastionRequest', name: {ru: 'Архивная копия проекта', en: 'Project\'s archive copy'}, icon: 'archive' }, { url: 'https://github.com/polyakovin/bastionRequest', name: {ru: 'Рабочий репозиторий проекта', en: 'Project\'s working repository'}, icon: 'github-alt' } ], feedback: true, best: true }, { year: 2016, name: {ru: 'Интерактивные уроки для детей', en: 'Interactive lessons for children'}, description: {ru: 'В рамках участия в образовательном проекте UCHi.RU создал несколько обучающих игр, полезных функций и компонентов общего назначений. Разработан и внедрён в систему разработки сборщик документации по программным компонентам компании.', en: 'While taking part in the educational project UCHi.RU, there were developed several training games, some useful functions and general purpose components. There also was developed and implemented the documentation collector for the software components of the company in the development system.'}, img: 'uchi.jpg', video: 'https://vk.com/video_ext.php?oid=-94792100&id=456239017&hash=3371d6e8fcab148c', links: [ { url: 'https://uchi.ru', name: {ru: 'Образовательный проект UCHi.RU', en: 'Educational project UCHi.RU'}, icon: 'globe' }, { url: 'https://vk.com/ip.painter?w=wall-94792100_15', name: {ru: 'Демонстрация работы функции Drug\'n\'Drop', en: 'Drag&drop function demonstration'}, icon: 'vk' } ], feedback: true, best: true, forBanner: true }, { year: 2016, name: {ru: 'Веб-сайт компании «Ваш Выбор!»', en: '“Your Choice!” company website'}, description: {ru: 'Ребрендинг веб-сайта фирмы в соответствии с новым фирменным стилем. Количество элементов на сайте сокращено до необходимого минимума. Выделены ключевые достоинства компании и продукции перед конкурентами.', en: 'Rebranding the company\'s website in accordance with the new corporate style guide. The number of elements on the site has been reduced to the required minimum. There are the key advantages of the company and products in compare to competitors highlighted.'}, img: 'yourChoice2.jpg', links: [ { url: 'https://polyakovin.github.io/yourChoice2', name: {ru: 'Архивная копия проекта', en: 'Project\'s archive copy'}, icon: 'archive' },
{ url: 'https://github.com/polyakovin/yourChoice2',
random_line_split
api.go
*dapr_pb.DeleteStateEnvelope) (*empty.Empty, error) } type api struct { actor actors.Actors directMessaging messaging.DirectMessaging componentsHandler components.ComponentHandler appChannel channel.AppChannel stateStores map[string]state.Store pubSub pubsub.PubSub id string sendToOutputBindingFn func(name string, req *bindings.WriteRequest) error } // NewAPI returns a new gRPC API func NewAPI(daprID string, appChannel channel.AppChannel, stateStores map[string]state.Store, pubSub pubsub.PubSub, directMessaging messaging.DirectMessaging, actor actors.Actors, sendToOutputBindingFn func(name string, req *bindings.WriteRequest) error, componentHandler components.ComponentHandler) API { return &api{ directMessaging: directMessaging, componentsHandler: componentHandler, actor: actor, id: daprID, appChannel: appChannel, pubSub: pubSub, stateStores: stateStores, sendToOutputBindingFn: sendToOutputBindingFn, } } // CallLocal is used for internal dapr to dapr calls. It is invoked by another Dapr instance with a request to the local app. func (a *api) CallLocal(ctx context.Context, in *daprinternal_pb.LocalCallEnvelope) (*daprinternal_pb.InvokeResponse, error) { if a.appChannel == nil { return nil, errors.New("app channel is not initialized") } req := channel.InvokeRequest{ Payload: in.Data.Value, Method: in.Method, Metadata: in.Metadata, } resp, err := a.appChannel.InvokeMethod(&req) if err != nil { return nil, err } return &daprinternal_pb.InvokeResponse{ Data: &any.Any{Value: resp.Data}, Metadata: resp.Metadata, }, nil } // CallActor invokes a virtual actor func (a *api) CallActor(ctx context.Context, in *daprinternal_pb.CallActorEnvelope) (*daprinternal_pb.InvokeResponse, error) { req := actors.CallRequest{ ActorType: in.ActorType, ActorID: in.ActorID, Data: in.Data.Value, Method: in.Method, Metadata: in.Metadata, } resp, err := a.actor.Call(&req) if err != nil { return nil, err } return &daprinternal_pb.InvokeResponse{ Data: &any.Any{Value: resp.Data}, Metadata: map[string]string{}, }, nil } // UpdateComponent is fired by the Dapr control plane when a component state changes func (a *api) UpdateComponent(ctx context.Context, in *daprinternal_pb.Component) (*empty.Empty, error) { c := components_v1alpha1.Component{ ObjectMeta: meta_v1.ObjectMeta{ Name: in.Metadata.Name, }, Auth: components_v1alpha1.Auth{ SecretStore: in.Auth.SecretStore, }, } for _, m := range in.Spec.Metadata { c.Spec.Metadata = append(c.Spec.Metadata, components_v1alpha1.MetadataItem{ Name: m.Name, Value: m.Value, SecretKeyRef: components_v1alpha1.SecretKeyRef{ Key: m.SecretKeyRef.Key, Name: m.SecretKeyRef.Name, }, }) } a.componentsHandler.OnComponentUpdated(c) return &empty.Empty{}, nil } func (a *api) PublishEvent(ctx context.Context, in *dapr_pb.PublishEventEnvelope) (*empty.Empty, error) { if a.pubSub == nil { return &empty.Empty{}, errors.New("ERR_PUBSUB_NOT_FOUND") } topic := in.Topic body := []byte{} if in.Data != nil { body = in.Data.Value } envelope := pubsub.NewCloudEventsEnvelope(uuid.New().String(), a.id, pubsub.DefaultCloudEventType, body) b, err := jsoniter.ConfigFastest.Marshal(envelope) if err != nil { return &empty.Empty{}, fmt.Errorf("ERR_PUBSUB_CLOUD_EVENTS_SER: %s", err) } req := pubsub.PublishRequest{ Topic: topic, Data: b, } err = a.pubSub.Publish(&req) if err != nil { return &empty.Empty{}, fmt.Errorf("ERR_PUBSUB_PUBLISH_MESSAGE: %s", err) } return &empty.Empty{}, nil } func (a *api) InvokeService(ctx context.Context, in *dapr_pb.InvokeServiceEnvelope) (*dapr_pb.InvokeServiceResponseEnvelope, error) { req := messaging.DirectMessageRequest{ Data: in.Data.Value, Method: in.Method, Metadata: in.Metadata, Target: in.Id, } resp, err := a.directMessaging.Invoke(&req) if err != nil { return nil, err } return &dapr_pb.InvokeServiceResponseEnvelope{ Data: &any.Any{Value: resp.Data}, Metadata: resp.Metadata, }, nil } func (a *api) InvokeBinding(ctx context.Context, in *dapr_pb.InvokeBindingEnvelope) (*empty.Empty, error) { req := &bindings.WriteRequest{ Metadata: in.Metadata, } if in.Data != nil { req.Data = in.Data.Value } err := a.sendToOutputBindingFn(in.Name, req) if err != nil { return &empty.Empty{}, fmt.Errorf("ERR_INVOKE_OUTPUT_BINDING: %s", err) } return &empty.Empty{}, nil } func (a *api) GetState(ctx context.Context, in *dapr_pb.GetStateEnvelope) (*dapr_pb.GetStateResponseEnvelope, error) { if a.stateStores == nil || len(a.stateStores) == 0 { return nil, errors.New("ERR_STATE_STORE_NOT_CONFIGURED") } storeName := in.StoreName if a.stateStores[storeName] == nil { return nil, errors.New("ERR_STATE_STORE_NOT_FOUND") } req := state.GetRequest{ Key: a.getModifiedStateKey(in.Key), Options: state.GetStateOption{ Consistency: in.Consistency, }, } getResponse, err := a.stateStores[storeName].Get(&req) if err != nil { return nil, fmt.Errorf("ERR_STATE_GET: %s", err) } response := &dapr_pb.GetStateResponseEnvelope{} if getResponse != nil { response.Etag = getResponse.ETag response.Data = &any.Any{Value: getResponse.Data} } return response, nil } func (a *api) SaveState(ctx context.Context, in *dapr_pb.SaveStateEnvelope) (*empty.Empty, error) { if a.stateStores == nil || len(a.stateStores) == 0 { return &empty.Empty{}, errors.New("ERR_STATE_STORE_NOT_CONFIGURED") } storeName := in.StoreName if a.stateStores[storeName] == nil { return &empty.Empty{}, errors.New("ERR_STATE_STORE_NOT_FOUND") } reqs := []state.SetRequest{} for _, s := range in.Requests { req := state.SetRequest{ Key: a.getModifiedStateKey(s.Key), Metadata: s.Metadata, Value: s.Value.Value, } if s.Options != nil { req.Options = state.SetStateOption{ Consistency: s.Options.Consistency, Concurrency: s.Options.Concurrency, } if s.Options.RetryPolicy != nil { req.Options.RetryPolicy = state.RetryPolicy{ Threshold: int(s.Options.RetryPolicy.Threshold), Pattern: s.Options.RetryPolicy.Pattern, } if s.Options.RetryPolicy.Interval != nil { dur, err := duration(s.Options.RetryPolicy.Interval) if err == nil { req.Options.RetryPolicy.Interval = dur } } } } reqs = append(reqs, req) } err := a.stateStores[storeName].BulkSet(reqs) if err != nil { return &empty.Empty{}, fmt.Errorf("ERR_STATE_SAVE: %s", err) } return &empty.Empty{}, nil } func (a *api) DeleteState(ctx context.Context, in *dapr_pb.DeleteStateEnvelope) (*empty.Empty, error) { if a.stateStores == nil || len(a.stateStores) == 0 { return &empty.Empty{}, errors.New("ERR_STATE_STORE_NOT_CONFIGURED") } storeName := in.StoreName if a.stateStores[storeName] == nil { return &empty.Empty{}, errors.New("ERR_STATE_STORE_NOT_FOUND") } req := state.DeleteRequest{ Key: a.getModifiedStateKey(in.Key), ETag: in.Etag, } if in.Options != nil { req.Options = state.DeleteStateOption{ Concurrency: in.Options.Concurrency, Consistency: in.Options.Consistency, } if in.Options.RetryPolicy != nil { retryPolicy := state.RetryPolicy{ Threshold: int(in.Options.RetryPolicy.Threshold), Pattern: in.Options.RetryPolicy.Pattern, } if in.Options.RetryPolicy.Interval != nil
{ dur, err := duration(in.Options.RetryPolicy.Interval) if err == nil { retryPolicy.Interval = dur } }
conditional_block
api.go
.WriteRequest) error } // NewAPI returns a new gRPC API func NewAPI(daprID string, appChannel channel.AppChannel, stateStores map[string]state.Store, pubSub pubsub.PubSub, directMessaging messaging.DirectMessaging, actor actors.Actors, sendToOutputBindingFn func(name string, req *bindings.WriteRequest) error, componentHandler components.ComponentHandler) API { return &api{ directMessaging: directMessaging, componentsHandler: componentHandler, actor: actor, id: daprID, appChannel: appChannel, pubSub: pubSub, stateStores: stateStores, sendToOutputBindingFn: sendToOutputBindingFn, } } // CallLocal is used for internal dapr to dapr calls. It is invoked by another Dapr instance with a request to the local app. func (a *api) CallLocal(ctx context.Context, in *daprinternal_pb.LocalCallEnvelope) (*daprinternal_pb.InvokeResponse, error) { if a.appChannel == nil { return nil, errors.New("app channel is not initialized") } req := channel.InvokeRequest{ Payload: in.Data.Value, Method: in.Method, Metadata: in.Metadata, } resp, err := a.appChannel.InvokeMethod(&req) if err != nil { return nil, err } return &daprinternal_pb.InvokeResponse{ Data: &any.Any{Value: resp.Data}, Metadata: resp.Metadata, }, nil } // CallActor invokes a virtual actor func (a *api) CallActor(ctx context.Context, in *daprinternal_pb.CallActorEnvelope) (*daprinternal_pb.InvokeResponse, error) { req := actors.CallRequest{ ActorType: in.ActorType, ActorID: in.ActorID, Data: in.Data.Value, Method: in.Method, Metadata: in.Metadata, } resp, err := a.actor.Call(&req) if err != nil { return nil, err } return &daprinternal_pb.InvokeResponse{ Data: &any.Any{Value: resp.Data}, Metadata: map[string]string{}, }, nil } // UpdateComponent is fired by the Dapr control plane when a component state changes func (a *api) UpdateComponent(ctx context.Context, in *daprinternal_pb.Component) (*empty.Empty, error) { c := components_v1alpha1.Component{ ObjectMeta: meta_v1.ObjectMeta{ Name: in.Metadata.Name, }, Auth: components_v1alpha1.Auth{ SecretStore: in.Auth.SecretStore, }, } for _, m := range in.Spec.Metadata { c.Spec.Metadata = append(c.Spec.Metadata, components_v1alpha1.MetadataItem{ Name: m.Name, Value: m.Value, SecretKeyRef: components_v1alpha1.SecretKeyRef{ Key: m.SecretKeyRef.Key, Name: m.SecretKeyRef.Name, }, }) } a.componentsHandler.OnComponentUpdated(c) return &empty.Empty{}, nil } func (a *api) PublishEvent(ctx context.Context, in *dapr_pb.PublishEventEnvelope) (*empty.Empty, error) { if a.pubSub == nil { return &empty.Empty{}, errors.New("ERR_PUBSUB_NOT_FOUND") } topic := in.Topic body := []byte{} if in.Data != nil { body = in.Data.Value } envelope := pubsub.NewCloudEventsEnvelope(uuid.New().String(), a.id, pubsub.DefaultCloudEventType, body) b, err := jsoniter.ConfigFastest.Marshal(envelope) if err != nil { return &empty.Empty{}, fmt.Errorf("ERR_PUBSUB_CLOUD_EVENTS_SER: %s", err) } req := pubsub.PublishRequest{ Topic: topic, Data: b, } err = a.pubSub.Publish(&req) if err != nil { return &empty.Empty{}, fmt.Errorf("ERR_PUBSUB_PUBLISH_MESSAGE: %s", err) } return &empty.Empty{}, nil } func (a *api) InvokeService(ctx context.Context, in *dapr_pb.InvokeServiceEnvelope) (*dapr_pb.InvokeServiceResponseEnvelope, error) { req := messaging.DirectMessageRequest{ Data: in.Data.Value, Method: in.Method, Metadata: in.Metadata, Target: in.Id, } resp, err := a.directMessaging.Invoke(&req) if err != nil { return nil, err } return &dapr_pb.InvokeServiceResponseEnvelope{ Data: &any.Any{Value: resp.Data}, Metadata: resp.Metadata, }, nil } func (a *api) InvokeBinding(ctx context.Context, in *dapr_pb.InvokeBindingEnvelope) (*empty.Empty, error) { req := &bindings.WriteRequest{ Metadata: in.Metadata, } if in.Data != nil { req.Data = in.Data.Value } err := a.sendToOutputBindingFn(in.Name, req) if err != nil { return &empty.Empty{}, fmt.Errorf("ERR_INVOKE_OUTPUT_BINDING: %s", err) } return &empty.Empty{}, nil } func (a *api) GetState(ctx context.Context, in *dapr_pb.GetStateEnvelope) (*dapr_pb.GetStateResponseEnvelope, error) { if a.stateStores == nil || len(a.stateStores) == 0 { return nil, errors.New("ERR_STATE_STORE_NOT_CONFIGURED") } storeName := in.StoreName if a.stateStores[storeName] == nil { return nil, errors.New("ERR_STATE_STORE_NOT_FOUND") } req := state.GetRequest{ Key: a.getModifiedStateKey(in.Key), Options: state.GetStateOption{ Consistency: in.Consistency, }, } getResponse, err := a.stateStores[storeName].Get(&req) if err != nil { return nil, fmt.Errorf("ERR_STATE_GET: %s", err) } response := &dapr_pb.GetStateResponseEnvelope{} if getResponse != nil { response.Etag = getResponse.ETag response.Data = &any.Any{Value: getResponse.Data} } return response, nil } func (a *api) SaveState(ctx context.Context, in *dapr_pb.SaveStateEnvelope) (*empty.Empty, error) { if a.stateStores == nil || len(a.stateStores) == 0 { return &empty.Empty{}, errors.New("ERR_STATE_STORE_NOT_CONFIGURED") } storeName := in.StoreName if a.stateStores[storeName] == nil { return &empty.Empty{}, errors.New("ERR_STATE_STORE_NOT_FOUND") } reqs := []state.SetRequest{} for _, s := range in.Requests { req := state.SetRequest{ Key: a.getModifiedStateKey(s.Key), Metadata: s.Metadata, Value: s.Value.Value, } if s.Options != nil { req.Options = state.SetStateOption{ Consistency: s.Options.Consistency, Concurrency: s.Options.Concurrency, } if s.Options.RetryPolicy != nil { req.Options.RetryPolicy = state.RetryPolicy{ Threshold: int(s.Options.RetryPolicy.Threshold), Pattern: s.Options.RetryPolicy.Pattern, } if s.Options.RetryPolicy.Interval != nil { dur, err := duration(s.Options.RetryPolicy.Interval) if err == nil { req.Options.RetryPolicy.Interval = dur } } } } reqs = append(reqs, req) } err := a.stateStores[storeName].BulkSet(reqs) if err != nil { return &empty.Empty{}, fmt.Errorf("ERR_STATE_SAVE: %s", err) } return &empty.Empty{}, nil } func (a *api) DeleteState(ctx context.Context, in *dapr_pb.DeleteStateEnvelope) (*empty.Empty, error) { if a.stateStores == nil || len(a.stateStores) == 0 { return &empty.Empty{}, errors.New("ERR_STATE_STORE_NOT_CONFIGURED") } storeName := in.StoreName if a.stateStores[storeName] == nil { return &empty.Empty{}, errors.New("ERR_STATE_STORE_NOT_FOUND") } req := state.DeleteRequest{ Key: a.getModifiedStateKey(in.Key), ETag: in.Etag, } if in.Options != nil { req.Options = state.DeleteStateOption{ Concurrency: in.Options.Concurrency, Consistency: in.Options.Consistency, } if in.Options.RetryPolicy != nil { retryPolicy := state.RetryPolicy{ Threshold: int(in.Options.RetryPolicy.Threshold), Pattern: in.Options.RetryPolicy.Pattern, } if in.Options.RetryPolicy.Interval != nil { dur, err := duration(in.Options.RetryPolicy.Interval) if err == nil { retryPolicy.Interval = dur } } req.Options.RetryPolicy = retryPolicy } } err := a.stateStores[storeName].Delete(&req) if err != nil { return &empty.Empty{}, fmt.Errorf("ERR_STATE_DELETE: failed deleting state with key %s: %s", in.Key, err) } return &empty.Empty{}, nil } func (a *api)
getModifiedStateKey
identifier_name
api.go
4 * 60 * 60) minSeconds = -maxSeconds daprSeparator = "||" ) // API is the gRPC interface for the Dapr gRPC API. It implements both the internal and external proto definitions. type API interface { CallActor(ctx context.Context, in *daprinternal_pb.CallActorEnvelope) (*daprinternal_pb.InvokeResponse, error) CallLocal(ctx context.Context, in *daprinternal_pb.LocalCallEnvelope) (*daprinternal_pb.InvokeResponse, error) UpdateComponent(ctx context.Context, in *daprinternal_pb.Component) (*empty.Empty, error) PublishEvent(ctx context.Context, in *dapr_pb.PublishEventEnvelope) (*empty.Empty, error) InvokeService(ctx context.Context, in *dapr_pb.InvokeServiceEnvelope) (*dapr_pb.InvokeServiceResponseEnvelope, error) InvokeBinding(ctx context.Context, in *dapr_pb.InvokeBindingEnvelope) (*empty.Empty, error) GetState(ctx context.Context, in *dapr_pb.GetStateEnvelope) (*dapr_pb.GetStateResponseEnvelope, error) SaveState(ctx context.Context, in *dapr_pb.SaveStateEnvelope) (*empty.Empty, error) DeleteState(ctx context.Context, in *dapr_pb.DeleteStateEnvelope) (*empty.Empty, error) } type api struct { actor actors.Actors directMessaging messaging.DirectMessaging componentsHandler components.ComponentHandler appChannel channel.AppChannel stateStores map[string]state.Store pubSub pubsub.PubSub id string sendToOutputBindingFn func(name string, req *bindings.WriteRequest) error } // NewAPI returns a new gRPC API func NewAPI(daprID string, appChannel channel.AppChannel, stateStores map[string]state.Store, pubSub pubsub.PubSub, directMessaging messaging.DirectMessaging, actor actors.Actors, sendToOutputBindingFn func(name string, req *bindings.WriteRequest) error, componentHandler components.ComponentHandler) API { return &api{ directMessaging: directMessaging, componentsHandler: componentHandler, actor: actor, id: daprID, appChannel: appChannel, pubSub: pubSub, stateStores: stateStores, sendToOutputBindingFn: sendToOutputBindingFn, } } // CallLocal is used for internal dapr to dapr calls. It is invoked by another Dapr instance with a request to the local app. func (a *api) CallLocal(ctx context.Context, in *daprinternal_pb.LocalCallEnvelope) (*daprinternal_pb.InvokeResponse, error) { if a.appChannel == nil { return nil, errors.New("app channel is not initialized") } req := channel.InvokeRequest{ Payload: in.Data.Value, Method: in.Method, Metadata: in.Metadata, } resp, err := a.appChannel.InvokeMethod(&req) if err != nil { return nil, err } return &daprinternal_pb.InvokeResponse{ Data: &any.Any{Value: resp.Data}, Metadata: resp.Metadata, }, nil } // CallActor invokes a virtual actor func (a *api) CallActor(ctx context.Context, in *daprinternal_pb.CallActorEnvelope) (*daprinternal_pb.InvokeResponse, error) { req := actors.CallRequest{ ActorType: in.ActorType, ActorID: in.ActorID, Data: in.Data.Value, Method: in.Method, Metadata: in.Metadata, } resp, err := a.actor.Call(&req) if err != nil { return nil, err } return &daprinternal_pb.InvokeResponse{ Data: &any.Any{Value: resp.Data}, Metadata: map[string]string{}, }, nil } // UpdateComponent is fired by the Dapr control plane when a component state changes func (a *api) UpdateComponent(ctx context.Context, in *daprinternal_pb.Component) (*empty.Empty, error) { c := components_v1alpha1.Component{ ObjectMeta: meta_v1.ObjectMeta{ Name: in.Metadata.Name, }, Auth: components_v1alpha1.Auth{ SecretStore: in.Auth.SecretStore, }, } for _, m := range in.Spec.Metadata { c.Spec.Metadata = append(c.Spec.Metadata, components_v1alpha1.MetadataItem{ Name: m.Name, Value: m.Value, SecretKeyRef: components_v1alpha1.SecretKeyRef{ Key: m.SecretKeyRef.Key, Name: m.SecretKeyRef.Name, }, }) } a.componentsHandler.OnComponentUpdated(c) return &empty.Empty{}, nil } func (a *api) PublishEvent(ctx context.Context, in *dapr_pb.PublishEventEnvelope) (*empty.Empty, error) { if a.pubSub == nil { return &empty.Empty{}, errors.New("ERR_PUBSUB_NOT_FOUND") } topic := in.Topic body := []byte{} if in.Data != nil { body = in.Data.Value } envelope := pubsub.NewCloudEventsEnvelope(uuid.New().String(), a.id, pubsub.DefaultCloudEventType, body) b, err := jsoniter.ConfigFastest.Marshal(envelope) if err != nil { return &empty.Empty{}, fmt.Errorf("ERR_PUBSUB_CLOUD_EVENTS_SER: %s", err) } req := pubsub.PublishRequest{ Topic: topic, Data: b, } err = a.pubSub.Publish(&req) if err != nil { return &empty.Empty{}, fmt.Errorf("ERR_PUBSUB_PUBLISH_MESSAGE: %s", err) } return &empty.Empty{}, nil } func (a *api) InvokeService(ctx context.Context, in *dapr_pb.InvokeServiceEnvelope) (*dapr_pb.InvokeServiceResponseEnvelope, error) { req := messaging.DirectMessageRequest{ Data: in.Data.Value, Method: in.Method, Metadata: in.Metadata, Target: in.Id, } resp, err := a.directMessaging.Invoke(&req) if err != nil { return nil, err } return &dapr_pb.InvokeServiceResponseEnvelope{ Data: &any.Any{Value: resp.Data}, Metadata: resp.Metadata, }, nil } func (a *api) InvokeBinding(ctx context.Context, in *dapr_pb.InvokeBindingEnvelope) (*empty.Empty, error) { req := &bindings.WriteRequest{ Metadata: in.Metadata, } if in.Data != nil { req.Data = in.Data.Value } err := a.sendToOutputBindingFn(in.Name, req) if err != nil { return &empty.Empty{}, fmt.Errorf("ERR_INVOKE_OUTPUT_BINDING: %s", err) } return &empty.Empty{}, nil } func (a *api) GetState(ctx context.Context, in *dapr_pb.GetStateEnvelope) (*dapr_pb.GetStateResponseEnvelope, error) { if a.stateStores == nil || len(a.stateStores) == 0 { return nil, errors.New("ERR_STATE_STORE_NOT_CONFIGURED") } storeName := in.StoreName if a.stateStores[storeName] == nil { return nil, errors.New("ERR_STATE_STORE_NOT_FOUND") } req := state.GetRequest{ Key: a.getModifiedStateKey(in.Key), Options: state.GetStateOption{ Consistency: in.Consistency, }, } getResponse, err := a.stateStores[storeName].Get(&req) if err != nil { return nil, fmt.Errorf("ERR_STATE_GET: %s", err) } response := &dapr_pb.GetStateResponseEnvelope{} if getResponse != nil { response.Etag = getResponse.ETag response.Data = &any.Any{Value: getResponse.Data} } return response, nil } func (a *api) SaveState(ctx context.Context, in *dapr_pb.SaveStateEnvelope) (*empty.Empty, error) { if a.stateStores == nil || len(a.stateStores) == 0 { return &empty.Empty{}, errors.New("ERR_STATE_STORE_NOT_CONFIGURED") } storeName := in.StoreName if a.stateStores[storeName] == nil { return &empty.Empty{}, errors.New("ERR_STATE_STORE_NOT_FOUND") }
for _, s := range in.Requests { req := state.SetRequest{ Key: a.getModifiedStateKey(s.Key), Metadata: s.Metadata, Value: s.Value.Value, } if s.Options != nil { req.Options = state.SetStateOption{ Consistency: s.Options.Consistency, Concurrency: s.Options.Concurrency, } if s.Options.RetryPolicy != nil { req.Options.RetryPolicy = state.RetryPolicy{ Threshold: int(s.Options.RetryPolicy.Threshold), Pattern: s.Options.RetryPolicy.Pattern, } if s.Options.RetryPolicy.Interval != nil { dur, err := duration(s.Options.RetryPolicy.Interval) if err == nil { req.Options.RetryPolicy.Interval = dur } } } } reqs = append(reqs, req) } err := a.stateStores[storeName].BulkSet(reqs) if err != nil { return &empty.Empty{}, fmt.Errorf("ERR_STATE_SAVE: %s", err) } return &empty.Empty{}, nil } func
reqs := []state.SetRequest{}
random_line_split
api.go
4 * 60 * 60) minSeconds = -maxSeconds daprSeparator = "||" ) // API is the gRPC interface for the Dapr gRPC API. It implements both the internal and external proto definitions. type API interface { CallActor(ctx context.Context, in *daprinternal_pb.CallActorEnvelope) (*daprinternal_pb.InvokeResponse, error) CallLocal(ctx context.Context, in *daprinternal_pb.LocalCallEnvelope) (*daprinternal_pb.InvokeResponse, error) UpdateComponent(ctx context.Context, in *daprinternal_pb.Component) (*empty.Empty, error) PublishEvent(ctx context.Context, in *dapr_pb.PublishEventEnvelope) (*empty.Empty, error) InvokeService(ctx context.Context, in *dapr_pb.InvokeServiceEnvelope) (*dapr_pb.InvokeServiceResponseEnvelope, error) InvokeBinding(ctx context.Context, in *dapr_pb.InvokeBindingEnvelope) (*empty.Empty, error) GetState(ctx context.Context, in *dapr_pb.GetStateEnvelope) (*dapr_pb.GetStateResponseEnvelope, error) SaveState(ctx context.Context, in *dapr_pb.SaveStateEnvelope) (*empty.Empty, error) DeleteState(ctx context.Context, in *dapr_pb.DeleteStateEnvelope) (*empty.Empty, error) } type api struct { actor actors.Actors directMessaging messaging.DirectMessaging componentsHandler components.ComponentHandler appChannel channel.AppChannel stateStores map[string]state.Store pubSub pubsub.PubSub id string sendToOutputBindingFn func(name string, req *bindings.WriteRequest) error } // NewAPI returns a new gRPC API func NewAPI(daprID string, appChannel channel.AppChannel, stateStores map[string]state.Store, pubSub pubsub.PubSub, directMessaging messaging.DirectMessaging, actor actors.Actors, sendToOutputBindingFn func(name string, req *bindings.WriteRequest) error, componentHandler components.ComponentHandler) API { return &api{ directMessaging: directMessaging, componentsHandler: componentHandler, actor: actor, id: daprID, appChannel: appChannel, pubSub: pubSub, stateStores: stateStores, sendToOutputBindingFn: sendToOutputBindingFn, } } // CallLocal is used for internal dapr to dapr calls. It is invoked by another Dapr instance with a request to the local app. func (a *api) CallLocal(ctx context.Context, in *daprinternal_pb.LocalCallEnvelope) (*daprinternal_pb.InvokeResponse, error) { if a.appChannel == nil { return nil, errors.New("app channel is not initialized") } req := channel.InvokeRequest{ Payload: in.Data.Value, Method: in.Method, Metadata: in.Metadata, } resp, err := a.appChannel.InvokeMethod(&req) if err != nil { return nil, err } return &daprinternal_pb.InvokeResponse{ Data: &any.Any{Value: resp.Data}, Metadata: resp.Metadata, }, nil } // CallActor invokes a virtual actor func (a *api) CallActor(ctx context.Context, in *daprinternal_pb.CallActorEnvelope) (*daprinternal_pb.InvokeResponse, error) { req := actors.CallRequest{ ActorType: in.ActorType, ActorID: in.ActorID, Data: in.Data.Value, Method: in.Method, Metadata: in.Metadata, } resp, err := a.actor.Call(&req) if err != nil { return nil, err } return &daprinternal_pb.InvokeResponse{ Data: &any.Any{Value: resp.Data}, Metadata: map[string]string{}, }, nil } // UpdateComponent is fired by the Dapr control plane when a component state changes func (a *api) UpdateComponent(ctx context.Context, in *daprinternal_pb.Component) (*empty.Empty, error) { c := components_v1alpha1.Component{ ObjectMeta: meta_v1.ObjectMeta{ Name: in.Metadata.Name, }, Auth: components_v1alpha1.Auth{ SecretStore: in.Auth.SecretStore, }, } for _, m := range in.Spec.Metadata { c.Spec.Metadata = append(c.Spec.Metadata, components_v1alpha1.MetadataItem{ Name: m.Name, Value: m.Value, SecretKeyRef: components_v1alpha1.SecretKeyRef{ Key: m.SecretKeyRef.Key, Name: m.SecretKeyRef.Name, }, }) } a.componentsHandler.OnComponentUpdated(c) return &empty.Empty{}, nil } func (a *api) PublishEvent(ctx context.Context, in *dapr_pb.PublishEventEnvelope) (*empty.Empty, error) { if a.pubSub == nil { return &empty.Empty{}, errors.New("ERR_PUBSUB_NOT_FOUND") } topic := in.Topic body := []byte{} if in.Data != nil { body = in.Data.Value } envelope := pubsub.NewCloudEventsEnvelope(uuid.New().String(), a.id, pubsub.DefaultCloudEventType, body) b, err := jsoniter.ConfigFastest.Marshal(envelope) if err != nil { return &empty.Empty{}, fmt.Errorf("ERR_PUBSUB_CLOUD_EVENTS_SER: %s", err) } req := pubsub.PublishRequest{ Topic: topic, Data: b, } err = a.pubSub.Publish(&req) if err != nil { return &empty.Empty{}, fmt.Errorf("ERR_PUBSUB_PUBLISH_MESSAGE: %s", err) } return &empty.Empty{}, nil } func (a *api) InvokeService(ctx context.Context, in *dapr_pb.InvokeServiceEnvelope) (*dapr_pb.InvokeServiceResponseEnvelope, error) { req := messaging.DirectMessageRequest{ Data: in.Data.Value, Method: in.Method, Metadata: in.Metadata, Target: in.Id, } resp, err := a.directMessaging.Invoke(&req) if err != nil { return nil, err } return &dapr_pb.InvokeServiceResponseEnvelope{ Data: &any.Any{Value: resp.Data}, Metadata: resp.Metadata, }, nil } func (a *api) InvokeBinding(ctx context.Context, in *dapr_pb.InvokeBindingEnvelope) (*empty.Empty, error) { req := &bindings.WriteRequest{ Metadata: in.Metadata, } if in.Data != nil { req.Data = in.Data.Value } err := a.sendToOutputBindingFn(in.Name, req) if err != nil { return &empty.Empty{}, fmt.Errorf("ERR_INVOKE_OUTPUT_BINDING: %s", err) } return &empty.Empty{}, nil } func (a *api) GetState(ctx context.Context, in *dapr_pb.GetStateEnvelope) (*dapr_pb.GetStateResponseEnvelope, error) { if a.stateStores == nil || len(a.stateStores) == 0 { return nil, errors.New("ERR_STATE_STORE_NOT_CONFIGURED") } storeName := in.StoreName if a.stateStores[storeName] == nil { return nil, errors.New("ERR_STATE_STORE_NOT_FOUND") } req := state.GetRequest{ Key: a.getModifiedStateKey(in.Key), Options: state.GetStateOption{ Consistency: in.Consistency, }, } getResponse, err := a.stateStores[storeName].Get(&req) if err != nil { return nil, fmt.Errorf("ERR_STATE_GET: %s", err) } response := &dapr_pb.GetStateResponseEnvelope{} if getResponse != nil { response.Etag = getResponse.ETag response.Data = &any.Any{Value: getResponse.Data} } return response, nil } func (a *api) SaveState(ctx context.Context, in *dapr_pb.SaveStateEnvelope) (*empty.Empty, error)
Consistency: s.Options.Consistency, Concurrency: s.Options.Concurrency, } if s.Options.RetryPolicy != nil { req.Options.RetryPolicy = state.RetryPolicy{ Threshold: int(s.Options.RetryPolicy.Threshold), Pattern: s.Options.RetryPolicy.Pattern, } if s.Options.RetryPolicy.Interval != nil { dur, err := duration(s.Options.RetryPolicy.Interval) if err == nil { req.Options.RetryPolicy.Interval = dur } } } } reqs = append(reqs, req) } err := a.stateStores[storeName].BulkSet(reqs) if err != nil { return &empty.Empty{}, fmt.Errorf("ERR_STATE_SAVE: %s", err) } return &empty.Empty{}, nil } func
{ if a.stateStores == nil || len(a.stateStores) == 0 { return &empty.Empty{}, errors.New("ERR_STATE_STORE_NOT_CONFIGURED") } storeName := in.StoreName if a.stateStores[storeName] == nil { return &empty.Empty{}, errors.New("ERR_STATE_STORE_NOT_FOUND") } reqs := []state.SetRequest{} for _, s := range in.Requests { req := state.SetRequest{ Key: a.getModifiedStateKey(s.Key), Metadata: s.Metadata, Value: s.Value.Value, } if s.Options != nil { req.Options = state.SetStateOption{
identifier_body
relay.py
_PUMP, GD.SYSTEM_UFH_PUMP) : return # Get the I2C parameters from our system control data. address = system.systemControl [systemRelay].GetAddress () mask = system.systemControl [systemRelay].GetBitMask () # Read existing relay status for all relay bits at this address. relayStatus = I2CPort.read_byte (address) # Do we need to set this bit high or low? if setHigh == True : # We need to turn relay on so invert bit mask so bit we want is now zero, for active low, and all others will be high. # AND it with existing bits to clear the bit we need to set low output for relay. mask ^= 0xff relayStatus &= mask else : # Need to turn relay off so we can just OR the bit with the existing bits to set high output for relay. relayStatus |= mask # Write new relay staus back for all the relay bits at this address. I2CPort.write_byte (address, relayStatus) ################################################################################ ## ## Function: UpdateSystemOutputs (I2CPort) ## ## Parameters: ## ## Returns: ## ## Globals modified: ## ## Comments: Scan through the system output config bits and update a relay that needs to be changed. ## ################################################################################ def UpdateSystemOutputs (I2CPort) : # Scan through the outputs until we find one that needs updating. for systemOutput in (GD.SYSTEM_OUTPUT_GROUP) : # Only do I2C transfer if relay needs updating. if system.systemControl [systemOutput].CheckIfBitChanged () == True : # Set relay as required by system status setHigh = system.systemControl [systemOutput].CheckIfBitHigh () ActivateSystemRelay (I2CPort, systemOutput, setHigh) # Update status for bit now we have done relay update. system.systemControl [systemOutput].UpdateBitChangedStatus () # Now that we have updated a relay we will leave. This is so that we only update 1 relay every time we are called, # which is once a second. This will minmise power surges on the system as devices will be powered gradually rather # than all at once. break for systemConfig in (GD.TANK_2_MANUAL_OVERRIDE_GROUP) : system.systemControl [systemConfig].UpdateBitChangedStatus () ################################################################################ ## ## Function: UpdatePulsedOutputLines () ## ## Parameters: ## ## Returns: ## ## Globals modified: ## ## Comments: Scan through and update all the output line pulse timers. If any are finished set the output line low. ## ################################################################################ def UpdatePulsedOutputLines (I2CPort) : for systemOutput in GD.SYSTEM_PULSED_OUTPUTS_GROUP : if system.systemControl [systemOutput].CheckIfBitTimerFinished () == True : ActivateSystemRelay (I2CPort, systemOutput, False) print 'SET IT LOW' ################################################################################ ## ## Function: PulseLatchingRelay (I2CPort, register, relayBit) ## ## Parameters: I2CPort - I2C smbus object ## register - the I2C address of the relay controller ## relayBit - the binary bit of the bit to be pulsed ## ## Returns: ## ## Globals modified: ## ## Comments: Pulses the required relay specified by relayBit. We are controlling latching relays in the valve relay matrix so ## we have to give the required activate time. ## ################################################################################ def PulseLatchingRelay (I2CPort, register, relayBit) : # Read existing relay status.
################################################################################ ## ## Function: ActivateHeatingZoneRelay (I2CPort, relayZone) ## ## Parameters: I2CPort - I2C smbus object ## relayZone - integer - the zone to check if activation required. ## ## Returns: ## ## Globals modified: ## ## Comments: ## ################################################################################ def ActivateHeatingZoneRelay (I2CPort, relayZone) : # Find out if status of this zone has changed, if it now needs to be on or needs a cleardown. statusChanged = zones.zoneData[relayZone].CheckIfZoneStatusChanged () == True statusOn = zones.zoneData[relayZone].CheckIfZoneOnRequested () == True clearDown = zones.zoneData[relayZone].CheckIfTimeForCleardown () == True # If the status has changed we need to update our current status. if statusChanged : zones.zoneData[relayZone].UpdateCurrentZoneStatus() # Has the status changed or is it time for cleardown on this zone? if statusChanged or clearDown : print 'STATUS CHANGED' # Select the correct I2C status register for UFH or RAD relays. register = GD.I2C_ADDRESS_0X38 if relayZone >= 14 else GD.I2C_ADDRESS_0X39 # Read the status register to get the current state of the pump bit. Mask off all except pump bit. # Bits are active low - so a 0 = on. relays = I2CPort.read_byte (register) relays &= 0x80 # Invert the pump bit as these are active low outputs and we are going to OR in bits. relays ^= 0x80 # OR in the zone required (bits 0-3). Adjust to get UFH zone in range 0-15 from 14-29. relays |= relayZone if relayZone >= 14 : relays -= 14 # Invert bits to make active low outputs. relays ^= 0xff # Activate the zone select relays in sequence so only 1 relay at a time is powered up to minimise current surge. for bitSelect in (0x07, 0x03, 0x01, 0x00) : I2CPort.write_byte (register, relays | bitSelect) time.sleep (0.1) # If we are in cleardown we need to turn off the power relay first. if clearDown and not statusChanged : # Set the mode bit to select the power relay (active low bit4). relays &= ~0x10 # Send to relay register, wait for relays to stabilise. I2CPort.write_byte (register, relays) print 'select mode power ', hex(relays^0xff) time.sleep (0.1) # Now pulse OFF relay (active low bit6) to ensure power is removed from the valve. PulseLatchingRelay (I2CPort, register, 0x40) # Clear the mode bit to select the open relay (active low bit4), Wait for relay to stabilise. relays |= 0x10 I2CPort.write_byte (register, relays) print 'select open ', hex(relays^0xff) time.sleep (0.1) # We get here if there has been a status change or it is a cleardown. If it is a status change and the new status = ON # then we will turn the relay on to open the valve when power is turned on. If it is a status change and the new # status = OFF or there is no status change (must be a cleardown) we will turn the relay off. This will either close the # valve if we apply power for a status change or simply turn the relay off for a cleardown. # Do we need to open the valve? if statusChanged and statusOn : # Valve needs to open so pulse the ON relay (active low bit5). PulseLatchingRelay (I2CPort, register, 0x20) # Set the cleardown timer for the period required before we can clear the valve down. ADJUST THIS LATER zones.zoneData[relayZone].SetCleardownTimer (30) else : # Valve needs to close so pulse OFF relay (active low bit6). PulseLatchingRelay (I2CPort, register, 0x40) # Set the cleardown timer for the period required before we can clear the valve down. ADJUST THIS LATER zones.zoneData[relayZone].SetCleardownTimer (65) # If we are here because of a status change we need to activate the power relay on. For a cleardown we do not need # to do anything as a cleardown simply turns off the power and open relays. if
relayStatus = I2CPort.read_byte (register) # Set the relay to pulse (active low pulse). relayStatus &= ~relayBit # Pulse it low. I2CPort.write_byte (register, relayStatus) print 'pulse on ', hex(relayStatus^0xff) # Give it some time to activate. time.sleep (0.1) # Now set up to clear the relay pulse (set it back high). relayStatus |= relayBit # Restore the level high. I2CPort.write_byte (register, relayStatus) print 'pulse off ', hex(relayStatus^0xff) # Give it time to activate. time.sleep (0.1)
identifier_body
relay.py
_PUMP, GD.SYSTEM_UFH_PUMP) : return # Get the I2C parameters from our system control data. address = system.systemControl [systemRelay].GetAddress () mask = system.systemControl [systemRelay].GetBitMask () # Read existing relay status for all relay bits at this address. relayStatus = I2CPort.read_byte (address) # Do we need to set this bit high or low? if setHigh == True : # We need to turn relay on so invert bit mask so bit we want is now zero, for active low, and all others will be high. # AND it with existing bits to clear the bit we need to set low output for relay. mask ^= 0xff relayStatus &= mask else : # Need to turn relay off so we can just OR the bit with the existing bits to set high output for relay. relayStatus |= mask # Write new relay staus back for all the relay bits at this address. I2CPort.write_byte (address, relayStatus) ################################################################################ ## ## Function: UpdateSystemOutputs (I2CPort) ## ## Parameters: ## ## Returns: ## ## Globals modified: ## ## Comments: Scan through the system output config bits and update a relay that needs to be changed. ## ################################################################################ def UpdateSystemOutputs (I2CPort) : # Scan through the outputs until we find one that needs updating. for systemOutput in (GD.SYSTEM_OUTPUT_GROUP) : # Only do I2C transfer if relay needs updating. if system.systemControl [systemOutput].CheckIfBitChanged () == True : # Set relay as required by system status setHigh = system.systemControl [systemOutput].CheckIfBitHigh () ActivateSystemRelay (I2CPort, systemOutput, setHigh) # Update status for bit now we have done relay update. system.systemControl [systemOutput].UpdateBitChangedStatus () # Now that we have updated a relay we will leave. This is so that we only update 1 relay every time we are called, # which is once a second. This will minmise power surges on the system as devices will be powered gradually rather # than all at once. break for systemConfig in (GD.TANK_2_MANUAL_OVERRIDE_GROUP) : system.systemControl [systemConfig].UpdateBitChangedStatus () ################################################################################ ## ## Function: UpdatePulsedOutputLines () ## ## Parameters: ## ## Returns: ## ## Globals modified: ## ## Comments: Scan through and update all the output line pulse timers. If any are finished set the output line low. ## ################################################################################ def
(I2CPort) : for systemOutput in GD.SYSTEM_PULSED_OUTPUTS_GROUP : if system.systemControl [systemOutput].CheckIfBitTimerFinished () == True : ActivateSystemRelay (I2CPort, systemOutput, False) print 'SET IT LOW' ################################################################################ ## ## Function: PulseLatchingRelay (I2CPort, register, relayBit) ## ## Parameters: I2CPort - I2C smbus object ## register - the I2C address of the relay controller ## relayBit - the binary bit of the bit to be pulsed ## ## Returns: ## ## Globals modified: ## ## Comments: Pulses the required relay specified by relayBit. We are controlling latching relays in the valve relay matrix so ## we have to give the required activate time. ## ################################################################################ def PulseLatchingRelay (I2CPort, register, relayBit) : # Read existing relay status. relayStatus = I2CPort.read_byte (register) # Set the relay to pulse (active low pulse). relayStatus &= ~relayBit # Pulse it low. I2CPort.write_byte (register, relayStatus) print 'pulse on ', hex(relayStatus^0xff) # Give it some time to activate. time.sleep (0.1) # Now set up to clear the relay pulse (set it back high). relayStatus |= relayBit # Restore the level high. I2CPort.write_byte (register, relayStatus) print 'pulse off ', hex(relayStatus^0xff) # Give it time to activate. time.sleep (0.1) ################################################################################ ## ## Function: ActivateHeatingZoneRelay (I2CPort, relayZone) ## ## Parameters: I2CPort - I2C smbus object ## relayZone - integer - the zone to check if activation required. ## ## Returns: ## ## Globals modified: ## ## Comments: ## ################################################################################ def ActivateHeatingZoneRelay (I2CPort, relayZone) : # Find out if status of this zone has changed, if it now needs to be on or needs a cleardown. statusChanged = zones.zoneData[relayZone].CheckIfZoneStatusChanged () == True statusOn = zones.zoneData[relayZone].CheckIfZoneOnRequested () == True clearDown = zones.zoneData[relayZone].CheckIfTimeForCleardown () == True # If the status has changed we need to update our current status. if statusChanged : zones.zoneData[relayZone].UpdateCurrentZoneStatus() # Has the status changed or is it time for cleardown on this zone? if statusChanged or clearDown : print 'STATUS CHANGED' # Select the correct I2C status register for UFH or RAD relays. register = GD.I2C_ADDRESS_0X38 if relayZone >= 14 else GD.I2C_ADDRESS_0X39 # Read the status register to get the current state of the pump bit. Mask off all except pump bit. # Bits are active low - so a 0 = on. relays = I2CPort.read_byte (register) relays &= 0x80 # Invert the pump bit as these are active low outputs and we are going to OR in bits. relays ^= 0x80 # OR in the zone required (bits 0-3). Adjust to get UFH zone in range 0-15 from 14-29. relays |= relayZone if relayZone >= 14 : relays -= 14 # Invert bits to make active low outputs. relays ^= 0xff # Activate the zone select relays in sequence so only 1 relay at a time is powered up to minimise current surge. for bitSelect in (0x07, 0x03, 0x01, 0x00) : I2CPort.write_byte (register, relays | bitSelect) time.sleep (0.1) # If we are in cleardown we need to turn off the power relay first. if clearDown and not statusChanged : # Set the mode bit to select the power relay (active low bit4). relays &= ~0x10 # Send to relay register, wait for relays to stabilise. I2CPort.write_byte (register, relays) print 'select mode power ', hex(relays^0xff) time.sleep (0.1) # Now pulse OFF relay (active low bit6) to ensure power is removed from the valve. PulseLatchingRelay (I2CPort, register, 0x40) # Clear the mode bit to select the open relay (active low bit4), Wait for relay to stabilise. relays |= 0x10 I2CPort.write_byte (register, relays) print 'select open ', hex(relays^0xff) time.sleep (0.1) # We get here if there has been a status change or it is a cleardown. If it is a status change and the new status = ON # then we will turn the relay on to open the valve when power is turned on. If it is a status change and the new # status = OFF or there is no status change (must be a cleardown) we will turn the relay off. This will either close the # valve if we apply power for a status change or simply turn the relay off for a cleardown. # Do we need to open the valve? if statusChanged and statusOn : # Valve needs to open so pulse the ON relay (active low bit5). PulseLatchingRelay (I2CPort, register, 0x20) # Set the cleardown timer for the period required before we can clear the valve down. ADJUST THIS LATER zones.zoneData[relayZone].SetCleardownTimer (30) else : # Valve needs to close so pulse OFF relay (active low bit6). PulseLatchingRelay (I2CPort, register, 0x40) # Set the cleardown timer for the period required before we can clear the valve down. ADJUST THIS LATER zones.zoneData[relayZone].SetCleardownTimer (65) # If we are here because of a status change we need to activate the power relay on. For a cleardown we do not need # to do anything as a cleardown simply turns off the power and open relays. if
UpdatePulsedOutputLines
identifier_name
relay.py
_PUMP, GD.SYSTEM_UFH_PUMP) : return # Get the I2C parameters from our system control data. address = system.systemControl [systemRelay].GetAddress () mask = system.systemControl [systemRelay].GetBitMask () # Read existing relay status for all relay bits at this address. relayStatus = I2CPort.read_byte (address) # Do we need to set this bit high or low? if setHigh == True : # We need to turn relay on so invert bit mask so bit we want is now zero, for active low, and all others will be high. # AND it with existing bits to clear the bit we need to set low output for relay. mask ^= 0xff relayStatus &= mask else : # Need to turn relay off so we can just OR the bit with the existing bits to set high output for relay. relayStatus |= mask # Write new relay staus back for all the relay bits at this address. I2CPort.write_byte (address, relayStatus) ################################################################################ ## ## Function: UpdateSystemOutputs (I2CPort) ## ## Parameters: ## ## Returns: ## ## Globals modified: ## ## Comments: Scan through the system output config bits and update a relay that needs to be changed. ## ################################################################################ def UpdateSystemOutputs (I2CPort) : # Scan through the outputs until we find one that needs updating. for systemOutput in (GD.SYSTEM_OUTPUT_GROUP) : # Only do I2C transfer if relay needs updating. if system.systemControl [systemOutput].CheckIfBitChanged () == True : # Set relay as required by system status setHigh = system.systemControl [systemOutput].CheckIfBitHigh () ActivateSystemRelay (I2CPort, systemOutput, setHigh) # Update status for bit now we have done relay update. system.systemControl [systemOutput].UpdateBitChangedStatus () # Now that we have updated a relay we will leave. This is so that we only update 1 relay every time we are called, # which is once a second. This will minmise power surges on the system as devices will be powered gradually rather # than all at once. break for systemConfig in (GD.TANK_2_MANUAL_OVERRIDE_GROUP) : system.systemControl [systemConfig].UpdateBitChangedStatus () ################################################################################ ## ## Function: UpdatePulsedOutputLines () ## ## Parameters: ## ## Returns: ## ## Globals modified: ## ## Comments: Scan through and update all the output line pulse timers. If any are finished set the output line low. ## ################################################################################ def UpdatePulsedOutputLines (I2CPort) : for systemOutput in GD.SYSTEM_PULSED_OUTPUTS_GROUP : if system.systemControl [systemOutput].CheckIfBitTimerFinished () == True : ActivateSystemRelay (I2CPort, systemOutput, False) print 'SET IT LOW' ################################################################################ ## ## Function: PulseLatchingRelay (I2CPort, register, relayBit) ## ## Parameters: I2CPort - I2C smbus object ## register - the I2C address of the relay controller ## relayBit - the binary bit of the bit to be pulsed ## ## Returns: ## ## Globals modified: ## ## Comments: Pulses the required relay specified by relayBit. We are controlling latching relays in the valve relay matrix so ## we have to give the required activate time. ## ################################################################################ def PulseLatchingRelay (I2CPort, register, relayBit) : # Read existing relay status. relayStatus = I2CPort.read_byte (register) # Set the relay to pulse (active low pulse). relayStatus &= ~relayBit # Pulse it low. I2CPort.write_byte (register, relayStatus) print 'pulse on ', hex(relayStatus^0xff) # Give it some time to activate. time.sleep (0.1) # Now set up to clear the relay pulse (set it back high). relayStatus |= relayBit # Restore the level high. I2CPort.write_byte (register, relayStatus) print 'pulse off ', hex(relayStatus^0xff) # Give it time to activate. time.sleep (0.1) ################################################################################ ## ## Function: ActivateHeatingZoneRelay (I2CPort, relayZone) ## ## Parameters: I2CPort - I2C smbus object ## relayZone - integer - the zone to check if activation required. ## ## Returns: ## ## Globals modified: ## ## Comments: ## ################################################################################ def ActivateHeatingZoneRelay (I2CPort, relayZone) : # Find out if status of this zone has changed, if it now needs to be on or needs a cleardown. statusChanged = zones.zoneData[relayZone].CheckIfZoneStatusChanged () == True statusOn = zones.zoneData[relayZone].CheckIfZoneOnRequested () == True clearDown = zones.zoneData[relayZone].CheckIfTimeForCleardown () == True # If the status has changed we need to update our current status. if statusChanged :
# Has the status changed or is it time for cleardown on this zone? if statusChanged or clearDown : print 'STATUS CHANGED' # Select the correct I2C status register for UFH or RAD relays. register = GD.I2C_ADDRESS_0X38 if relayZone >= 14 else GD.I2C_ADDRESS_0X39 # Read the status register to get the current state of the pump bit. Mask off all except pump bit. # Bits are active low - so a 0 = on. relays = I2CPort.read_byte (register) relays &= 0x80 # Invert the pump bit as these are active low outputs and we are going to OR in bits. relays ^= 0x80 # OR in the zone required (bits 0-3). Adjust to get UFH zone in range 0-15 from 14-29. relays |= relayZone if relayZone >= 14 : relays -= 14 # Invert bits to make active low outputs. relays ^= 0xff # Activate the zone select relays in sequence so only 1 relay at a time is powered up to minimise current surge. for bitSelect in (0x07, 0x03, 0x01, 0x00) : I2CPort.write_byte (register, relays | bitSelect) time.sleep (0.1) # If we are in cleardown we need to turn off the power relay first. if clearDown and not statusChanged : # Set the mode bit to select the power relay (active low bit4). relays &= ~0x10 # Send to relay register, wait for relays to stabilise. I2CPort.write_byte (register, relays) print 'select mode power ', hex(relays^0xff) time.sleep (0.1) # Now pulse OFF relay (active low bit6) to ensure power is removed from the valve. PulseLatchingRelay (I2CPort, register, 0x40) # Clear the mode bit to select the open relay (active low bit4), Wait for relay to stabilise. relays |= 0x10 I2CPort.write_byte (register, relays) print 'select open ', hex(relays^0xff) time.sleep (0.1) # We get here if there has been a status change or it is a cleardown. If it is a status change and the new status = ON # then we will turn the relay on to open the valve when power is turned on. If it is a status change and the new # status = OFF or there is no status change (must be a cleardown) we will turn the relay off. This will either close the # valve if we apply power for a status change or simply turn the relay off for a cleardown. # Do we need to open the valve? if statusChanged and statusOn : # Valve needs to open so pulse the ON relay (active low bit5). PulseLatchingRelay (I2CPort, register, 0x20) # Set the cleardown timer for the period required before we can clear the valve down. ADJUST THIS LATER zones.zoneData[relayZone].SetCleardownTimer (30) else : # Valve needs to close so pulse OFF relay (active low bit6). PulseLatchingRelay (I2CPort, register, 0x40) # Set the cleardown timer for the period required before we can clear the valve down. ADJUST THIS LATER zones.zoneData[relayZone].SetCleardownTimer (65) # If we are here because of a status change we need to activate the power relay on. For a cleardown we do not need # to do anything as a cleardown simply turns off the power and open relays. if
zones.zoneData[relayZone].UpdateCurrentZoneStatus()
conditional_block
relay.py
# TEMP TO ALLOW WITHOUT SYSTEM HARDWARE ## if systemRelay not in (GD.SYSTEM_RAD_PUMP, GD.SYSTEM_UFH_PUMP) : return # Get the I2C parameters from our system control data. address = system.systemControl [systemRelay].GetAddress () mask = system.systemControl [systemRelay].GetBitMask () # Read existing relay status for all relay bits at this address. relayStatus = I2CPort.read_byte (address) # Do we need to set this bit high or low? if setHigh == True : # We need to turn relay on so invert bit mask so bit we want is now zero, for active low, and all others will be high. # AND it with existing bits to clear the bit we need to set low output for relay. mask ^= 0xff relayStatus &= mask else : # Need to turn relay off so we can just OR the bit with the existing bits to set high output for relay. relayStatus |= mask # Write new relay staus back for all the relay bits at this address. I2CPort.write_byte (address, relayStatus) ################################################################################ ## ## Function: UpdateSystemOutputs (I2CPort) ## ## Parameters: ## ## Returns: ## ## Globals modified: ## ## Comments: Scan through the system output config bits and update a relay that needs to be changed. ## ################################################################################ def UpdateSystemOutputs (I2CPort) : # Scan through the outputs until we find one that needs updating. for systemOutput in (GD.SYSTEM_OUTPUT_GROUP) : # Only do I2C transfer if relay needs updating. if system.systemControl [systemOutput].CheckIfBitChanged () == True : # Set relay as required by system status setHigh = system.systemControl [systemOutput].CheckIfBitHigh () ActivateSystemRelay (I2CPort, systemOutput, setHigh) # Update status for bit now we have done relay update. system.systemControl [systemOutput].UpdateBitChangedStatus () # Now that we have updated a relay we will leave. This is so that we only update 1 relay every time we are called, # which is once a second. This will minmise power surges on the system as devices will be powered gradually rather # than all at once. break for systemConfig in (GD.TANK_2_MANUAL_OVERRIDE_GROUP) : system.systemControl [systemConfig].UpdateBitChangedStatus () ################################################################################ ## ## Function: UpdatePulsedOutputLines () ## ## Parameters: ## ## Returns: ## ## Globals modified: ## ## Comments: Scan through and update all the output line pulse timers. If any are finished set the output line low. ## ################################################################################ def UpdatePulsedOutputLines (I2CPort) : for systemOutput in GD.SYSTEM_PULSED_OUTPUTS_GROUP : if system.systemControl [systemOutput].CheckIfBitTimerFinished () == True : ActivateSystemRelay (I2CPort, systemOutput, False) print 'SET IT LOW' ################################################################################ ## ## Function: PulseLatchingRelay (I2CPort, register, relayBit) ## ## Parameters: I2CPort - I2C smbus object ## register - the I2C address of the relay controller ## relayBit - the binary bit of the bit to be pulsed ## ## Returns: ## ## Globals modified: ## ## Comments: Pulses the required relay specified by relayBit. We are controlling latching relays in the valve relay matrix so ## we have to give the required activate time. ## ################################################################################ def PulseLatchingRelay (I2CPort, register, relayBit) : # Read existing relay status. relayStatus = I2CPort.read_byte (register) # Set the relay to pulse (active low pulse). relayStatus &= ~relayBit # Pulse it low. I2CPort.write_byte (register, relayStatus) print 'pulse on ', hex(relayStatus^0xff) # Give it some time to activate. time.sleep (0.1) # Now set up to clear the relay pulse (set it back high). relayStatus |= relayBit # Restore the level high. I2CPort.write_byte (register, relayStatus) print 'pulse off ', hex(relayStatus^0xff) # Give it time to activate. time.sleep (0.1) ################################################################################ ## ## Function: ActivateHeatingZoneRelay (I2CPort, relayZone) ## ## Parameters: I2CPort - I2C smbus object ## relayZone - integer - the zone to check if activation required. ## ## Returns: ## ## Globals modified: ## ## Comments: ## ################################################################################ def ActivateHeatingZoneRelay (I2CPort, relayZone) : # Find out if status of this zone has changed, if it now needs to be on or needs a cleardown. statusChanged = zones.zoneData[relayZone].CheckIfZoneStatusChanged () == True statusOn = zones.zoneData[relayZone].CheckIfZoneOnRequested () == True clearDown = zones.zoneData[relayZone].CheckIfTimeForCleardown () == True # If the status has changed we need to update our current status. if statusChanged : zones.zoneData[relayZone].UpdateCurrentZoneStatus() # Has the status changed or is it time for cleardown on this zone? if statusChanged or clearDown : print 'STATUS CHANGED' # Select the correct I2C status register for UFH or RAD relays. register = GD.I2C_ADDRESS_0X38 if relayZone >= 14 else GD.I2C_ADDRESS_0X39 # Read the status register to get the current state of the pump bit. Mask off all except pump bit. # Bits are active low - so a 0 = on. relays = I2CPort.read_byte (register) relays &= 0x80 # Invert the pump bit as these are active low outputs and we are going to OR in bits. relays ^= 0x80 # OR in the zone required (bits 0-3). Adjust to get UFH zone in range 0-15 from 14-29. relays |= relayZone if relayZone >= 14 : relays -= 14 # Invert bits to make active low outputs. relays ^= 0xff # Activate the zone select relays in sequence so only 1 relay at a time is powered up to minimise current surge. for bitSelect in (0x07, 0x03, 0x01, 0x00) : I2CPort.write_byte (register, relays | bitSelect) time.sleep (0.1) # If we are in cleardown we need to turn off the power relay first. if clearDown and not statusChanged : # Set the mode bit to select the power relay (active low bit4). relays &= ~0x10 # Send to relay register, wait for relays to stabilise. I2CPort.write_byte (register, relays) print 'select mode power ', hex(relays^0xff) time.sleep (0.1) # Now pulse OFF relay (active low bit6) to ensure power is removed from the valve. PulseLatchingRelay (I2CPort, register, 0x40) # Clear the mode bit to select the open relay (active low bit4), Wait for relay to stabilise. relays |= 0x10 I2CPort.write_byte (register, relays) print 'select open ', hex(relays^0xff) time.sleep (0.1) # We get here if there has been a status change or it is a cleardown. If it is a status change and the new status = ON # then we will turn the relay on to open the valve when power is turned on. If it is a status change and the new # status = OFF or there is no status change (must be a cleardown) we will turn the relay off. This will either close the # valve if we apply power for a status change or simply turn the relay off for a cleardown. # Do we need to open the valve? if statusChanged and statusOn : # Valve needs to open so pulse the ON relay (active low bit5). PulseLatchingRelay (I2CPort, register, 0x20) # Set the cleardown timer for the period required before we can clear the valve down. ADJUST THIS LATER zones.zoneData[relayZone].SetCleardownTimer (30) else : # Valve needs to close so pulse OFF relay (active low bit6). PulseLatchingRelay (I2CPort, register, 0x40) # Set the cleardown timer for the period required before we can clear the valve down. ADJUST THIS LATER zones.zoneData[relayZone].SetCleardownTimer (65) # If we are here because of a status change we need to activate the power relay on. For a cleardown we do not need
random_line_split
util.rs
, v, on_inserted).await?; } } &Ipld::Link(cid) => { // WASM blocks are stored as IPLD_RAW. They should be loaded but not traversed. if cid.codec() == crate::shim::crypto::IPLD_RAW { if !walked.insert(cid) { return Ok(()); } on_inserted(walked.len()); let _ = load_block(cid).await?; } if cid.codec() == fvm_ipld_encoding::DAG_CBOR { if !walked.insert(cid) { return Ok(()); } on_inserted(walked.len()); let bytes = load_block(cid).await?; let ipld = from_slice_with_fallback(&bytes)?; traverse_ipld_links_hash(walked, load_block, &ipld, on_inserted).await?; } } _ => (), } Ok(()) } /// Load and hash CIDs and resolve recursively. pub async fn recurse_links_hash<F, T>( walked: &mut CidHashSet, root: Cid, load_block: &mut F, on_inserted: &(impl Fn(usize) + Send + Sync), ) -> Result<(), anyhow::Error> where F: FnMut(Cid) -> T + Send, T: Future<Output = Result<Vec<u8>, anyhow::Error>> + Send, { if !walked.insert(root) { // Cid has already been traversed return Ok(()); } on_inserted(walked.len()); if root.codec() != fvm_ipld_encoding::DAG_CBOR { return Ok(()); } let bytes = load_block(root).await?; let ipld = from_slice_with_fallback(&bytes)?; traverse_ipld_links_hash(walked, load_block, &ipld, on_inserted).await?; Ok(()) } pub type ProgressBarCurrentTotalPair = Arc<(AtomicU64, AtomicU64)>; lazy_static! { pub static ref WALK_SNAPSHOT_PROGRESS_DB_GC: ProgressBarCurrentTotalPair = Default::default(); } /// Walks over tipset and state data and loads all blocks not yet seen. /// This is tracked based on the callback function loading blocks. pub async fn walk_snapshot<F, T>( tipset: &Tipset, recent_roots: i64, mut load_block: F, progress_bar_message: Option<&str>, progress_tracker: Option<ProgressBarCurrentTotalPair>, estimated_total_records: Option<u64>, ) -> anyhow::Result<usize> where F: FnMut(Cid) -> T + Send, T: Future<Output = anyhow::Result<Vec<u8>>> + Send, { let estimated_total_records = estimated_total_records.unwrap_or_default(); let message = progress_bar_message.unwrap_or("Walking snapshot"); #[allow(deprecated)] // Tracking issue: https://github.com/ChainSafe/forest/issues/3157 let wp = WithProgressRaw::new(message, estimated_total_records); let mut seen = CidHashSet::default(); let mut blocks_to_walk: VecDeque<Cid> = tipset.cids().to_vec().into(); let mut current_min_height = tipset.epoch(); let incl_roots_epoch = tipset.epoch() - recent_roots; let on_inserted = { let wp = wp.clone(); let progress_tracker = progress_tracker.clone(); move |len: usize| { let progress = len as u64; let total = progress.max(estimated_total_records); wp.set(progress); wp.set_total(total); if let Some(progress_tracker) = &progress_tracker { progress_tracker .0 .store(progress, atomic::Ordering::Relaxed); progress_tracker.1.store(total, atomic::Ordering::Relaxed); } } }; while let Some(next) = blocks_to_walk.pop_front() { if !seen.insert(next) { continue; }; on_inserted(seen.len()); if !should_save_block_to_snapshot(next) { continue; } let data = load_block(next).await?; let h = from_slice_with_fallback::<BlockHeader>(&data)?; if current_min_height > h.epoch() { current_min_height = h.epoch(); } if h.epoch() > incl_roots_epoch { recurse_links_hash(&mut seen, *h.messages(), &mut load_block, &on_inserted).await?; } if h.epoch() > 0 { for p in h.parents().cids() { blocks_to_walk.push_back(*p); } } else { for p in h.parents().cids() { load_block(*p).await?; } } if h.epoch() == 0 || h.epoch() > incl_roots_epoch { recurse_links_hash(&mut seen, *h.state_root(), &mut load_block, &on_inserted).await?; } } Ok(seen.len()) } fn should_save_block_to_snapshot(cid: Cid) -> bool { // Don't include identity CIDs. // We only include raw and dagcbor, for now. // Raw for "code" CIDs. if cid.hash().code() == u64::from(cid::multihash::Code::Identity) { false } else { matches!( cid.codec(), crate::shim::crypto::IPLD_RAW | fvm_ipld_encoding::DAG_CBOR ) } } /// Depth-first-search iterator for `ipld` leaf nodes. /// /// This iterator consumes the given `ipld` structure and returns leaf nodes (i.e., /// no list or map) in depth-first order. The iterator can be extended at any /// point by the caller. /// /// Consider walking this `ipld` graph: /// ```text /// List /// ├ Integer(5) /// ├ Link(Y) /// └ String("string") /// /// Link(Y): /// Map /// ├ "key1" => Bool(true) /// └ "key2" => Float(3.14) /// ``` /// /// If we walk the above `ipld` graph (replacing `Link(Y)` when it is encountered), the leaf nodes will be seen in this order: /// 1. `Integer(5)` /// 2. `Bool(true)` /// 3. `Float(3.14)` /// 4. `String("string")` pub struct DfsIter { dfs: VecDeque<Ipld>, } impl DfsIter { pub fn new(root: Ipld) -> Self { DfsIter { dfs: VecDeque::from([root]), } } pub fn walk_next(&mut self, ipld: Ipld) { self.dfs.push_front(ipld) } } impl From<Cid> for DfsIter { fn from(cid: Cid) -> Self { DfsIter::new(Ipld::Link(cid)) } } impl Iterator for DfsIter { type Item = Ipld; fn next(&mut self) -> Option<Self::Item> { while let Some(ipld) = self.dfs.pop_front() { match ipld { Ipld::List(list) => list.into_iter().rev().for_each(|elt| self.walk_next(elt)),
} } enum Task { // Yield the block, don't visit it. Emit(Cid), // Visit all the elements, recursively. Iterate(DfsIter), } pin_project! { pub struct ChainStream<DB, T> { #[pin] tipset_iter: T, db: DB, dfs: VecDeque<Task>, // Depth-first work queue. seen: CidHashSet, stateroot_limit: ChainEpoch, fail_on_dead_links: bool, } } impl<DB, T> ChainStream<DB, T> { pub fn with_seen(self, seen: CidHashSet) -> Self { ChainStream { seen, ..self } } pub fn into_seen(self) -> CidHashSet { self.seen } } /// Stream all blocks that are reachable before the `stateroot_limit` epoch. After this limit, only /// block headers are streamed. Any dead links are reported as errors. /// /// # Arguments /// /// * `db` - A database that implements [`Blockstore`] interface. /// * `tipset_iter` - An iterator of [`Tipset`], descending order `$child -> $parent`. /// * `stateroot_limit` - An epoch that signifies how far back we need to inspect tipsets. /// in-depth. This has to be pre-calculated using this formula: `$cur_epoch - $depth`, where /// `$depth` is the number of `[`Tipset`]` that needs inspection. pub fn stream_chain<DB: Blockstore, T: Iterator<Item = Tipset> + Unpin>( db: DB, tipset_iter: T, stateroot_limit: ChainEpoch, ) -> ChainStream<DB, T> { ChainStream { tipset_iter, db, dfs: VecDeque::new(), seen: CidHashSet::default(),
Ipld::Map(map) => map.into_values().rev().for_each(|elt| self.walk_next(elt)), other => return Some(other), } } None
random_line_split
util.rs
v, on_inserted).await?; } } &Ipld::Link(cid) => { // WASM blocks are stored as IPLD_RAW. They should be loaded but not traversed. if cid.codec() == crate::shim::crypto::IPLD_RAW { if !walked.insert(cid) { return Ok(()); } on_inserted(walked.len()); let _ = load_block(cid).await?; } if cid.codec() == fvm_ipld_encoding::DAG_CBOR { if !walked.insert(cid) { return Ok(()); } on_inserted(walked.len()); let bytes = load_block(cid).await?; let ipld = from_slice_with_fallback(&bytes)?; traverse_ipld_links_hash(walked, load_block, &ipld, on_inserted).await?; } } _ => (), } Ok(()) } /// Load and hash CIDs and resolve recursively. pub async fn recurse_links_hash<F, T>( walked: &mut CidHashSet, root: Cid, load_block: &mut F, on_inserted: &(impl Fn(usize) + Send + Sync), ) -> Result<(), anyhow::Error> where F: FnMut(Cid) -> T + Send, T: Future<Output = Result<Vec<u8>, anyhow::Error>> + Send, { if !walked.insert(root) { // Cid has already been traversed return Ok(()); } on_inserted(walked.len()); if root.codec() != fvm_ipld_encoding::DAG_CBOR { return Ok(()); } let bytes = load_block(root).await?; let ipld = from_slice_with_fallback(&bytes)?; traverse_ipld_links_hash(walked, load_block, &ipld, on_inserted).await?; Ok(()) } pub type ProgressBarCurrentTotalPair = Arc<(AtomicU64, AtomicU64)>; lazy_static! { pub static ref WALK_SNAPSHOT_PROGRESS_DB_GC: ProgressBarCurrentTotalPair = Default::default(); } /// Walks over tipset and state data and loads all blocks not yet seen. /// This is tracked based on the callback function loading blocks. pub async fn walk_snapshot<F, T>( tipset: &Tipset, recent_roots: i64, mut load_block: F, progress_bar_message: Option<&str>, progress_tracker: Option<ProgressBarCurrentTotalPair>, estimated_total_records: Option<u64>, ) -> anyhow::Result<usize> where F: FnMut(Cid) -> T + Send, T: Future<Output = anyhow::Result<Vec<u8>>> + Send, { let estimated_total_records = estimated_total_records.unwrap_or_default(); let message = progress_bar_message.unwrap_or("Walking snapshot"); #[allow(deprecated)] // Tracking issue: https://github.com/ChainSafe/forest/issues/3157 let wp = WithProgressRaw::new(message, estimated_total_records); let mut seen = CidHashSet::default(); let mut blocks_to_walk: VecDeque<Cid> = tipset.cids().to_vec().into(); let mut current_min_height = tipset.epoch(); let incl_roots_epoch = tipset.epoch() - recent_roots; let on_inserted = { let wp = wp.clone(); let progress_tracker = progress_tracker.clone(); move |len: usize| { let progress = len as u64; let total = progress.max(estimated_total_records); wp.set(progress); wp.set_total(total); if let Some(progress_tracker) = &progress_tracker { progress_tracker .0 .store(progress, atomic::Ordering::Relaxed); progress_tracker.1.store(total, atomic::Ordering::Relaxed); } } }; while let Some(next) = blocks_to_walk.pop_front() { if !seen.insert(next) { continue; }; on_inserted(seen.len()); if !should_save_block_to_snapshot(next) { continue; } let data = load_block(next).await?; let h = from_slice_with_fallback::<BlockHeader>(&data)?; if current_min_height > h.epoch() { current_min_height = h.epoch(); } if h.epoch() > incl_roots_epoch { recurse_links_hash(&mut seen, *h.messages(), &mut load_block, &on_inserted).await?; } if h.epoch() > 0 { for p in h.parents().cids() { blocks_to_walk.push_back(*p); } } else { for p in h.parents().cids() { load_block(*p).await?; } } if h.epoch() == 0 || h.epoch() > incl_roots_epoch { recurse_links_hash(&mut seen, *h.state_root(), &mut load_block, &on_inserted).await?; } } Ok(seen.len()) } fn should_save_block_to_snapshot(cid: Cid) -> bool
/// Depth-first-search iterator for `ipld` leaf nodes. /// /// This iterator consumes the given `ipld` structure and returns leaf nodes (i.e., /// no list or map) in depth-first order. The iterator can be extended at any /// point by the caller. /// /// Consider walking this `ipld` graph: /// ```text /// List /// ├ Integer(5) /// ├ Link(Y) /// └ String("string") /// /// Link(Y): /// Map /// ├ "key1" => Bool(true) /// └ "key2" => Float(3.14) /// ``` /// /// If we walk the above `ipld` graph (replacing `Link(Y)` when it is encountered), the leaf nodes will be seen in this order: /// 1. `Integer(5)` /// 2. `Bool(true)` /// 3. `Float(3.14)` /// 4. `String("string")` pub struct DfsIter { dfs: VecDeque<Ipld>, } impl DfsIter { pub fn new(root: Ipld) -> Self { DfsIter { dfs: VecDeque::from([root]), } } pub fn walk_next(&mut self, ipld: Ipld) { self.dfs.push_front(ipld) } } impl From<Cid> for DfsIter { fn from(cid: Cid) -> Self { DfsIter::new(Ipld::Link(cid)) } } impl Iterator for DfsIter { type Item = Ipld; fn next(&mut self) -> Option<Self::Item> { while let Some(ipld) = self.dfs.pop_front() { match ipld { Ipld::List(list) => list.into_iter().rev().for_each(|elt| self.walk_next(elt)), Ipld::Map(map) => map.into_values().rev().for_each(|elt| self.walk_next(elt)), other => return Some(other), } } None } } enum Task { // Yield the block, don't visit it. Emit(Cid), // Visit all the elements, recursively. Iterate(DfsIter), } pin_project! { pub struct ChainStream<DB, T> { #[pin] tipset_iter: T, db: DB, dfs: VecDeque<Task>, // Depth-first work queue. seen: CidHashSet, stateroot_limit: ChainEpoch, fail_on_dead_links: bool, } } impl<DB, T> ChainStream<DB, T> { pub fn with_seen(self, seen: CidHashSet) -> Self { ChainStream { seen, ..self } } pub fn into_seen(self) -> CidHashSet { self.seen } } /// Stream all blocks that are reachable before the `stateroot_limit` epoch. After this limit, only /// block headers are streamed. Any dead links are reported as errors. /// /// # Arguments /// /// * `db` - A database that implements [`Blockstore`] interface. /// * `tipset_iter` - An iterator of [`Tipset`], descending order `$child -> $parent`. /// * `stateroot_limit` - An epoch that signifies how far back we need to inspect tipsets. /// in-depth. This has to be pre-calculated using this formula: `$cur_epoch - $depth`, where /// `$depth` is the number of `[`Tipset`]` that needs inspection. pub fn stream_chain<DB: Blockstore, T: Iterator<Item = Tipset> + Unpin>( db: DB, tipset_iter: T, stateroot_limit: ChainEpoch, ) -> ChainStream<DB, T> { ChainStream { tipset_iter, db, dfs: VecDeque::new(), seen: CidHashSet::default
{ // Don't include identity CIDs. // We only include raw and dagcbor, for now. // Raw for "code" CIDs. if cid.hash().code() == u64::from(cid::multihash::Code::Identity) { false } else { matches!( cid.codec(), crate::shim::crypto::IPLD_RAW | fvm_ipld_encoding::DAG_CBOR ) } }
identifier_body
util.rs
v, on_inserted).await?; } } &Ipld::Link(cid) => { // WASM blocks are stored as IPLD_RAW. They should be loaded but not traversed. if cid.codec() == crate::shim::crypto::IPLD_RAW { if !walked.insert(cid) { return Ok(()); } on_inserted(walked.len()); let _ = load_block(cid).await?; } if cid.codec() == fvm_ipld_encoding::DAG_CBOR { if !walked.insert(cid) { return Ok(()); } on_inserted(walked.len()); let bytes = load_block(cid).await?; let ipld = from_slice_with_fallback(&bytes)?; traverse_ipld_links_hash(walked, load_block, &ipld, on_inserted).await?; } } _ => (), } Ok(()) } /// Load and hash CIDs and resolve recursively. pub async fn recurse_links_hash<F, T>( walked: &mut CidHashSet, root: Cid, load_block: &mut F, on_inserted: &(impl Fn(usize) + Send + Sync), ) -> Result<(), anyhow::Error> where F: FnMut(Cid) -> T + Send, T: Future<Output = Result<Vec<u8>, anyhow::Error>> + Send, { if !walked.insert(root) { // Cid has already been traversed return Ok(()); } on_inserted(walked.len()); if root.codec() != fvm_ipld_encoding::DAG_CBOR { return Ok(()); } let bytes = load_block(root).await?; let ipld = from_slice_with_fallback(&bytes)?; traverse_ipld_links_hash(walked, load_block, &ipld, on_inserted).await?; Ok(()) } pub type ProgressBarCurrentTotalPair = Arc<(AtomicU64, AtomicU64)>; lazy_static! { pub static ref WALK_SNAPSHOT_PROGRESS_DB_GC: ProgressBarCurrentTotalPair = Default::default(); } /// Walks over tipset and state data and loads all blocks not yet seen. /// This is tracked based on the callback function loading blocks. pub async fn walk_snapshot<F, T>( tipset: &Tipset, recent_roots: i64, mut load_block: F, progress_bar_message: Option<&str>, progress_tracker: Option<ProgressBarCurrentTotalPair>, estimated_total_records: Option<u64>, ) -> anyhow::Result<usize> where F: FnMut(Cid) -> T + Send, T: Future<Output = anyhow::Result<Vec<u8>>> + Send, { let estimated_total_records = estimated_total_records.unwrap_or_default(); let message = progress_bar_message.unwrap_or("Walking snapshot"); #[allow(deprecated)] // Tracking issue: https://github.com/ChainSafe/forest/issues/3157 let wp = WithProgressRaw::new(message, estimated_total_records); let mut seen = CidHashSet::default(); let mut blocks_to_walk: VecDeque<Cid> = tipset.cids().to_vec().into(); let mut current_min_height = tipset.epoch(); let incl_roots_epoch = tipset.epoch() - recent_roots; let on_inserted = { let wp = wp.clone(); let progress_tracker = progress_tracker.clone(); move |len: usize| { let progress = len as u64; let total = progress.max(estimated_total_records); wp.set(progress); wp.set_total(total); if let Some(progress_tracker) = &progress_tracker { progress_tracker .0 .store(progress, atomic::Ordering::Relaxed); progress_tracker.1.store(total, atomic::Ordering::Relaxed); } } }; while let Some(next) = blocks_to_walk.pop_front() { if !seen.insert(next) { continue; }; on_inserted(seen.len()); if !should_save_block_to_snapshot(next) { continue; } let data = load_block(next).await?; let h = from_slice_with_fallback::<BlockHeader>(&data)?; if current_min_height > h.epoch() { current_min_height = h.epoch(); } if h.epoch() > incl_roots_epoch { recurse_links_hash(&mut seen, *h.messages(), &mut load_block, &on_inserted).await?; } if h.epoch() > 0 { for p in h.parents().cids() { blocks_to_walk.push_back(*p); } } else { for p in h.parents().cids() { load_block(*p).await?; } } if h.epoch() == 0 || h.epoch() > incl_roots_epoch { recurse_links_hash(&mut seen, *h.state_root(), &mut load_block, &on_inserted).await?; } } Ok(seen.len()) } fn should_save_block_to_snapshot(cid: Cid) -> bool { // Don't include identity CIDs. // We only include raw and dagcbor, for now. // Raw for "code" CIDs. if cid.hash().code() == u64::from(cid::multihash::Code::Identity) { false } else { matches!( cid.codec(), crate::shim::crypto::IPLD_RAW | fvm_ipld_encoding::DAG_CBOR ) } } /// Depth-first-search iterator for `ipld` leaf nodes. /// /// This iterator consumes the given `ipld` structure and returns leaf nodes (i.e., /// no list or map) in depth-first order. The iterator can be extended at any /// point by the caller. /// /// Consider walking this `ipld` graph: /// ```text /// List /// ├ Integer(5) /// ├ Link(Y) /// └ String("string") /// /// Link(Y): /// Map /// ├ "key1" => Bool(true) /// └ "key2" => Float(3.14) /// ``` /// /// If we walk the above `ipld` graph (replacing `Link(Y)` when it is encountered), the leaf nodes will be seen in this order: /// 1. `Integer(5)` /// 2. `Bool(true)` /// 3. `Float(3.14)` /// 4. `String("string")` pub struct DfsIter { dfs: VecDeque<Ipld>, } impl DfsIter { pub fn new(root: Ipld) -> Self { DfsIter { dfs: VecDeque::from([root]), } } pub fn walk_next(&mut self, ipld: Ipld) { self.dfs.push_front(ipld) } } impl From<Cid> for DfsIter { fn from(cid: Cid) -> Self { DfsIter::new(Ipld::Link(cid)) } } impl Iterator for DfsIter { type Item = Ipld; fn next(&mut self) -> Option<Self::Item> { while let Some(ipld) = self.dfs.pop_front() { match ipld { Ipld::List(list) => list.into_iter().rev().for_each(|elt| self.walk_next(elt)), Ipld::Map(map) => map.into_values().rev().for_each(|elt| self.walk_next(elt)), other => return Some(other), } } None } } enum Task {
Yield the block, don't visit it. Emit(Cid), // Visit all the elements, recursively. Iterate(DfsIter), } pin_project! { pub struct ChainStream<DB, T> { #[pin] tipset_iter: T, db: DB, dfs: VecDeque<Task>, // Depth-first work queue. seen: CidHashSet, stateroot_limit: ChainEpoch, fail_on_dead_links: bool, } } impl<DB, T> ChainStream<DB, T> { pub fn with_seen(self, seen: CidHashSet) -> Self { ChainStream { seen, ..self } } pub fn into_seen(self) -> CidHashSet { self.seen } } /// Stream all blocks that are reachable before the `stateroot_limit` epoch. After this limit, only /// block headers are streamed. Any dead links are reported as errors. /// /// # Arguments /// /// * `db` - A database that implements [`Blockstore`] interface. /// * `tipset_iter` - An iterator of [`Tipset`], descending order `$child -> $parent`. /// * `stateroot_limit` - An epoch that signifies how far back we need to inspect tipsets. /// in-depth. This has to be pre-calculated using this formula: `$cur_epoch - $depth`, where /// `$depth` is the number of `[`Tipset`]` that needs inspection. pub fn stream_chain<DB: Blockstore, T: Iterator<Item = Tipset> + Unpin>( db: DB, tipset_iter: T, stateroot_limit: ChainEpoch, ) -> ChainStream<DB, T> { ChainStream { tipset_iter, db, dfs: VecDeque::new(), seen: CidHashSet::default
//
identifier_name
octree_gui.rs
::new() .with_title("Octree - Config") .with_decorations(true) .with_inner_size(glutin::dpi::LogicalSize::new(420f64, 768f64)); let display = Display::new(builder, context, &nse.event_loop).expect("Failed to initialize display"); let mut platform = WinitPlatform::init(&mut imgui); // step 1 platform.attach_window( imgui.io_mut(), &display.gl_window().window(), HiDpiMode::Default, ); // step 2 let hidpi_factor = platform.hidpi_factor(); let font_size = (13.0 * hidpi_factor) as f32; imgui.fonts().add_font(&[ FontSource::DefaultFontData { config: Some(FontConfig { size_pixels: font_size, ..FontConfig::default() }), }, FontSource::TtfData { data: include_bytes!("resources/mplus-1p-regular.ttf"), size_pixels: font_size, config: Some(FontConfig { rasterizer_multiply: 1.75, glyph_ranges: FontGlyphRanges::japanese(), ..FontConfig::default() }), }, ]); imgui.io_mut().font_global_scale = (1.0 / hidpi_factor) as f32; let renderer = Renderer::init(&mut imgui, &display).expect("Failed to initialize renderer"); let mut frame_times = VecDeque::new(); frame_times.resize(500, 0.0); Arc::new(Mutex::new(OctreeGuiSystem { imgui: Arc::new(Mutex::new(imgui)), platform, renderer, display: Arc::new(Mutex::new(display)), octree_config: OctreeConfig::default(), octree_optimizations: OctreeOptimizations::default(), profiling_data: ProfilingData::default(), frame_times, messages: vec![], })) } fn display_octree_ui(&mut self, ui: &Ui, _config: &OctreeConfig, _info: &OctreeInfo) { if CollapsingHeader::new(im_str!("Settings")) .default_open(true) .build(&ui) { // reset the reset flag self.octree_config.reset = None; let mut modified = false; ui.text(format!("Fractal Selection")); let mut selected_fractal = self.octree_config.fractal.as_mut().unwrap().to_usize().unwrap_or(0); let mut fractal_names = vec![]; for x in 0.. { match FromPrimitive::from_i32(x) { Some(FractalSelection::MandelBulb) => fractal_names.push(im_str!("Mandel Bulb")), Some(FractalSelection::MandelBrot) => fractal_names.push(im_str!("Mandel Brot")), Some(FractalSelection::SierpinskiPyramid) => fractal_names.push(im_str!("Sierpinski Pyramid")), Some(FractalSelection::SierpinskiTetrahedron) => fractal_names.push(im_str!("Sierpinski Tetrahedron")), Some(FractalSelection::MengerSponge) => fractal_names.push(im_str!("Menger Sponge")), Some(FractalSelection::MidpointDisplacement) => fractal_names.push(im_str!("Midpoint Displacement")), _ => break, // leave loop } } if ComboBox::new(im_str!("Select Fractal")) .build_simple_string( &ui, &mut selected_fractal, &fractal_names) { self.octree_config = OctreeConfig::default(); self.octree_config.fractal = FromPrimitive::from_usize(selected_fractal); self.octree_config.reset = Some(true); modified = true; } ui.separator(); ui.text(format!("Performance Settings")); if ui.button(im_str!("Update Now"), [0.0, 0.0]) { self.messages.push(Message::new(self.octree_config.clone())); }; ui.same_line(0.0); if ui.checkbox(im_str!("Continuous Update"), &mut self.octree_config.continuous_update.as_mut().unwrap()) { modified = true; } if Slider::new(im_str!("Subdivision Threshold (px)")) .range(RangeInclusive::new(1.0, 50.0)) .flags(SliderFlags::LOGARITHMIC) .build(&ui, &mut self.octree_config.subdiv_threshold.as_mut().unwrap()) { modified = true; } if Slider::new(im_str!("Distance Scale")) .range(RangeInclusive::new(0.05 as f64, 1.0 as f64)) // .flags(SliderFlags::LOGARITHMIC) .build(&ui, self.octree_config.distance_scale.as_mut().unwrap()) { modified = true; } if Slider::new(im_str!("Max. Octree Nodes")) .range(RangeInclusive::new(1e4 as u64, 2e7 as u64)) .build(&ui, self.octree_config.max_rendered_nodes.as_mut().unwrap()) { modified = true; } if modified { self.messages.push(Message::new(self.octree_config.clone())); } if ui.button(im_str!("Reset Octree"), [0.0, 0.0]) { let prev_selection = self.octree_config.fractal; self.octree_config = OctreeConfig::default(); self.octree_config.reset = Some(true); self.octree_config.fractal = prev_selection; self.messages.push(Message::new(self.octree_config.clone())); }; } } fn display_profiling_ui(&mut self, delta_time: Duration, ui: &Ui) { let rendered_nodes = &mut self.profiling_data.rendered_nodes.unwrap_or(0); let render_time = self.profiling_data.render_time.unwrap_or(0) as f64 / 1e6 as f64; let frame_times = &mut self.frame_times; frame_times.pop_front(); frame_times.push_back(delta_time.as_secs_f32()); let f_times: Vec<f32> = frame_times.iter().cloned().collect(); if CollapsingHeader::new(im_str!("Profiling")) .default_open(true) .build(&ui) { // Plot Frame Times ui.plot_lines(im_str!("Frame Times"), &f_times[..]) .graph_size([0.0, 50.0]) .overlay_text(&im_str!("{} ms", delta_time.as_millis())) .build(); // print times of seperate systems if self.profiling_data.system_times.is_some() { for (system_name, system_time) in self.profiling_data.system_times.as_ref().unwrap() { ui.text(im_str!("{}: {}", system_name, system_time.as_millis())); } } ui.separator(); ui.text(im_str!("Rendered Nodes: {}", rendered_nodes)); ui.text(im_str!("Render Time: {:.2} ms", render_time)); } } fn display_camera_ui(&mut self, ui: &Ui, _camera: &Camera, camera_transform: &mut Transformation) { if CollapsingHeader::new(im_str!("Camera")) .default_open(true) .build(&ui) { let mut view_dir = camera_transform.rotation.rotate_vector(-Vector3::unit_z()); InputFloat3::new( &ui, im_str!("View Direction (read only)"), view_dir.as_mut(), ).read_only(true).build(); InputFloat3::new( &ui, im_str!("Camera Position"), camera_transform.position.as_mut(), ).build(); camera_transform.update(); } } } impl System for OctreeGuiSystem { fn
(&mut self) -> Vec<Filter> { vec![ crate::filter!(Octree, Mesh, Transformation), crate::filter!(Camera, Transformation), ] } fn handle_input(&mut self, _event: &Event<()>) { let platform = &mut self.platform; let display = self.display.lock().unwrap(); let gl_window = display.gl_window(); let mut imgui = self.imgui.lock().unwrap(); match _event { Event::MainEventsCleared => { platform .prepare_frame(imgui.io_mut(), &gl_window.window()) // step 4 .expect("Failed to prepare frame"); } Event::WindowEvent { event: WindowEvent::CloseRequested, window_id, } => { if *window_id == gl_window.window().id() { println!("Close Octree Config Window"); gl_window.window().set_visible(false); return; } } Event::WindowEvent { event, .. } => match event { WindowEvent::KeyboardInput { input, .. } => match input { winit::event::KeyboardInput { virtual_keycode, state, .. } => match (virtual_keycode, state) { (Some(VirtualKeyCode::F12), ElementState::Pressed) => { println!("Open Octree Config Window");
get_filter
identifier_name
octree_gui.rs
::new() .with_title("Octree - Config") .with_decorations(true) .with_inner_size(glutin::dpi::LogicalSize::new(420f64, 768f64)); let display = Display::new(builder, context, &nse.event_loop).expect("Failed to initialize display"); let mut platform = WinitPlatform::init(&mut imgui); // step 1 platform.attach_window( imgui.io_mut(), &display.gl_window().window(), HiDpiMode::Default, ); // step 2 let hidpi_factor = platform.hidpi_factor(); let font_size = (13.0 * hidpi_factor) as f32; imgui.fonts().add_font(&[ FontSource::DefaultFontData { config: Some(FontConfig { size_pixels: font_size, ..FontConfig::default() }), }, FontSource::TtfData { data: include_bytes!("resources/mplus-1p-regular.ttf"), size_pixels: font_size, config: Some(FontConfig { rasterizer_multiply: 1.75, glyph_ranges: FontGlyphRanges::japanese(), ..FontConfig::default() }), }, ]); imgui.io_mut().font_global_scale = (1.0 / hidpi_factor) as f32; let renderer = Renderer::init(&mut imgui, &display).expect("Failed to initialize renderer"); let mut frame_times = VecDeque::new(); frame_times.resize(500, 0.0); Arc::new(Mutex::new(OctreeGuiSystem { imgui: Arc::new(Mutex::new(imgui)), platform, renderer, display: Arc::new(Mutex::new(display)), octree_config: OctreeConfig::default(), octree_optimizations: OctreeOptimizations::default(), profiling_data: ProfilingData::default(), frame_times, messages: vec![], })) } fn display_octree_ui(&mut self, ui: &Ui, _config: &OctreeConfig, _info: &OctreeInfo) { if CollapsingHeader::new(im_str!("Settings")) .default_open(true) .build(&ui) { // reset the reset flag self.octree_config.reset = None; let mut modified = false; ui.text(format!("Fractal Selection")); let mut selected_fractal = self.octree_config.fractal.as_mut().unwrap().to_usize().unwrap_or(0); let mut fractal_names = vec![]; for x in 0.. { match FromPrimitive::from_i32(x) { Some(FractalSelection::MandelBulb) => fractal_names.push(im_str!("Mandel Bulb")), Some(FractalSelection::MandelBrot) => fractal_names.push(im_str!("Mandel Brot")), Some(FractalSelection::SierpinskiPyramid) => fractal_names.push(im_str!("Sierpinski Pyramid")), Some(FractalSelection::SierpinskiTetrahedron) => fractal_names.push(im_str!("Sierpinski Tetrahedron")), Some(FractalSelection::MengerSponge) => fractal_names.push(im_str!("Menger Sponge")), Some(FractalSelection::MidpointDisplacement) => fractal_names.push(im_str!("Midpoint Displacement")), _ => break, // leave loop } } if ComboBox::new(im_str!("Select Fractal")) .build_simple_string( &ui, &mut selected_fractal, &fractal_names) { self.octree_config = OctreeConfig::default(); self.octree_config.fractal = FromPrimitive::from_usize(selected_fractal); self.octree_config.reset = Some(true); modified = true; } ui.separator(); ui.text(format!("Performance Settings")); if ui.button(im_str!("Update Now"), [0.0, 0.0]) { self.messages.push(Message::new(self.octree_config.clone())); }; ui.same_line(0.0); if ui.checkbox(im_str!("Continuous Update"), &mut self.octree_config.continuous_update.as_mut().unwrap()) { modified = true; } if Slider::new(im_str!("Subdivision Threshold (px)")) .range(RangeInclusive::new(1.0, 50.0)) .flags(SliderFlags::LOGARITHMIC) .build(&ui, &mut self.octree_config.subdiv_threshold.as_mut().unwrap()) { modified = true; } if Slider::new(im_str!("Distance Scale")) .range(RangeInclusive::new(0.05 as f64, 1.0 as f64)) // .flags(SliderFlags::LOGARITHMIC) .build(&ui, self.octree_config.distance_scale.as_mut().unwrap()) { modified = true; } if Slider::new(im_str!("Max. Octree Nodes")) .range(RangeInclusive::new(1e4 as u64, 2e7 as u64)) .build(&ui, self.octree_config.max_rendered_nodes.as_mut().unwrap()) { modified = true; } if modified { self.messages.push(Message::new(self.octree_config.clone())); } if ui.button(im_str!("Reset Octree"), [0.0, 0.0]) { let prev_selection = self.octree_config.fractal; self.octree_config = OctreeConfig::default(); self.octree_config.reset = Some(true); self.octree_config.fractal = prev_selection; self.messages.push(Message::new(self.octree_config.clone())); }; } } fn display_profiling_ui(&mut self, delta_time: Duration, ui: &Ui) { let rendered_nodes = &mut self.profiling_data.rendered_nodes.unwrap_or(0); let render_time = self.profiling_data.render_time.unwrap_or(0) as f64 / 1e6 as f64; let frame_times = &mut self.frame_times; frame_times.pop_front(); frame_times.push_back(delta_time.as_secs_f32()); let f_times: Vec<f32> = frame_times.iter().cloned().collect(); if CollapsingHeader::new(im_str!("Profiling")) .default_open(true) .build(&ui) { // Plot Frame Times ui.plot_lines(im_str!("Frame Times"), &f_times[..]) .graph_size([0.0, 50.0]) .overlay_text(&im_str!("{} ms", delta_time.as_millis())) .build(); // print times of seperate systems if self.profiling_data.system_times.is_some() { for (system_name, system_time) in self.profiling_data.system_times.as_ref().unwrap() { ui.text(im_str!("{}: {}", system_name, system_time.as_millis())); } } ui.separator(); ui.text(im_str!("Rendered Nodes: {}", rendered_nodes)); ui.text(im_str!("Render Time: {:.2} ms", render_time)); } } fn display_camera_ui(&mut self, ui: &Ui, _camera: &Camera, camera_transform: &mut Transformation) { if CollapsingHeader::new(im_str!("Camera")) .default_open(true) .build(&ui) { let mut view_dir = camera_transform.rotation.rotate_vector(-Vector3::unit_z()); InputFloat3::new( &ui, im_str!("View Direction (read only)"), view_dir.as_mut(), ).read_only(true).build(); InputFloat3::new( &ui, im_str!("Camera Position"), camera_transform.position.as_mut(), ).build(); camera_transform.update(); } } } impl System for OctreeGuiSystem { fn get_filter(&mut self) -> Vec<Filter>
fn handle_input(&mut self, _event: &Event<()>) { let platform = &mut self.platform; let display = self.display.lock().unwrap(); let gl_window = display.gl_window(); let mut imgui = self.imgui.lock().unwrap(); match _event { Event::MainEventsCleared => { platform .prepare_frame(imgui.io_mut(), &gl_window.window()) // step 4 .expect("Failed to prepare frame"); } Event::WindowEvent { event: WindowEvent::CloseRequested, window_id, } => { if *window_id == gl_window.window().id() { println!("Close Octree Config Window"); gl_window.window().set_visible(false); return; } } Event::WindowEvent { event, .. } => match event { WindowEvent::KeyboardInput { input, .. } => match input { winit::event::KeyboardInput { virtual_keycode, state, .. } => match (virtual_keycode, state) { (Some(VirtualKeyCode::F12), ElementState::Pressed) => { println!("Open Octree Config Window
{ vec![ crate::filter!(Octree, Mesh, Transformation), crate::filter!(Camera, Transformation), ] }
identifier_body
octree_gui.rs
Builder::new() .with_title("Octree - Config") .with_decorations(true) .with_inner_size(glutin::dpi::LogicalSize::new(420f64, 768f64)); let display = Display::new(builder, context, &nse.event_loop).expect("Failed to initialize display"); let mut platform = WinitPlatform::init(&mut imgui); // step 1 platform.attach_window( imgui.io_mut(), &display.gl_window().window(), HiDpiMode::Default, ); // step 2 let hidpi_factor = platform.hidpi_factor(); let font_size = (13.0 * hidpi_factor) as f32; imgui.fonts().add_font(&[ FontSource::DefaultFontData { config: Some(FontConfig { size_pixels: font_size, ..FontConfig::default() }), }, FontSource::TtfData { data: include_bytes!("resources/mplus-1p-regular.ttf"), size_pixels: font_size, config: Some(FontConfig { rasterizer_multiply: 1.75, glyph_ranges: FontGlyphRanges::japanese(), ..FontConfig::default() }), }, ]); imgui.io_mut().font_global_scale = (1.0 / hidpi_factor) as f32; let renderer = Renderer::init(&mut imgui, &display).expect("Failed to initialize renderer"); let mut frame_times = VecDeque::new(); frame_times.resize(500, 0.0); Arc::new(Mutex::new(OctreeGuiSystem { imgui: Arc::new(Mutex::new(imgui)), platform, renderer, display: Arc::new(Mutex::new(display)), octree_config: OctreeConfig::default(), octree_optimizations: OctreeOptimizations::default(), profiling_data: ProfilingData::default(), frame_times, messages: vec![], })) } fn display_octree_ui(&mut self, ui: &Ui, _config: &OctreeConfig, _info: &OctreeInfo) { if CollapsingHeader::new(im_str!("Settings")) .default_open(true) .build(&ui) { // reset the reset flag self.octree_config.reset = None; let mut modified = false; ui.text(format!("Fractal Selection")); let mut selected_fractal = self.octree_config.fractal.as_mut().unwrap().to_usize().unwrap_or(0); let mut fractal_names = vec![]; for x in 0.. { match FromPrimitive::from_i32(x) { Some(FractalSelection::MandelBulb) => fractal_names.push(im_str!("Mandel Bulb")), Some(FractalSelection::MandelBrot) => fractal_names.push(im_str!("Mandel Brot")), Some(FractalSelection::SierpinskiPyramid) => fractal_names.push(im_str!("Sierpinski Pyramid")), Some(FractalSelection::SierpinskiTetrahedron) => fractal_names.push(im_str!("Sierpinski Tetrahedron")), Some(FractalSelection::MengerSponge) => fractal_names.push(im_str!("Menger Sponge")), Some(FractalSelection::MidpointDisplacement) => fractal_names.push(im_str!("Midpoint Displacement")), _ => break, // leave loop } } if ComboBox::new(im_str!("Select Fractal")) .build_simple_string( &ui, &mut selected_fractal, &fractal_names) { self.octree_config = OctreeConfig::default(); self.octree_config.fractal = FromPrimitive::from_usize(selected_fractal); self.octree_config.reset = Some(true); modified = true; } ui.separator(); ui.text(format!("Performance Settings")); if ui.button(im_str!("Update Now"), [0.0, 0.0]) { self.messages.push(Message::new(self.octree_config.clone())); }; ui.same_line(0.0); if ui.checkbox(im_str!("Continuous Update"), &mut self.octree_config.continuous_update.as_mut().unwrap()) { modified = true; } if Slider::new(im_str!("Subdivision Threshold (px)")) .range(RangeInclusive::new(1.0, 50.0)) .flags(SliderFlags::LOGARITHMIC) .build(&ui, &mut self.octree_config.subdiv_threshold.as_mut().unwrap()) { modified = true; } if Slider::new(im_str!("Distance Scale")) .range(RangeInclusive::new(0.05 as f64, 1.0 as f64)) // .flags(SliderFlags::LOGARITHMIC) .build(&ui, self.octree_config.distance_scale.as_mut().unwrap()) { modified = true; } if Slider::new(im_str!("Max. Octree Nodes")) .range(RangeInclusive::new(1e4 as u64, 2e7 as u64)) .build(&ui, self.octree_config.max_rendered_nodes.as_mut().unwrap()) { modified = true; } if modified { self.messages.push(Message::new(self.octree_config.clone())); } if ui.button(im_str!("Reset Octree"), [0.0, 0.0]) { let prev_selection = self.octree_config.fractal; self.octree_config = OctreeConfig::default(); self.octree_config.reset = Some(true); self.octree_config.fractal = prev_selection; self.messages.push(Message::new(self.octree_config.clone())); }; } } fn display_profiling_ui(&mut self, delta_time: Duration, ui: &Ui) { let rendered_nodes = &mut self.profiling_data.rendered_nodes.unwrap_or(0); let render_time = self.profiling_data.render_time.unwrap_or(0) as f64 / 1e6 as f64; let frame_times = &mut self.frame_times; frame_times.pop_front(); frame_times.push_back(delta_time.as_secs_f32()); let f_times: Vec<f32> = frame_times.iter().cloned().collect(); if CollapsingHeader::new(im_str!("Profiling")) .default_open(true) .build(&ui) { // Plot Frame Times ui.plot_lines(im_str!("Frame Times"), &f_times[..]) .graph_size([0.0, 50.0]) .overlay_text(&im_str!("{} ms", delta_time.as_millis())) .build(); // print times of seperate systems if self.profiling_data.system_times.is_some() { for (system_name, system_time) in self.profiling_data.system_times.as_ref().unwrap() { ui.text(im_str!("{}: {}", system_name, system_time.as_millis())); } } ui.separator(); ui.text(im_str!("Rendered Nodes: {}", rendered_nodes)); ui.text(im_str!("Render Time: {:.2} ms", render_time)); } } fn display_camera_ui(&mut self, ui: &Ui, _camera: &Camera, camera_transform: &mut Transformation) { if CollapsingHeader::new(im_str!("Camera")) .default_open(true) .build(&ui) { let mut view_dir = camera_transform.rotation.rotate_vector(-Vector3::unit_z()); InputFloat3::new( &ui, im_str!("View Direction (read only)"),
view_dir.as_mut(), ).read_only(true).build(); InputFloat3::new( &ui, im_str!("Camera Position"), camera_transform.position.as_mut(), ).build(); camera_transform.update(); } } } impl System for OctreeGuiSystem { fn get_filter(&mut self) -> Vec<Filter> { vec![ crate::filter!(Octree, Mesh, Transformation), crate::filter!(Camera, Transformation), ] } fn handle_input(&mut self, _event: &Event<()>) { let platform = &mut self.platform; let display = self.display.lock().unwrap(); let gl_window = display.gl_window(); let mut imgui = self.imgui.lock().unwrap(); match _event { Event::MainEventsCleared => { platform .prepare_frame(imgui.io_mut(), &gl_window.window()) // step 4 .expect("Failed to prepare frame"); } Event::WindowEvent { event: WindowEvent::CloseRequested, window_id, } => { if *window_id == gl_window.window().id() { println!("Close Octree Config Window"); gl_window.window().set_visible(false); return; } } Event::WindowEvent { event, .. } => match event { WindowEvent::KeyboardInput { input, .. } => match input { winit::event::KeyboardInput { virtual_keycode, state, .. } => match (virtual_keycode, state) { (Some(VirtualKeyCode::F12), ElementState::Pressed) => { println!("Open Octree Config Window");
random_line_split
lib.rs
().unwrap(); //! max30102.set_pulse_amplitude(Led::All, 15).unwrap(); //! max30102.set_led_time_slots([ //! TimeSlot::Led1, //! TimeSlot::Led2, //! TimeSlot::Led1, //! TimeSlot::Disabled //! ]).unwrap(); //! max30102.enable_fifo_rollover().unwrap(); //! let mut data = [0; 2]; //! let samples_read = max30102.read_fifo(&mut data).unwrap(); //! //! // get the I2C device back //! let dev = max30102.destroy(); //! # } //! ``` //! #![deny(missing_docs, unsafe_code)] #![no_std] extern crate embedded_hal as hal; use hal::blocking::i2c; extern crate nb; use core::marker::PhantomData; /// All possible errors in this crate #[derive(Debug)] pub enum Error<E> { /// I²C bus error I2C(E), /// Invalid arguments provided InvalidArguments, } /// LEDs #[derive(Debug, Clone, Copy, PartialEq)] pub enum Led { /// LED1 corresponds to Red in MAX30102 Led1, /// LED1 corresponds to IR in MAX30102 Led2, /// Select all available LEDs in the device All, } /// Multi-LED mode sample time slot configuration #[derive(Debug, Clone, Copy, PartialEq)] pub enum TimeSlot { /// Time slot is disabled Disabled, /// LED 1 active during time slot (corresponds to Red in MAX30102) Led1, /// LED 2 active during time slot (corresponds to IR in MAX30102) Led2, } /// Sample averaging #[derive(Debug, Clone, Copy, PartialEq)] pub enum SampleAveraging { /// 1 (no averaging) (default) Sa1, /// 2 Sa2, /// 4 Sa4, /// 8 Sa8, /// 16 Sa16, /// 32 Sa32, } /// Number of empty data samples when the FIFO almost full interrupt is issued. #[derive(Debug, Clone, Copy, PartialEq)] pub enum FifoAlmostFullLevelInterrupt { /// Interrupt issue when 0 spaces are left in FIFO. (default) L0, /// Interrupt issue when 1 space is left in FIFO. L1, /// Interrupt issue when 2 spaces are left in FIFO. L2, /// Interrupt issue when 3 spaces are left in FIFO. L3, /// Interrupt issue when 4 spaces are left in FIFO. L4, /// Interrupt issue when 5 spaces are left in FIFO. L5, /// Interrupt issue when 6 spaces are left in FIFO. L6, /// Interrupt issue when 7 spaces are left in FIFO. L7, /// Interrupt issue when 8 spaces are left in FIFO. L8, /// Interrupt issue when 9 spaces are left in FIFO. L9, /// Interrupt issue when 10 spaces are left in FIFO. L10, /// Interrupt issue when 11 spaces are left in FIFO. L11, /// Interrupt issue when 12 spaces are left in FIFO. L12, /// Interrupt issue when 13 spaces are left in FIFO. L13, /// Interrupt issue when 14 spaces are left in FIFO. L14, /// Interrupt issue when 15 spaces are left in FIFO. L15, } /// LED pulse width (determines ADC resolution) /// /// This is limited by the current mode and the selected sample rate. #[derive(Debug, Clone, Copy, PartialEq)] pub enum LedPulseWidth { /// 69 μs pulse width (15-bit ADC resolution) Pw69, /// 118 μs pulse width (16-bit ADC resolution) Pw118, /// 215 μs pulse width (17-bit ADC resolution) Pw215, /// 411 μs pulse width (18-bit ADC resolution) Pw411, } /// Sampling rate /// /// This is limited by the current mode and the selected LED pulse width. #[derive(Debug, Clone, Copy, PartialEq)] pub enum SamplingRate { /// 50 samples per second Sps50, /// 100 samples per second Sps100, /// 200 samples per second Sps200, /// 400 samples per second Sps400, /// 800 samples per second Sps800, /// 1000 samples per second Sps1000, /// 1600 samples per second Sps1600, /// 3200 samples per second Sps3200, } /// ADC range #[derive(Debug, Clone, Copy, PartialEq)] pub enum AdcRange { /// Full scale 2048 nA Fs2k, /// Full scale 4094 nA Fs4k, /// Full scale 8192 nA Fs8k, /// Full scale 16394 nA Fs16k, } /// Interrupt status flags #[derive(Debug, Clone, Copy)] pub struct InterruptStatus { /// Power ready interrupt pub power_ready: bool, /// FIFO almost full interrupt pub fifo_almost_full: bool, /// New FIFO data ready interrupt pub new_fifo_data_ready: bool, /// Ambient light cancellation overflow interrupt pub alc_overflow: bool, /// Internal die temperature conversion ready interrupt pub temperature_ready: bool, } const DEVICE_ADDRESS: u8 = 0b101_0111; struct Register; impl Register { const INT_STATUS: u8 = 0x0; const INT_EN1: u8 = 0x02; const INT_EN2: u8 = 0x03; const FIFO_WR_PTR: u8 = 0x04; const OVF_COUNTER: u8 = 0x05; const FIFO_DATA: u8 = 0x07; const FIFO_CONFIG: u8 = 0x08; const MODE: u8 = 0x09; const SPO2_CONFIG: u8 = 0x0A; const LED1_PA: u8 = 0x0C; const LED2_PA: u8 = 0x0D; const SLOT_CONFIG0: u8 = 0x11; const TEMP_INT: u8 = 0x1F; const TEMP_CONFIG: u8 = 0x21; const REV_ID: u8 = 0xFE; const PART_ID: u8 = 0xFF; } struct BitFlags; impl BitFlags { const FIFO_A_FULL_INT: u8 = 0b1000_0000; const ALC_OVF_INT: u8 = 0b0010_0000; const DIE_TEMP_RDY_INT: u8 = 0b0000_0010; const PPG_RDY_INT: u8 = 0b0100_0000; const PWR_RDY_INT: u8 = 0b0000_0001; const TEMP_EN: u8 = 0b0000_0001; const SHUTDOWN: u8 = 0b1000_0000; const RESET: u8 = 0b0100_0000; const FIFO_ROLLOVER_EN: u8 = 0b0001_0000; const ADC_RGE0: u8 = 0b0010_0000; const ADC_RGE1: u8 = 0b0100_0000; const LED_PW0: u8 = 0b0000_0001; const LED_PW1: u8 = 0b0000_0010; const SPO2_SR0: u8 = 0b0000_0100; const SPO2_SR1: u8 = 0b0000_1000; const SPO2_SR2: u8 = 0b0001_0000; } #[derive(Debug, Default, Clone, PartialEq)] struct Config { bits: u8, } impl Config { fn with_high(&self, mask: u8) -> Self { Config { bits: self.bits | mask, } } fn with_low(&self, mask: u8) -> Self { Config { bits: self.bits & !mask, } } } #[doc(hidden)] pub mod marker { pub mod mode { pub struct None(()); pub struct HeartRate(()); pub struct Oxime
ter(());
identifier_name
lib.rs
x.html#method.read_interrupt_status //! [`enable_fifo_almost_full_interrupt()`]: struct.Max3010x.html#method.enable_fifo_almost_full_interrupt //! [`enable_alc_overflow_interrupt()`]: struct.Max3010x.html#method.enable_alc_overflow_interrupt //! [`enable_temperature_ready_interrupt()`]: struct.Max3010x.html#method.enable_temperature_ready_interrupt //! [`enable_new_fifo_data_ready_interrupt()`]: struct.Max3010x.html#method.enable_new_fifo_data_ready_interrupt //! [`get_part_id()`]: struct.Max3010x.html#method.get_part_id //! //! ## The device //! The `MAX30102` is an integrated pulse oximetry and heart-rate monitor module. //! It includes internal LEDs, photodetectors, optical elements, and low-noise //! electronics with ambient light rejection. The `MAX30102` provides a complete //! system solution to ease the design-in process for mobile and //! wearable devices. //! //! The `MAX30102` operates on a single 1.8V power supply and a separate 3.3V //! power supply for the internal LEDs. Communication is through a standard //! I2C-compatible interface. The module can be shut down through software //! with zero standby current, allowing the power rails to remain //! powered at all times. //! //! Datasheet: //! - [`MAX30102`](https://datasheets.maximintegrated.com/en/ds/MAX30102.pdf) //! //! ## Usage examples (see also examples folder) //! //! To use this driver, import this crate and an `embedded_hal` implementation, //! then instantiate the device. //! //! Please find additional examples using hardware in this repository: [driver-examples] //! //! [driver-examples]: https://github.com/eldruin/driver-examples //! //! ### Read samples in heart-rate mode //! //! ```no_run //! extern crate linux_embedded_hal as hal; //! extern crate max3010x; //! use max3010x::{Max3010x, Led, SampleAveraging}; //! //! # fn main() { //! let dev = hal::I2cdev::new("/dev/i2c-1").unwrap(); //! let mut sensor = Max3010x::new_max30102(dev); //! let mut sensor = sensor.into_heart_rate().unwrap(); //! sensor.set_sample_averaging(SampleAveraging::Sa4).unwrap(); //! sensor.set_pulse_amplitude(Led::All, 15).unwrap(); //! sensor.enable_fifo_rollover().unwrap(); //! let mut data = [0; 3]; //! let samples_read = sensor.read_fifo(&mut data).unwrap(); //! //! // get the I2C device back //! let dev = sensor.destroy(); //! # } //! ``` //! //! ### Set led slots in multi-led mode //! //! ```no_run //! extern crate linux_embedded_hal as hal; //! extern crate max3010x; //! use max3010x::{ Max3010x, Led, TimeSlot }; //! //! # fn main() { //! let dev = hal::I2cdev::new("/dev/i2c-1").unwrap(); //! let mut max30102 = Max3010x::new_max30102(dev); //! let mut max30102 = max30102.into_multi_led().unwrap(); //! max30102.set_pulse_amplitude(Led::All, 15).unwrap(); //! max30102.set_led_time_slots([ //! TimeSlot::Led1, //! TimeSlot::Led2, //! TimeSlot::Led1, //! TimeSlot::Disabled //! ]).unwrap(); //! max30102.enable_fifo_rollover().unwrap(); //! let mut data = [0; 2]; //! let samples_read = max30102.read_fifo(&mut data).unwrap(); //! //! // get the I2C device back //! let dev = max30102.destroy(); //! # } //! ``` //! #![deny(missing_docs, unsafe_code)] #![no_std] extern crate embedded_hal as hal; use hal::blocking::i2c; extern crate nb; use core::marker::PhantomData; /// All possible errors in this crate #[derive(Debug)] pub enum Error<E> { /// I²C bus error I2C(E), /// Invalid arguments provided InvalidArguments, } /// LEDs #[derive(Debug, Clone, Copy, PartialEq)] pub enum Led { /// LED1 corresponds to Red in MAX30102 Led1, /// LED1 corresponds to IR in MAX30102 Led2, /// Select all available LEDs in the device All, } /// Multi-LED mode sample time slot configuration #[derive(Debug, Clone, Copy, PartialEq)] pub enum TimeSlot { /// Time slot is disabled Disabled, /// LED 1 active during time slot (corresponds to Red in MAX30102) Led1, /// LED 2 active during time slot (corresponds to IR in MAX30102) Led2, } /// Sample averaging #[derive(Debug, Clone, Copy, PartialEq)] pub enum SampleAveraging { /// 1 (no averaging) (default) Sa1, /// 2 Sa2, /// 4 Sa4, /// 8 Sa8, /// 16 Sa16, /// 32 Sa32, } /// Number of empty data samples when the FIFO almost full interrupt is issued. #[derive(Debug, Clone, Copy, PartialEq)] pub enum FifoAlmostFullLevelInterrupt { /// Interrupt issue when 0 spaces are left in FIFO. (default) L0, /// Interrupt issue when 1 space is left in FIFO. L1, /// Interrupt issue when 2 spaces are left in FIFO. L2, /// Interrupt issue when 3 spaces are left in FIFO. L3, /// Interrupt issue when 4 spaces are left in FIFO. L4, /// Interrupt issue when 5 spaces are left in FIFO. L5, /// Interrupt issue when 6 spaces are left in FIFO. L6, /// Interrupt issue when 7 spaces are left in FIFO. L7, /// Interrupt issue when 8 spaces are left in FIFO. L8, /// Interrupt issue when 9 spaces are left in FIFO. L9, /// Interrupt issue when 10 spaces are left in FIFO. L10, /// Interrupt issue when 11 spaces are left in FIFO. L11, /// Interrupt issue when 12 spaces are left in FIFO. L12, /// Interrupt issue when 13 spaces are left in FIFO. L13, /// Interrupt issue when 14 spaces are left in FIFO. L14, /// Interrupt issue when 15 spaces are left in FIFO. L15, } /// LED pulse width (determines ADC resolution) /// /// This is limited by the current mode and the selected sample rate. #[derive(Debug, Clone, Copy, PartialEq)] pub enum LedPulseWidth { /// 69 μs pulse width (15-bit ADC resolution) Pw69, /// 118 μs pulse width (16-bit ADC resolution) Pw118, /// 215 μs pulse width (17-bit ADC resolution) Pw215, /// 411 μs pulse width (18-bit ADC resolution) Pw411, } /// Sampling rate /// /// This is limited by the current mode and the selected LED pulse width. #[derive(Debug, Clone, Copy, PartialEq)] pub enum SamplingRate { /// 50 samples per second Sps50, /// 100 samples per second Sps100, /// 200 samples per second Sps200, /// 400 samples per second Sps400, /// 800 samples per second Sps800, /// 1000 samples per second Sps1000, /// 1600 samples per second Sps1600, /// 3200 samples per second Sps3200, } /// ADC range #[derive(Debug, Clone, Copy, PartialEq)] pub enum AdcRange { /// Full scale 2048 nA Fs2k, /// Full scale 4094 nA Fs4k, /// Full scale 8192 nA Fs8k, /// Full scale 16394 nA Fs16k, } /// Interrupt status flags #[derive(Debug, Clone, Copy)] pub struct InterruptStatus { /// Power ready interrupt pub power_ready: bool, /// FIFO almost full interrupt pub fifo_almost_full: bool, /// New FIFO data ready interrupt pub new_fifo_data_ready: bool, /// Ambient light cancellation overflow interrupt
pub alc_overflow: bool, /// Internal die temperature conversion ready interrupt pub temperature_ready: bool, }
random_line_split
grpc.go
GrpcClient, error) { var descSource grpcurl.DescriptorSource if addr == "" { return nil, fmt.Errorf("addr should not be empty") } conn, err := grpc.Dial(addr, opts...) if err != nil { return nil, fmt.Errorf("did not connect: %v", err) } if len(protos) > 0 { descSource, err := grpcurl.DescriptorSourceFromProtoFiles([]string{}, protos...) if err != nil { return nil, fmt.Errorf("cannot parse proto file: %v", err) } return &GrpcClient{addr: addr, conn: conn, desc: descSource}, nil }
c := rpb.NewServerReflectionClient(conn) refClient := grpcreflect.NewClient(clientCTX, c) descSource = grpcurl.DescriptorSourceFromServer(clientCTX, refClient) return &GrpcClient{addr: addr, conn: conn, desc: descSource}, nil } func (gc *GrpcClient) ListServices() ([]string, error) { svcs, err := grpcurl.ListServices(gc.desc) if err != nil { return nil, err } return svcs, nil } func (gc *GrpcClient) ListMethods(svcName string) ([]string, error) { mtds, err := grpcurl.ListMethods(gc.desc, svcName) if err != nil { return nil, err } return mtds, nil } func (gc *GrpcClient) Close() error { if gc.conn == nil { return nil } return gc.conn.Close() } type rpcResponse struct { messages []bytes.Buffer } func (rr *rpcResponse) Write(p []byte) (int, error) { var msg bytes.Buffer n, err := msg.Write(p) rr.messages = append(rr.messages, msg) return n, err } func (rr *rpcResponse) ToJSON() (interface{}, error) { switch len(rr.messages) { case 0: return map[string]interface{}{}, nil case 1: resp := make(map[string]interface{}) if err := json.Unmarshal(rr.messages[0].Bytes(), &resp); err != nil { return nil, err } return resp, nil default: resp := make([]map[string]interface{}, len(rr.messages)) for idx, msg := range rr.messages { oneResp := make(map[string]interface{}) if err := json.Unmarshal(msg.Bytes(), &oneResp); err != nil { return nil, err } resp[idx] = oneResp } return resp, nil } } func (gc *GrpcClient) InvokeRPC(mtdName string, reqData interface{}) (interface{}, error) { var in bytes.Buffer var out = rpcResponse{messages: []bytes.Buffer{}} switch reflect.TypeOf(reqData).Kind() { case reflect.Slice: for _, data := range reqData.([]map[string]interface{}) { reqBytes, err := json.Marshal(data) if err != nil { return nil, err } in.Write(reqBytes) } case reflect.Map: reqBytes, err := json.Marshal(reqData) if err != nil { return nil, err } in.Write(reqBytes) default: in.WriteString(reqData.(string)) } rf, formatter, err := grpcurl.RequestParserAndFormatterFor(grpcurl.FormatJSON, gc.desc, true, false, &in) if err != nil { return nil, err } h := grpcurl.NewDefaultEventHandler(&out, gc.desc, formatter, false) if err = grpcurl.InvokeRPC(clientCTX, gc.desc, gc.conn, mtdName, []string{}, h, rf.Next); err != nil { return nil, err } return out.ToJSON() } // ================================== server ================================== type GrpcServer struct { addr string desc grpcurl.DescriptorSource server *grpc.Server handlerM map[string]func(in *dynamic.Message, out *dynamic.Message, stream grpc.ServerStream) error listeners []func(mtd, direction, from, to, body string) error } // create a new grpc server func NewGrpcServer(addr string, protos []string, opts ...grpc.ServerOption) (*GrpcServer, error) { descFromProto, err := grpcurl.DescriptorSourceFromProtoFiles([]string{}, protos...) if err != nil { return nil, fmt.Errorf("cannot parse proto file: %v", err) } gs := &GrpcServer{ addr: addr, desc: descFromProto, server: grpc.NewServer(opts...), handlerM: map[string]func(in *dynamic.Message, out *dynamic.Message, stream grpc.ServerStream) error{}, } gs.server = grpc.NewServer() services, err := grpcurl.ListServices(gs.desc) if err != nil { return nil, fmt.Errorf("failed to list services") } for _, svcName := range services { dsc, err := gs.desc.FindSymbol(svcName) if err != nil { return nil, fmt.Errorf("unable to find service: %s, error: %v", svcName, err) } sd := dsc.(*desc.ServiceDescriptor) unaryMethods := []grpc.MethodDesc{} streamMethods := []grpc.StreamDesc{} for _, mtd := range sd.GetMethods() { logger.Debugf("protocols/grpc", "try to add method: %v of service: %s", mtd, svcName) if mtd.IsClientStreaming() || mtd.IsServerStreaming() { streamMethods = append(streamMethods, grpc.StreamDesc{ StreamName: mtd.GetName(), Handler: gs.getStreamHandler(mtd), ServerStreams: mtd.IsServerStreaming(), ClientStreams: mtd.IsClientStreaming(), }) } else { unaryMethods = append(unaryMethods, grpc.MethodDesc{ MethodName: mtd.GetName(), Handler: gs.getUnaryHandler(mtd), }) } } svcDesc := grpc.ServiceDesc{ ServiceName: svcName, HandlerType: (*interface{})(nil), Methods: unaryMethods, Streams: streamMethods, Metadata: sd.GetFile().GetName(), } gs.server.RegisterService(&svcDesc, &mockServer{}) } return gs, nil } func (gs *GrpcServer) Start() error { lis, err := net.Listen("tcp", gs.addr) if err != nil { return err } logger.Infof("protocols/grpc", "server listening at %v", lis.Addr()) go func() { if err := gs.server.Serve(lis); err != nil { logger.Errorf("protocols/grpc", "failed to serve: %v", err) } }() return nil } func (gs *GrpcServer) Close() error { if gs.server != nil { gs.server.Stop() gs.server = nil gs.handlerM = map[string]func(in *dynamic.Message, out *dynamic.Message, stream grpc.ServerStream) error{} logger.Infof("protocols/grpc", "grpc server %s stopped", gs.addr) } return nil } func (gs *GrpcServer) AddListener(listener func(mtd, direction, from, to, body string) error) { gs.listeners = append(gs.listeners, listener) logger.Infof("protocols/grpc", "new listener added, now %d listeners", len(gs.listeners)) } // set specified method handler, one method only have one handler, it's the highest priority // if you want to return error, see https://github.com/avinassh/grpc-errors/blob/master/go/server.go // NOTE: thread unsafe, use lock in ops level func (gs *GrpcServer) SetMethodHandler(mtd string, handler func(in *dynamic.Message, out *dynamic.Message, stream grpc.ServerStream) error) error { if _, exists := gs.handlerM[mtd]; exists { logger.Warnf("protocols/grpc", "handler for method %s exists, will be overrided", mtd) } gs.handlerM[mtd] = handler return nil } // NOTE: thread unsafe, use lock in ops level func (gs *GrpcServer) RemoveMethodHandler(mtd string) error { if _, exists := gs.handlerM[mtd]; exists { delete(gs.handlerM, mtd) } return nil } func (gs *GrpcServer) ListMethods() ([]string, error) { methods := []string{} services, err := grpcurl.ListServices(gs.desc) if err != nil { return nil, fmt.Errorf("failed to list services") } for _, svcName := range services { dsc, err := gs.desc.FindSymbol(svcName) if err != nil { return nil, fmt.Errorf("unable to find service: %s, error: %v", svcName, err) } sd := dsc.(*desc.ServiceDescriptor) for _, mtd := range sd.GetMethods() { methods = append(methods, mtd.GetFullyQualifiedName()) } } return methods, nil } func (gs *GrpcServer) getMethodHandler(mtd string) (func(in *dynamic.Message, out *dynamic.Message, stream grpc.ServerStream) error, error) { handler, ok := gs.handlerM
// fetch from server reflection RPC
random_line_split
grpc.go
GrpcClient, error) { var descSource grpcurl.DescriptorSource if addr == "" { return nil, fmt.Errorf("addr should not be empty") } conn, err := grpc.Dial(addr, opts...) if err != nil { return nil, fmt.Errorf("did not connect: %v", err) } if len(protos) > 0 { descSource, err := grpcurl.DescriptorSourceFromProtoFiles([]string{}, protos...) if err != nil { return nil, fmt.Errorf("cannot parse proto file: %v", err) } return &GrpcClient{addr: addr, conn: conn, desc: descSource}, nil } // fetch from server reflection RPC c := rpb.NewServerReflectionClient(conn) refClient := grpcreflect.NewClient(clientCTX, c) descSource = grpcurl.DescriptorSourceFromServer(clientCTX, refClient) return &GrpcClient{addr: addr, conn: conn, desc: descSource}, nil } func (gc *GrpcClient) ListServices() ([]string, error) { svcs, err := grpcurl.ListServices(gc.desc) if err != nil { return nil, err } return svcs, nil } func (gc *GrpcClient) ListMethods(svcName string) ([]string, error) { mtds, err := grpcurl.ListMethods(gc.desc, svcName) if err != nil { return nil, err } return mtds, nil } func (gc *GrpcClient) Close() error { if gc.conn == nil { return nil } return gc.conn.Close() } type rpcResponse struct { messages []bytes.Buffer } func (rr *rpcResponse) Write(p []byte) (int, error) { var msg bytes.Buffer n, err := msg.Write(p) rr.messages = append(rr.messages, msg) return n, err } func (rr *rpcResponse) ToJSON() (interface{}, error) { switch len(rr.messages) { case 0: return map[string]interface{}{}, nil case 1: resp := make(map[string]interface{}) if err := json.Unmarshal(rr.messages[0].Bytes(), &resp); err != nil { return nil, err } return resp, nil default: resp := make([]map[string]interface{}, len(rr.messages)) for idx, msg := range rr.messages { oneResp := make(map[string]interface{}) if err := json.Unmarshal(msg.Bytes(), &oneResp); err != nil { return nil, err } resp[idx] = oneResp } return resp, nil } } func (gc *GrpcClient) InvokeRPC(mtdName string, reqData interface{}) (interface{}, error) { var in bytes.Buffer var out = rpcResponse{messages: []bytes.Buffer{}} switch reflect.TypeOf(reqData).Kind() { case reflect.Slice: for _, data := range reqData.([]map[string]interface{}) { reqBytes, err := json.Marshal(data) if err != nil { return nil, err } in.Write(reqBytes) } case reflect.Map: reqBytes, err := json.Marshal(reqData) if err != nil { return nil, err } in.Write(reqBytes) default: in.WriteString(reqData.(string)) } rf, formatter, err := grpcurl.RequestParserAndFormatterFor(grpcurl.FormatJSON, gc.desc, true, false, &in) if err != nil { return nil, err } h := grpcurl.NewDefaultEventHandler(&out, gc.desc, formatter, false) if err = grpcurl.InvokeRPC(clientCTX, gc.desc, gc.conn, mtdName, []string{}, h, rf.Next); err != nil { return nil, err } return out.ToJSON() } // ================================== server ================================== type GrpcServer struct { addr string desc grpcurl.DescriptorSource server *grpc.Server handlerM map[string]func(in *dynamic.Message, out *dynamic.Message, stream grpc.ServerStream) error listeners []func(mtd, direction, from, to, body string) error } // create a new grpc server func NewGrpcServer(addr string, protos []string, opts ...grpc.ServerOption) (*GrpcServer, error) { descFromProto, err := grpcurl.DescriptorSourceFromProtoFiles([]string{}, protos...) if err != nil { return nil, fmt.Errorf("cannot parse proto file: %v", err) } gs := &GrpcServer{ addr: addr, desc: descFromProto, server: grpc.NewServer(opts...), handlerM: map[string]func(in *dynamic.Message, out *dynamic.Message, stream grpc.ServerStream) error{}, } gs.server = grpc.NewServer() services, err := grpcurl.ListServices(gs.desc) if err != nil { return nil, fmt.Errorf("failed to list services") } for _, svcName := range services { dsc, err := gs.desc.FindSymbol(svcName) if err != nil { return nil, fmt.Errorf("unable to find service: %s, error: %v", svcName, err) } sd := dsc.(*desc.ServiceDescriptor) unaryMethods := []grpc.MethodDesc{} streamMethods := []grpc.StreamDesc{} for _, mtd := range sd.GetMethods() { logger.Debugf("protocols/grpc", "try to add method: %v of service: %s", mtd, svcName) if mtd.IsClientStreaming() || mtd.IsServerStreaming() { streamMethods = append(streamMethods, grpc.StreamDesc{ StreamName: mtd.GetName(), Handler: gs.getStreamHandler(mtd), ServerStreams: mtd.IsServerStreaming(), ClientStreams: mtd.IsClientStreaming(), }) } else { unaryMethods = append(unaryMethods, grpc.MethodDesc{ MethodName: mtd.GetName(), Handler: gs.getUnaryHandler(mtd), }) } } svcDesc := grpc.ServiceDesc{ ServiceName: svcName, HandlerType: (*interface{})(nil), Methods: unaryMethods, Streams: streamMethods, Metadata: sd.GetFile().GetName(), } gs.server.RegisterService(&svcDesc, &mockServer{}) } return gs, nil } func (gs *GrpcServer) Start() error { lis, err := net.Listen("tcp", gs.addr) if err != nil { return err } logger.Infof("protocols/grpc", "server listening at %v", lis.Addr()) go func() { if err := gs.server.Serve(lis); err != nil { logger.Errorf("protocols/grpc", "failed to serve: %v", err) } }() return nil } func (gs *GrpcServer) Close() error { if gs.server != nil { gs.server.Stop() gs.server = nil gs.handlerM = map[string]func(in *dynamic.Message, out *dynamic.Message, stream grpc.ServerStream) error{} logger.Infof("protocols/grpc", "grpc server %s stopped", gs.addr) } return nil } func (gs *GrpcServer) AddListener(listener func(mtd, direction, from, to, body string) error) { gs.listeners = append(gs.listeners, listener) logger.Infof("protocols/grpc", "new listener added, now %d listeners", len(gs.listeners)) } // set specified method handler, one method only have one handler, it's the highest priority // if you want to return error, see https://github.com/avinassh/grpc-errors/blob/master/go/server.go // NOTE: thread unsafe, use lock in ops level func (gs *GrpcServer)
(mtd string, handler func(in *dynamic.Message, out *dynamic.Message, stream grpc.ServerStream) error) error { if _, exists := gs.handlerM[mtd]; exists { logger.Warnf("protocols/grpc", "handler for method %s exists, will be overrided", mtd) } gs.handlerM[mtd] = handler return nil } // NOTE: thread unsafe, use lock in ops level func (gs *GrpcServer) RemoveMethodHandler(mtd string) error { if _, exists := gs.handlerM[mtd]; exists { delete(gs.handlerM, mtd) } return nil } func (gs *GrpcServer) ListMethods() ([]string, error) { methods := []string{} services, err := grpcurl.ListServices(gs.desc) if err != nil { return nil, fmt.Errorf("failed to list services") } for _, svcName := range services { dsc, err := gs.desc.FindSymbol(svcName) if err != nil { return nil, fmt.Errorf("unable to find service: %s, error: %v", svcName, err) } sd := dsc.(*desc.ServiceDescriptor) for _, mtd := range sd.GetMethods() { methods = append(methods, mtd.GetFullyQualifiedName()) } } return methods, nil } func (gs *GrpcServer) getMethodHandler(mtd string) (func(in *dynamic.Message, out *dynamic.Message, stream grpc.ServerStream) error, error) { handler, ok := gs.handler
SetMethodHandler
identifier_name
grpc.go
GrpcClient, error) { var descSource grpcurl.DescriptorSource if addr == "" { return nil, fmt.Errorf("addr should not be empty") } conn, err := grpc.Dial(addr, opts...) if err != nil { return nil, fmt.Errorf("did not connect: %v", err) } if len(protos) > 0 { descSource, err := grpcurl.DescriptorSourceFromProtoFiles([]string{}, protos...) if err != nil { return nil, fmt.Errorf("cannot parse proto file: %v", err) } return &GrpcClient{addr: addr, conn: conn, desc: descSource}, nil } // fetch from server reflection RPC c := rpb.NewServerReflectionClient(conn) refClient := grpcreflect.NewClient(clientCTX, c) descSource = grpcurl.DescriptorSourceFromServer(clientCTX, refClient) return &GrpcClient{addr: addr, conn: conn, desc: descSource}, nil } func (gc *GrpcClient) ListServices() ([]string, error) { svcs, err := grpcurl.ListServices(gc.desc) if err != nil { return nil, err } return svcs, nil } func (gc *GrpcClient) ListMethods(svcName string) ([]string, error) { mtds, err := grpcurl.ListMethods(gc.desc, svcName) if err != nil { return nil, err } return mtds, nil } func (gc *GrpcClient) Close() error { if gc.conn == nil { return nil } return gc.conn.Close() } type rpcResponse struct { messages []bytes.Buffer } func (rr *rpcResponse) Write(p []byte) (int, error) { var msg bytes.Buffer n, err := msg.Write(p) rr.messages = append(rr.messages, msg) return n, err } func (rr *rpcResponse) ToJSON() (interface{}, error) { switch len(rr.messages) { case 0: return map[string]interface{}{}, nil case 1: resp := make(map[string]interface{}) if err := json.Unmarshal(rr.messages[0].Bytes(), &resp); err != nil { return nil, err } return resp, nil default: resp := make([]map[string]interface{}, len(rr.messages)) for idx, msg := range rr.messages { oneResp := make(map[string]interface{}) if err := json.Unmarshal(msg.Bytes(), &oneResp); err != nil { return nil, err } resp[idx] = oneResp } return resp, nil } } func (gc *GrpcClient) InvokeRPC(mtdName string, reqData interface{}) (interface{}, error) { var in bytes.Buffer var out = rpcResponse{messages: []bytes.Buffer{}} switch reflect.TypeOf(reqData).Kind() { case reflect.Slice: for _, data := range reqData.([]map[string]interface{}) { reqBytes, err := json.Marshal(data) if err != nil { return nil, err } in.Write(reqBytes) } case reflect.Map: reqBytes, err := json.Marshal(reqData) if err != nil { return nil, err } in.Write(reqBytes) default: in.WriteString(reqData.(string)) } rf, formatter, err := grpcurl.RequestParserAndFormatterFor(grpcurl.FormatJSON, gc.desc, true, false, &in) if err != nil { return nil, err } h := grpcurl.NewDefaultEventHandler(&out, gc.desc, formatter, false) if err = grpcurl.InvokeRPC(clientCTX, gc.desc, gc.conn, mtdName, []string{}, h, rf.Next); err != nil { return nil, err } return out.ToJSON() } // ================================== server ================================== type GrpcServer struct { addr string desc grpcurl.DescriptorSource server *grpc.Server handlerM map[string]func(in *dynamic.Message, out *dynamic.Message, stream grpc.ServerStream) error listeners []func(mtd, direction, from, to, body string) error } // create a new grpc server func NewGrpcServer(addr string, protos []string, opts ...grpc.ServerOption) (*GrpcServer, error)
return nil, fmt.Errorf("unable to find service: %s, error: %v", svcName, err) } sd := dsc.(*desc.ServiceDescriptor) unaryMethods := []grpc.MethodDesc{} streamMethods := []grpc.StreamDesc{} for _, mtd := range sd.GetMethods() { logger.Debugf("protocols/grpc", "try to add method: %v of service: %s", mtd, svcName) if mtd.IsClientStreaming() || mtd.IsServerStreaming() { streamMethods = append(streamMethods, grpc.StreamDesc{ StreamName: mtd.GetName(), Handler: gs.getStreamHandler(mtd), ServerStreams: mtd.IsServerStreaming(), ClientStreams: mtd.IsClientStreaming(), }) } else { unaryMethods = append(unaryMethods, grpc.MethodDesc{ MethodName: mtd.GetName(), Handler: gs.getUnaryHandler(mtd), }) } } svcDesc := grpc.ServiceDesc{ ServiceName: svcName, HandlerType: (*interface{})(nil), Methods: unaryMethods, Streams: streamMethods, Metadata: sd.GetFile().GetName(), } gs.server.RegisterService(&svcDesc, &mockServer{}) } return gs, nil } func (gs *GrpcServer) Start() error { lis, err := net.Listen("tcp", gs.addr) if err != nil { return err } logger.Infof("protocols/grpc", "server listening at %v", lis.Addr()) go func() { if err := gs.server.Serve(lis); err != nil { logger.Errorf("protocols/grpc", "failed to serve: %v", err) } }() return nil } func (gs *GrpcServer) Close() error { if gs.server != nil { gs.server.Stop() gs.server = nil gs.handlerM = map[string]func(in *dynamic.Message, out *dynamic.Message, stream grpc.ServerStream) error{} logger.Infof("protocols/grpc", "grpc server %s stopped", gs.addr) } return nil } func (gs *GrpcServer) AddListener(listener func(mtd, direction, from, to, body string) error) { gs.listeners = append(gs.listeners, listener) logger.Infof("protocols/grpc", "new listener added, now %d listeners", len(gs.listeners)) } // set specified method handler, one method only have one handler, it's the highest priority // if you want to return error, see https://github.com/avinassh/grpc-errors/blob/master/go/server.go // NOTE: thread unsafe, use lock in ops level func (gs *GrpcServer) SetMethodHandler(mtd string, handler func(in *dynamic.Message, out *dynamic.Message, stream grpc.ServerStream) error) error { if _, exists := gs.handlerM[mtd]; exists { logger.Warnf("protocols/grpc", "handler for method %s exists, will be overrided", mtd) } gs.handlerM[mtd] = handler return nil } // NOTE: thread unsafe, use lock in ops level func (gs *GrpcServer) RemoveMethodHandler(mtd string) error { if _, exists := gs.handlerM[mtd]; exists { delete(gs.handlerM, mtd) } return nil } func (gs *GrpcServer) ListMethods() ([]string, error) { methods := []string{} services, err := grpcurl.ListServices(gs.desc) if err != nil { return nil, fmt.Errorf("failed to list services") } for _, svcName := range services { dsc, err := gs.desc.FindSymbol(svcName) if err != nil { return nil, fmt.Errorf("unable to find service: %s, error: %v", svcName, err) } sd := dsc.(*desc.ServiceDescriptor) for _, mtd := range sd.GetMethods() { methods = append(methods, mtd.GetFullyQualifiedName()) } } return methods, nil } func (gs *GrpcServer) getMethodHandler(mtd string) (func(in *dynamic.Message, out *dynamic.Message, stream grpc.ServerStream) error, error) { handler, ok := gs.handler
{ descFromProto, err := grpcurl.DescriptorSourceFromProtoFiles([]string{}, protos...) if err != nil { return nil, fmt.Errorf("cannot parse proto file: %v", err) } gs := &GrpcServer{ addr: addr, desc: descFromProto, server: grpc.NewServer(opts...), handlerM: map[string]func(in *dynamic.Message, out *dynamic.Message, stream grpc.ServerStream) error{}, } gs.server = grpc.NewServer() services, err := grpcurl.ListServices(gs.desc) if err != nil { return nil, fmt.Errorf("failed to list services") } for _, svcName := range services { dsc, err := gs.desc.FindSymbol(svcName) if err != nil {
identifier_body
grpc.go
GrpcClient, error) { var descSource grpcurl.DescriptorSource if addr == "" { return nil, fmt.Errorf("addr should not be empty") } conn, err := grpc.Dial(addr, opts...) if err != nil { return nil, fmt.Errorf("did not connect: %v", err) } if len(protos) > 0 { descSource, err := grpcurl.DescriptorSourceFromProtoFiles([]string{}, protos...) if err != nil { return nil, fmt.Errorf("cannot parse proto file: %v", err) } return &GrpcClient{addr: addr, conn: conn, desc: descSource}, nil } // fetch from server reflection RPC c := rpb.NewServerReflectionClient(conn) refClient := grpcreflect.NewClient(clientCTX, c) descSource = grpcurl.DescriptorSourceFromServer(clientCTX, refClient) return &GrpcClient{addr: addr, conn: conn, desc: descSource}, nil } func (gc *GrpcClient) ListServices() ([]string, error) { svcs, err := grpcurl.ListServices(gc.desc) if err != nil { return nil, err } return svcs, nil } func (gc *GrpcClient) ListMethods(svcName string) ([]string, error) { mtds, err := grpcurl.ListMethods(gc.desc, svcName) if err != nil { return nil, err } return mtds, nil } func (gc *GrpcClient) Close() error { if gc.conn == nil { return nil } return gc.conn.Close() } type rpcResponse struct { messages []bytes.Buffer } func (rr *rpcResponse) Write(p []byte) (int, error) { var msg bytes.Buffer n, err := msg.Write(p) rr.messages = append(rr.messages, msg) return n, err } func (rr *rpcResponse) ToJSON() (interface{}, error) { switch len(rr.messages) { case 0: return map[string]interface{}{}, nil case 1: resp := make(map[string]interface{}) if err := json.Unmarshal(rr.messages[0].Bytes(), &resp); err != nil { return nil, err } return resp, nil default: resp := make([]map[string]interface{}, len(rr.messages)) for idx, msg := range rr.messages { oneResp := make(map[string]interface{}) if err := json.Unmarshal(msg.Bytes(), &oneResp); err != nil { return nil, err } resp[idx] = oneResp } return resp, nil } } func (gc *GrpcClient) InvokeRPC(mtdName string, reqData interface{}) (interface{}, error) { var in bytes.Buffer var out = rpcResponse{messages: []bytes.Buffer{}} switch reflect.TypeOf(reqData).Kind() { case reflect.Slice: for _, data := range reqData.([]map[string]interface{}) { reqBytes, err := json.Marshal(data) if err != nil { return nil, err } in.Write(reqBytes) } case reflect.Map: reqBytes, err := json.Marshal(reqData) if err != nil { return nil, err } in.Write(reqBytes) default: in.WriteString(reqData.(string)) } rf, formatter, err := grpcurl.RequestParserAndFormatterFor(grpcurl.FormatJSON, gc.desc, true, false, &in) if err != nil { return nil, err } h := grpcurl.NewDefaultEventHandler(&out, gc.desc, formatter, false) if err = grpcurl.InvokeRPC(clientCTX, gc.desc, gc.conn, mtdName, []string{}, h, rf.Next); err != nil { return nil, err } return out.ToJSON() } // ================================== server ================================== type GrpcServer struct { addr string desc grpcurl.DescriptorSource server *grpc.Server handlerM map[string]func(in *dynamic.Message, out *dynamic.Message, stream grpc.ServerStream) error listeners []func(mtd, direction, from, to, body string) error } // create a new grpc server func NewGrpcServer(addr string, protos []string, opts ...grpc.ServerOption) (*GrpcServer, error) { descFromProto, err := grpcurl.DescriptorSourceFromProtoFiles([]string{}, protos...) if err != nil { return nil, fmt.Errorf("cannot parse proto file: %v", err) } gs := &GrpcServer{ addr: addr, desc: descFromProto, server: grpc.NewServer(opts...), handlerM: map[string]func(in *dynamic.Message, out *dynamic.Message, stream grpc.ServerStream) error{}, } gs.server = grpc.NewServer() services, err := grpcurl.ListServices(gs.desc) if err != nil { return nil, fmt.Errorf("failed to list services") } for _, svcName := range services { dsc, err := gs.desc.FindSymbol(svcName) if err != nil { return nil, fmt.Errorf("unable to find service: %s, error: %v", svcName, err) } sd := dsc.(*desc.ServiceDescriptor) unaryMethods := []grpc.MethodDesc{} streamMethods := []grpc.StreamDesc{} for _, mtd := range sd.GetMethods() { logger.Debugf("protocols/grpc", "try to add method: %v of service: %s", mtd, svcName) if mtd.IsClientStreaming() || mtd.IsServerStreaming() { streamMethods = append(streamMethods, grpc.StreamDesc{ StreamName: mtd.GetName(), Handler: gs.getStreamHandler(mtd), ServerStreams: mtd.IsServerStreaming(), ClientStreams: mtd.IsClientStreaming(), }) } else { unaryMethods = append(unaryMethods, grpc.MethodDesc{ MethodName: mtd.GetName(), Handler: gs.getUnaryHandler(mtd), }) } } svcDesc := grpc.ServiceDesc{ ServiceName: svcName, HandlerType: (*interface{})(nil), Methods: unaryMethods, Streams: streamMethods, Metadata: sd.GetFile().GetName(), } gs.server.RegisterService(&svcDesc, &mockServer{}) } return gs, nil } func (gs *GrpcServer) Start() error { lis, err := net.Listen("tcp", gs.addr) if err != nil { return err } logger.Infof("protocols/grpc", "server listening at %v", lis.Addr()) go func() { if err := gs.server.Serve(lis); err != nil { logger.Errorf("protocols/grpc", "failed to serve: %v", err) } }() return nil } func (gs *GrpcServer) Close() error { if gs.server != nil { gs.server.Stop() gs.server = nil gs.handlerM = map[string]func(in *dynamic.Message, out *dynamic.Message, stream grpc.ServerStream) error{} logger.Infof("protocols/grpc", "grpc server %s stopped", gs.addr) } return nil } func (gs *GrpcServer) AddListener(listener func(mtd, direction, from, to, body string) error) { gs.listeners = append(gs.listeners, listener) logger.Infof("protocols/grpc", "new listener added, now %d listeners", len(gs.listeners)) } // set specified method handler, one method only have one handler, it's the highest priority // if you want to return error, see https://github.com/avinassh/grpc-errors/blob/master/go/server.go // NOTE: thread unsafe, use lock in ops level func (gs *GrpcServer) SetMethodHandler(mtd string, handler func(in *dynamic.Message, out *dynamic.Message, stream grpc.ServerStream) error) error { if _, exists := gs.handlerM[mtd]; exists { logger.Warnf("protocols/grpc", "handler for method %s exists, will be overrided", mtd) } gs.handlerM[mtd] = handler return nil } // NOTE: thread unsafe, use lock in ops level func (gs *GrpcServer) RemoveMethodHandler(mtd string) error { if _, exists := gs.handlerM[mtd]; exists
return nil } func (gs *GrpcServer) ListMethods() ([]string, error) { methods := []string{} services, err := grpcurl.ListServices(gs.desc) if err != nil { return nil, fmt.Errorf("failed to list services") } for _, svcName := range services { dsc, err := gs.desc.FindSymbol(svcName) if err != nil { return nil, fmt.Errorf("unable to find service: %s, error: %v", svcName, err) } sd := dsc.(*desc.ServiceDescriptor) for _, mtd := range sd.GetMethods() { methods = append(methods, mtd.GetFullyQualifiedName()) } } return methods, nil } func (gs *GrpcServer) getMethodHandler(mtd string) (func(in *dynamic.Message, out *dynamic.Message, stream grpc.ServerStream) error, error) { handler, ok := gs
{ delete(gs.handlerM, mtd) }
conditional_block
asn1.rs
pub type MaxSize<C> = <<<C as elliptic_curve::Curve>::FieldSize as Add>::Output as Add<MaxOverhead>>::Output; /// Byte array containing a serialized ASN.1 signature type DocumentBytes<C> = GenericArray<u8, MaxSize<C>>; /// ASN.1 `INTEGER` tag const INTEGER_TAG: u8 = 0x02; /// ASN.1 `SEQUENCE` tag const SEQUENCE_TAG: u8 = 0x30; /// ASN.1 DER-encoded signature. /// /// Generic over the scalar size of the elliptic curve. pub struct Signature<C> where C: Curve, C::FieldSize: Add + ArrayLength<u8>, MaxSize<C>: ArrayLength<u8>, <C::FieldSize as Add>::Output: Add<MaxOverhead> + ArrayLength<u8>, { /// ASN.1 DER-encoded signature data bytes: DocumentBytes<C>, /// Range of the `r` value within the signature r_range: Range<usize>, /// Range of the `s` value within the signature s_range: Range<usize>, } impl<C> signature::Signature for Signature<C> where C: Curve, C::FieldSize: Add + ArrayLength<u8>, MaxSize<C>: ArrayLength<u8>, <C::FieldSize as Add>::Output: Add<MaxOverhead> + ArrayLength<u8>, { /// Parse an ASN.1 DER-encoded ECDSA signature from a byte slice fn from_bytes(bytes: &[u8]) -> Result<Self, Error> { bytes.try_into() } } #[allow(clippy::len_without_is_empty)] impl<C> Signature<C> where C: Curve, C::FieldSize: Add + ArrayLength<u8>, MaxSize<C>: ArrayLength<u8>, <C::FieldSize as Add>::Output: Add<MaxOverhead> + ArrayLength<u8>, { /// Get the length of the signature in bytes pub fn len(&self) -> usize { self.s_range.end } /// Borrow this signature as a byte slice pub fn
(&self) -> &[u8] { &self.bytes.as_slice()[..self.len()] } /// Serialize this signature as a boxed byte slice #[cfg(feature = "alloc")] pub fn to_bytes(&self) -> Box<[u8]> { self.as_bytes().to_vec().into_boxed_slice() } /// Create an ASN.1 DER encoded signature from big endian `r` and `s` scalars pub(crate) fn from_scalar_bytes(r: &[u8], s: &[u8]) -> Self { let r_len = int_length(r); let s_len = int_length(s); let scalar_size = C::FieldSize::to_usize(); let mut bytes = DocumentBytes::<C>::default(); // SEQUENCE header bytes[0] = SEQUENCE_TAG as u8; let zlen = r_len.checked_add(s_len).unwrap().checked_add(4).unwrap(); let offset = if zlen >= 0x80 { bytes[1] = 0x81; bytes[2] = zlen as u8; 3 } else { bytes[1] = zlen as u8; 2 }; // First INTEGER (r) serialize_int(r, &mut bytes[offset..], r_len, scalar_size); let r_end = offset.checked_add(2).unwrap().checked_add(r_len).unwrap(); // Second INTEGER (s) serialize_int(s, &mut bytes[r_end..], s_len, scalar_size); let s_end = r_end.checked_add(2).unwrap().checked_add(s_len).unwrap(); bytes[..s_end] .try_into() .expect("generated invalid ASN.1 DER") } /// Get the `r` component of the signature (leading zeros removed) pub(crate) fn r(&self) -> &[u8] { &self.bytes[self.r_range.clone()] } /// Get the `s` component of the signature (leading zeros removed) pub(crate) fn s(&self) -> &[u8] { &self.bytes[self.s_range.clone()] } } impl<C> AsRef<[u8]> for Signature<C> where C: Curve, C::FieldSize: Add + ArrayLength<u8>, MaxSize<C>: ArrayLength<u8>, <C::FieldSize as Add>::Output: Add<MaxOverhead> + ArrayLength<u8>, { fn as_ref(&self) -> &[u8] { self.as_bytes() } } impl<C> fmt::Debug for Signature<C> where C: Curve, C::FieldSize: Add + ArrayLength<u8>, MaxSize<C>: ArrayLength<u8>, <C::FieldSize as Add>::Output: Add<MaxOverhead> + ArrayLength<u8>, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("asn1::Signature") .field("r", &self.r()) .field("s", &self.s()) .finish() } } impl<C> TryFrom<&[u8]> for Signature<C> where C: Curve, C::FieldSize: Add + ArrayLength<u8>, MaxSize<C>: ArrayLength<u8>, <C::FieldSize as Add>::Output: Add<MaxOverhead> + ArrayLength<u8>, { type Error = Error; fn try_from(bytes: &[u8]) -> Result<Self, Error> { // Signature format is a SEQUENCE of two INTEGER values. We // support only integers of less than 127 bytes each (signed // encoding) so the resulting raw signature will have length // at most 254 bytes. // // First byte is SEQUENCE tag. if bytes[0] != SEQUENCE_TAG as u8 { return Err(Error::new()); } // The SEQUENCE length will be encoded over one or two bytes. We // limit the total SEQUENCE contents to 255 bytes, because it // makes things simpler; this is enough for subgroup orders up // to 999 bits. let mut zlen = bytes[1] as usize; let offset = if zlen > 0x80 { if zlen != 0x81 { return Err(Error::new()); } zlen = bytes[2] as usize; 3 } else { 2 }; if zlen != bytes.len().checked_sub(offset).unwrap() { return Err(Error::new()); } // First INTEGER (r) let r_range = parse_int(&bytes[offset..], C::FieldSize::to_usize())?; let r_start = offset.checked_add(r_range.start).unwrap(); let r_end = offset.checked_add(r_range.end).unwrap(); // Second INTEGER (s) let s_range = parse_int(&bytes[r_end..], C::FieldSize::to_usize())?; let s_start = r_end.checked_add(s_range.start).unwrap(); let s_end = r_end.checked_add(s_range.end).unwrap(); if s_end != bytes.as_ref().len() { return Err(Error::new()); } let mut byte_arr = DocumentBytes::<C>::default(); byte_arr[..s_end].copy_from_slice(bytes.as_ref()); Ok(Signature { bytes: byte_arr, r_range: Range { start: r_start, end: r_end, }, s_range: Range { start: s_start, end: s_end, }, }) } } #[cfg(all(feature = "digest", feature = "hazmat"))] impl<C> signature::PrehashSignature for Signature<C> where C: Curve + crate::hazmat::DigestPrimitive, C::FieldSize: Add + ArrayLength<u8>, MaxSize<C>: ArrayLength<u8>, <C::FieldSize as Add>::Output: Add<MaxOverhead> + ArrayLength<u8>, { type Digest = C::Digest; } /// Parse an integer from its ASN.1 DER serialization fn parse_int(bytes: &[u8], scalar_size: usize) -> Result<Range<usize>, Error> { if bytes.len() < 3 { return Err(Error::new()); } if bytes[0] != INTEGER_TAG as u8 { return Err(Error::new()); } let len = bytes[1] as usize; if len >= 0x80 || len.checked_add(2).unwrap() > bytes.len() { return Err(Error::new()); } let mut start = 2usize; let end = start.checked_add(len).unwrap(); start = start .checked_add(trim_zeroes(&bytes[start..end], scalar_size)?) .unwrap(); Ok(Range { start, end }) } /// Serialize scalar as ASN.1 DER fn serialize_int(scalar: &[u8], out: &mut [u8], len: usize, scalar_size: usize) { out[0] = INTEGER_TAG as u8; out[1] = len as u8; if len > scalar_size { out[2] = 0x00
as_bytes
identifier_name
asn1.rs
pub type MaxSize<C> = <<<C as elliptic_curve::Curve>::FieldSize as Add>::Output as Add<MaxOverhead>>::Output; /// Byte array containing a serialized ASN.1 signature type DocumentBytes<C> = GenericArray<u8, MaxSize<C>>; /// ASN.1 `INTEGER` tag const INTEGER_TAG: u8 = 0x02; /// ASN.1 `SEQUENCE` tag const SEQUENCE_TAG: u8 = 0x30; /// ASN.1 DER-encoded signature. /// /// Generic over the scalar size of the elliptic curve. pub struct Signature<C> where C: Curve, C::FieldSize: Add + ArrayLength<u8>, MaxSize<C>: ArrayLength<u8>, <C::FieldSize as Add>::Output: Add<MaxOverhead> + ArrayLength<u8>, { /// ASN.1 DER-encoded signature data bytes: DocumentBytes<C>, /// Range of the `r` value within the signature r_range: Range<usize>, /// Range of the `s` value within the signature s_range: Range<usize>, } impl<C> signature::Signature for Signature<C> where C: Curve, C::FieldSize: Add + ArrayLength<u8>, MaxSize<C>: ArrayLength<u8>, <C::FieldSize as Add>::Output: Add<MaxOverhead> + ArrayLength<u8>, { /// Parse an ASN.1 DER-encoded ECDSA signature from a byte slice fn from_bytes(bytes: &[u8]) -> Result<Self, Error> { bytes.try_into() } } #[allow(clippy::len_without_is_empty)] impl<C> Signature<C> where C: Curve, C::FieldSize: Add + ArrayLength<u8>, MaxSize<C>: ArrayLength<u8>, <C::FieldSize as Add>::Output: Add<MaxOverhead> + ArrayLength<u8>, { /// Get the length of the signature in bytes pub fn len(&self) -> usize { self.s_range.end } /// Borrow this signature as a byte slice pub fn as_bytes(&self) -> &[u8] { &self.bytes.as_slice()[..self.len()] } /// Serialize this signature as a boxed byte slice #[cfg(feature = "alloc")] pub fn to_bytes(&self) -> Box<[u8]> { self.as_bytes().to_vec().into_boxed_slice() } /// Create an ASN.1 DER encoded signature from big endian `r` and `s` scalars pub(crate) fn from_scalar_bytes(r: &[u8], s: &[u8]) -> Self
serialize_int(r, &mut bytes[offset..], r_len, scalar_size); let r_end = offset.checked_add(2).unwrap().checked_add(r_len).unwrap(); // Second INTEGER (s) serialize_int(s, &mut bytes[r_end..], s_len, scalar_size); let s_end = r_end.checked_add(2).unwrap().checked_add(s_len).unwrap(); bytes[..s_end] .try_into() .expect("generated invalid ASN.1 DER") } /// Get the `r` component of the signature (leading zeros removed) pub(crate) fn r(&self) -> &[u8] { &self.bytes[self.r_range.clone()] } /// Get the `s` component of the signature (leading zeros removed) pub(crate) fn s(&self) -> &[u8] { &self.bytes[self.s_range.clone()] } } impl<C> AsRef<[u8]> for Signature<C> where C: Curve, C::FieldSize: Add + ArrayLength<u8>, MaxSize<C>: ArrayLength<u8>, <C::FieldSize as Add>::Output: Add<MaxOverhead> + ArrayLength<u8>, { fn as_ref(&self) -> &[u8] { self.as_bytes() } } impl<C> fmt::Debug for Signature<C> where C: Curve, C::FieldSize: Add + ArrayLength<u8>, MaxSize<C>: ArrayLength<u8>, <C::FieldSize as Add>::Output: Add<MaxOverhead> + ArrayLength<u8>, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("asn1::Signature") .field("r", &self.r()) .field("s", &self.s()) .finish() } } impl<C> TryFrom<&[u8]> for Signature<C> where C: Curve, C::FieldSize: Add + ArrayLength<u8>, MaxSize<C>: ArrayLength<u8>, <C::FieldSize as Add>::Output: Add<MaxOverhead> + ArrayLength<u8>, { type Error = Error; fn try_from(bytes: &[u8]) -> Result<Self, Error> { // Signature format is a SEQUENCE of two INTEGER values. We // support only integers of less than 127 bytes each (signed // encoding) so the resulting raw signature will have length // at most 254 bytes. // // First byte is SEQUENCE tag. if bytes[0] != SEQUENCE_TAG as u8 { return Err(Error::new()); } // The SEQUENCE length will be encoded over one or two bytes. We // limit the total SEQUENCE contents to 255 bytes, because it // makes things simpler; this is enough for subgroup orders up // to 999 bits. let mut zlen = bytes[1] as usize; let offset = if zlen > 0x80 { if zlen != 0x81 { return Err(Error::new()); } zlen = bytes[2] as usize; 3 } else { 2 }; if zlen != bytes.len().checked_sub(offset).unwrap() { return Err(Error::new()); } // First INTEGER (r) let r_range = parse_int(&bytes[offset..], C::FieldSize::to_usize())?; let r_start = offset.checked_add(r_range.start).unwrap(); let r_end = offset.checked_add(r_range.end).unwrap(); // Second INTEGER (s) let s_range = parse_int(&bytes[r_end..], C::FieldSize::to_usize())?; let s_start = r_end.checked_add(s_range.start).unwrap(); let s_end = r_end.checked_add(s_range.end).unwrap(); if s_end != bytes.as_ref().len() { return Err(Error::new()); } let mut byte_arr = DocumentBytes::<C>::default(); byte_arr[..s_end].copy_from_slice(bytes.as_ref()); Ok(Signature { bytes: byte_arr, r_range: Range { start: r_start, end: r_end, }, s_range: Range { start: s_start, end: s_end, }, }) } } #[cfg(all(feature = "digest", feature = "hazmat"))] impl<C> signature::PrehashSignature for Signature<C> where C: Curve + crate::hazmat::DigestPrimitive, C::FieldSize: Add + ArrayLength<u8>, MaxSize<C>: ArrayLength<u8>, <C::FieldSize as Add>::Output: Add<MaxOverhead> + ArrayLength<u8>, { type Digest = C::Digest; } /// Parse an integer from its ASN.1 DER serialization fn parse_int(bytes: &[u8], scalar_size: usize) -> Result<Range<usize>, Error> { if bytes.len() < 3 { return Err(Error::new()); } if bytes[0] != INTEGER_TAG as u8 { return Err(Error::new()); } let len = bytes[1] as usize; if len >= 0x80 || len.checked_add(2).unwrap() > bytes.len() { return Err(Error::new()); } let mut start = 2usize; let end = start.checked_add(len).unwrap(); start = start .checked_add(trim_zeroes(&bytes[start..end], scalar_size)?) .unwrap(); Ok(Range { start, end }) } /// Serialize scalar as ASN.1 DER fn serialize_int(scalar: &[u8], out: &mut [u8], len: usize, scalar_size: usize) { out[0] = INTEGER_TAG as u8; out[1] = len as u8; if len > scalar_size { out[2] = 0x00
{ let r_len = int_length(r); let s_len = int_length(s); let scalar_size = C::FieldSize::to_usize(); let mut bytes = DocumentBytes::<C>::default(); // SEQUENCE header bytes[0] = SEQUENCE_TAG as u8; let zlen = r_len.checked_add(s_len).unwrap().checked_add(4).unwrap(); let offset = if zlen >= 0x80 { bytes[1] = 0x81; bytes[2] = zlen as u8; 3 } else { bytes[1] = zlen as u8; 2 }; // First INTEGER (r)
identifier_body
asn1.rs
C::FieldSize as Add>::Output: Add<MaxOverhead> + ArrayLength<u8>, { /// Parse an ASN.1 DER-encoded ECDSA signature from a byte slice fn from_bytes(bytes: &[u8]) -> Result<Self, Error> { bytes.try_into() } } #[allow(clippy::len_without_is_empty)] impl<C> Signature<C> where C: Curve, C::FieldSize: Add + ArrayLength<u8>, MaxSize<C>: ArrayLength<u8>, <C::FieldSize as Add>::Output: Add<MaxOverhead> + ArrayLength<u8>, { /// Get the length of the signature in bytes pub fn len(&self) -> usize { self.s_range.end } /// Borrow this signature as a byte slice pub fn as_bytes(&self) -> &[u8] { &self.bytes.as_slice()[..self.len()] } /// Serialize this signature as a boxed byte slice #[cfg(feature = "alloc")] pub fn to_bytes(&self) -> Box<[u8]> { self.as_bytes().to_vec().into_boxed_slice() } /// Create an ASN.1 DER encoded signature from big endian `r` and `s` scalars pub(crate) fn from_scalar_bytes(r: &[u8], s: &[u8]) -> Self { let r_len = int_length(r); let s_len = int_length(s); let scalar_size = C::FieldSize::to_usize(); let mut bytes = DocumentBytes::<C>::default(); // SEQUENCE header bytes[0] = SEQUENCE_TAG as u8; let zlen = r_len.checked_add(s_len).unwrap().checked_add(4).unwrap(); let offset = if zlen >= 0x80 { bytes[1] = 0x81; bytes[2] = zlen as u8; 3 } else { bytes[1] = zlen as u8; 2 }; // First INTEGER (r) serialize_int(r, &mut bytes[offset..], r_len, scalar_size); let r_end = offset.checked_add(2).unwrap().checked_add(r_len).unwrap(); // Second INTEGER (s) serialize_int(s, &mut bytes[r_end..], s_len, scalar_size); let s_end = r_end.checked_add(2).unwrap().checked_add(s_len).unwrap(); bytes[..s_end] .try_into() .expect("generated invalid ASN.1 DER") } /// Get the `r` component of the signature (leading zeros removed) pub(crate) fn r(&self) -> &[u8] { &self.bytes[self.r_range.clone()] } /// Get the `s` component of the signature (leading zeros removed) pub(crate) fn s(&self) -> &[u8] { &self.bytes[self.s_range.clone()] } } impl<C> AsRef<[u8]> for Signature<C> where C: Curve, C::FieldSize: Add + ArrayLength<u8>, MaxSize<C>: ArrayLength<u8>, <C::FieldSize as Add>::Output: Add<MaxOverhead> + ArrayLength<u8>, { fn as_ref(&self) -> &[u8] { self.as_bytes() } } impl<C> fmt::Debug for Signature<C> where C: Curve, C::FieldSize: Add + ArrayLength<u8>, MaxSize<C>: ArrayLength<u8>, <C::FieldSize as Add>::Output: Add<MaxOverhead> + ArrayLength<u8>, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("asn1::Signature") .field("r", &self.r()) .field("s", &self.s()) .finish() } } impl<C> TryFrom<&[u8]> for Signature<C> where C: Curve, C::FieldSize: Add + ArrayLength<u8>, MaxSize<C>: ArrayLength<u8>, <C::FieldSize as Add>::Output: Add<MaxOverhead> + ArrayLength<u8>, { type Error = Error; fn try_from(bytes: &[u8]) -> Result<Self, Error> { // Signature format is a SEQUENCE of two INTEGER values. We // support only integers of less than 127 bytes each (signed // encoding) so the resulting raw signature will have length // at most 254 bytes. // // First byte is SEQUENCE tag. if bytes[0] != SEQUENCE_TAG as u8 { return Err(Error::new()); } // The SEQUENCE length will be encoded over one or two bytes. We // limit the total SEQUENCE contents to 255 bytes, because it // makes things simpler; this is enough for subgroup orders up // to 999 bits. let mut zlen = bytes[1] as usize; let offset = if zlen > 0x80 { if zlen != 0x81 { return Err(Error::new()); } zlen = bytes[2] as usize; 3 } else { 2 }; if zlen != bytes.len().checked_sub(offset).unwrap() { return Err(Error::new()); } // First INTEGER (r) let r_range = parse_int(&bytes[offset..], C::FieldSize::to_usize())?; let r_start = offset.checked_add(r_range.start).unwrap(); let r_end = offset.checked_add(r_range.end).unwrap(); // Second INTEGER (s) let s_range = parse_int(&bytes[r_end..], C::FieldSize::to_usize())?; let s_start = r_end.checked_add(s_range.start).unwrap(); let s_end = r_end.checked_add(s_range.end).unwrap(); if s_end != bytes.as_ref().len() { return Err(Error::new()); } let mut byte_arr = DocumentBytes::<C>::default(); byte_arr[..s_end].copy_from_slice(bytes.as_ref()); Ok(Signature { bytes: byte_arr, r_range: Range { start: r_start, end: r_end, }, s_range: Range { start: s_start, end: s_end, }, }) } } #[cfg(all(feature = "digest", feature = "hazmat"))] impl<C> signature::PrehashSignature for Signature<C> where C: Curve + crate::hazmat::DigestPrimitive, C::FieldSize: Add + ArrayLength<u8>, MaxSize<C>: ArrayLength<u8>, <C::FieldSize as Add>::Output: Add<MaxOverhead> + ArrayLength<u8>, { type Digest = C::Digest; } /// Parse an integer from its ASN.1 DER serialization fn parse_int(bytes: &[u8], scalar_size: usize) -> Result<Range<usize>, Error> { if bytes.len() < 3 { return Err(Error::new()); } if bytes[0] != INTEGER_TAG as u8 { return Err(Error::new()); } let len = bytes[1] as usize; if len >= 0x80 || len.checked_add(2).unwrap() > bytes.len() { return Err(Error::new()); } let mut start = 2usize; let end = start.checked_add(len).unwrap(); start = start .checked_add(trim_zeroes(&bytes[start..end], scalar_size)?) .unwrap(); Ok(Range { start, end }) } /// Serialize scalar as ASN.1 DER fn serialize_int(scalar: &[u8], out: &mut [u8], len: usize, scalar_size: usize) { out[0] = INTEGER_TAG as u8; out[1] = len as u8; if len > scalar_size { out[2] = 0x00; out[3..scalar_size.checked_add(3).unwrap()].copy_from_slice(scalar); } else { out[2..len.checked_add(2).unwrap()] .copy_from_slice(&scalar[scalar_size.checked_sub(len).unwrap()..]); } } /// Compute ASN.1 DER encoded length for the provided scalar. The ASN.1 /// encoding is signed, so its leading bit must have value 0; it must also be /// of minimal length (so leading bytes of value 0 must be removed, except if /// that would contradict the rule about the sign bit). fn int_length(mut x: &[u8]) -> usize { while !x.is_empty() && x[0] == 0 { x = &x[1..]; } if x.is_empty() || x[0] >= 0x80 { x.len().checked_add(1).unwrap() } else { x.len() } } /// Compute an offset within an ASN.1 INTEGER after skipping leading zeroes fn trim_zeroes(mut bytes: &[u8], scalar_size: usize) -> Result<usize, Error> { let mut offset = 0; if bytes.len() > scalar_size { if bytes.len() != scalar_size.checked_add(1).unwrap()
{ return Err(Error::new()); }
conditional_block
asn1.rs
pub type MaxSize<C> = <<<C as elliptic_curve::Curve>::FieldSize as Add>::Output as Add<MaxOverhead>>::Output; /// Byte array containing a serialized ASN.1 signature type DocumentBytes<C> = GenericArray<u8, MaxSize<C>>; /// ASN.1 `INTEGER` tag const INTEGER_TAG: u8 = 0x02; /// ASN.1 `SEQUENCE` tag const SEQUENCE_TAG: u8 = 0x30; /// ASN.1 DER-encoded signature. /// /// Generic over the scalar size of the elliptic curve. pub struct Signature<C> where C: Curve, C::FieldSize: Add + ArrayLength<u8>, MaxSize<C>: ArrayLength<u8>, <C::FieldSize as Add>::Output: Add<MaxOverhead> + ArrayLength<u8>, { /// ASN.1 DER-encoded signature data bytes: DocumentBytes<C>, /// Range of the `r` value within the signature r_range: Range<usize>, /// Range of the `s` value within the signature s_range: Range<usize>, } impl<C> signature::Signature for Signature<C> where C: Curve, C::FieldSize: Add + ArrayLength<u8>, MaxSize<C>: ArrayLength<u8>, <C::FieldSize as Add>::Output: Add<MaxOverhead> + ArrayLength<u8>, { /// Parse an ASN.1 DER-encoded ECDSA signature from a byte slice fn from_bytes(bytes: &[u8]) -> Result<Self, Error> { bytes.try_into() } } #[allow(clippy::len_without_is_empty)] impl<C> Signature<C> where C: Curve, C::FieldSize: Add + ArrayLength<u8>, MaxSize<C>: ArrayLength<u8>, <C::FieldSize as Add>::Output: Add<MaxOverhead> + ArrayLength<u8>, { /// Get the length of the signature in bytes pub fn len(&self) -> usize { self.s_range.end } /// Borrow this signature as a byte slice pub fn as_bytes(&self) -> &[u8] { &self.bytes.as_slice()[..self.len()] } /// Serialize this signature as a boxed byte slice #[cfg(feature = "alloc")] pub fn to_bytes(&self) -> Box<[u8]> { self.as_bytes().to_vec().into_boxed_slice() } /// Create an ASN.1 DER encoded signature from big endian `r` and `s` scalars pub(crate) fn from_scalar_bytes(r: &[u8], s: &[u8]) -> Self { let r_len = int_length(r); let s_len = int_length(s); let scalar_size = C::FieldSize::to_usize(); let mut bytes = DocumentBytes::<C>::default(); // SEQUENCE header bytes[0] = SEQUENCE_TAG as u8; let zlen = r_len.checked_add(s_len).unwrap().checked_add(4).unwrap(); let offset = if zlen >= 0x80 { bytes[1] = 0x81; bytes[2] = zlen as u8; 3 } else { bytes[1] = zlen as u8; 2 }; // First INTEGER (r) serialize_int(r, &mut bytes[offset..], r_len, scalar_size); let r_end = offset.checked_add(2).unwrap().checked_add(r_len).unwrap(); // Second INTEGER (s) serialize_int(s, &mut bytes[r_end..], s_len, scalar_size); let s_end = r_end.checked_add(2).unwrap().checked_add(s_len).unwrap(); bytes[..s_end] .try_into() .expect("generated invalid ASN.1 DER") } /// Get the `r` component of the signature (leading zeros removed) pub(crate) fn r(&self) -> &[u8] { &self.bytes[self.r_range.clone()] } /// Get the `s` component of the signature (leading zeros removed) pub(crate) fn s(&self) -> &[u8] { &self.bytes[self.s_range.clone()] } } impl<C> AsRef<[u8]> for Signature<C> where C: Curve, C::FieldSize: Add + ArrayLength<u8>, MaxSize<C>: ArrayLength<u8>, <C::FieldSize as Add>::Output: Add<MaxOverhead> + ArrayLength<u8>, { fn as_ref(&self) -> &[u8] { self.as_bytes() } } impl<C> fmt::Debug for Signature<C> where C: Curve, C::FieldSize: Add + ArrayLength<u8>, MaxSize<C>: ArrayLength<u8>, <C::FieldSize as Add>::Output: Add<MaxOverhead> + ArrayLength<u8>, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("asn1::Signature") .field("r", &self.r()) .field("s", &self.s()) .finish() } } impl<C> TryFrom<&[u8]> for Signature<C> where C: Curve, C::FieldSize: Add + ArrayLength<u8>, MaxSize<C>: ArrayLength<u8>, <C::FieldSize as Add>::Output: Add<MaxOverhead> + ArrayLength<u8>, { type Error = Error; fn try_from(bytes: &[u8]) -> Result<Self, Error> { // Signature format is a SEQUENCE of two INTEGER values. We // support only integers of less than 127 bytes each (signed // encoding) so the resulting raw signature will have length // at most 254 bytes. // // First byte is SEQUENCE tag. if bytes[0] != SEQUENCE_TAG as u8 { return Err(Error::new()); } // The SEQUENCE length will be encoded over one or two bytes. We // limit the total SEQUENCE contents to 255 bytes, because it // makes things simpler; this is enough for subgroup orders up // to 999 bits. let mut zlen = bytes[1] as usize; let offset = if zlen > 0x80 { if zlen != 0x81 { return Err(Error::new()); } zlen = bytes[2] as usize; 3 } else { 2 }; if zlen != bytes.len().checked_sub(offset).unwrap() { return Err(Error::new()); } // First INTEGER (r) let r_range = parse_int(&bytes[offset..], C::FieldSize::to_usize())?; let r_start = offset.checked_add(r_range.start).unwrap(); let r_end = offset.checked_add(r_range.end).unwrap(); // Second INTEGER (s)
if s_end != bytes.as_ref().len() { return Err(Error::new()); } let mut byte_arr = DocumentBytes::<C>::default(); byte_arr[..s_end].copy_from_slice(bytes.as_ref()); Ok(Signature { bytes: byte_arr, r_range: Range { start: r_start, end: r_end, }, s_range: Range { start: s_start, end: s_end, }, }) } } #[cfg(all(feature = "digest", feature = "hazmat"))] impl<C> signature::PrehashSignature for Signature<C> where C: Curve + crate::hazmat::DigestPrimitive, C::FieldSize: Add + ArrayLength<u8>, MaxSize<C>: ArrayLength<u8>, <C::FieldSize as Add>::Output: Add<MaxOverhead> + ArrayLength<u8>, { type Digest = C::Digest; } /// Parse an integer from its ASN.1 DER serialization fn parse_int(bytes: &[u8], scalar_size: usize) -> Result<Range<usize>, Error> { if bytes.len() < 3 { return Err(Error::new()); } if bytes[0] != INTEGER_TAG as u8 { return Err(Error::new()); } let len = bytes[1] as usize; if len >= 0x80 || len.checked_add(2).unwrap() > bytes.len() { return Err(Error::new()); } let mut start = 2usize; let end = start.checked_add(len).unwrap(); start = start .checked_add(trim_zeroes(&bytes[start..end], scalar_size)?) .unwrap(); Ok(Range { start, end }) } /// Serialize scalar as ASN.1 DER fn serialize_int(scalar: &[u8], out: &mut [u8], len: usize, scalar_size: usize) { out[0] = INTEGER_TAG as u8; out[1] = len as u8; if len > scalar_size { out[2] = 0x00;
let s_range = parse_int(&bytes[r_end..], C::FieldSize::to_usize())?; let s_start = r_end.checked_add(s_range.start).unwrap(); let s_end = r_end.checked_add(s_range.end).unwrap();
random_line_split
lsp_plugin.rs
file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Implementation of Language Server Plugin use std::collections::HashMap; use std::path::Path; use std::sync::{Arc, Mutex}; use url::Url; use xi_plugin_lib::{ChunkCache, CoreProxy, Plugin, View}; use xi_rope::rope::RopeDelta; use crate::conversion_utils::*; use crate::language_server_client::LanguageServerClient; use crate::lsp_types::*; use crate::result_queue::ResultQueue; use crate::types::{Config, LanguageResponseError, LspResponse}; use crate::utils::*; use crate::xi_core::{ConfigTable, ViewId}; pub struct ViewInfo { version: u64, ls_identifier: String, } /// Represents the state of the Language Server Plugin pub struct LspPlugin { pub config: Config, view_info: HashMap<ViewId, ViewInfo>, core: Option<CoreProxy>, result_queue: ResultQueue, language_server_clients: HashMap<String, Arc<Mutex<LanguageServerClient>>>, } impl LspPlugin { pub fn new(config: Config) -> Self { LspPlugin { config, core: None, result_queue: ResultQueue::new(), view_info: HashMap::new(), language_server_clients: HashMap::new(), } } } impl Plugin for LspPlugin { type Cache = ChunkCache; fn initialize(&mut self, core: CoreProxy) { self.core = Some(core) } fn update( &mut self, view: &mut View<Self::Cache>, delta: Option<&RopeDelta>, _edit_type: String, _author: String, ) { let view_info = self.view_info.get_mut(&view.get_id()); if let Some(view_info) = view_info { // This won't fail since we definitely have a client for the given // client identifier let ls_client = &self.language_server_clients[&view_info.ls_identifier]; let mut ls_client = ls_client.lock().unwrap(); let sync_kind = ls_client.get_sync_kind(); view_info.version += 1; if let Some(changes) = get_change_for_sync_kind(sync_kind, view, delta) { ls_client.send_did_change(view.get_id(), changes, view_info.version); } } } fn did_save(&mut self, view: &mut View<Self::Cache>, _old: Option<&Path>) { trace!("saved view {}", view.get_id()); let document_text = view.get_document().unwrap(); self.with_language_server_for_view(view, |ls_client| { ls_client.send_did_save(view.get_id(), &document_text); }); } fn did_close(&mut self, view: &View<Self::Cache>) { trace!("close view {}", view.get_id()); self.with_language_server_for_view(view, |ls_client| { ls_client.send_did_close(view.get_id()); }); } fn new_view(&mut self, view: &mut View<Self::Cache>) { trace!("new view {}", view.get_id()); let document_text = view.get_document().unwrap(); let path = view.get_path(); let view_id = view.get_id(); // TODO: Use Language Idenitifier assigned by core when the // implementation is settled if let Some(language_id) = self.get_language_for_view(view) { let path = path.unwrap(); let workspace_root_uri = { let config = &self.config.language_config.get_mut(&language_id).unwrap(); config.workspace_identifier.clone().and_then(|identifier| { let path = view.get_path().unwrap(); let q = get_workspace_root_uri(&identifier, path); q.ok() }) }; let result = self.get_lsclient_from_workspace_root(&language_id, &workspace_root_uri); if let Some((identifier, ls_client)) = result { self.view_info .insert(view.get_id(), ViewInfo { version: 0, ls_identifier: identifier }); let mut ls_client = ls_client.lock().unwrap(); let document_uri = Url::from_file_path(path).unwrap(); if !ls_client.is_initialized { ls_client.send_initialize(workspace_root_uri, move |ls_client, result| { if let Ok(result) = result { let init_result: InitializeResult = serde_json::from_value(result).unwrap(); debug!("Init Result: {:?}", init_result); ls_client.server_capabilities = Some(init_result.capabilities); ls_client.is_initialized = true; ls_client.send_did_open(view_id, document_uri, document_text); } }); } else { ls_client.send_did_open(view_id, document_uri, document_text); } } } } fn config_changed(&mut self, _view: &mut View<Self::Cache>, _changes: &ConfigTable) {} fn get_hover(&mut self, view: &mut View<Self::Cache>, request_id: usize, position: usize) { let view_id = view.get_id(); let position_ls = get_position_of_offset(view, position); self.with_language_server_for_view(view, |ls_client| match position_ls { Ok(position) => ls_client.request_hover(view_id, position, move |ls_client, result| { let res = result .map_err(|e| LanguageResponseError::LanguageServerError(format!("{:?}", e))) .and_then(|h| { let hover: Option<Hover> = serde_json::from_value(h).unwrap(); hover.ok_or(LanguageResponseError::NullResponse) }); ls_client.result_queue.push_result(request_id, LspResponse::Hover(res)); ls_client.core.schedule_idle(view_id); }), Err(err) => { ls_client.result_queue.push_result(request_id, LspResponse::Hover(Err(err.into()))); ls_client.core.schedule_idle(view_id); } }); } fn idle(&mut self, view: &mut View<Self::Cache>) { let result = self.result_queue.pop_result(); if let Some((request_id, reponse)) = result { match reponse { LspResponse::Hover(res) => { let res = res.and_then(|h| core_hover_from_hover(view, h)).map_err(|e| e.into()); self.with_language_server_for_view(view, |ls_client| { ls_client.core.display_hover(view.get_id(), request_id, &res) }); } } } } } /// Util Methods impl LspPlugin { /// Get the Language Server Client given the Workspace root /// This method checks if a language server is running at the specified root /// and returns it else it tries to spawn a new language server and returns a /// Arc reference to it fn
( &mut self, language_id: &str, workspace_root: &Option<Url>, ) -> Option<(String, Arc<Mutex<LanguageServerClient>>)> { workspace_root .clone() .map(|r| r.into_string()) .or_else(|| { let config = &self.config.language_config[language_id]; if config.supports_single_file { // A generic client is the one that supports single files i.e. // Non-Workspace projects as well Some(String::from("generic")) } else { None } }) .and_then(|language_server_identifier| { let contains = self.language_server_clients.contains_key(&language_server_identifier); if contains { let client = self.language_server_clients[&language_server_identifier].clone(); Some((language_server_identifier, client)) } else { let config = &self.config.language_config[language_id]; let client = start_new_server( config.start_command.clone(), config.start_arguments.clone(), config.extensions.clone(), language_id, // Unwrap is safe self.core.clone().unwrap(), self.result_queue.clone(), ); match client { Ok(client) => { let client_clone = client.clone(); self.language_server_clients .insert(language_server_identifier.clone(), client); Some((language_server_identifier, client_clone)) } Err(err) => { error!( "Error occured while starting server for Language: {}: {:?}", language_id, err ); None } } } }) } /// Tries to get language for the View using the extension of the document. /// Only searches for the languages supported by the Language Plugin as /// defined in the config fn get_language_for_view(&mut self, view: &View<ChunkCache>) -> Option<String> { view.get_path() .and_then(|path| path.extension()) .and_then(|extension| extension.to_str()) .and_then(|extension_str| { for (lang, config) in &self.config.language_config { if config.extensions.iter().any(|x| x == extension_str) { return Some(lang.clone()); } } None }) } fn with_language_server_for_view<F, R>(&mut self, view: &View<Chunk
get_lsclient_from_workspace_root
identifier_name
lsp_plugin.rs
file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Implementation of Language Server Plugin use std::collections::HashMap; use std::path::Path; use std::sync::{Arc, Mutex}; use url::Url; use xi_plugin_lib::{ChunkCache, CoreProxy, Plugin, View}; use xi_rope::rope::RopeDelta; use crate::conversion_utils::*; use crate::language_server_client::LanguageServerClient; use crate::lsp_types::*; use crate::result_queue::ResultQueue; use crate::types::{Config, LanguageResponseError, LspResponse}; use crate::utils::*; use crate::xi_core::{ConfigTable, ViewId}; pub struct ViewInfo { version: u64, ls_identifier: String, } /// Represents the state of the Language Server Plugin pub struct LspPlugin { pub config: Config, view_info: HashMap<ViewId, ViewInfo>, core: Option<CoreProxy>, result_queue: ResultQueue, language_server_clients: HashMap<String, Arc<Mutex<LanguageServerClient>>>, } impl LspPlugin { pub fn new(config: Config) -> Self { LspPlugin { config, core: None, result_queue: ResultQueue::new(), view_info: HashMap::new(), language_server_clients: HashMap::new(), } } } impl Plugin for LspPlugin { type Cache = ChunkCache; fn initialize(&mut self, core: CoreProxy) { self.core = Some(core) } fn update( &mut self, view: &mut View<Self::Cache>, delta: Option<&RopeDelta>, _edit_type: String, _author: String, ) { let view_info = self.view_info.get_mut(&view.get_id()); if let Some(view_info) = view_info { // This won't fail since we definitely have a client for the given // client identifier let ls_client = &self.language_server_clients[&view_info.ls_identifier]; let mut ls_client = ls_client.lock().unwrap(); let sync_kind = ls_client.get_sync_kind(); view_info.version += 1; if let Some(changes) = get_change_for_sync_kind(sync_kind, view, delta) { ls_client.send_did_change(view.get_id(), changes, view_info.version); } } } fn did_save(&mut self, view: &mut View<Self::Cache>, _old: Option<&Path>) { trace!("saved view {}", view.get_id()); let document_text = view.get_document().unwrap(); self.with_language_server_for_view(view, |ls_client| { ls_client.send_did_save(view.get_id(), &document_text); }); } fn did_close(&mut self, view: &View<Self::Cache>) { trace!("close view {}", view.get_id()); self.with_language_server_for_view(view, |ls_client| { ls_client.send_did_close(view.get_id()); }); } fn new_view(&mut self, view: &mut View<Self::Cache>) { trace!("new view {}", view.get_id()); let document_text = view.get_document().unwrap(); let path = view.get_path(); let view_id = view.get_id(); // TODO: Use Language Idenitifier assigned by core when the // implementation is settled if let Some(language_id) = self.get_language_for_view(view) { let path = path.unwrap(); let workspace_root_uri = { let config = &self.config.language_config.get_mut(&language_id).unwrap(); config.workspace_identifier.clone().and_then(|identifier| { let path = view.get_path().unwrap(); let q = get_workspace_root_uri(&identifier, path); q.ok() }) }; let result = self.get_lsclient_from_workspace_root(&language_id, &workspace_root_uri); if let Some((identifier, ls_client)) = result { self.view_info .insert(view.get_id(), ViewInfo { version: 0, ls_identifier: identifier }); let mut ls_client = ls_client.lock().unwrap(); let document_uri = Url::from_file_path(path).unwrap(); if !ls_client.is_initialized { ls_client.send_initialize(workspace_root_uri, move |ls_client, result| { if let Ok(result) = result { let init_result: InitializeResult = serde_json::from_value(result).unwrap(); debug!("Init Result: {:?}", init_result); ls_client.server_capabilities = Some(init_result.capabilities); ls_client.is_initialized = true; ls_client.send_did_open(view_id, document_uri, document_text); } }); } else { ls_client.send_did_open(view_id, document_uri, document_text); } } } } fn config_changed(&mut self, _view: &mut View<Self::Cache>, _changes: &ConfigTable) {} fn get_hover(&mut self, view: &mut View<Self::Cache>, request_id: usize, position: usize) { let view_id = view.get_id(); let position_ls = get_position_of_offset(view, position); self.with_language_server_for_view(view, |ls_client| match position_ls { Ok(position) => ls_client.request_hover(view_id, position, move |ls_client, result| { let res = result .map_err(|e| LanguageResponseError::LanguageServerError(format!("{:?}", e))) .and_then(|h| { let hover: Option<Hover> = serde_json::from_value(h).unwrap(); hover.ok_or(LanguageResponseError::NullResponse) }); ls_client.result_queue.push_result(request_id, LspResponse::Hover(res)); ls_client.core.schedule_idle(view_id); }), Err(err) => { ls_client.result_queue.push_result(request_id, LspResponse::Hover(Err(err.into()))); ls_client.core.schedule_idle(view_id); } }); } fn idle(&mut self, view: &mut View<Self::Cache>) { let result = self.result_queue.pop_result(); if let Some((request_id, reponse)) = result { match reponse { LspResponse::Hover(res) => { let res = res.and_then(|h| core_hover_from_hover(view, h)).map_err(|e| e.into()); self.with_language_server_for_view(view, |ls_client| { ls_client.core.display_hover(view.get_id(), request_id, &res) }); } } } } } /// Util Methods impl LspPlugin { /// Get the Language Server Client given the Workspace root /// This method checks if a language server is running at the specified root /// and returns it else it tries to spawn a new language server and returns a /// Arc reference to it fn get_lsclient_from_workspace_root( &mut self, language_id: &str, workspace_root: &Option<Url>, ) -> Option<(String, Arc<Mutex<LanguageServerClient>>)> { workspace_root .clone() .map(|r| r.into_string()) .or_else(|| { let config = &self.config.language_config[language_id]; if config.supports_single_file { // A generic client is the one that supports single files i.e. // Non-Workspace projects as well Some(String::from("generic")) } else { None } }) .and_then(|language_server_identifier| { let contains = self.language_server_clients.contains_key(&language_server_identifier); if contains { let client = self.language_server_clients[&language_server_identifier].clone(); Some((language_server_identifier, client)) } else
Err(err) => { error!( "Error occured while starting server for Language: {}: {:?}", language_id, err ); None } } } }) } /// Tries to get language for the View using the extension of the document. /// Only searches for the languages supported by the Language Plugin as /// defined in the config fn get_language_for_view(&mut self, view: &View<ChunkCache>) -> Option<String> { view.get_path() .and_then(|path| path.extension()) .and_then(|extension| extension.to_str()) .and_then(|extension_str| { for (lang, config) in &self.config.language_config { if config.extensions.iter().any(|x| x == extension_str) { return Some(lang.clone()); } } None }) } fn with_language_server_for_view<F, R>(&mut self, view: &View<Chunk
{ let config = &self.config.language_config[language_id]; let client = start_new_server( config.start_command.clone(), config.start_arguments.clone(), config.extensions.clone(), language_id, // Unwrap is safe self.core.clone().unwrap(), self.result_queue.clone(), ); match client { Ok(client) => { let client_clone = client.clone(); self.language_server_clients .insert(language_server_identifier.clone(), client); Some((language_server_identifier, client_clone)) }
conditional_block
lsp_plugin.rs
file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Implementation of Language Server Plugin use std::collections::HashMap; use std::path::Path; use std::sync::{Arc, Mutex}; use url::Url; use xi_plugin_lib::{ChunkCache, CoreProxy, Plugin, View}; use xi_rope::rope::RopeDelta; use crate::conversion_utils::*; use crate::language_server_client::LanguageServerClient; use crate::lsp_types::*; use crate::result_queue::ResultQueue; use crate::types::{Config, LanguageResponseError, LspResponse}; use crate::utils::*; use crate::xi_core::{ConfigTable, ViewId}; pub struct ViewInfo { version: u64, ls_identifier: String, } /// Represents the state of the Language Server Plugin pub struct LspPlugin { pub config: Config, view_info: HashMap<ViewId, ViewInfo>, core: Option<CoreProxy>, result_queue: ResultQueue, language_server_clients: HashMap<String, Arc<Mutex<LanguageServerClient>>>, } impl LspPlugin { pub fn new(config: Config) -> Self { LspPlugin { config, core: None, result_queue: ResultQueue::new(), view_info: HashMap::new(), language_server_clients: HashMap::new(), } } } impl Plugin for LspPlugin { type Cache = ChunkCache; fn initialize(&mut self, core: CoreProxy) { self.core = Some(core) } fn update( &mut self, view: &mut View<Self::Cache>, delta: Option<&RopeDelta>, _edit_type: String, _author: String, ) { let view_info = self.view_info.get_mut(&view.get_id()); if let Some(view_info) = view_info { // This won't fail since we definitely have a client for the given // client identifier let ls_client = &self.language_server_clients[&view_info.ls_identifier]; let mut ls_client = ls_client.lock().unwrap(); let sync_kind = ls_client.get_sync_kind(); view_info.version += 1; if let Some(changes) = get_change_for_sync_kind(sync_kind, view, delta) { ls_client.send_did_change(view.get_id(), changes, view_info.version); } } } fn did_save(&mut self, view: &mut View<Self::Cache>, _old: Option<&Path>) { trace!("saved view {}", view.get_id()); let document_text = view.get_document().unwrap(); self.with_language_server_for_view(view, |ls_client| { ls_client.send_did_save(view.get_id(), &document_text); }); } fn did_close(&mut self, view: &View<Self::Cache>) { trace!("close view {}", view.get_id()); self.with_language_server_for_view(view, |ls_client| { ls_client.send_did_close(view.get_id()); }); } fn new_view(&mut self, view: &mut View<Self::Cache>) { trace!("new view {}", view.get_id()); let document_text = view.get_document().unwrap(); let path = view.get_path(); let view_id = view.get_id(); // TODO: Use Language Idenitifier assigned by core when the // implementation is settled if let Some(language_id) = self.get_language_for_view(view) { let path = path.unwrap(); let workspace_root_uri = { let config = &self.config.language_config.get_mut(&language_id).unwrap(); config.workspace_identifier.clone().and_then(|identifier| { let path = view.get_path().unwrap(); let q = get_workspace_root_uri(&identifier, path); q.ok() }) }; let result = self.get_lsclient_from_workspace_root(&language_id, &workspace_root_uri); if let Some((identifier, ls_client)) = result { self.view_info .insert(view.get_id(), ViewInfo { version: 0, ls_identifier: identifier }); let mut ls_client = ls_client.lock().unwrap(); let document_uri = Url::from_file_path(path).unwrap(); if !ls_client.is_initialized { ls_client.send_initialize(workspace_root_uri, move |ls_client, result| { if let Ok(result) = result { let init_result: InitializeResult = serde_json::from_value(result).unwrap(); debug!("Init Result: {:?}", init_result); ls_client.server_capabilities = Some(init_result.capabilities); ls_client.is_initialized = true; ls_client.send_did_open(view_id, document_uri, document_text); } }); } else { ls_client.send_did_open(view_id, document_uri, document_text); } } } } fn config_changed(&mut self, _view: &mut View<Self::Cache>, _changes: &ConfigTable) {} fn get_hover(&mut self, view: &mut View<Self::Cache>, request_id: usize, position: usize) { let view_id = view.get_id(); let position_ls = get_position_of_offset(view, position); self.with_language_server_for_view(view, |ls_client| match position_ls { Ok(position) => ls_client.request_hover(view_id, position, move |ls_client, result| { let res = result .map_err(|e| LanguageResponseError::LanguageServerError(format!("{:?}", e))) .and_then(|h| { let hover: Option<Hover> = serde_json::from_value(h).unwrap(); hover.ok_or(LanguageResponseError::NullResponse) }); ls_client.result_queue.push_result(request_id, LspResponse::Hover(res)); ls_client.core.schedule_idle(view_id); }), Err(err) => { ls_client.result_queue.push_result(request_id, LspResponse::Hover(Err(err.into()))); ls_client.core.schedule_idle(view_id); } }); } fn idle(&mut self, view: &mut View<Self::Cache>) { let result = self.result_queue.pop_result(); if let Some((request_id, reponse)) = result { match reponse { LspResponse::Hover(res) => { let res = res.and_then(|h| core_hover_from_hover(view, h)).map_err(|e| e.into()); self.with_language_server_for_view(view, |ls_client| { ls_client.core.display_hover(view.get_id(), request_id, &res) }); } } } } } /// Util Methods impl LspPlugin { /// Get the Language Server Client given the Workspace root /// This method checks if a language server is running at the specified root /// and returns it else it tries to spawn a new language server and returns a /// Arc reference to it fn get_lsclient_from_workspace_root( &mut self, language_id: &str, workspace_root: &Option<Url>, ) -> Option<(String, Arc<Mutex<LanguageServerClient>>)> { workspace_root .clone() .map(|r| r.into_string()) .or_else(|| { let config = &self.config.language_config[language_id]; if config.supports_single_file { // A generic client is the one that supports single files i.e. // Non-Workspace projects as well Some(String::from("generic")) } else { None } }) .and_then(|language_server_identifier| { let contains = self.language_server_clients.contains_key(&language_server_identifier); if contains { let client = self.language_server_clients[&language_server_identifier].clone(); Some((language_server_identifier, client)) } else { let config = &self.config.language_config[language_id]; let client = start_new_server( config.start_command.clone(), config.start_arguments.clone(), config.extensions.clone(), language_id, // Unwrap is safe self.core.clone().unwrap(), self.result_queue.clone(), ); match client { Ok(client) => { let client_clone = client.clone();
Err(err) => { error!( "Error occured while starting server for Language: {}: {:?}", language_id, err ); None } } } }) } /// Tries to get language for the View using the extension of the document. /// Only searches for the languages supported by the Language Plugin as /// defined in the config fn get_language_for_view(&mut self, view: &View<ChunkCache>) -> Option<String> { view.get_path() .and_then(|path| path.extension()) .and_then(|extension| extension.to_str()) .and_then(|extension_str| { for (lang, config) in &self.config.language_config { if config.extensions.iter().any(|x| x == extension_str) { return Some(lang.clone()); } } None }) } fn with_language_server_for_view<F, R>(&mut self, view: &View<ChunkCache
self.language_server_clients .insert(language_server_identifier.clone(), client); Some((language_server_identifier, client_clone)) }
random_line_split
lsp_plugin.rs
except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Implementation of Language Server Plugin use std::collections::HashMap; use std::path::Path; use std::sync::{Arc, Mutex}; use url::Url; use xi_plugin_lib::{ChunkCache, CoreProxy, Plugin, View}; use xi_rope::rope::RopeDelta; use crate::conversion_utils::*; use crate::language_server_client::LanguageServerClient; use crate::lsp_types::*; use crate::result_queue::ResultQueue; use crate::types::{Config, LanguageResponseError, LspResponse}; use crate::utils::*; use crate::xi_core::{ConfigTable, ViewId}; pub struct ViewInfo { version: u64, ls_identifier: String, } /// Represents the state of the Language Server Plugin pub struct LspPlugin { pub config: Config, view_info: HashMap<ViewId, ViewInfo>, core: Option<CoreProxy>, result_queue: ResultQueue, language_server_clients: HashMap<String, Arc<Mutex<LanguageServerClient>>>, } impl LspPlugin { pub fn new(config: Config) -> Self { LspPlugin { config, core: None, result_queue: ResultQueue::new(), view_info: HashMap::new(), language_server_clients: HashMap::new(), } } } impl Plugin for LspPlugin { type Cache = ChunkCache; fn initialize(&mut self, core: CoreProxy) { self.core = Some(core) } fn update( &mut self, view: &mut View<Self::Cache>, delta: Option<&RopeDelta>, _edit_type: String, _author: String, ) { let view_info = self.view_info.get_mut(&view.get_id()); if let Some(view_info) = view_info { // This won't fail since we definitely have a client for the given // client identifier let ls_client = &self.language_server_clients[&view_info.ls_identifier]; let mut ls_client = ls_client.lock().unwrap(); let sync_kind = ls_client.get_sync_kind(); view_info.version += 1; if let Some(changes) = get_change_for_sync_kind(sync_kind, view, delta) { ls_client.send_did_change(view.get_id(), changes, view_info.version); } } } fn did_save(&mut self, view: &mut View<Self::Cache>, _old: Option<&Path>) { trace!("saved view {}", view.get_id()); let document_text = view.get_document().unwrap(); self.with_language_server_for_view(view, |ls_client| { ls_client.send_did_save(view.get_id(), &document_text); }); } fn did_close(&mut self, view: &View<Self::Cache>)
fn new_view(&mut self, view: &mut View<Self::Cache>) { trace!("new view {}", view.get_id()); let document_text = view.get_document().unwrap(); let path = view.get_path(); let view_id = view.get_id(); // TODO: Use Language Idenitifier assigned by core when the // implementation is settled if let Some(language_id) = self.get_language_for_view(view) { let path = path.unwrap(); let workspace_root_uri = { let config = &self.config.language_config.get_mut(&language_id).unwrap(); config.workspace_identifier.clone().and_then(|identifier| { let path = view.get_path().unwrap(); let q = get_workspace_root_uri(&identifier, path); q.ok() }) }; let result = self.get_lsclient_from_workspace_root(&language_id, &workspace_root_uri); if let Some((identifier, ls_client)) = result { self.view_info .insert(view.get_id(), ViewInfo { version: 0, ls_identifier: identifier }); let mut ls_client = ls_client.lock().unwrap(); let document_uri = Url::from_file_path(path).unwrap(); if !ls_client.is_initialized { ls_client.send_initialize(workspace_root_uri, move |ls_client, result| { if let Ok(result) = result { let init_result: InitializeResult = serde_json::from_value(result).unwrap(); debug!("Init Result: {:?}", init_result); ls_client.server_capabilities = Some(init_result.capabilities); ls_client.is_initialized = true; ls_client.send_did_open(view_id, document_uri, document_text); } }); } else { ls_client.send_did_open(view_id, document_uri, document_text); } } } } fn config_changed(&mut self, _view: &mut View<Self::Cache>, _changes: &ConfigTable) {} fn get_hover(&mut self, view: &mut View<Self::Cache>, request_id: usize, position: usize) { let view_id = view.get_id(); let position_ls = get_position_of_offset(view, position); self.with_language_server_for_view(view, |ls_client| match position_ls { Ok(position) => ls_client.request_hover(view_id, position, move |ls_client, result| { let res = result .map_err(|e| LanguageResponseError::LanguageServerError(format!("{:?}", e))) .and_then(|h| { let hover: Option<Hover> = serde_json::from_value(h).unwrap(); hover.ok_or(LanguageResponseError::NullResponse) }); ls_client.result_queue.push_result(request_id, LspResponse::Hover(res)); ls_client.core.schedule_idle(view_id); }), Err(err) => { ls_client.result_queue.push_result(request_id, LspResponse::Hover(Err(err.into()))); ls_client.core.schedule_idle(view_id); } }); } fn idle(&mut self, view: &mut View<Self::Cache>) { let result = self.result_queue.pop_result(); if let Some((request_id, reponse)) = result { match reponse { LspResponse::Hover(res) => { let res = res.and_then(|h| core_hover_from_hover(view, h)).map_err(|e| e.into()); self.with_language_server_for_view(view, |ls_client| { ls_client.core.display_hover(view.get_id(), request_id, &res) }); } } } } } /// Util Methods impl LspPlugin { /// Get the Language Server Client given the Workspace root /// This method checks if a language server is running at the specified root /// and returns it else it tries to spawn a new language server and returns a /// Arc reference to it fn get_lsclient_from_workspace_root( &mut self, language_id: &str, workspace_root: &Option<Url>, ) -> Option<(String, Arc<Mutex<LanguageServerClient>>)> { workspace_root .clone() .map(|r| r.into_string()) .or_else(|| { let config = &self.config.language_config[language_id]; if config.supports_single_file { // A generic client is the one that supports single files i.e. // Non-Workspace projects as well Some(String::from("generic")) } else { None } }) .and_then(|language_server_identifier| { let contains = self.language_server_clients.contains_key(&language_server_identifier); if contains { let client = self.language_server_clients[&language_server_identifier].clone(); Some((language_server_identifier, client)) } else { let config = &self.config.language_config[language_id]; let client = start_new_server( config.start_command.clone(), config.start_arguments.clone(), config.extensions.clone(), language_id, // Unwrap is safe self.core.clone().unwrap(), self.result_queue.clone(), ); match client { Ok(client) => { let client_clone = client.clone(); self.language_server_clients .insert(language_server_identifier.clone(), client); Some((language_server_identifier, client_clone)) } Err(err) => { error!( "Error occured while starting server for Language: {}: {:?}", language_id, err ); None } } } }) } /// Tries to get language for the View using the extension of the document. /// Only searches for the languages supported by the Language Plugin as /// defined in the config fn get_language_for_view(&mut self, view: &View<ChunkCache>) -> Option<String> { view.get_path() .and_then(|path| path.extension()) .and_then(|extension| extension.to_str()) .and_then(|extension_str| { for (lang, config) in &self.config.language_config { if config.extensions.iter().any(|x| x == extension_str) { return Some(lang.clone()); } } None }) } fn with_language_server_for_view<F, R>(&mut self, view: &View<Chunk
{ trace!("close view {}", view.get_id()); self.with_language_server_for_view(view, |ls_client| { ls_client.send_did_close(view.get_id()); }); }
identifier_body
cluster.ts
id: string, props: ClusterProps) { super(scope, id); this.vpc = props.vpc; this.vpcSubnets = props.vpcSubnets ?? { subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS, }; this.parameterGroup = props.parameterGroup; this.roles = props?.roles ? [...props.roles] : []; const removalPolicy = props.removalPolicy ?? RemovalPolicy.RETAIN; const subnetGroup = props.subnetGroup ?? new ClusterSubnetGroup(this, 'Subnets', { description: `Subnets for ${id} Redshift cluster`, vpc: this.vpc, vpcSubnets: this.vpcSubnets, removalPolicy: removalPolicy, }); const securityGroups = props.securityGroups ?? [new ec2.SecurityGroup(this, 'SecurityGroup', { description: 'Redshift security group', vpc: this.vpc, })]; const securityGroupIds = securityGroups.map(sg => sg.securityGroupId); let secret: DatabaseSecret | undefined; if (!props.masterUser.masterPassword) { secret = new DatabaseSecret(this, 'Secret', { username: props.masterUser.masterUsername, encryptionKey: props.masterUser.encryptionKey, }); } const clusterType = props.clusterType || ClusterType.MULTI_NODE; const nodeCount = this.validateNodeCount(clusterType, props.numberOfNodes); if (props.encrypted === false && props.encryptionKey !== undefined) { throw new Error('Cannot set property encryptionKey without enabling encryption!'); } this.singleUserRotationApplication = secretsmanager.SecretRotationApplication.REDSHIFT_ROTATION_SINGLE_USER; this.multiUserRotationApplication = secretsmanager.SecretRotationApplication.REDSHIFT_ROTATION_MULTI_USER; let loggingProperties; if (props.loggingProperties) { loggingProperties = { bucketName: props.loggingProperties.loggingBucket.bucketName, s3KeyPrefix: props.loggingProperties.loggingKeyPrefix, }; props.loggingProperties.loggingBucket.addToResourcePolicy( new iam.PolicyStatement( { actions: [ 's3:GetBucketAcl', 's3:PutObject', ], resources: [ props.loggingProperties.loggingBucket.arnForObjects('*'), props.loggingProperties.loggingBucket.bucketArn, ], principals: [ new iam.ServicePrincipal('redshift.amazonaws.com'), ], }, ), ); } this.cluster = new CfnCluster(this, 'Resource', { // Basic allowVersionUpgrade: true, automatedSnapshotRetentionPeriod: 1, clusterType, clusterIdentifier: props.clusterName, clusterSubnetGroupName: subnetGroup.clusterSubnetGroupName, vpcSecurityGroupIds: securityGroupIds, port: props.port, clusterParameterGroupName: props.parameterGroup && props.parameterGroup.clusterParameterGroupName, // Admin (unsafeUnwrap here is safe) masterUsername: secret?.secretValueFromJson('username').unsafeUnwrap() ?? props.masterUser.masterUsername, masterUserPassword: secret?.secretValueFromJson('password').unsafeUnwrap() ?? props.masterUser.masterPassword?.unsafeUnwrap() ?? 'default', preferredMaintenanceWindow: props.preferredMaintenanceWindow, nodeType: props.nodeType || NodeType.DC2_LARGE, numberOfNodes: nodeCount, loggingProperties, iamRoles: Lazy.list({ produce: () => this.roles.map(role => role.roleArn) }, { omitEmpty: true }), dbName: props.defaultDatabaseName || 'default_db', publiclyAccessible: props.publiclyAccessible || false, // Encryption kmsKeyId: props.encryptionKey?.keyId, encrypted: props.encrypted ?? true, classic: props.classicResizing, elasticIp: props.elasticIp, enhancedVpcRouting: props.enhancedVpcRouting, }); this.cluster.applyRemovalPolicy(removalPolicy, { applyToUpdateReplacePolicy: true, }); this.clusterName = this.cluster.ref; // create a number token that represents the port of the cluster const portAttribute = Token.asNumber(this.cluster.attrEndpointPort); this.clusterEndpoint = new Endpoint(this.cluster.attrEndpointAddress, portAttribute); if (secret) { this.secret = secret.attach(this); } const defaultPort = ec2.Port.tcp(this.clusterEndpoint.port); this.connections = new ec2.Connections({ securityGroups, defaultPort }); if (props.rebootForParameterChanges) { this.enableRebootForParameterChanges(); } // Add default role if specified and also available in the roles list if (props.defaultRole) { if (props.roles?.some(x => x === props.defaultRole)) { this.addDefaultIamRole(props.defaultRole); } else { throw new Error('Default role must be included in role list.'); } } } /** * Adds the single user rotation of the master password to this cluster. * * @param [automaticallyAfter=Duration.days(30)] Specifies the number of days after the previous rotation * before Secrets Manager triggers the next automatic rotation. */ public addRotationSingleUser(automaticallyAfter?: Duration): secretsmanager.SecretRotation { if (!this.secret) { throw new Error('Cannot add single user rotation for a cluster without secret.'); } const id = 'RotationSingleUser'; const existing = this.node.tryFindChild(id); if (existing) { throw new Error('A single user rotation was already added to this cluster.'); } return new secretsmanager.SecretRotation(this, id, { secret: this.secret, automaticallyAfter, application: this.singleUserRotationApplication, vpc: this.vpc, vpcSubnets: this.vpcSubnets, target: this, }); } /** * Adds the multi user rotation to this cluster. */ public addRotationMultiUser(id: string, options: RotationMultiUserOptions): secretsmanager.SecretRotation { if (!this.secret) { throw new Error('Cannot add multi user rotation for a cluster without secret.'); } return new secretsmanager.SecretRotation(this, id, { secret: options.secret, masterSecret: this.secret, automaticallyAfter: options.automaticallyAfter, application: this.multiUserRotationApplication, vpc: this.vpc, vpcSubnets: this.vpcSubnets, target: this, }); } private validateNodeCount(clusterType: ClusterType, numberOfNodes?: number): number | undefined { if (clusterType === ClusterType.SINGLE_NODE) { // This property must not be set for single-node clusters; be generous and treat a value of 1 node as undefined. if (numberOfNodes !== undefined && numberOfNodes !== 1) { throw new Error('Number of nodes must be not be supplied or be 1 for cluster type single-node'); } return undefined; } else { if (Token.isUnresolved(numberOfNodes)) { return numberOfNodes; } const nodeCount = numberOfNodes ?? 2; if (nodeCount < 2 || nodeCount > 100) { throw new Error('Number of nodes for cluster type multi-node must be at least 2 and no more than 100'); } return nodeCount; } } /** * Adds a parameter to the Clusters' parameter group * * @param name the parameter name * @param value the parameter name */ public addToParameterGroup(name: string, value: string): void { if (!this.parameterGroup) { const param: { [name: string]: string } = {}; param[name] = value; this.parameterGroup = new ClusterParameterGroup(this, 'ParameterGroup', { description: this.cluster.clusterIdentifier ? `Parameter Group for the ${this.cluster.clusterIdentifier} Redshift cluster` : 'Cluster parameter group for family redshift-1.0', parameters: param, }); this.cluster.clusterParameterGroupName = this.parameterGroup.clusterParameterGroupName; } else if (this.parameterGroup instanceof ClusterParameterGroup) { this.parameterGroup.addParameter(name, value); } else { throw new Error('Cannot add a parameter to an imported parameter group.'); } } /** * Enables automatic cluster rebooting when changes to the cluster's parameter group require a restart to apply. */ public enableRebootForParameterChanges(): void { if (this.node.tryFindChild('RedshiftClusterRebooterCustomResource')) { return; } const rebootFunction = new lambda.SingletonFunction(this, 'RedshiftClusterRebooterFunction', { uuid: '511e207f-13df-4b8b-b632-c32b30b65ac2', runtime: lambda.Runtime.NODEJS_18_X, code: lambda.Code.fromAsset(path.join(__dirname, 'cluster-parameter-change-reboot-handler')), handler: 'index.handler', timeout: Duration.seconds(900), }); rebootFunction.addToRolePolicy(new iam.PolicyStatement({ actions: ['redshift:DescribeClusters'], resources: ['*'], })); rebootFunction.addToRolePolicy(new iam.PolicyStatement({ actions: ['redshift:RebootCluster'], resources: [ Stack.of(this).formatArn({ service: 'redshift', resource: 'cluster',
resourceName: this.clusterName, arnFormat: ArnFormat.COLON_RESOURCE_NAME, }), ],
random_line_split
cluster.ts
*/ readonly clusterName: string; /** * Cluster endpoint address */ readonly clusterEndpointAddress: string; /** * Cluster endpoint port */ readonly clusterEndpointPort: number; } /** * Properties for a new database cluster */ export interface ClusterProps { /** * An optional identifier for the cluster * * @default - A name is automatically generated. */ readonly clusterName?: string; /** * Additional parameters to pass to the database engine * https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-parameter-groups.html * * @default - No parameter group. */ readonly parameterGroup?: IClusterParameterGroup; /** * Number of compute nodes in the cluster. Only specify this property for multi-node clusters. * * Value must be at least 2 and no more than 100. * * @default - 2 if `clusterType` is ClusterType.MULTI_NODE, undefined otherwise */ readonly numberOfNodes?: number; /** * The node type to be provisioned for the cluster. * * @default `NodeType.DC2_LARGE` */ readonly nodeType?: NodeType; /** * Settings for the individual instances that are launched * * @default `ClusterType.MULTI_NODE` */ readonly clusterType?: ClusterType; /** * What port to listen on * * @default - The default for the engine is used. */ readonly port?: number; /** * Whether to enable encryption of data at rest in the cluster. * * @default true */ readonly encrypted?: boolean /** * The KMS key to use for encryption of data at rest. * * @default - AWS-managed key, if encryption at rest is enabled */ readonly encryptionKey?: kms.IKey; /** * A preferred maintenance window day/time range. Should be specified as a range ddd:hh24:mi-ddd:hh24:mi (24H Clock UTC). * * Example: 'Sun:23:45-Mon:00:15' * * @default - 30-minute window selected at random from an 8-hour block of time for * each AWS Region, occurring on a random day of the week. * @see https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_UpgradeDBInstance.Maintenance.html#Concepts.DBMaintenance */ readonly preferredMaintenanceWindow?: string; /** * The VPC to place the cluster in. */ readonly vpc: ec2.IVpc; /** * Where to place the instances within the VPC * * @default - private subnets */ readonly vpcSubnets?: ec2.SubnetSelection; /** * Security group. * * @default - a new security group is created. */ readonly securityGroups?: ec2.ISecurityGroup[]; /** * A cluster subnet group to use with this cluster. * * @default - a new subnet group will be created. */ readonly subnetGroup?: IClusterSubnetGroup; /** * Username and password for the administrative user */ readonly masterUser: Login; /** * A list of AWS Identity and Access Management (IAM) role that can be used by the cluster to access other AWS services. * The maximum number of roles to attach to a cluster is subject to a quota. * * @default - No role is attached to the cluster. */ readonly roles?: iam.IRole[]; /** * A single AWS Identity and Access Management (IAM) role to be used as the default role for the cluster. * The default role must be included in the roles list. * * @default - No default role is specified for the cluster. */ readonly defaultRole?: iam.IRole; /** * Name of a database which is automatically created inside the cluster * * @default - default_db */ readonly defaultDatabaseName?: string; /** * Bucket details for log files to be sent to, including prefix. * * @default - No logging bucket is used */ readonly loggingProperties?: LoggingProperties; /** * The removal policy to apply when the cluster and its instances are removed * from the stack or replaced during an update. * * @default RemovalPolicy.RETAIN */ readonly removalPolicy?: RemovalPolicy /** * Whether to make cluster publicly accessible. * * @default false */ readonly publiclyAccessible?: boolean /** * If this flag is set, the cluster resizing type will be set to classic. * When resizing a cluster, classic resizing will always provision a new cluster and transfer the data there. * * Classic resize takes more time to complete, but it can be useful in cases where the change in node count or * the node type to migrate to doesn't fall within the bounds for elastic resize. * * @see https://docs.aws.amazon.com/redshift/latest/mgmt/managing-cluster-operations.html#elastic-resize * * @default - Elastic resize type */ readonly classicResizing?: boolean /** * The Elastic IP (EIP) address for the cluster. * * @see https://docs.aws.amazon.com/redshift/latest/mgmt/managing-clusters-vpc.html * * @default - No Elastic IP */ readonly elasticIp?: string /** * If this flag is set, the cluster will be rebooted when changes to the cluster's parameter group that require a restart to apply. * @default false */ readonly rebootForParameterChanges?: boolean /** * If this flag is set, Amazon Redshift forces all COPY and UNLOAD traffic between your cluster and your data repositories through your virtual private cloud (VPC). * * @see https://docs.aws.amazon.com/redshift/latest/mgmt/enhanced-vpc-routing.html * * @default - false */ readonly enhancedVpcRouting?: boolean } /** * A new or imported clustered database. */ abstract class ClusterBase extends Resource implements ICluster { /** * Name of the cluster */ public abstract readonly clusterName: string; /** * The endpoint to use for read/write operations */ public abstract readonly clusterEndpoint: Endpoint; /** * Access to the network connections */ public abstract readonly connections: ec2.Connections; /** * Renders the secret attachment target specifications. */ public
(): secretsmanager.SecretAttachmentTargetProps { return { targetId: this.clusterName, targetType: secretsmanager.AttachmentTargetType.REDSHIFT_CLUSTER, }; } } /** * Create a Redshift cluster a given number of nodes. * * @resource AWS::Redshift::Cluster */ export class Cluster extends ClusterBase { /** * Import an existing DatabaseCluster from properties */ public static fromClusterAttributes(scope: Construct, id: string, attrs: ClusterAttributes): ICluster { class Import extends ClusterBase { public readonly connections = new ec2.Connections({ securityGroups: attrs.securityGroups, defaultPort: ec2.Port.tcp(attrs.clusterEndpointPort), }); public readonly clusterName = attrs.clusterName; public readonly instanceIdentifiers: string[] = []; public readonly clusterEndpoint = new Endpoint(attrs.clusterEndpointAddress, attrs.clusterEndpointPort); } return new Import(scope, id); } /** * Identifier of the cluster */ public readonly clusterName: string; /** * The endpoint to use for read/write operations */ public readonly clusterEndpoint: Endpoint; /** * Access to the network connections */ public readonly connections: ec2.Connections; /** * The secret attached to this cluster */ public readonly secret?: secretsmanager.ISecret; private readonly singleUserRotationApplication: secretsmanager.SecretRotationApplication; private readonly multiUserRotationApplication: secretsmanager.SecretRotationApplication; /** * The VPC where the DB subnet group is created. */ private readonly vpc: ec2.IVpc; /** * The subnets used by the DB subnet group. */ private readonly vpcSubnets?: ec2.SubnetSelection; /** * The underlying CfnCluster */ private readonly cluster: CfnCluster; /** * The cluster's parameter group */ protected parameterGroup?: IClusterParameterGroup; /** * The ARNs of the roles that will be attached to the cluster. * * **NOTE** Please do not access this directly, use the `addIamRole` method instead. */ private readonly roles: iam.IRole[]; constructor(scope: Construct, id: string, props: ClusterProps) { super(scope, id); this.vpc = props.vpc; this.vpcSubnets = props.vpcSubnets ?? { subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS, }; this.parameterGroup = props.parameterGroup; this.roles = props?.roles ? [...props.roles] : []; const removalPolicy = props.removalPolicy ?? RemovalPolicy.RETAIN; const subnetGroup = props.subnetGroup ?? new ClusterSubnetGroup(this, 'Subnets', { description: `Subnets
asSecretAttachmentTarget
identifier_name
cluster.ts
more time to complete, but it can be useful in cases where the change in node count or * the node type to migrate to doesn't fall within the bounds for elastic resize. * * @see https://docs.aws.amazon.com/redshift/latest/mgmt/managing-cluster-operations.html#elastic-resize * * @default - Elastic resize type */ readonly classicResizing?: boolean /** * The Elastic IP (EIP) address for the cluster. * * @see https://docs.aws.amazon.com/redshift/latest/mgmt/managing-clusters-vpc.html * * @default - No Elastic IP */ readonly elasticIp?: string /** * If this flag is set, the cluster will be rebooted when changes to the cluster's parameter group that require a restart to apply. * @default false */ readonly rebootForParameterChanges?: boolean /** * If this flag is set, Amazon Redshift forces all COPY and UNLOAD traffic between your cluster and your data repositories through your virtual private cloud (VPC). * * @see https://docs.aws.amazon.com/redshift/latest/mgmt/enhanced-vpc-routing.html * * @default - false */ readonly enhancedVpcRouting?: boolean } /** * A new or imported clustered database. */ abstract class ClusterBase extends Resource implements ICluster { /** * Name of the cluster */ public abstract readonly clusterName: string; /** * The endpoint to use for read/write operations */ public abstract readonly clusterEndpoint: Endpoint; /** * Access to the network connections */ public abstract readonly connections: ec2.Connections; /** * Renders the secret attachment target specifications. */ public asSecretAttachmentTarget(): secretsmanager.SecretAttachmentTargetProps { return { targetId: this.clusterName, targetType: secretsmanager.AttachmentTargetType.REDSHIFT_CLUSTER, }; } } /** * Create a Redshift cluster a given number of nodes. * * @resource AWS::Redshift::Cluster */ export class Cluster extends ClusterBase { /** * Import an existing DatabaseCluster from properties */ public static fromClusterAttributes(scope: Construct, id: string, attrs: ClusterAttributes): ICluster { class Import extends ClusterBase { public readonly connections = new ec2.Connections({ securityGroups: attrs.securityGroups, defaultPort: ec2.Port.tcp(attrs.clusterEndpointPort), }); public readonly clusterName = attrs.clusterName; public readonly instanceIdentifiers: string[] = []; public readonly clusterEndpoint = new Endpoint(attrs.clusterEndpointAddress, attrs.clusterEndpointPort); } return new Import(scope, id); } /** * Identifier of the cluster */ public readonly clusterName: string; /** * The endpoint to use for read/write operations */ public readonly clusterEndpoint: Endpoint; /** * Access to the network connections */ public readonly connections: ec2.Connections; /** * The secret attached to this cluster */ public readonly secret?: secretsmanager.ISecret; private readonly singleUserRotationApplication: secretsmanager.SecretRotationApplication; private readonly multiUserRotationApplication: secretsmanager.SecretRotationApplication; /** * The VPC where the DB subnet group is created. */ private readonly vpc: ec2.IVpc; /** * The subnets used by the DB subnet group. */ private readonly vpcSubnets?: ec2.SubnetSelection; /** * The underlying CfnCluster */ private readonly cluster: CfnCluster; /** * The cluster's parameter group */ protected parameterGroup?: IClusterParameterGroup; /** * The ARNs of the roles that will be attached to the cluster. * * **NOTE** Please do not access this directly, use the `addIamRole` method instead. */ private readonly roles: iam.IRole[]; constructor(scope: Construct, id: string, props: ClusterProps) { super(scope, id); this.vpc = props.vpc; this.vpcSubnets = props.vpcSubnets ?? { subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS, }; this.parameterGroup = props.parameterGroup; this.roles = props?.roles ? [...props.roles] : []; const removalPolicy = props.removalPolicy ?? RemovalPolicy.RETAIN; const subnetGroup = props.subnetGroup ?? new ClusterSubnetGroup(this, 'Subnets', { description: `Subnets for ${id} Redshift cluster`, vpc: this.vpc, vpcSubnets: this.vpcSubnets, removalPolicy: removalPolicy, }); const securityGroups = props.securityGroups ?? [new ec2.SecurityGroup(this, 'SecurityGroup', { description: 'Redshift security group', vpc: this.vpc, })]; const securityGroupIds = securityGroups.map(sg => sg.securityGroupId); let secret: DatabaseSecret | undefined; if (!props.masterUser.masterPassword) { secret = new DatabaseSecret(this, 'Secret', { username: props.masterUser.masterUsername, encryptionKey: props.masterUser.encryptionKey, }); } const clusterType = props.clusterType || ClusterType.MULTI_NODE; const nodeCount = this.validateNodeCount(clusterType, props.numberOfNodes); if (props.encrypted === false && props.encryptionKey !== undefined) { throw new Error('Cannot set property encryptionKey without enabling encryption!'); } this.singleUserRotationApplication = secretsmanager.SecretRotationApplication.REDSHIFT_ROTATION_SINGLE_USER; this.multiUserRotationApplication = secretsmanager.SecretRotationApplication.REDSHIFT_ROTATION_MULTI_USER; let loggingProperties; if (props.loggingProperties) { loggingProperties = { bucketName: props.loggingProperties.loggingBucket.bucketName, s3KeyPrefix: props.loggingProperties.loggingKeyPrefix, }; props.loggingProperties.loggingBucket.addToResourcePolicy( new iam.PolicyStatement( { actions: [ 's3:GetBucketAcl', 's3:PutObject', ], resources: [ props.loggingProperties.loggingBucket.arnForObjects('*'), props.loggingProperties.loggingBucket.bucketArn, ], principals: [ new iam.ServicePrincipal('redshift.amazonaws.com'), ], }, ), ); } this.cluster = new CfnCluster(this, 'Resource', { // Basic allowVersionUpgrade: true, automatedSnapshotRetentionPeriod: 1, clusterType, clusterIdentifier: props.clusterName, clusterSubnetGroupName: subnetGroup.clusterSubnetGroupName, vpcSecurityGroupIds: securityGroupIds, port: props.port, clusterParameterGroupName: props.parameterGroup && props.parameterGroup.clusterParameterGroupName, // Admin (unsafeUnwrap here is safe) masterUsername: secret?.secretValueFromJson('username').unsafeUnwrap() ?? props.masterUser.masterUsername, masterUserPassword: secret?.secretValueFromJson('password').unsafeUnwrap() ?? props.masterUser.masterPassword?.unsafeUnwrap() ?? 'default', preferredMaintenanceWindow: props.preferredMaintenanceWindow, nodeType: props.nodeType || NodeType.DC2_LARGE, numberOfNodes: nodeCount, loggingProperties, iamRoles: Lazy.list({ produce: () => this.roles.map(role => role.roleArn) }, { omitEmpty: true }), dbName: props.defaultDatabaseName || 'default_db', publiclyAccessible: props.publiclyAccessible || false, // Encryption kmsKeyId: props.encryptionKey?.keyId, encrypted: props.encrypted ?? true, classic: props.classicResizing, elasticIp: props.elasticIp, enhancedVpcRouting: props.enhancedVpcRouting, }); this.cluster.applyRemovalPolicy(removalPolicy, { applyToUpdateReplacePolicy: true, }); this.clusterName = this.cluster.ref; // create a number token that represents the port of the cluster const portAttribute = Token.asNumber(this.cluster.attrEndpointPort); this.clusterEndpoint = new Endpoint(this.cluster.attrEndpointAddress, portAttribute); if (secret) { this.secret = secret.attach(this); } const defaultPort = ec2.Port.tcp(this.clusterEndpoint.port); this.connections = new ec2.Connections({ securityGroups, defaultPort }); if (props.rebootForParameterChanges) { this.enableRebootForParameterChanges(); } // Add default role if specified and also available in the roles list if (props.defaultRole) { if (props.roles?.some(x => x === props.defaultRole)) { this.addDefaultIamRole(props.defaultRole); } else { throw new Error('Default role must be included in role list.'); } } } /** * Adds the single user rotation of the master password to this cluster. * * @param [automaticallyAfter=Duration.days(30)] Specifies the number of days after the previous rotation * before Secrets Manager triggers the next automatic rotation. */ public addRotationSingleUser(automaticallyAfter?: Duration): secretsmanager.SecretRotation { if (!this.secret) { throw new Error('Cannot add single user rotation for a cluster without secret.'); } const id = 'RotationSingleUser'; const existing = this.node.tryFindChild(id); if (existing)
{ throw new Error('A single user rotation was already added to this cluster.'); }
conditional_block
cluster.ts
*/ readonly clusterName: string; /** * Cluster endpoint address */ readonly clusterEndpointAddress: string; /** * Cluster endpoint port */ readonly clusterEndpointPort: number; } /** * Properties for a new database cluster */ export interface ClusterProps { /** * An optional identifier for the cluster * * @default - A name is automatically generated. */ readonly clusterName?: string; /** * Additional parameters to pass to the database engine * https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-parameter-groups.html * * @default - No parameter group. */ readonly parameterGroup?: IClusterParameterGroup; /** * Number of compute nodes in the cluster. Only specify this property for multi-node clusters. * * Value must be at least 2 and no more than 100. * * @default - 2 if `clusterType` is ClusterType.MULTI_NODE, undefined otherwise */ readonly numberOfNodes?: number; /** * The node type to be provisioned for the cluster. * * @default `NodeType.DC2_LARGE` */ readonly nodeType?: NodeType; /** * Settings for the individual instances that are launched * * @default `ClusterType.MULTI_NODE` */ readonly clusterType?: ClusterType; /** * What port to listen on * * @default - The default for the engine is used. */ readonly port?: number; /** * Whether to enable encryption of data at rest in the cluster. * * @default true */ readonly encrypted?: boolean /** * The KMS key to use for encryption of data at rest. * * @default - AWS-managed key, if encryption at rest is enabled */ readonly encryptionKey?: kms.IKey; /** * A preferred maintenance window day/time range. Should be specified as a range ddd:hh24:mi-ddd:hh24:mi (24H Clock UTC). * * Example: 'Sun:23:45-Mon:00:15' * * @default - 30-minute window selected at random from an 8-hour block of time for * each AWS Region, occurring on a random day of the week. * @see https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_UpgradeDBInstance.Maintenance.html#Concepts.DBMaintenance */ readonly preferredMaintenanceWindow?: string; /** * The VPC to place the cluster in. */ readonly vpc: ec2.IVpc; /** * Where to place the instances within the VPC * * @default - private subnets */ readonly vpcSubnets?: ec2.SubnetSelection; /** * Security group. * * @default - a new security group is created. */ readonly securityGroups?: ec2.ISecurityGroup[]; /** * A cluster subnet group to use with this cluster. * * @default - a new subnet group will be created. */ readonly subnetGroup?: IClusterSubnetGroup; /** * Username and password for the administrative user */ readonly masterUser: Login; /** * A list of AWS Identity and Access Management (IAM) role that can be used by the cluster to access other AWS services. * The maximum number of roles to attach to a cluster is subject to a quota. * * @default - No role is attached to the cluster. */ readonly roles?: iam.IRole[]; /** * A single AWS Identity and Access Management (IAM) role to be used as the default role for the cluster. * The default role must be included in the roles list. * * @default - No default role is specified for the cluster. */ readonly defaultRole?: iam.IRole; /** * Name of a database which is automatically created inside the cluster * * @default - default_db */ readonly defaultDatabaseName?: string; /** * Bucket details for log files to be sent to, including prefix. * * @default - No logging bucket is used */ readonly loggingProperties?: LoggingProperties; /** * The removal policy to apply when the cluster and its instances are removed * from the stack or replaced during an update. * * @default RemovalPolicy.RETAIN */ readonly removalPolicy?: RemovalPolicy /** * Whether to make cluster publicly accessible. * * @default false */ readonly publiclyAccessible?: boolean /** * If this flag is set, the cluster resizing type will be set to classic. * When resizing a cluster, classic resizing will always provision a new cluster and transfer the data there. * * Classic resize takes more time to complete, but it can be useful in cases where the change in node count or * the node type to migrate to doesn't fall within the bounds for elastic resize. * * @see https://docs.aws.amazon.com/redshift/latest/mgmt/managing-cluster-operations.html#elastic-resize * * @default - Elastic resize type */ readonly classicResizing?: boolean /** * The Elastic IP (EIP) address for the cluster. * * @see https://docs.aws.amazon.com/redshift/latest/mgmt/managing-clusters-vpc.html * * @default - No Elastic IP */ readonly elasticIp?: string /** * If this flag is set, the cluster will be rebooted when changes to the cluster's parameter group that require a restart to apply. * @default false */ readonly rebootForParameterChanges?: boolean /** * If this flag is set, Amazon Redshift forces all COPY and UNLOAD traffic between your cluster and your data repositories through your virtual private cloud (VPC). * * @see https://docs.aws.amazon.com/redshift/latest/mgmt/enhanced-vpc-routing.html * * @default - false */ readonly enhancedVpcRouting?: boolean } /** * A new or imported clustered database. */ abstract class ClusterBase extends Resource implements ICluster { /** * Name of the cluster */ public abstract readonly clusterName: string; /** * The endpoint to use for read/write operations */ public abstract readonly clusterEndpoint: Endpoint; /** * Access to the network connections */ public abstract readonly connections: ec2.Connections; /** * Renders the secret attachment target specifications. */ public asSecretAttachmentTarget(): secretsmanager.SecretAttachmentTargetProps { return { targetId: this.clusterName, targetType: secretsmanager.AttachmentTargetType.REDSHIFT_CLUSTER, }; } } /** * Create a Redshift cluster a given number of nodes. * * @resource AWS::Redshift::Cluster */ export class Cluster extends ClusterBase { /** * Import an existing DatabaseCluster from properties */ public static fromClusterAttributes(scope: Construct, id: string, attrs: ClusterAttributes): ICluster
/** * Identifier of the cluster */ public readonly clusterName: string; /** * The endpoint to use for read/write operations */ public readonly clusterEndpoint: Endpoint; /** * Access to the network connections */ public readonly connections: ec2.Connections; /** * The secret attached to this cluster */ public readonly secret?: secretsmanager.ISecret; private readonly singleUserRotationApplication: secretsmanager.SecretRotationApplication; private readonly multiUserRotationApplication: secretsmanager.SecretRotationApplication; /** * The VPC where the DB subnet group is created. */ private readonly vpc: ec2.IVpc; /** * The subnets used by the DB subnet group. */ private readonly vpcSubnets?: ec2.SubnetSelection; /** * The underlying CfnCluster */ private readonly cluster: CfnCluster; /** * The cluster's parameter group */ protected parameterGroup?: IClusterParameterGroup; /** * The ARNs of the roles that will be attached to the cluster. * * **NOTE** Please do not access this directly, use the `addIamRole` method instead. */ private readonly roles: iam.IRole[]; constructor(scope: Construct, id: string, props: ClusterProps) { super(scope, id); this.vpc = props.vpc; this.vpcSubnets = props.vpcSubnets ?? { subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS, }; this.parameterGroup = props.parameterGroup; this.roles = props?.roles ? [...props.roles] : []; const removalPolicy = props.removalPolicy ?? RemovalPolicy.RETAIN; const subnetGroup = props.subnetGroup ?? new ClusterSubnetGroup(this, 'Subnets', { description: `Sub
{ class Import extends ClusterBase { public readonly connections = new ec2.Connections({ securityGroups: attrs.securityGroups, defaultPort: ec2.Port.tcp(attrs.clusterEndpointPort), }); public readonly clusterName = attrs.clusterName; public readonly instanceIdentifiers: string[] = []; public readonly clusterEndpoint = new Endpoint(attrs.clusterEndpointAddress, attrs.clusterEndpointPort); } return new Import(scope, id); }
identifier_body
ipProcess.py
of class instances containing recorded data. a = [] for t in range(len(fileArr)): a.append(fileClass()) # Read the data in from the files. for t in range(len(a)): # Packet choice if saving raw voltages. rawPkt = 102 # 1-indexed. filePath = os.path.join(rawFolder, fileArr[t]) a[t].introduce(fileArr[t]) a[t].readTxt(filePath, saveThis) # Remove unwanted fields to cut down on the saved file size. if saveThis == 'zAnyF' or saveThis == 'upsideDown': del a[t].raw del a[t].fft del a[t].phaseUnCorr del a[t].mag16Bit if not savePhase: del a[t].phase # Array mask for saving. mask = sp.zeros(a[t].n, dtype=bool) # Save non-zero frequencies and the DC frequency. mask[:freqCount + 1] = True a[t].freq = a[t].freq[mask] a[t].phaseDiff = a[t].phaseDiff[..., mask] a[t].magPhys = a[t].magPhys[..., mask] a[t].zMag = a[t].zMag[..., mask] if savePhase: a[t].phase = a[t].phase[..., mask] elif saveThis == 'raw': del a[t].fft del a[t].phaseUnCorr del a[t].mag16Bit del a[t].phase del a[t].freq del a[t].phaseDiff del a[t].magPhys del a[t].zMag p = cs.find(a[t].pkt, rawPkt) if p == -1: # Save the last packet if the requested packet number isn't in # the file. rawPkt = a[t].pkt[p] a[t].raw = a[t].raw[:, p, :] # Overwrite the list of packet numbers with the one packet number # that was saved. a[t].pkt = rawPkt # Save the object to a file named after the folder name. lastSlash = pklFolder.rfind('\\') saveFile = pklFolder[lastSlash+1:] + '_' + saveThis + '.pkl' savePath = os.path.join(pklFolder, saveFile) # Saving the list object: with open(savePath, 'wb') as f: # Python 3: open(..., 'wb') pickle.dump(a, f) class fileClass: def introduce(self, fileName): print('Creating %s from %s.' % (self, fileName)) def readTxt(self, filePath, saveThis): # Read IP measurements from a text file. with open(filePath, 'r') as fh: # Number of lines in the file. lineCount = self.countLines(fh) # Rewind the pointer in the file back to the beginning. fh.seek(0) # Initialize the packet counter. p = -1 # Initialize the sample index. s = -1 for lidx, line in enumerate(fh, 1): # Strip off trailing newline characters. line = line.rstrip('\n') if s >= 0: # Read in raw voltage values. self.raw[:, p, s] = ( sp.fromstring(line, dtype=float, sep=',')) if s == self.n - 1: # Reset the counter to below zero. s = -1 else: # Increment the sample counter for the next read. s += 1 elif lidx > 10: if line[0] == '$': # Increment the packet index. p += 1 # Reset the time domain quality parameter index. qp = 0 # Packet number self.pkt[p] = int(line[1:]) elif line[0] == '\'': # CPU UTC Date and Time Strings. (self.cpuDTStr[p].d, self.cpuDTStr[p].t) = line[1:].split(',') # Translate to datetime object. self.cpuDT[p] = self.str2DateTime(self.cpuDTStr[p]) elif line[0] == '@': # GPS UTC Date and Time Strings, # and latitude and longitude fixes. (self.gpsDTStr[p].d, self.gpsDTStr[p].t, self.lat[p], self.longi[p]) = line[1:].split(',') # Translate to datetime object. self.gpsDT[p] = self.str2DateTime(self.gpsDTStr[p]) # Type casting. self.lat[p] = float(self.lat[p]) self.longi[p] = float(self.longi[p]) elif qp < 7: qp += 1 if qp == 3 or qp == 4 or qp == 5: typ = float # Means are saved as floats. else: typ = int # Counts are saved as integers. assignArr = sp.fromstring(line, dtype=typ, sep=',') if qp == 1: # Count of measurements clipped on the high end of # the MccDaq board's input range. self.clipHi[:, p] = assignArr elif qp == 2: # Count of measurements clipped on the low end of # the MccDaq board's input range. self.clipLo[:, p] = assignArr elif qp == 3: # Mean measurement value over the packet as a # percentage of the AIn() half range. self.meanPct[:, p] = assignArr elif qp == 4: # (pct) Mean value of sample measurements above # or equal to the mean. self.meanUpPct[:, p] = assignArr elif qp == 5: # (pct) Mean value of sample measurements below # the mean. self.meanDnPct[:, p] = assignArr elif qp == 6: # Count of measurements above or equal to the mean. self.countUp[:, p] = assignArr elif qp == 7: # Count of measurements below the mean. self.countDn[:, p] = assignArr # Set the sample index to 0 to start. s = 0 elif lidx == 1: (self.fileDateStr, # UTC date file was created. self.fileNum) = line.split(',') # File number in set. # Type casting. self.fileNum = int(self.fileNum) elif lidx == 2: self.descript = line # Description of the test. elif lidx == 3: self.minor = line # Minor note. elif lidx == 4: self.major = line # Major note. elif lidx == 5: (self.scanChCount, # number of channels in each A/D scan. self.chCount, # number of channels written to the file. self.n, # Number of samples in the FFT time series. self.fs, # (Hz) FFT sampling frequency. self.xmitFund) = line.split(',') # (Hz) Transmit Square # wave fundamental frequency. # Type casting. self.scanChCount = int(self.scanChCount) self.chCount = int(self.chCount) self.n = int(self.n) self.fs = int(self.fs) self.xmitFund = float(self.xmitFund) # Each file contains a file header of length 10 lines, # followed by packets. Packets contain (11 + n) lines each. self.pktCount = int((lineCount - 10)/(11 + self.n)) # Dimension arrays indexed by packet. self.dimArrays() elif lidx == 6:
elif lidx == 7: # Voltage measurement names. # 0-indexed by channel number. self.measStr = line.split(',') elif lidx == 8: # Construct arrays using the scipy package. # 5B amplifier maximum of the input range (V). # 0-indexed by channel number. self.In5BHi = sp.fromstring(line, dtype=float, sep=',') elif lidx == 9: # 5B amplifier maximum of the output range (V). # 0-indexed by channel number. self.Out5BHi = sp.fromstring(line, dtype=float, sep=',') elif lidx == 10: # MccDaq board AIn() maximum of the input range (V). # 0-indexed by channel number. self.ALoadQHi = sp.fromstring(line, dtype=float, sep=',') # After the file has been read, perform some calculations. self.postRead(saveThis) def dimArrays(self): # Initialize numpy arrays and python lists as zeros. shape2D =
(self.rCurrentMeas, # (Ohm) resistance. self.rExtraSeries) = line.split(',') # (Ohm). # Type casting. self.rCurrentMeas = float(self.rCurrentMeas) self.rExtraSeries = float(self.rCurrentMeas)
conditional_block
ipProcess.py
enumerate(fh, 1): # Strip off trailing newline characters. line = line.rstrip('\n') if s >= 0: # Read in raw voltage values. self.raw[:, p, s] = ( sp.fromstring(line, dtype=float, sep=',')) if s == self.n - 1: # Reset the counter to below zero. s = -1 else: # Increment the sample counter for the next read. s += 1 elif lidx > 10: if line[0] == '$': # Increment the packet index. p += 1 # Reset the time domain quality parameter index. qp = 0 # Packet number self.pkt[p] = int(line[1:]) elif line[0] == '\'': # CPU UTC Date and Time Strings. (self.cpuDTStr[p].d, self.cpuDTStr[p].t) = line[1:].split(',') # Translate to datetime object. self.cpuDT[p] = self.str2DateTime(self.cpuDTStr[p]) elif line[0] == '@': # GPS UTC Date and Time Strings, # and latitude and longitude fixes. (self.gpsDTStr[p].d, self.gpsDTStr[p].t, self.lat[p], self.longi[p]) = line[1:].split(',') # Translate to datetime object. self.gpsDT[p] = self.str2DateTime(self.gpsDTStr[p]) # Type casting. self.lat[p] = float(self.lat[p]) self.longi[p] = float(self.longi[p]) elif qp < 7: qp += 1 if qp == 3 or qp == 4 or qp == 5: typ = float # Means are saved as floats. else: typ = int # Counts are saved as integers. assignArr = sp.fromstring(line, dtype=typ, sep=',') if qp == 1: # Count of measurements clipped on the high end of # the MccDaq board's input range. self.clipHi[:, p] = assignArr elif qp == 2: # Count of measurements clipped on the low end of # the MccDaq board's input range. self.clipLo[:, p] = assignArr elif qp == 3: # Mean measurement value over the packet as a # percentage of the AIn() half range. self.meanPct[:, p] = assignArr elif qp == 4: # (pct) Mean value of sample measurements above # or equal to the mean. self.meanUpPct[:, p] = assignArr elif qp == 5: # (pct) Mean value of sample measurements below # the mean. self.meanDnPct[:, p] = assignArr elif qp == 6: # Count of measurements above or equal to the mean. self.countUp[:, p] = assignArr elif qp == 7: # Count of measurements below the mean. self.countDn[:, p] = assignArr # Set the sample index to 0 to start. s = 0 elif lidx == 1: (self.fileDateStr, # UTC date file was created. self.fileNum) = line.split(',') # File number in set. # Type casting. self.fileNum = int(self.fileNum) elif lidx == 2: self.descript = line # Description of the test. elif lidx == 3: self.minor = line # Minor note. elif lidx == 4: self.major = line # Major note. elif lidx == 5: (self.scanChCount, # number of channels in each A/D scan. self.chCount, # number of channels written to the file. self.n, # Number of samples in the FFT time series. self.fs, # (Hz) FFT sampling frequency. self.xmitFund) = line.split(',') # (Hz) Transmit Square # wave fundamental frequency. # Type casting. self.scanChCount = int(self.scanChCount) self.chCount = int(self.chCount) self.n = int(self.n) self.fs = int(self.fs) self.xmitFund = float(self.xmitFund) # Each file contains a file header of length 10 lines, # followed by packets. Packets contain (11 + n) lines each. self.pktCount = int((lineCount - 10)/(11 + self.n)) # Dimension arrays indexed by packet. self.dimArrays() elif lidx == 6: (self.rCurrentMeas, # (Ohm) resistance. self.rExtraSeries) = line.split(',') # (Ohm). # Type casting. self.rCurrentMeas = float(self.rCurrentMeas) self.rExtraSeries = float(self.rCurrentMeas) elif lidx == 7: # Voltage measurement names. # 0-indexed by channel number. self.measStr = line.split(',') elif lidx == 8: # Construct arrays using the scipy package. # 5B amplifier maximum of the input range (V). # 0-indexed by channel number. self.In5BHi = sp.fromstring(line, dtype=float, sep=',') elif lidx == 9: # 5B amplifier maximum of the output range (V). # 0-indexed by channel number. self.Out5BHi = sp.fromstring(line, dtype=float, sep=',') elif lidx == 10: # MccDaq board AIn() maximum of the input range (V). # 0-indexed by channel number. self.ALoadQHi = sp.fromstring(line, dtype=float, sep=',') # After the file has been read, perform some calculations. self.postRead(saveThis) def dimArrays(self): # Initialize numpy arrays and python lists as zeros. shape2D = (self.chCount, self.pktCount) # 0-indexed by packet number. self.pkt = sp.zeros(self.pktCount, dtype=int) self.cpuDTStr = [cs.emptyClass()]*self.pktCount self.cpuDT = [0]*self.pktCount self.gpsDTStr = [cs.emptyClass()]*self.pktCount self.gpsDT = [0]*self.pktCount self.lat = sp.zeros(self.pktCount, dtype=float) self.longi = sp.zeros(self.pktCount, dtype=float) # 0-indexed by channel number. # 0-indexed by packet number. self.clipHi = sp.zeros(shape2D, dtype=int) self.clipLo = sp.zeros(shape2D, dtype=int) self.meanPct = sp.zeros(shape2D, dtype=float) self.meanUpPct = sp.zeros(shape2D, dtype=float) self.meanDnPct = sp.zeros(shape2D, dtype=float) self.meanPhys = sp.zeros(shape2D, dtype=float) self.meanUpPhys = sp.zeros(shape2D, dtype=float) self.meanDnPhys = sp.zeros(shape2D, dtype=float) self.countUp = sp.zeros(shape2D, dtype=int) self.countDn = sp.zeros(shape2D, dtype=int) # 0-indexed by channel number. # 0-indexed by packet number. # 0-indexed by sample number. self.raw = sp.zeros((self.chCount, self.pktCount, self.n), dtype=float) def str2DateTime(self, dTStr): YY = 2000 + int(dTStr.d[0: 0+2]) MO = int(dTStr.d[2: 2+2]) DD = int(dTStr.d[4: 4+2]) HH = int(dTStr.t[0: 0+2]) MM = int(dTStr.t[2: 2+2]) SS = int(dTStr.t[4: 4+2]) micro = 1000 * int(dTStr.t[7: 7+3]) if YY == 2000: return datetime.min else: return datetime(YY, MO, DD, HH, MM, SS, micro) def computePhys(self, currentCh): self.meanPhys = self.pct2Phys(self.meanPct, currentCh) self.meanUpPhys = self.pct2Phys(self.meanUpPct, currentCh) self.meanDnPhys = self.pct2Phys(self.meanDnPct, currentCh) def pct2Phys(self, pct, currentCh):
phys = sp.zeros_like(pct, dtype=float) for ch in range(self.chCount): phys[ch, :] = (pct[ch, :] / 100 * self.ALoadQHi[ch] * self.In5BHi[ch] / self.Out5BHi[ch]) # (V) # Convert the voltage on the current measurement channel to a current. phys[currentCh, :] /= self.rCurrentMeas # (A) return phys
identifier_body
ipProcess.py
string(line, dtype=float, sep=',')) if s == self.n - 1: # Reset the counter to below zero. s = -1 else: # Increment the sample counter for the next read. s += 1 elif lidx > 10: if line[0] == '$': # Increment the packet index. p += 1 # Reset the time domain quality parameter index. qp = 0 # Packet number self.pkt[p] = int(line[1:]) elif line[0] == '\'': # CPU UTC Date and Time Strings. (self.cpuDTStr[p].d, self.cpuDTStr[p].t) = line[1:].split(',') # Translate to datetime object. self.cpuDT[p] = self.str2DateTime(self.cpuDTStr[p]) elif line[0] == '@': # GPS UTC Date and Time Strings, # and latitude and longitude fixes. (self.gpsDTStr[p].d, self.gpsDTStr[p].t, self.lat[p], self.longi[p]) = line[1:].split(',') # Translate to datetime object. self.gpsDT[p] = self.str2DateTime(self.gpsDTStr[p]) # Type casting. self.lat[p] = float(self.lat[p]) self.longi[p] = float(self.longi[p]) elif qp < 7: qp += 1 if qp == 3 or qp == 4 or qp == 5: typ = float # Means are saved as floats. else: typ = int # Counts are saved as integers. assignArr = sp.fromstring(line, dtype=typ, sep=',') if qp == 1: # Count of measurements clipped on the high end of # the MccDaq board's input range. self.clipHi[:, p] = assignArr elif qp == 2: # Count of measurements clipped on the low end of # the MccDaq board's input range. self.clipLo[:, p] = assignArr elif qp == 3: # Mean measurement value over the packet as a # percentage of the AIn() half range. self.meanPct[:, p] = assignArr elif qp == 4: # (pct) Mean value of sample measurements above # or equal to the mean. self.meanUpPct[:, p] = assignArr elif qp == 5: # (pct) Mean value of sample measurements below # the mean. self.meanDnPct[:, p] = assignArr elif qp == 6: # Count of measurements above or equal to the mean. self.countUp[:, p] = assignArr elif qp == 7: # Count of measurements below the mean. self.countDn[:, p] = assignArr # Set the sample index to 0 to start. s = 0 elif lidx == 1: (self.fileDateStr, # UTC date file was created. self.fileNum) = line.split(',') # File number in set. # Type casting. self.fileNum = int(self.fileNum) elif lidx == 2: self.descript = line # Description of the test. elif lidx == 3: self.minor = line # Minor note. elif lidx == 4: self.major = line # Major note. elif lidx == 5: (self.scanChCount, # number of channels in each A/D scan. self.chCount, # number of channels written to the file. self.n, # Number of samples in the FFT time series. self.fs, # (Hz) FFT sampling frequency. self.xmitFund) = line.split(',') # (Hz) Transmit Square # wave fundamental frequency. # Type casting. self.scanChCount = int(self.scanChCount) self.chCount = int(self.chCount) self.n = int(self.n) self.fs = int(self.fs) self.xmitFund = float(self.xmitFund) # Each file contains a file header of length 10 lines, # followed by packets. Packets contain (11 + n) lines each. self.pktCount = int((lineCount - 10)/(11 + self.n)) # Dimension arrays indexed by packet. self.dimArrays() elif lidx == 6: (self.rCurrentMeas, # (Ohm) resistance. self.rExtraSeries) = line.split(',') # (Ohm). # Type casting. self.rCurrentMeas = float(self.rCurrentMeas) self.rExtraSeries = float(self.rCurrentMeas) elif lidx == 7: # Voltage measurement names. # 0-indexed by channel number. self.measStr = line.split(',') elif lidx == 8: # Construct arrays using the scipy package. # 5B amplifier maximum of the input range (V). # 0-indexed by channel number. self.In5BHi = sp.fromstring(line, dtype=float, sep=',') elif lidx == 9: # 5B amplifier maximum of the output range (V). # 0-indexed by channel number. self.Out5BHi = sp.fromstring(line, dtype=float, sep=',') elif lidx == 10: # MccDaq board AIn() maximum of the input range (V). # 0-indexed by channel number. self.ALoadQHi = sp.fromstring(line, dtype=float, sep=',') # After the file has been read, perform some calculations. self.postRead(saveThis) def dimArrays(self): # Initialize numpy arrays and python lists as zeros. shape2D = (self.chCount, self.pktCount) # 0-indexed by packet number. self.pkt = sp.zeros(self.pktCount, dtype=int) self.cpuDTStr = [cs.emptyClass()]*self.pktCount self.cpuDT = [0]*self.pktCount self.gpsDTStr = [cs.emptyClass()]*self.pktCount self.gpsDT = [0]*self.pktCount self.lat = sp.zeros(self.pktCount, dtype=float) self.longi = sp.zeros(self.pktCount, dtype=float) # 0-indexed by channel number. # 0-indexed by packet number. self.clipHi = sp.zeros(shape2D, dtype=int) self.clipLo = sp.zeros(shape2D, dtype=int) self.meanPct = sp.zeros(shape2D, dtype=float) self.meanUpPct = sp.zeros(shape2D, dtype=float) self.meanDnPct = sp.zeros(shape2D, dtype=float) self.meanPhys = sp.zeros(shape2D, dtype=float) self.meanUpPhys = sp.zeros(shape2D, dtype=float) self.meanDnPhys = sp.zeros(shape2D, dtype=float) self.countUp = sp.zeros(shape2D, dtype=int) self.countDn = sp.zeros(shape2D, dtype=int) # 0-indexed by channel number. # 0-indexed by packet number. # 0-indexed by sample number. self.raw = sp.zeros((self.chCount, self.pktCount, self.n), dtype=float) def str2DateTime(self, dTStr): YY = 2000 + int(dTStr.d[0: 0+2]) MO = int(dTStr.d[2: 2+2]) DD = int(dTStr.d[4: 4+2]) HH = int(dTStr.t[0: 0+2]) MM = int(dTStr.t[2: 2+2]) SS = int(dTStr.t[4: 4+2]) micro = 1000 * int(dTStr.t[7: 7+3]) if YY == 2000: return datetime.min else: return datetime(YY, MO, DD, HH, MM, SS, micro) def computePhys(self, currentCh): self.meanPhys = self.pct2Phys(self.meanPct, currentCh) self.meanUpPhys = self.pct2Phys(self.meanUpPct, currentCh) self.meanDnPhys = self.pct2Phys(self.meanDnPct, currentCh) def pct2Phys(self, pct, currentCh): phys = sp.zeros_like(pct, dtype=float) for ch in range(self.chCount): phys[ch, :] = (pct[ch, :] / 100 * self.ALoadQHi[ch] * self.In5BHi[ch] / self.Out5BHi[ch]) # (V) # Convert the voltage on the current measurement channel to a current. phys[currentCh, :] /= self.rCurrentMeas # (A) return phys def countLines(self, fh): # Counter lidx starts counting at 1 for the first line. for lidx, line in enumerate(fh, 1): pass return lidx def
postRead
identifier_name
ipProcess.py
of class instances containing recorded data. a = [] for t in range(len(fileArr)): a.append(fileClass()) # Read the data in from the files. for t in range(len(a)): # Packet choice if saving raw voltages. rawPkt = 102 # 1-indexed. filePath = os.path.join(rawFolder, fileArr[t]) a[t].introduce(fileArr[t]) a[t].readTxt(filePath, saveThis) # Remove unwanted fields to cut down on the saved file size. if saveThis == 'zAnyF' or saveThis == 'upsideDown': del a[t].raw del a[t].fft del a[t].phaseUnCorr del a[t].mag16Bit if not savePhase: del a[t].phase # Array mask for saving. mask = sp.zeros(a[t].n, dtype=bool) # Save non-zero frequencies and the DC frequency. mask[:freqCount + 1] = True a[t].freq = a[t].freq[mask] a[t].phaseDiff = a[t].phaseDiff[..., mask] a[t].magPhys = a[t].magPhys[..., mask] a[t].zMag = a[t].zMag[..., mask] if savePhase: a[t].phase = a[t].phase[..., mask] elif saveThis == 'raw': del a[t].fft del a[t].phaseUnCorr del a[t].mag16Bit del a[t].phase del a[t].freq del a[t].phaseDiff del a[t].magPhys del a[t].zMag p = cs.find(a[t].pkt, rawPkt) if p == -1: # Save the last packet if the requested packet number isn't in # the file. rawPkt = a[t].pkt[p] a[t].raw = a[t].raw[:, p, :] # Overwrite the list of packet numbers with the one packet number # that was saved. a[t].pkt = rawPkt # Save the object to a file named after the folder name. lastSlash = pklFolder.rfind('\\') saveFile = pklFolder[lastSlash+1:] + '_' + saveThis + '.pkl' savePath = os.path.join(pklFolder, saveFile) # Saving the list object: with open(savePath, 'wb') as f: # Python 3: open(..., 'wb') pickle.dump(a, f) class fileClass: def introduce(self, fileName): print('Creating %s from %s.' % (self, fileName)) def readTxt(self, filePath, saveThis): # Read IP measurements from a text file. with open(filePath, 'r') as fh: # Number of lines in the file. lineCount = self.countLines(fh) # Rewind the pointer in the file back to the beginning. fh.seek(0) # Initialize the packet counter. p = -1 # Initialize the sample index. s = -1 for lidx, line in enumerate(fh, 1): # Strip off trailing newline characters. line = line.rstrip('\n') if s >= 0: # Read in raw voltage values. self.raw[:, p, s] = ( sp.fromstring(line, dtype=float, sep=',')) if s == self.n - 1: # Reset the counter to below zero. s = -1 else: # Increment the sample counter for the next read. s += 1 elif lidx > 10: if line[0] == '$': # Increment the packet index. p += 1 # Reset the time domain quality parameter index. qp = 0 # Packet number self.pkt[p] = int(line[1:]) elif line[0] == '\'': # CPU UTC Date and Time Strings. (self.cpuDTStr[p].d, self.cpuDTStr[p].t) = line[1:].split(',') # Translate to datetime object. self.cpuDT[p] = self.str2DateTime(self.cpuDTStr[p]) elif line[0] == '@': # GPS UTC Date and Time Strings, # and latitude and longitude fixes. (self.gpsDTStr[p].d, self.gpsDTStr[p].t, self.lat[p], self.longi[p]) = line[1:].split(',') # Translate to datetime object. self.gpsDT[p] = self.str2DateTime(self.gpsDTStr[p]) # Type casting. self.lat[p] = float(self.lat[p])
if qp == 3 or qp == 4 or qp == 5: typ = float # Means are saved as floats. else: typ = int # Counts are saved as integers. assignArr = sp.fromstring(line, dtype=typ, sep=',') if qp == 1: # Count of measurements clipped on the high end of # the MccDaq board's input range. self.clipHi[:, p] = assignArr elif qp == 2: # Count of measurements clipped on the low end of # the MccDaq board's input range. self.clipLo[:, p] = assignArr elif qp == 3: # Mean measurement value over the packet as a # percentage of the AIn() half range. self.meanPct[:, p] = assignArr elif qp == 4: # (pct) Mean value of sample measurements above # or equal to the mean. self.meanUpPct[:, p] = assignArr elif qp == 5: # (pct) Mean value of sample measurements below # the mean. self.meanDnPct[:, p] = assignArr elif qp == 6: # Count of measurements above or equal to the mean. self.countUp[:, p] = assignArr elif qp == 7: # Count of measurements below the mean. self.countDn[:, p] = assignArr # Set the sample index to 0 to start. s = 0 elif lidx == 1: (self.fileDateStr, # UTC date file was created. self.fileNum) = line.split(',') # File number in set. # Type casting. self.fileNum = int(self.fileNum) elif lidx == 2: self.descript = line # Description of the test. elif lidx == 3: self.minor = line # Minor note. elif lidx == 4: self.major = line # Major note. elif lidx == 5: (self.scanChCount, # number of channels in each A/D scan. self.chCount, # number of channels written to the file. self.n, # Number of samples in the FFT time series. self.fs, # (Hz) FFT sampling frequency. self.xmitFund) = line.split(',') # (Hz) Transmit Square # wave fundamental frequency. # Type casting. self.scanChCount = int(self.scanChCount) self.chCount = int(self.chCount) self.n = int(self.n) self.fs = int(self.fs) self.xmitFund = float(self.xmitFund) # Each file contains a file header of length 10 lines, # followed by packets. Packets contain (11 + n) lines each. self.pktCount = int((lineCount - 10)/(11 + self.n)) # Dimension arrays indexed by packet. self.dimArrays() elif lidx == 6: (self.rCurrentMeas, # (Ohm) resistance. self.rExtraSeries) = line.split(',') # (Ohm). # Type casting. self.rCurrentMeas = float(self.rCurrentMeas) self.rExtraSeries = float(self.rCurrentMeas) elif lidx == 7: # Voltage measurement names. # 0-indexed by channel number. self.measStr = line.split(',') elif lidx == 8: # Construct arrays using the scipy package. # 5B amplifier maximum of the input range (V). # 0-indexed by channel number. self.In5BHi = sp.fromstring(line, dtype=float, sep=',') elif lidx == 9: # 5B amplifier maximum of the output range (V). # 0-indexed by channel number. self.Out5BHi = sp.fromstring(line, dtype=float, sep=',') elif lidx == 10: # MccDaq board AIn() maximum of the input range (V). # 0-indexed by channel number. self.ALoadQHi = sp.fromstring(line, dtype=float, sep=',') # After the file has been read, perform some calculations. self.postRead(saveThis) def dimArrays(self): # Initialize numpy arrays and python lists as zeros. shape2D = (
self.longi[p] = float(self.longi[p]) elif qp < 7: qp += 1
random_line_split