file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
kek.py
#Импортирование библиотек import PySimpleGUI as sg from nltk.tokenize import word_tokenize from nltk.corpus import stopwords from nltk.stem import PorterStemmer import matplotlib.pyplot as plt from wordcloud import WordCloud from math import log
from sklearn.feature_extraction.text import TfidfTransformer from sklearn.naive_bayes import MultinomialNB from sklearn.metrics import confusion_matrix import pickle #Функция сохранения состояния обученности классификатора def save(obj): with open('sis.pickle', 'wb') as f: pickle.dump(obj, f) #Функция загрузки состояния обученности классификатора def load(): with open('sis.pickle', 'rb') as f: obj_new = pickle.load(f) return obj_new #Функция визуализации словаря спам слов def show_spam(spam_words): spam_wc = WordCloud(width = 512,height = 512).generate(spam_words) plt.figure(figsize = (10, 8), facecolor = 'k') plt.imshow(spam_wc) plt.axis('off') plt.tight_layout(pad = 0) plt.show() #Функция визуализации словаря легетимных слов def show_ham(ham_words): ham_wc = WordCloud(width = 512,height = 512).generate(ham_words) plt.figure(figsize = (10, 8), facecolor = 'k') plt.imshow(ham_wc) plt.axis('off') plt.tight_layout(pad = 0) plt.show() #Чтение данных из таблицы oldmails = pd.read_csv('spam.csv', encoding = 'latin-1') oldmails.head() mailz = pd.read_csv('messages.csv', encoding = 'latin-1') mailz.head() #Преобразовани таблицы с данными, удаление лишних столбцов oldmails.drop(['Unnamed: 2', 'Unnamed: 3', 'Unnamed: 4'], axis = 1, inplace = True) oldmails.head() mailz.drop(['subject'], axis = 1, inplace = True) mailz.head() #Преобразовани таблицы с данными, переименование столбцов oldmails.rename(columns = {'v1': 'labels', 'v2': 'message'}, inplace = True) oldmails.head() oldmails['labels'].value_counts() mailz['label'].value_counts() #Преобразовани таблицы с данными, переименование значений столбцов oldmails['label'] = oldmails['labels'].map({'ham': 0, 'spam': 1}) oldmails.head() #Преобразовани таблицы с данными, удаление лишних столбцов oldmails.drop(['labels'], axis = 1, inplace = True) oldmails.head() #Преобразовани таблицы с данными, слияние двух массивов для обучения mails = pd.concat((mailz, oldmails), ignore_index=True) #Разбиение данных на два массива totalMails = (int(len(mails))-1) trainIndex, testIndex = list(), list() for i in range(mails.shape[0]): if np.random.uniform(0, 1) < 0.75: trainIndex += [i] else: testIndex += [i] trainData = mails.loc[trainIndex] testData = mails.loc[testIndex] #Отображение данных в таблице trainData.reset_index(inplace = True) trainData.drop(['index'], axis = 1, inplace = True) trainData.head() testData.reset_index(inplace = True) testData.drop(['index'], axis = 1, inplace = True) testData.head() #Отображение набора тренировочных данных trainData['label'].value_counts() #Отображение набора данных для тестирования testData['label'].value_counts() #Формирование словрей спам и не спам слов spam_words = ' '.join(list(mails[mails['label'] == 1]['message'])) ham_words = ' '.join(list(mails[mails['label'] == 0]['message'])) trainData.head() trainData['label'].value_counts() testData.head() testData['label'].value_counts() #Обработка текста сообщений def process_message(message, lower_case = True, stem = True, stop_words = True, gram = 2): if lower_case: message = message.lower() words = word_tokenize(message) words = [w for w in words if len(w) > 2] if gram > 1: w = [] for i in range(len(words) - gram + 1): w += [' '.join(words[i:i + gram])] return w if stop_words: sw = stopwords.words('english') words = [word for word in words if word not in sw] if stem: stemmer = PorterStemmer() words = [stemmer.stem(word) for word in words] print(words) return words #Классификация данных class SpamClassifier(object): def __init__(self, trainData, method='tf-idf'): self.mails, self.labels = trainData['message'], trainData['label'] self.method = method #Функция обучения def train(self): self.calc_TF_and_IDF() if self.method == 'tf-idf': self.calc_TF_IDF() else: self.calc_prob() def calc_prob(self): self.prob_spam = dict() self.prob_ham = dict() for word in self.tf_spam: self.prob_spam[word] = (self.tf_spam[word] + 1) / (self.spam_words + \ len(list(self.tf_spam.keys()))) for word in self.tf_ham: self.prob_ham[word] = (self.tf_ham[word] + 1) / (self.ham_words + \ len(list(self.tf_ham.keys()))) self.prob_spam_mail, self.prob_ham_mail = self.spam_mails / self.total_mails, self.ham_mails / self.total_mails #Вычисление вероятностей def calc_TF_and_IDF(self): noOfMessages = self.mails.shape[0] self.spam_mails, self.ham_mails = self.labels.value_counts()[1], self.labels.value_counts()[0] self.total_mails = self.spam_mails + self.ham_mails self.spam_words = 0 self.ham_words = 0 self.tf_spam = dict() self.tf_ham = dict() self.idf_spam = dict() self.idf_ham = dict() for i in range(noOfMessages): message_processed = process_message(self.mails[i]) count = list() for word in message_processed: if self.labels[i]: self.tf_spam[word] = self.tf_spam.get(word, 0) + 1 self.spam_words += 1 else: self.tf_ham[word] = self.tf_ham.get(word, 0) + 1 self.ham_words += 1 if word not in count: count += [word] for word in count: if self.labels[i]: self.idf_spam[word] = self.idf_spam.get(word, 0) + 1 else: self.idf_ham[word] = self.idf_ham.get(word, 0) + 1 def calc_TF_IDF(self): self.prob_spam = dict() self.prob_ham = dict() self.sum_tf_idf_spam = 0 self.sum_tf_idf_ham = 0 for word in self.tf_spam: self.prob_spam[word] = (self.tf_spam[word]) * log((self.spam_mails + self.ham_mails) \ / (self.idf_spam[word] + self.idf_ham.get(word, 0))) self.sum_tf_idf_spam += self.prob_spam[word] for word in self.tf_spam: self.prob_spam[word] = (self.prob_spam[word] + 1) / ( self.sum_tf_idf_spam + len(list(self.prob_spam.keys()))) for word in self.tf_ham: self.prob_ham[word] = (self.tf_ham[word]) * log((self.spam_mails + self.ham_mails) \ / (self.idf_spam.get(word, 0) + self.idf_ham[word])) self.sum_tf_idf_ham += self.prob_ham[word] for word in self.tf_ham: self.prob_ham[word] = (self.prob_ham[word] + 1) / (self.sum_tf_idf_ham + len(list(self.prob_ham.keys()))) self.prob_spam_mail, self.prob_ham_mail = self.spam_mails / self.total_mails, self.ham_mails / self.total_mails #Непосредственно функция классификации на основе теоремы Байеса def classify(self, processed_message): pSpam, pHam = 0, 0 for word in processed_message: if word in self.prob_spam: pSpam += log(self.prob_spam[word]) else: if self.method == 'tf-idf': pSpam -= log(self.sum_tf_idf_spam + len(list(self.prob_spam.keys()))) else: pSpam -= log(self.spam_words + len(list(self.prob_spam.keys()))) if word in self.prob_ham: pHam += log(self.prob_ham[word]) else: if self.method == 'tf-idf': pHam -= log(self.sum_tf_idf_ham + len(list(self.prob_ham.keys()))) else: pHam -= log(self.ham_words + len(list(self.prob_ham.keys()))) pSpam += log(self.prob_spam_mail) pHam += log(self.prob_ham_mail) return pSpam >= pHam #Функция предсказания является ли сообщение спамом или нет def predict(self, testData): result = dict() for (i, message) in enumerate(testData): processed_message = process_message(message) result[i] = int(self.classify(processed_message)) return result #Функция вычисления качества работы алгоритма def metrics(labels, predictions): true_pos, true_neg, false_pos, false_neg = 0, 0, 0, 0 for i in range(len(labels)): true_pos += int(labels[i] == 1 and predictions[i] == 1) true_neg += int(labels[i] == 0 and predictions[i] == 0) false_pos += int(labels[i] == 0 and predictions[i] == 1) false_neg += int(labels[i] == 1 and predictions[i] == 0) precision = true_pos / (true_pos + false_pos) recall = true_pos / (true_pos + false_neg) Fscore = 2 * precision * recall / (precision + recall) accuracy = (true_pos + true_neg) / (true_pos + true_neg + false_pos + false_neg) return precision, recall, Fscore, accuracy df = mails #Обработка сообщений с помощью библиотек df['message'] = df.message.map(lambda x: x.lower()) df['message'] = df.message.str.replace('[^\w\s]', '') df['message'] = df['message'].apply(nltk.word_tokenize) stemmer = PorterStemmer() df['message'] = df['message'].apply(lambda x: [stemmer.stem(y) for y in x]) df['message'] = df['message'].apply(lambda x: ' '.join(x)) #Преобразование сообщений в таблицу векторов count_vect = CountVectorizer() counts = count_vect.fit_transform(df['message']) transformer = TfidfTransformer().fit(counts) counts = transformer.transform(counts) #Разбиение данных на обучающий и тестирующие наборы с использованием библиотек X_train, X_test, y_train, y_test = train_test_split(counts, df['label'], test_size=0.1, random_state=69) #Классификация данных с помощью библиотеки scikitlearn model = MultinomialNB().fit(X_train, y_train) #Вычисление качества работы алгоритма библиотеки predicted = model.predict(X_test) #Интерфейс программы layout = [ [sg.Button('Обучение'), sg.Button('Показать спам слова'), sg.Button('Показать не спам слова')], [sg.Text('Введите сообщение для проверки на спамовость')], [sg.Input(size=(50, 30), key='-IN-')], [sg.Button('Проверить'), sg.Button('Выход'), sg.Button('Посчитать метрики')] ] window = sg.Window('Настройка классификатора', layout) while True: event, values = window.read() if event == sg.WIN_CLOSED or event == 'Выход': break if event == 'Посчитать метрики': sc_tf_idf = load() preds_tf_idf = sc_tf_idf.predict(testData['message']) precision, recall, Fscore, accuracy = metrics(testData['label'], preds_tf_idf) sg.popup('Метрики', "Точность:", precision, "Полнота:", recall, "F-мера:", Fscore, "Численная оценка качества алгоритма:", accuracy, "Точность классификации для тестового набора данных:", np.mean(predicted == y_test), "Размер тестовой выборки:", len(y_test), "Количество легитимных писем попавших в не спам:", confusion_matrix(y_test, predicted)[0][0], "Количество легитимных писем попавших в спам:", confusion_matrix(y_test, predicted)[0][1], "Количество спам писем попавших в не спам:", confusion_matrix(y_test, predicted)[1][0], "Количество спам писем попавших в спам:", confusion_matrix(y_test, predicted)[1][1]) if event == 'Проверить': text_input = values['-IN-'] pm = process_message(text_input) sc_tf_idf = load() sc_tf_idf.classify(pm) if sc_tf_idf.classify(pm) == True: sg.popup('Спам') else: sg.popup('Не спам') if event == 'Показать спам слова': show_spam(spam_words) if event == 'Показать не спам слова': show_ham(ham_words) if event == 'Обучение': sc_tf_idf = SpamClassifier(trainData, 'tf-idf') sc_tf_idf.train() save(sc_tf_idf) window.close()
import numpy as np import pandas as pd import nltk from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import CountVectorizer
random_line_split
lib.rs
// Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). #![deny(warnings)] // Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to include inner attributes from a common source. #![deny( clippy::all, clippy::default_trait_access, clippy::expl_impl_clone_on_copy, clippy::if_not_else, clippy::needless_continue, clippy::unseparated_literal_suffix, clippy::used_underscore_binding )] // It is often more clear to show that nothing is being moved. #![allow(clippy::match_ref_pats)] // Subjective style. #![allow( clippy::len_without_is_empty, clippy::redundant_field_names, clippy::too_many_arguments )] // Default isn't as big a deal as people seem to think it is. #![allow(clippy::new_without_default, clippy::new_ret_no_self)] // Arc<Mutex> can be more clear than needing to grok Orderings: #![allow(clippy::mutex_atomic)] #[macro_use] extern crate derivative; use std::collections::{BTreeMap, BTreeSet, HashSet}; use std::convert::{TryFrom, TryInto}; use std::fmt::{self, Debug, Display}; use std::path::PathBuf; use std::sync::Arc; use async_trait::async_trait; use concrete_time::{Duration, TimeSpan}; use deepsize::DeepSizeOf; use fs::{DirectoryDigest, RelativePath, EMPTY_DIRECTORY_DIGEST}; use futures::future::try_join_all; use futures::try_join; use hashing::Digest; use itertools::Itertools; use protos::gen::build::bazel::remote::execution::v2 as remexec; use remexec::ExecutedActionMetadata; use serde::{Deserialize, Serialize}; use store::{SnapshotOps, Store, StoreError}; use task_executor::TailTasks; use workunit_store::{in_workunit, Level, RunId, RunningWorkunit, WorkunitStore}; pub mod bounded; #[cfg(test)] mod bounded_tests; pub mod cache; #[cfg(test)] mod cache_tests; pub mod switched; pub mod children; pub mod docker; #[cfg(test)] mod docker_tests; pub mod local; #[cfg(test)] mod local_tests; pub mod nailgun; pub mod named_caches; pub mod remote; #[cfg(test)] pub mod remote_tests; pub mod remote_cache; #[cfg(test)] mod remote_cache_tests; extern crate uname; pub use crate::children::ManagedChild; pub use crate::named_caches::{CacheName, NamedCaches}; pub use crate::remote_cache::RemoteCacheWarningsBehavior; use crate::remote::EntireExecuteRequest; #[derive(Clone, Debug, PartialEq, Eq)] pub enum ProcessError { /// A Digest was not present in either of the local or remote Stores. MissingDigest(String, Digest), /// All other error types. Unclassified(String), } impl ProcessError { pub fn enrich(self, prefix: &str) -> Self { match self { Self::MissingDigest(s, d) => Self::MissingDigest(format!("{prefix}: {s}"), d), Self::Unclassified(s) => Self::Unclassified(format!("{prefix}: {s}")), } } } impl Display for ProcessError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::MissingDigest(s, d) => { write!(f, "{s}: {d:?}") } Self::Unclassified(s) => write!(f, "{s}"), } } } impl From<StoreError> for ProcessError { fn from(err: StoreError) -> Self { match err { StoreError::MissingDigest(s, d) => Self::MissingDigest(s, d), StoreError::Unclassified(s) => Self::Unclassified(s), } } } impl From<String> for ProcessError { fn from(err: String) -> Self { Self::Unclassified(err) } } #[derive( PartialOrd, Ord, Clone, Copy, Debug, DeepSizeOf, Eq, PartialEq, Hash, Serialize, Deserialize, )] #[allow(non_camel_case_types)] pub enum Platform { Macos_x86_64, Macos_arm64, Linux_x86_64, Linux_arm64, } impl Platform { pub fn current() -> Result<Platform, String> { let platform_info = uname::uname().map_err(|_| "Failed to get local platform info!".to_string())?; match platform_info { uname::Info { ref sysname, ref machine, .. } if sysname.to_lowercase() == "linux" && machine.to_lowercase() == "x86_64" => { Ok(Platform::Linux_x86_64) } uname::Info { ref sysname, ref machine, .. } if sysname.to_lowercase() == "linux" && (machine.to_lowercase() == "arm64" || machine.to_lowercase() == "aarch64") => { Ok(Platform::Linux_arm64) } uname::Info { ref sysname, ref machine, .. } if sysname.to_lowercase() == "darwin" && machine.to_lowercase() == "arm64" => { Ok(Platform::Macos_arm64) } uname::Info { ref sysname, ref machine, .. } if sysname.to_lowercase() == "darwin" && machine.to_lowercase() == "x86_64" => { Ok(Platform::Macos_x86_64) } uname::Info { ref sysname, ref machine, .. } => Err(format!( "Found unknown system/arch name pair {sysname} {machine}" )), } } } impl From<Platform> for String { fn from(platform: Platform) -> String { match platform { Platform::Linux_x86_64 => "linux_x86_64".to_string(), Platform::Linux_arm64 => "linux_arm64".to_string(), Platform::Macos_arm64 => "macos_arm64".to_string(), Platform::Macos_x86_64 => "macos_x86_64".to_string(), } } } impl TryFrom<String> for Platform { type Error = String; fn try_from(variant_candidate: String) -> Result<Self, Self::Error> { match variant_candidate.as_ref() { "macos_arm64" => Ok(Platform::Macos_arm64), "macos_x86_64" => Ok(Platform::Macos_x86_64), "linux_x86_64" => Ok(Platform::Linux_x86_64), "linux_arm64" => Ok(Platform::Linux_arm64), other => Err(format!("Unknown platform {other:?} encountered in parsing")), } } } #[derive(Clone, Copy, Debug, DeepSizeOf, Eq, PartialEq, Hash, Serialize)] pub enum ProcessCacheScope { // Cached in all locations, regardless of success or failure. Always, // Cached in all locations, but only if the process exits successfully. Successful, // Cached only in memory (i.e. memoized in pantsd), but never persistently, regardless of // success vs. failure. PerRestartAlways, // Cached only in memory (i.e. memoized in pantsd), but never persistently, and only if // successful. PerRestartSuccessful, // Will run once per Session, i.e. once per run of Pants. This happens because the engine // de-duplicates identical work; the process is neither memoized in memory nor cached to disk. PerSession, } impl TryFrom<String> for ProcessCacheScope { type Error = String; fn try_from(variant_candidate: String) -> Result<Self, Self::Error> { match variant_candidate.to_lowercase().as_ref() { "always" => Ok(ProcessCacheScope::Always), "successful" => Ok(ProcessCacheScope::Successful), "per_restart_always" => Ok(ProcessCacheScope::PerRestartAlways), "per_restart_successful" => Ok(ProcessCacheScope::PerRestartSuccessful), "per_session" => Ok(ProcessCacheScope::PerSession), other => Err(format!("Unknown Process cache scope: {other:?}")), } } } fn serialize_level<S: serde::Serializer>(level: &log::Level, s: S) -> Result<S::Ok, S::Error> { s.serialize_str(&level.to_string()) } /// Input Digests for a process execution. /// /// The `complete` and `nailgun` Digests are the computed union of various inputs. /// /// TODO: See `crate::local::prepare_workdir` regarding validation of overlapping inputs. #[derive(Clone, Debug, DeepSizeOf, Eq, Hash, PartialEq, Serialize)] pub struct InputDigests { /// All of the input Digests, merged and relativized. Runners without the ability to consume the /// Digests individually should directly consume this value. pub complete: DirectoryDigest, /// The merged Digest of any `use_nailgun`-relevant Digests. pub nailgun: DirectoryDigest, /// The input files for the process execution, which will be materialized as mutable inputs in a /// sandbox for the process. /// /// TODO: Rename to `inputs` for symmetry with `immutable_inputs`. pub input_files: DirectoryDigest, /// Immutable input digests to make available in the input root. /// /// These digests are intended for inputs that will be reused between multiple Process /// invocations, without being mutated. This might be useful to provide the tools being executed, /// but can also be used for tool inputs such as compilation artifacts. /// /// The digests will be mounted at the relative path represented by the `RelativePath` keys. /// The executor may choose how to make the digests available, including by just merging /// the digest normally into the input root, creating a symlink to a persistent cache, /// or bind mounting the directory read-only into a persistent cache. Consequently, the mount /// point of each input must not overlap the `input_files`, even for directory entries. /// /// Assumes the build action does not modify the Digest as made available. This may be /// enforced by an executor, for example by bind mounting the directory read-only. pub immutable_inputs: BTreeMap<RelativePath, DirectoryDigest>, /// If non-empty, use nailgun in supported runners, using the specified `immutable_inputs` keys /// as server inputs. All other keys (and the input_files) will be client inputs. pub use_nailgun: BTreeSet<RelativePath>, } impl InputDigests { pub async fn new( store: &Store, input_files: DirectoryDigest, immutable_inputs: BTreeMap<RelativePath, DirectoryDigest>, use_nailgun: BTreeSet<RelativePath>, ) -> Result<Self, StoreError> { // Collect all digests into `complete`. let mut complete_digests = try_join_all( immutable_inputs .iter() .map(|(path, digest)| store.add_prefix(digest.clone(), path)) .collect::<Vec<_>>(), ) .await?; // And collect only the subset of the Digests which impact nailgun into `nailgun`. let nailgun_digests = immutable_inputs .keys() .zip(complete_digests.iter()) .filter_map(|(path, digest)| { if use_nailgun.contains(path) { Some(digest.clone()) } else { None } }) .collect::<Vec<_>>(); complete_digests.push(input_files.clone()); let (complete, nailgun) = try_join!(store.merge(complete_digests), store.merge(nailgun_digests),)?; Ok(Self { complete: complete, nailgun: nailgun, input_files, immutable_inputs, use_nailgun, }) } pub async fn new_from_merged(store: &Store, from: Vec<InputDigests>) -> Result<Self, StoreError> { let mut merged_immutable_inputs = BTreeMap::new(); for input_digests in from.iter() { let size_before = merged_immutable_inputs.len(); let immutable_inputs = &input_digests.immutable_inputs; merged_immutable_inputs.append(&mut immutable_inputs.clone()); if size_before + immutable_inputs.len() != merged_immutable_inputs.len() { return Err( format!( "Tried to merge two-or-more immutable inputs at the same path with different values! \ The collision involved one of the entries in: {immutable_inputs:?}" ) .into(), ); } } let complete_digests = from .iter() .map(|input_digests| input_digests.complete.clone()) .collect(); let nailgun_digests = from .iter() .map(|input_digests| input_digests.nailgun.clone()) .collect(); let input_files_digests = from .iter() .map(|input_digests| input_digests.input_files.clone()) .collect(); let (complete, nailgun, input_files) = try_join!( store.merge(complete_digests), store.merge(nailgun_digests), store.merge(input_files_digests), )?; Ok(Self { complete: complete, nailgun: nailgun, input_files: input_files, immutable_inputs: merged_immutable_inputs, use_nailgun: Itertools::concat( from .iter() .map(|input_digests| input_digests.use_nailgun.clone()), ) .into_iter() .collect(), }) } pub fn with_input_files(input_files: DirectoryDigest) -> Self { Self { complete: input_files.clone(), nailgun: EMPTY_DIRECTORY_DIGEST.clone(), input_files, immutable_inputs: BTreeMap::new(), use_nailgun: BTreeSet::new(), } } /// Split the InputDigests into client and server subsets. /// /// TODO: The server subset will have an accurate `complete` Digest, but the client will not. /// This is currently safe because the nailgun client code does not consume that field, but it /// would be good to find a better factoring. pub fn nailgun_client_and_server(&self) -> (InputDigests, InputDigests) { let (server, client) = self .immutable_inputs .clone() .into_iter() .partition(|(path, _digest)| self.use_nailgun.contains(path)); ( // Client. InputDigests { // TODO: See method doc. complete: EMPTY_DIRECTORY_DIGEST.clone(), nailgun: EMPTY_DIRECTORY_DIGEST.clone(), input_files: self.input_files.clone(), immutable_inputs: client, use_nailgun: BTreeSet::new(), }, // Server. InputDigests { complete: self.nailgun.clone(), nailgun: EMPTY_DIRECTORY_DIGEST.clone(), input_files: EMPTY_DIRECTORY_DIGEST.clone(), immutable_inputs: server, use_nailgun: BTreeSet::new(), }, ) } } impl Default for InputDigests { fn default() -> Self { Self { complete: EMPTY_DIRECTORY_DIGEST.clone(), nailgun: EMPTY_DIRECTORY_DIGEST.clone(), input_files: EMPTY_DIRECTORY_DIGEST.clone(), immutable_inputs: BTreeMap::new(), use_nailgun: BTreeSet::new(), } } } #[derive(DeepSizeOf, Debug, Clone, Hash, PartialEq, Eq, Serialize)] pub enum ProcessExecutionStrategy { Local, /// Stores the platform_properties. RemoteExecution(Vec<(String, String)>), /// Stores the image name. Docker(String), } impl ProcessExecutionStrategy { /// What to insert into the Command proto so that we don't incorrectly cache /// Docker vs remote execution vs local execution. pub fn cache_value(&self) -> String { match self { Self::Local => "local_execution".to_string(), Self::RemoteExecution(_) => "remote_execution".to_string(), // NB: this image will include the container ID, thanks to // https://github.com/pantsbuild/pants/pull/17101. Self::Docker(image) => format!("docker_execution: {image}"), } } } /// /// A process to be executed. /// /// When executing a `Process` using the `local::CommandRunner`, any `{chroot}` placeholders in the /// environment variables are replaced with the temporary sandbox path. /// #[derive(DeepSizeOf, Derivative, Clone, Debug, Eq, Serialize)] #[derivative(PartialEq, Hash)] pub struct Process { /// /// The arguments to execute. /// /// The first argument should be an absolute or relative path to the binary to execute. /// /// No PATH lookup will be performed unless a PATH environment variable is specified. /// /// No shell expansion will take place. /// pub argv: Vec<String>, /// /// The environment variables to set for the execution. /// /// No other environment variables will be set (except possibly for an empty PATH variable). /// pub env: BTreeMap<String, String>, /// /// A relative path to a directory existing in the `input_files` digest to execute the process /// from. Defaults to the `input_files` root. /// pub working_directory: Option<RelativePath>, /// /// All of the input digests for the process. /// pub input_digests: InputDigests, pub output_files: BTreeSet<RelativePath>, pub output_directories: BTreeSet<RelativePath>, pub timeout: Option<std::time::Duration>, /// If not None, then a bounded::CommandRunner executing this Process will set an environment /// variable with this name containing a unique execution slot number. pub execution_slot_variable: Option<String>, /// If non-zero, the amount of parallelism that this process is capable of given its inputs. This /// value does not directly set the number of cores allocated to the process: that is computed /// based on availability, and provided as a template value in the arguments of the process. /// /// When set, a `{pants_concurrency}` variable will be templated into the `argv` of the process. /// /// Processes which set this value may be preempted (i.e. canceled and restarted) for a short /// period after starting if available resources have changed (because other processes have /// started or finished). pub concurrency_available: usize, #[derivative(PartialEq = "ignore", Hash = "ignore")] pub description: String, // NB: We serialize with a function to avoid adding a serde dep to the logging crate. #[serde(serialize_with = "serialize_level")] pub level: log::Level, /// /// Declares that this process uses the given named caches (which might have associated config /// in the future) at the associated relative paths within its workspace. Cache names must /// contain only lowercase ascii characters or underscores. /// /// Caches are exposed to processes within their workspaces at the relative paths represented /// by the values of the dict. A process may optionally check for the existence of the relevant /// directory, and disable use of that cache if it has not been created by the executor /// (indicating a lack of support for this feature). /// /// These caches are globally shared and so must be concurrency safe: a consumer of the cache /// must never assume that it has exclusive access to the provided directory. /// pub append_only_caches: BTreeMap<CacheName, RelativePath>, /// /// If present, a symlink will be created at .jdk which points to this directory for local /// execution, or a system-installed JDK (ignoring the value of the present Some) for remote /// execution. /// /// This is some technical debt we should clean up; /// see <https://github.com/pantsbuild/pants/issues/6416>. /// pub jdk_home: Option<PathBuf>, pub platform: Platform, pub cache_scope: ProcessCacheScope, pub execution_strategy: ProcessExecutionStrategy, pub remote_cache_speculation_delay: std::time::Duration, } impl Process { /// /// Constructs a Process with default values for most fields, after which the builder pattern can /// be used to set values. /// /// We use the more ergonomic (but possibly slightly slower) "move self for each builder method" /// pattern, so this method is only enabled for test usage: production usage should construct the /// Process struct wholesale. We can reconsider this if we end up with more production callsites /// that require partial options. /// #[cfg(test)] pub fn new(argv: Vec<String>) -> Process { Process { argv, env: BTreeMap::new(), working_directory: None, input_digests: InputDigests::default(), output_files: BTreeSet::new(), output_directories: BTreeSet::new(), timeout: None, description: "".to_string(), level: log::Level::Info, append_only_caches: BTreeMap::new(), jdk_home: None, platform: Platform::current().unwrap(), execution_slot_variable: None, concurrency_available: 0, cache_scope: ProcessCacheScope::Successful, execution_strategy: ProcessExecutionStrategy::Local, remote_cache_speculation_delay: std::time::Duration::from_millis(0), } } /// /// Replaces the environment for this process. /// pub fn env(mut self, env: BTreeMap<String, String>) -> Process { self.env = env; self } /// /// Replaces the working_directory for this process. /// pub fn working_directory(mut self, working_directory: Option<RelativePath>) -> Process { self.working_directory = working_directory; self } /// /// Replaces the output files for this process. /// pub fn output_files(mut self, output_files: BTreeSet<RelativePath>) -> Process { self.output_files = output_files; self } /// /// Replaces the output directories for this process. /// pub fn output_directories(mut self, output_directories: BTreeSet<RelativePath>) -> Process { self.output_directories = output_directories; self } /// /// Replaces the append only caches for this process. /// pub fn append_only_caches( mut self, append_only_caches: BTreeMap<CacheName, RelativePath>, ) -> Process { self.append_only_caches = append_only_caches; self } /// /// Set the execution strategy to Docker, with the specified image. /// pub fn docker(mut self, image: String) -> Process { self.execution_strategy = ProcessExecutionStrategy::Docker(image); self } /// /// Set the execution strategy to remote execution with the provided platform properties. /// pub fn remote_execution_platform_properties( mut self, properties: Vec<(String, String)>, ) -> Process { self.execution_strategy = ProcessExecutionStrategy::RemoteExecution(properties); self } pub fn remote_cache_speculation_delay(mut self, delay: std::time::Duration) -> Process { self.remote_cache_speculation_delay = delay; self } pub fn cache_scope(mut self, cache_scope: ProcessCacheScope) -> Process { self.cache_scope = cache_scope; self } } /// /// The result of running a process. /// #[derive(DeepSizeOf, Derivative, Clone, Debug, Eq)] #[derivative(PartialEq, Hash)] pub struct FallibleProcessResultWithPlatform { pub stdout_digest: Digest, pub stderr_digest: Digest, pub exit_code: i32, pub output_directory: DirectoryDigest, pub platform: Platform, #[derivative(PartialEq = "ignore", Hash = "ignore")] pub metadata: ProcessResultMetadata, } /// Metadata for a ProcessResult corresponding to the REAPI `ExecutedActionMetadata` proto. This /// conversion is lossy, but the interesting parts are preserved. #[derive(Clone, Debug, DeepSizeOf, Eq, PartialEq)] pub struct ProcessResultMetadata { /// The time from starting to completion, including preparing the chroot and cleanup. /// Corresponds to `worker_start_timestamp` and `worker_completed_timestamp` from /// `ExecutedActionMetadata`. /// /// NB: This is optional because the REAPI does not guarantee that it is returned. pub total_elapsed: Option<Duration>, /// The source of the result. pub source: ProcessResultSource, /// The RunId of the Session in which the `ProcessResultSource` was accurate. In further runs /// within the same process, the source of the process implicitly becomes memoization. pub source_run_id: RunId, } impl ProcessResultMetadata { pub fn new( total_elapsed: Option<Duration>, source: ProcessResultSource, source_run_id: RunId, ) -> Self { Self { total_elapsed, source, source_run_id, } } pub fn new_from_metadata( metadata: ExecutedActionMetadata, source: ProcessResultSource, source_run_id: RunId, ) -> Self { let total_elapsed = match ( metadata.worker_start_timestamp, metadata.worker_completed_timestamp, ) { (Some(started), Some(completed)) => TimeSpan::from_start_and_end(&started, &completed, "") .map(|span| span.duration) .ok(), _ => None, }; Self { total_elapsed, source, source_run_id, } } /// How much faster a cache hit was than running the process again. /// /// This includes the overhead of setting up and cleaning up the process for execution, and it /// should include all overhead for the cache lookup. /// /// If the cache hit was slower than the original process, we return 0. Note that the cache hit /// may still have been faster than rerunning the process a second time, e.g. if speculation /// is used and the cache hit completed before the rerun; still, we cannot know how long the /// second run would have taken, so the best we can do is report 0. /// /// If the original process's execution time was not recorded, we return None because we /// cannot make a meaningful comparison. pub fn time_saved_from_cache( &self, cache_lookup: std::time::Duration, ) -> Option<std::time::Duration> { self.total_elapsed.and_then(|original_process| { let original_process: std::time::Duration = original_process.into(); original_process .checked_sub(cache_lookup) .or_else(|| Some(std::time::Duration::new(0, 0))) }) } } impl From<ProcessResultMetadata> for ExecutedActionMetadata { fn from(metadata: ProcessResultMetadata) -> ExecutedActionMetadata { let (total_start, total_end) = match metadata.total_elapsed { Some(elapsed) => { // Because we do not have the precise start time, we hardcode to starting at UNIX_EPOCH. We // only care about accurately preserving the duration. let start = prost_types::Timestamp { seconds: 0, nanos: 0, }; let end = prost_types::Timestamp { seconds: elapsed.secs as i64, nanos: elapsed.nanos as i32, }; (Some(start), Some(end)) } None => (None, None), }; ExecutedActionMetadata { worker_start_timestamp: total_start, worker_completed_timestamp: total_end, ..ExecutedActionMetadata::default() } } } #[derive(Clone, Copy, Debug, DeepSizeOf, Eq, PartialEq)] pub enum ProcessResultSource { RanLocally, RanRemotely, HitLocally, HitRemotely, } impl From<ProcessResultSource> for &'static str { fn from(prs: ProcessResultSource) -> &'static str { match prs { ProcessResultSource::RanLocally => "ran_locally", ProcessResultSource::RanRemotely => "ran_remotely", ProcessResultSource::HitLocally => "hit_locally", ProcessResultSource::HitRemotely => "hit_remotely", } } } #[derive(Clone, Copy, Debug, PartialEq, Eq, strum_macros::EnumString)] #[strum(serialize_all = "snake_case")] pub enum CacheContentBehavior { Fetch, Validate, Defer, } /// /// Optionally validate that all digests in the result are loadable, returning false if any are not. /// /// If content loading is deferred, a Digest which is discovered to be missing later on during /// execution will cause backtracking. /// pub(crate) async fn check_cache_content( response: &FallibleProcessResultWithPlatform, store: &Store, cache_content_behavior: CacheContentBehavior, ) -> Result<bool, StoreError> { match cache_content_behavior { CacheContentBehavior::Fetch => { let response = response.clone(); let fetch_result = in_workunit!("eager_fetch_action_cache", Level::Trace, |_workunit| store .ensure_downloaded( HashSet::from([response.stdout_digest, response.stderr_digest]), HashSet::from([response.output_directory]) )) .await; match fetch_result { Err(StoreError::MissingDigest { .. }) => Ok(false), Ok(_) => Ok(true), Err(e) => Err(e), } } CacheContentBehavior::Validate =>
CacheContentBehavior::Defer => Ok(true), } } #[derive(Clone)] pub struct Context { workunit_store: WorkunitStore, build_id: String, run_id: RunId, tail_tasks: TailTasks, } impl Default for Context { fn default() -> Self { Context { workunit_store: WorkunitStore::new(false, log::Level::Debug), build_id: String::default(), run_id: RunId(0), tail_tasks: TailTasks::new(), } } } impl Context { pub fn new( workunit_store: WorkunitStore, build_id: String, run_id: RunId, tail_tasks: TailTasks, ) -> Context { Context { workunit_store, build_id, run_id, tail_tasks, } } } #[async_trait] pub trait CommandRunner: Send + Sync + Debug { /// /// Submit a request for execution on the underlying runtime, and return /// a future for it. /// async fn run( &self, context: Context, workunit: &mut RunningWorkunit, req: Process, ) -> Result<FallibleProcessResultWithPlatform, ProcessError>; /// Shutdown this CommandRunner cleanly. async fn shutdown(&self) -> Result<(), String>; } #[async_trait] impl<T: CommandRunner + ?Sized> CommandRunner for Box<T> { async fn run( &self, context: Context, workunit: &mut RunningWorkunit, req: Process, ) -> Result<FallibleProcessResultWithPlatform, ProcessError> { (**self).run(context, workunit, req).await } async fn shutdown(&self) -> Result<(), String> { (**self).shutdown().await } } #[async_trait] impl<T: CommandRunner + ?Sized> CommandRunner for Arc<T> { async fn run( &self, context: Context, workunit: &mut RunningWorkunit, req: Process, ) -> Result<FallibleProcessResultWithPlatform, ProcessError> { (**self).run(context, workunit, req).await } async fn shutdown(&self) -> Result<(), String> { (**self).shutdown().await } } // TODO(#8513) possibly move to the MEPR struct, or to the hashing crate? pub async fn digest( process: &Process, instance_name: Option<String>, process_cache_namespace: Option<String>, store: &Store, append_only_caches_base_path: Option<&str>, ) -> Digest { let EntireExecuteRequest { execute_request, .. } = remote::make_execute_request( process, instance_name, process_cache_namespace, store, append_only_caches_base_path, ) .await .unwrap(); execute_request.action_digest.unwrap().try_into().unwrap() } #[cfg(test)] mod tests;
{ let directory_digests = vec![response.output_directory.clone()]; let file_digests = vec![response.stdout_digest, response.stderr_digest]; in_workunit!( "eager_validate_action_cache", Level::Trace, |_workunit| async move { store .exists_recursive(directory_digests, file_digests) .await } ) .await }
conditional_block
lib.rs
// Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). #![deny(warnings)] // Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to include inner attributes from a common source. #![deny( clippy::all, clippy::default_trait_access, clippy::expl_impl_clone_on_copy, clippy::if_not_else, clippy::needless_continue, clippy::unseparated_literal_suffix, clippy::used_underscore_binding )] // It is often more clear to show that nothing is being moved. #![allow(clippy::match_ref_pats)] // Subjective style. #![allow( clippy::len_without_is_empty, clippy::redundant_field_names, clippy::too_many_arguments )] // Default isn't as big a deal as people seem to think it is. #![allow(clippy::new_without_default, clippy::new_ret_no_self)] // Arc<Mutex> can be more clear than needing to grok Orderings: #![allow(clippy::mutex_atomic)] #[macro_use] extern crate derivative; use std::collections::{BTreeMap, BTreeSet, HashSet}; use std::convert::{TryFrom, TryInto}; use std::fmt::{self, Debug, Display}; use std::path::PathBuf; use std::sync::Arc; use async_trait::async_trait; use concrete_time::{Duration, TimeSpan}; use deepsize::DeepSizeOf; use fs::{DirectoryDigest, RelativePath, EMPTY_DIRECTORY_DIGEST}; use futures::future::try_join_all; use futures::try_join; use hashing::Digest; use itertools::Itertools; use protos::gen::build::bazel::remote::execution::v2 as remexec; use remexec::ExecutedActionMetadata; use serde::{Deserialize, Serialize}; use store::{SnapshotOps, Store, StoreError}; use task_executor::TailTasks; use workunit_store::{in_workunit, Level, RunId, RunningWorkunit, WorkunitStore}; pub mod bounded; #[cfg(test)] mod bounded_tests; pub mod cache; #[cfg(test)] mod cache_tests; pub mod switched; pub mod children; pub mod docker; #[cfg(test)] mod docker_tests; pub mod local; #[cfg(test)] mod local_tests; pub mod nailgun; pub mod named_caches; pub mod remote; #[cfg(test)] pub mod remote_tests; pub mod remote_cache; #[cfg(test)] mod remote_cache_tests; extern crate uname; pub use crate::children::ManagedChild; pub use crate::named_caches::{CacheName, NamedCaches}; pub use crate::remote_cache::RemoteCacheWarningsBehavior; use crate::remote::EntireExecuteRequest; #[derive(Clone, Debug, PartialEq, Eq)] pub enum ProcessError { /// A Digest was not present in either of the local or remote Stores. MissingDigest(String, Digest), /// All other error types. Unclassified(String), } impl ProcessError { pub fn enrich(self, prefix: &str) -> Self { match self { Self::MissingDigest(s, d) => Self::MissingDigest(format!("{prefix}: {s}"), d), Self::Unclassified(s) => Self::Unclassified(format!("{prefix}: {s}")), } } } impl Display for ProcessError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::MissingDigest(s, d) => { write!(f, "{s}: {d:?}") } Self::Unclassified(s) => write!(f, "{s}"), } } } impl From<StoreError> for ProcessError { fn from(err: StoreError) -> Self { match err { StoreError::MissingDigest(s, d) => Self::MissingDigest(s, d), StoreError::Unclassified(s) => Self::Unclassified(s), } } } impl From<String> for ProcessError { fn from(err: String) -> Self { Self::Unclassified(err) } } #[derive( PartialOrd, Ord, Clone, Copy, Debug, DeepSizeOf, Eq, PartialEq, Hash, Serialize, Deserialize, )] #[allow(non_camel_case_types)] pub enum Platform { Macos_x86_64, Macos_arm64, Linux_x86_64, Linux_arm64, } impl Platform { pub fn current() -> Result<Platform, String> { let platform_info = uname::uname().map_err(|_| "Failed to get local platform info!".to_string())?; match platform_info { uname::Info { ref sysname, ref machine, .. } if sysname.to_lowercase() == "linux" && machine.to_lowercase() == "x86_64" => { Ok(Platform::Linux_x86_64) } uname::Info { ref sysname, ref machine, .. } if sysname.to_lowercase() == "linux" && (machine.to_lowercase() == "arm64" || machine.to_lowercase() == "aarch64") => { Ok(Platform::Linux_arm64) } uname::Info { ref sysname, ref machine, .. } if sysname.to_lowercase() == "darwin" && machine.to_lowercase() == "arm64" => { Ok(Platform::Macos_arm64) } uname::Info { ref sysname, ref machine, .. } if sysname.to_lowercase() == "darwin" && machine.to_lowercase() == "x86_64" => { Ok(Platform::Macos_x86_64) } uname::Info { ref sysname, ref machine, .. } => Err(format!( "Found unknown system/arch name pair {sysname} {machine}" )), } } } impl From<Platform> for String { fn from(platform: Platform) -> String { match platform { Platform::Linux_x86_64 => "linux_x86_64".to_string(), Platform::Linux_arm64 => "linux_arm64".to_string(), Platform::Macos_arm64 => "macos_arm64".to_string(), Platform::Macos_x86_64 => "macos_x86_64".to_string(), } } } impl TryFrom<String> for Platform { type Error = String; fn try_from(variant_candidate: String) -> Result<Self, Self::Error> { match variant_candidate.as_ref() { "macos_arm64" => Ok(Platform::Macos_arm64), "macos_x86_64" => Ok(Platform::Macos_x86_64), "linux_x86_64" => Ok(Platform::Linux_x86_64), "linux_arm64" => Ok(Platform::Linux_arm64), other => Err(format!("Unknown platform {other:?} encountered in parsing")), } } } #[derive(Clone, Copy, Debug, DeepSizeOf, Eq, PartialEq, Hash, Serialize)] pub enum ProcessCacheScope { // Cached in all locations, regardless of success or failure. Always, // Cached in all locations, but only if the process exits successfully. Successful, // Cached only in memory (i.e. memoized in pantsd), but never persistently, regardless of // success vs. failure. PerRestartAlways, // Cached only in memory (i.e. memoized in pantsd), but never persistently, and only if // successful. PerRestartSuccessful, // Will run once per Session, i.e. once per run of Pants. This happens because the engine // de-duplicates identical work; the process is neither memoized in memory nor cached to disk. PerSession, } impl TryFrom<String> for ProcessCacheScope { type Error = String; fn try_from(variant_candidate: String) -> Result<Self, Self::Error> { match variant_candidate.to_lowercase().as_ref() { "always" => Ok(ProcessCacheScope::Always), "successful" => Ok(ProcessCacheScope::Successful), "per_restart_always" => Ok(ProcessCacheScope::PerRestartAlways), "per_restart_successful" => Ok(ProcessCacheScope::PerRestartSuccessful), "per_session" => Ok(ProcessCacheScope::PerSession), other => Err(format!("Unknown Process cache scope: {other:?}")), } } } fn serialize_level<S: serde::Serializer>(level: &log::Level, s: S) -> Result<S::Ok, S::Error> { s.serialize_str(&level.to_string()) } /// Input Digests for a process execution. /// /// The `complete` and `nailgun` Digests are the computed union of various inputs. /// /// TODO: See `crate::local::prepare_workdir` regarding validation of overlapping inputs. #[derive(Clone, Debug, DeepSizeOf, Eq, Hash, PartialEq, Serialize)] pub struct InputDigests { /// All of the input Digests, merged and relativized. Runners without the ability to consume the /// Digests individually should directly consume this value. pub complete: DirectoryDigest, /// The merged Digest of any `use_nailgun`-relevant Digests. pub nailgun: DirectoryDigest, /// The input files for the process execution, which will be materialized as mutable inputs in a /// sandbox for the process. /// /// TODO: Rename to `inputs` for symmetry with `immutable_inputs`. pub input_files: DirectoryDigest, /// Immutable input digests to make available in the input root. /// /// These digests are intended for inputs that will be reused between multiple Process /// invocations, without being mutated. This might be useful to provide the tools being executed, /// but can also be used for tool inputs such as compilation artifacts. /// /// The digests will be mounted at the relative path represented by the `RelativePath` keys. /// The executor may choose how to make the digests available, including by just merging /// the digest normally into the input root, creating a symlink to a persistent cache, /// or bind mounting the directory read-only into a persistent cache. Consequently, the mount /// point of each input must not overlap the `input_files`, even for directory entries. /// /// Assumes the build action does not modify the Digest as made available. This may be /// enforced by an executor, for example by bind mounting the directory read-only. pub immutable_inputs: BTreeMap<RelativePath, DirectoryDigest>, /// If non-empty, use nailgun in supported runners, using the specified `immutable_inputs` keys /// as server inputs. All other keys (and the input_files) will be client inputs. pub use_nailgun: BTreeSet<RelativePath>, } impl InputDigests { pub async fn new( store: &Store, input_files: DirectoryDigest, immutable_inputs: BTreeMap<RelativePath, DirectoryDigest>, use_nailgun: BTreeSet<RelativePath>, ) -> Result<Self, StoreError> { // Collect all digests into `complete`. let mut complete_digests = try_join_all( immutable_inputs .iter() .map(|(path, digest)| store.add_prefix(digest.clone(), path)) .collect::<Vec<_>>(), ) .await?; // And collect only the subset of the Digests which impact nailgun into `nailgun`. let nailgun_digests = immutable_inputs .keys() .zip(complete_digests.iter()) .filter_map(|(path, digest)| { if use_nailgun.contains(path) { Some(digest.clone()) } else { None } }) .collect::<Vec<_>>(); complete_digests.push(input_files.clone()); let (complete, nailgun) = try_join!(store.merge(complete_digests), store.merge(nailgun_digests),)?; Ok(Self { complete: complete, nailgun: nailgun, input_files, immutable_inputs, use_nailgun, }) } pub async fn new_from_merged(store: &Store, from: Vec<InputDigests>) -> Result<Self, StoreError> { let mut merged_immutable_inputs = BTreeMap::new(); for input_digests in from.iter() { let size_before = merged_immutable_inputs.len(); let immutable_inputs = &input_digests.immutable_inputs; merged_immutable_inputs.append(&mut immutable_inputs.clone()); if size_before + immutable_inputs.len() != merged_immutable_inputs.len() { return Err( format!( "Tried to merge two-or-more immutable inputs at the same path with different values! \ The collision involved one of the entries in: {immutable_inputs:?}" ) .into(), ); } } let complete_digests = from .iter() .map(|input_digests| input_digests.complete.clone()) .collect(); let nailgun_digests = from .iter() .map(|input_digests| input_digests.nailgun.clone()) .collect(); let input_files_digests = from .iter() .map(|input_digests| input_digests.input_files.clone()) .collect(); let (complete, nailgun, input_files) = try_join!( store.merge(complete_digests), store.merge(nailgun_digests), store.merge(input_files_digests), )?; Ok(Self { complete: complete, nailgun: nailgun, input_files: input_files, immutable_inputs: merged_immutable_inputs, use_nailgun: Itertools::concat( from .iter() .map(|input_digests| input_digests.use_nailgun.clone()), ) .into_iter() .collect(), }) } pub fn with_input_files(input_files: DirectoryDigest) -> Self { Self { complete: input_files.clone(), nailgun: EMPTY_DIRECTORY_DIGEST.clone(), input_files, immutable_inputs: BTreeMap::new(), use_nailgun: BTreeSet::new(), } } /// Split the InputDigests into client and server subsets. /// /// TODO: The server subset will have an accurate `complete` Digest, but the client will not. /// This is currently safe because the nailgun client code does not consume that field, but it /// would be good to find a better factoring. pub fn nailgun_client_and_server(&self) -> (InputDigests, InputDigests) { let (server, client) = self .immutable_inputs .clone() .into_iter() .partition(|(path, _digest)| self.use_nailgun.contains(path)); ( // Client. InputDigests { // TODO: See method doc. complete: EMPTY_DIRECTORY_DIGEST.clone(), nailgun: EMPTY_DIRECTORY_DIGEST.clone(), input_files: self.input_files.clone(), immutable_inputs: client, use_nailgun: BTreeSet::new(), }, // Server. InputDigests { complete: self.nailgun.clone(), nailgun: EMPTY_DIRECTORY_DIGEST.clone(), input_files: EMPTY_DIRECTORY_DIGEST.clone(), immutable_inputs: server, use_nailgun: BTreeSet::new(), }, ) } } impl Default for InputDigests { fn default() -> Self { Self { complete: EMPTY_DIRECTORY_DIGEST.clone(), nailgun: EMPTY_DIRECTORY_DIGEST.clone(), input_files: EMPTY_DIRECTORY_DIGEST.clone(), immutable_inputs: BTreeMap::new(), use_nailgun: BTreeSet::new(), } } } #[derive(DeepSizeOf, Debug, Clone, Hash, PartialEq, Eq, Serialize)] pub enum ProcessExecutionStrategy { Local, /// Stores the platform_properties. RemoteExecution(Vec<(String, String)>), /// Stores the image name. Docker(String), } impl ProcessExecutionStrategy { /// What to insert into the Command proto so that we don't incorrectly cache /// Docker vs remote execution vs local execution. pub fn cache_value(&self) -> String { match self { Self::Local => "local_execution".to_string(), Self::RemoteExecution(_) => "remote_execution".to_string(), // NB: this image will include the container ID, thanks to // https://github.com/pantsbuild/pants/pull/17101. Self::Docker(image) => format!("docker_execution: {image}"), } } } /// /// A process to be executed. /// /// When executing a `Process` using the `local::CommandRunner`, any `{chroot}` placeholders in the /// environment variables are replaced with the temporary sandbox path. /// #[derive(DeepSizeOf, Derivative, Clone, Debug, Eq, Serialize)] #[derivative(PartialEq, Hash)] pub struct Process { /// /// The arguments to execute. /// /// The first argument should be an absolute or relative path to the binary to execute. /// /// No PATH lookup will be performed unless a PATH environment variable is specified. /// /// No shell expansion will take place. /// pub argv: Vec<String>, /// /// The environment variables to set for the execution. /// /// No other environment variables will be set (except possibly for an empty PATH variable). ///
/// from. Defaults to the `input_files` root. /// pub working_directory: Option<RelativePath>, /// /// All of the input digests for the process. /// pub input_digests: InputDigests, pub output_files: BTreeSet<RelativePath>, pub output_directories: BTreeSet<RelativePath>, pub timeout: Option<std::time::Duration>, /// If not None, then a bounded::CommandRunner executing this Process will set an environment /// variable with this name containing a unique execution slot number. pub execution_slot_variable: Option<String>, /// If non-zero, the amount of parallelism that this process is capable of given its inputs. This /// value does not directly set the number of cores allocated to the process: that is computed /// based on availability, and provided as a template value in the arguments of the process. /// /// When set, a `{pants_concurrency}` variable will be templated into the `argv` of the process. /// /// Processes which set this value may be preempted (i.e. canceled and restarted) for a short /// period after starting if available resources have changed (because other processes have /// started or finished). pub concurrency_available: usize, #[derivative(PartialEq = "ignore", Hash = "ignore")] pub description: String, // NB: We serialize with a function to avoid adding a serde dep to the logging crate. #[serde(serialize_with = "serialize_level")] pub level: log::Level, /// /// Declares that this process uses the given named caches (which might have associated config /// in the future) at the associated relative paths within its workspace. Cache names must /// contain only lowercase ascii characters or underscores. /// /// Caches are exposed to processes within their workspaces at the relative paths represented /// by the values of the dict. A process may optionally check for the existence of the relevant /// directory, and disable use of that cache if it has not been created by the executor /// (indicating a lack of support for this feature). /// /// These caches are globally shared and so must be concurrency safe: a consumer of the cache /// must never assume that it has exclusive access to the provided directory. /// pub append_only_caches: BTreeMap<CacheName, RelativePath>, /// /// If present, a symlink will be created at .jdk which points to this directory for local /// execution, or a system-installed JDK (ignoring the value of the present Some) for remote /// execution. /// /// This is some technical debt we should clean up; /// see <https://github.com/pantsbuild/pants/issues/6416>. /// pub jdk_home: Option<PathBuf>, pub platform: Platform, pub cache_scope: ProcessCacheScope, pub execution_strategy: ProcessExecutionStrategy, pub remote_cache_speculation_delay: std::time::Duration, } impl Process { /// /// Constructs a Process with default values for most fields, after which the builder pattern can /// be used to set values. /// /// We use the more ergonomic (but possibly slightly slower) "move self for each builder method" /// pattern, so this method is only enabled for test usage: production usage should construct the /// Process struct wholesale. We can reconsider this if we end up with more production callsites /// that require partial options. /// #[cfg(test)] pub fn new(argv: Vec<String>) -> Process { Process { argv, env: BTreeMap::new(), working_directory: None, input_digests: InputDigests::default(), output_files: BTreeSet::new(), output_directories: BTreeSet::new(), timeout: None, description: "".to_string(), level: log::Level::Info, append_only_caches: BTreeMap::new(), jdk_home: None, platform: Platform::current().unwrap(), execution_slot_variable: None, concurrency_available: 0, cache_scope: ProcessCacheScope::Successful, execution_strategy: ProcessExecutionStrategy::Local, remote_cache_speculation_delay: std::time::Duration::from_millis(0), } } /// /// Replaces the environment for this process. /// pub fn env(mut self, env: BTreeMap<String, String>) -> Process { self.env = env; self } /// /// Replaces the working_directory for this process. /// pub fn working_directory(mut self, working_directory: Option<RelativePath>) -> Process { self.working_directory = working_directory; self } /// /// Replaces the output files for this process. /// pub fn output_files(mut self, output_files: BTreeSet<RelativePath>) -> Process { self.output_files = output_files; self } /// /// Replaces the output directories for this process. /// pub fn output_directories(mut self, output_directories: BTreeSet<RelativePath>) -> Process { self.output_directories = output_directories; self } /// /// Replaces the append only caches for this process. /// pub fn append_only_caches( mut self, append_only_caches: BTreeMap<CacheName, RelativePath>, ) -> Process { self.append_only_caches = append_only_caches; self } /// /// Set the execution strategy to Docker, with the specified image. /// pub fn docker(mut self, image: String) -> Process { self.execution_strategy = ProcessExecutionStrategy::Docker(image); self } /// /// Set the execution strategy to remote execution with the provided platform properties. /// pub fn remote_execution_platform_properties( mut self, properties: Vec<(String, String)>, ) -> Process { self.execution_strategy = ProcessExecutionStrategy::RemoteExecution(properties); self } pub fn remote_cache_speculation_delay(mut self, delay: std::time::Duration) -> Process { self.remote_cache_speculation_delay = delay; self } pub fn cache_scope(mut self, cache_scope: ProcessCacheScope) -> Process { self.cache_scope = cache_scope; self } } /// /// The result of running a process. /// #[derive(DeepSizeOf, Derivative, Clone, Debug, Eq)] #[derivative(PartialEq, Hash)] pub struct FallibleProcessResultWithPlatform { pub stdout_digest: Digest, pub stderr_digest: Digest, pub exit_code: i32, pub output_directory: DirectoryDigest, pub platform: Platform, #[derivative(PartialEq = "ignore", Hash = "ignore")] pub metadata: ProcessResultMetadata, } /// Metadata for a ProcessResult corresponding to the REAPI `ExecutedActionMetadata` proto. This /// conversion is lossy, but the interesting parts are preserved. #[derive(Clone, Debug, DeepSizeOf, Eq, PartialEq)] pub struct ProcessResultMetadata { /// The time from starting to completion, including preparing the chroot and cleanup. /// Corresponds to `worker_start_timestamp` and `worker_completed_timestamp` from /// `ExecutedActionMetadata`. /// /// NB: This is optional because the REAPI does not guarantee that it is returned. pub total_elapsed: Option<Duration>, /// The source of the result. pub source: ProcessResultSource, /// The RunId of the Session in which the `ProcessResultSource` was accurate. In further runs /// within the same process, the source of the process implicitly becomes memoization. pub source_run_id: RunId, } impl ProcessResultMetadata { pub fn new( total_elapsed: Option<Duration>, source: ProcessResultSource, source_run_id: RunId, ) -> Self { Self { total_elapsed, source, source_run_id, } } pub fn new_from_metadata( metadata: ExecutedActionMetadata, source: ProcessResultSource, source_run_id: RunId, ) -> Self { let total_elapsed = match ( metadata.worker_start_timestamp, metadata.worker_completed_timestamp, ) { (Some(started), Some(completed)) => TimeSpan::from_start_and_end(&started, &completed, "") .map(|span| span.duration) .ok(), _ => None, }; Self { total_elapsed, source, source_run_id, } } /// How much faster a cache hit was than running the process again. /// /// This includes the overhead of setting up and cleaning up the process for execution, and it /// should include all overhead for the cache lookup. /// /// If the cache hit was slower than the original process, we return 0. Note that the cache hit /// may still have been faster than rerunning the process a second time, e.g. if speculation /// is used and the cache hit completed before the rerun; still, we cannot know how long the /// second run would have taken, so the best we can do is report 0. /// /// If the original process's execution time was not recorded, we return None because we /// cannot make a meaningful comparison. pub fn time_saved_from_cache( &self, cache_lookup: std::time::Duration, ) -> Option<std::time::Duration> { self.total_elapsed.and_then(|original_process| { let original_process: std::time::Duration = original_process.into(); original_process .checked_sub(cache_lookup) .or_else(|| Some(std::time::Duration::new(0, 0))) }) } } impl From<ProcessResultMetadata> for ExecutedActionMetadata { fn from(metadata: ProcessResultMetadata) -> ExecutedActionMetadata { let (total_start, total_end) = match metadata.total_elapsed { Some(elapsed) => { // Because we do not have the precise start time, we hardcode to starting at UNIX_EPOCH. We // only care about accurately preserving the duration. let start = prost_types::Timestamp { seconds: 0, nanos: 0, }; let end = prost_types::Timestamp { seconds: elapsed.secs as i64, nanos: elapsed.nanos as i32, }; (Some(start), Some(end)) } None => (None, None), }; ExecutedActionMetadata { worker_start_timestamp: total_start, worker_completed_timestamp: total_end, ..ExecutedActionMetadata::default() } } } #[derive(Clone, Copy, Debug, DeepSizeOf, Eq, PartialEq)] pub enum ProcessResultSource { RanLocally, RanRemotely, HitLocally, HitRemotely, } impl From<ProcessResultSource> for &'static str { fn from(prs: ProcessResultSource) -> &'static str { match prs { ProcessResultSource::RanLocally => "ran_locally", ProcessResultSource::RanRemotely => "ran_remotely", ProcessResultSource::HitLocally => "hit_locally", ProcessResultSource::HitRemotely => "hit_remotely", } } } #[derive(Clone, Copy, Debug, PartialEq, Eq, strum_macros::EnumString)] #[strum(serialize_all = "snake_case")] pub enum CacheContentBehavior { Fetch, Validate, Defer, } /// /// Optionally validate that all digests in the result are loadable, returning false if any are not. /// /// If content loading is deferred, a Digest which is discovered to be missing later on during /// execution will cause backtracking. /// pub(crate) async fn check_cache_content( response: &FallibleProcessResultWithPlatform, store: &Store, cache_content_behavior: CacheContentBehavior, ) -> Result<bool, StoreError> { match cache_content_behavior { CacheContentBehavior::Fetch => { let response = response.clone(); let fetch_result = in_workunit!("eager_fetch_action_cache", Level::Trace, |_workunit| store .ensure_downloaded( HashSet::from([response.stdout_digest, response.stderr_digest]), HashSet::from([response.output_directory]) )) .await; match fetch_result { Err(StoreError::MissingDigest { .. }) => Ok(false), Ok(_) => Ok(true), Err(e) => Err(e), } } CacheContentBehavior::Validate => { let directory_digests = vec![response.output_directory.clone()]; let file_digests = vec![response.stdout_digest, response.stderr_digest]; in_workunit!( "eager_validate_action_cache", Level::Trace, |_workunit| async move { store .exists_recursive(directory_digests, file_digests) .await } ) .await } CacheContentBehavior::Defer => Ok(true), } } #[derive(Clone)] pub struct Context { workunit_store: WorkunitStore, build_id: String, run_id: RunId, tail_tasks: TailTasks, } impl Default for Context { fn default() -> Self { Context { workunit_store: WorkunitStore::new(false, log::Level::Debug), build_id: String::default(), run_id: RunId(0), tail_tasks: TailTasks::new(), } } } impl Context { pub fn new( workunit_store: WorkunitStore, build_id: String, run_id: RunId, tail_tasks: TailTasks, ) -> Context { Context { workunit_store, build_id, run_id, tail_tasks, } } } #[async_trait] pub trait CommandRunner: Send + Sync + Debug { /// /// Submit a request for execution on the underlying runtime, and return /// a future for it. /// async fn run( &self, context: Context, workunit: &mut RunningWorkunit, req: Process, ) -> Result<FallibleProcessResultWithPlatform, ProcessError>; /// Shutdown this CommandRunner cleanly. async fn shutdown(&self) -> Result<(), String>; } #[async_trait] impl<T: CommandRunner + ?Sized> CommandRunner for Box<T> { async fn run( &self, context: Context, workunit: &mut RunningWorkunit, req: Process, ) -> Result<FallibleProcessResultWithPlatform, ProcessError> { (**self).run(context, workunit, req).await } async fn shutdown(&self) -> Result<(), String> { (**self).shutdown().await } } #[async_trait] impl<T: CommandRunner + ?Sized> CommandRunner for Arc<T> { async fn run( &self, context: Context, workunit: &mut RunningWorkunit, req: Process, ) -> Result<FallibleProcessResultWithPlatform, ProcessError> { (**self).run(context, workunit, req).await } async fn shutdown(&self) -> Result<(), String> { (**self).shutdown().await } } // TODO(#8513) possibly move to the MEPR struct, or to the hashing crate? pub async fn digest( process: &Process, instance_name: Option<String>, process_cache_namespace: Option<String>, store: &Store, append_only_caches_base_path: Option<&str>, ) -> Digest { let EntireExecuteRequest { execute_request, .. } = remote::make_execute_request( process, instance_name, process_cache_namespace, store, append_only_caches_base_path, ) .await .unwrap(); execute_request.action_digest.unwrap().try_into().unwrap() } #[cfg(test)] mod tests;
pub env: BTreeMap<String, String>, /// /// A relative path to a directory existing in the `input_files` digest to execute the process
random_line_split
lib.rs
// Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). #![deny(warnings)] // Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to include inner attributes from a common source. #![deny( clippy::all, clippy::default_trait_access, clippy::expl_impl_clone_on_copy, clippy::if_not_else, clippy::needless_continue, clippy::unseparated_literal_suffix, clippy::used_underscore_binding )] // It is often more clear to show that nothing is being moved. #![allow(clippy::match_ref_pats)] // Subjective style. #![allow( clippy::len_without_is_empty, clippy::redundant_field_names, clippy::too_many_arguments )] // Default isn't as big a deal as people seem to think it is. #![allow(clippy::new_without_default, clippy::new_ret_no_self)] // Arc<Mutex> can be more clear than needing to grok Orderings: #![allow(clippy::mutex_atomic)] #[macro_use] extern crate derivative; use std::collections::{BTreeMap, BTreeSet, HashSet}; use std::convert::{TryFrom, TryInto}; use std::fmt::{self, Debug, Display}; use std::path::PathBuf; use std::sync::Arc; use async_trait::async_trait; use concrete_time::{Duration, TimeSpan}; use deepsize::DeepSizeOf; use fs::{DirectoryDigest, RelativePath, EMPTY_DIRECTORY_DIGEST}; use futures::future::try_join_all; use futures::try_join; use hashing::Digest; use itertools::Itertools; use protos::gen::build::bazel::remote::execution::v2 as remexec; use remexec::ExecutedActionMetadata; use serde::{Deserialize, Serialize}; use store::{SnapshotOps, Store, StoreError}; use task_executor::TailTasks; use workunit_store::{in_workunit, Level, RunId, RunningWorkunit, WorkunitStore}; pub mod bounded; #[cfg(test)] mod bounded_tests; pub mod cache; #[cfg(test)] mod cache_tests; pub mod switched; pub mod children; pub mod docker; #[cfg(test)] mod docker_tests; pub mod local; #[cfg(test)] mod local_tests; pub mod nailgun; pub mod named_caches; pub mod remote; #[cfg(test)] pub mod remote_tests; pub mod remote_cache; #[cfg(test)] mod remote_cache_tests; extern crate uname; pub use crate::children::ManagedChild; pub use crate::named_caches::{CacheName, NamedCaches}; pub use crate::remote_cache::RemoteCacheWarningsBehavior; use crate::remote::EntireExecuteRequest; #[derive(Clone, Debug, PartialEq, Eq)] pub enum ProcessError { /// A Digest was not present in either of the local or remote Stores. MissingDigest(String, Digest), /// All other error types. Unclassified(String), } impl ProcessError { pub fn enrich(self, prefix: &str) -> Self { match self { Self::MissingDigest(s, d) => Self::MissingDigest(format!("{prefix}: {s}"), d), Self::Unclassified(s) => Self::Unclassified(format!("{prefix}: {s}")), } } } impl Display for ProcessError { fn
(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::MissingDigest(s, d) => { write!(f, "{s}: {d:?}") } Self::Unclassified(s) => write!(f, "{s}"), } } } impl From<StoreError> for ProcessError { fn from(err: StoreError) -> Self { match err { StoreError::MissingDigest(s, d) => Self::MissingDigest(s, d), StoreError::Unclassified(s) => Self::Unclassified(s), } } } impl From<String> for ProcessError { fn from(err: String) -> Self { Self::Unclassified(err) } } #[derive( PartialOrd, Ord, Clone, Copy, Debug, DeepSizeOf, Eq, PartialEq, Hash, Serialize, Deserialize, )] #[allow(non_camel_case_types)] pub enum Platform { Macos_x86_64, Macos_arm64, Linux_x86_64, Linux_arm64, } impl Platform { pub fn current() -> Result<Platform, String> { let platform_info = uname::uname().map_err(|_| "Failed to get local platform info!".to_string())?; match platform_info { uname::Info { ref sysname, ref machine, .. } if sysname.to_lowercase() == "linux" && machine.to_lowercase() == "x86_64" => { Ok(Platform::Linux_x86_64) } uname::Info { ref sysname, ref machine, .. } if sysname.to_lowercase() == "linux" && (machine.to_lowercase() == "arm64" || machine.to_lowercase() == "aarch64") => { Ok(Platform::Linux_arm64) } uname::Info { ref sysname, ref machine, .. } if sysname.to_lowercase() == "darwin" && machine.to_lowercase() == "arm64" => { Ok(Platform::Macos_arm64) } uname::Info { ref sysname, ref machine, .. } if sysname.to_lowercase() == "darwin" && machine.to_lowercase() == "x86_64" => { Ok(Platform::Macos_x86_64) } uname::Info { ref sysname, ref machine, .. } => Err(format!( "Found unknown system/arch name pair {sysname} {machine}" )), } } } impl From<Platform> for String { fn from(platform: Platform) -> String { match platform { Platform::Linux_x86_64 => "linux_x86_64".to_string(), Platform::Linux_arm64 => "linux_arm64".to_string(), Platform::Macos_arm64 => "macos_arm64".to_string(), Platform::Macos_x86_64 => "macos_x86_64".to_string(), } } } impl TryFrom<String> for Platform { type Error = String; fn try_from(variant_candidate: String) -> Result<Self, Self::Error> { match variant_candidate.as_ref() { "macos_arm64" => Ok(Platform::Macos_arm64), "macos_x86_64" => Ok(Platform::Macos_x86_64), "linux_x86_64" => Ok(Platform::Linux_x86_64), "linux_arm64" => Ok(Platform::Linux_arm64), other => Err(format!("Unknown platform {other:?} encountered in parsing")), } } } #[derive(Clone, Copy, Debug, DeepSizeOf, Eq, PartialEq, Hash, Serialize)] pub enum ProcessCacheScope { // Cached in all locations, regardless of success or failure. Always, // Cached in all locations, but only if the process exits successfully. Successful, // Cached only in memory (i.e. memoized in pantsd), but never persistently, regardless of // success vs. failure. PerRestartAlways, // Cached only in memory (i.e. memoized in pantsd), but never persistently, and only if // successful. PerRestartSuccessful, // Will run once per Session, i.e. once per run of Pants. This happens because the engine // de-duplicates identical work; the process is neither memoized in memory nor cached to disk. PerSession, } impl TryFrom<String> for ProcessCacheScope { type Error = String; fn try_from(variant_candidate: String) -> Result<Self, Self::Error> { match variant_candidate.to_lowercase().as_ref() { "always" => Ok(ProcessCacheScope::Always), "successful" => Ok(ProcessCacheScope::Successful), "per_restart_always" => Ok(ProcessCacheScope::PerRestartAlways), "per_restart_successful" => Ok(ProcessCacheScope::PerRestartSuccessful), "per_session" => Ok(ProcessCacheScope::PerSession), other => Err(format!("Unknown Process cache scope: {other:?}")), } } } fn serialize_level<S: serde::Serializer>(level: &log::Level, s: S) -> Result<S::Ok, S::Error> { s.serialize_str(&level.to_string()) } /// Input Digests for a process execution. /// /// The `complete` and `nailgun` Digests are the computed union of various inputs. /// /// TODO: See `crate::local::prepare_workdir` regarding validation of overlapping inputs. #[derive(Clone, Debug, DeepSizeOf, Eq, Hash, PartialEq, Serialize)] pub struct InputDigests { /// All of the input Digests, merged and relativized. Runners without the ability to consume the /// Digests individually should directly consume this value. pub complete: DirectoryDigest, /// The merged Digest of any `use_nailgun`-relevant Digests. pub nailgun: DirectoryDigest, /// The input files for the process execution, which will be materialized as mutable inputs in a /// sandbox for the process. /// /// TODO: Rename to `inputs` for symmetry with `immutable_inputs`. pub input_files: DirectoryDigest, /// Immutable input digests to make available in the input root. /// /// These digests are intended for inputs that will be reused between multiple Process /// invocations, without being mutated. This might be useful to provide the tools being executed, /// but can also be used for tool inputs such as compilation artifacts. /// /// The digests will be mounted at the relative path represented by the `RelativePath` keys. /// The executor may choose how to make the digests available, including by just merging /// the digest normally into the input root, creating a symlink to a persistent cache, /// or bind mounting the directory read-only into a persistent cache. Consequently, the mount /// point of each input must not overlap the `input_files`, even for directory entries. /// /// Assumes the build action does not modify the Digest as made available. This may be /// enforced by an executor, for example by bind mounting the directory read-only. pub immutable_inputs: BTreeMap<RelativePath, DirectoryDigest>, /// If non-empty, use nailgun in supported runners, using the specified `immutable_inputs` keys /// as server inputs. All other keys (and the input_files) will be client inputs. pub use_nailgun: BTreeSet<RelativePath>, } impl InputDigests { pub async fn new( store: &Store, input_files: DirectoryDigest, immutable_inputs: BTreeMap<RelativePath, DirectoryDigest>, use_nailgun: BTreeSet<RelativePath>, ) -> Result<Self, StoreError> { // Collect all digests into `complete`. let mut complete_digests = try_join_all( immutable_inputs .iter() .map(|(path, digest)| store.add_prefix(digest.clone(), path)) .collect::<Vec<_>>(), ) .await?; // And collect only the subset of the Digests which impact nailgun into `nailgun`. let nailgun_digests = immutable_inputs .keys() .zip(complete_digests.iter()) .filter_map(|(path, digest)| { if use_nailgun.contains(path) { Some(digest.clone()) } else { None } }) .collect::<Vec<_>>(); complete_digests.push(input_files.clone()); let (complete, nailgun) = try_join!(store.merge(complete_digests), store.merge(nailgun_digests),)?; Ok(Self { complete: complete, nailgun: nailgun, input_files, immutable_inputs, use_nailgun, }) } pub async fn new_from_merged(store: &Store, from: Vec<InputDigests>) -> Result<Self, StoreError> { let mut merged_immutable_inputs = BTreeMap::new(); for input_digests in from.iter() { let size_before = merged_immutable_inputs.len(); let immutable_inputs = &input_digests.immutable_inputs; merged_immutable_inputs.append(&mut immutable_inputs.clone()); if size_before + immutable_inputs.len() != merged_immutable_inputs.len() { return Err( format!( "Tried to merge two-or-more immutable inputs at the same path with different values! \ The collision involved one of the entries in: {immutable_inputs:?}" ) .into(), ); } } let complete_digests = from .iter() .map(|input_digests| input_digests.complete.clone()) .collect(); let nailgun_digests = from .iter() .map(|input_digests| input_digests.nailgun.clone()) .collect(); let input_files_digests = from .iter() .map(|input_digests| input_digests.input_files.clone()) .collect(); let (complete, nailgun, input_files) = try_join!( store.merge(complete_digests), store.merge(nailgun_digests), store.merge(input_files_digests), )?; Ok(Self { complete: complete, nailgun: nailgun, input_files: input_files, immutable_inputs: merged_immutable_inputs, use_nailgun: Itertools::concat( from .iter() .map(|input_digests| input_digests.use_nailgun.clone()), ) .into_iter() .collect(), }) } pub fn with_input_files(input_files: DirectoryDigest) -> Self { Self { complete: input_files.clone(), nailgun: EMPTY_DIRECTORY_DIGEST.clone(), input_files, immutable_inputs: BTreeMap::new(), use_nailgun: BTreeSet::new(), } } /// Split the InputDigests into client and server subsets. /// /// TODO: The server subset will have an accurate `complete` Digest, but the client will not. /// This is currently safe because the nailgun client code does not consume that field, but it /// would be good to find a better factoring. pub fn nailgun_client_and_server(&self) -> (InputDigests, InputDigests) { let (server, client) = self .immutable_inputs .clone() .into_iter() .partition(|(path, _digest)| self.use_nailgun.contains(path)); ( // Client. InputDigests { // TODO: See method doc. complete: EMPTY_DIRECTORY_DIGEST.clone(), nailgun: EMPTY_DIRECTORY_DIGEST.clone(), input_files: self.input_files.clone(), immutable_inputs: client, use_nailgun: BTreeSet::new(), }, // Server. InputDigests { complete: self.nailgun.clone(), nailgun: EMPTY_DIRECTORY_DIGEST.clone(), input_files: EMPTY_DIRECTORY_DIGEST.clone(), immutable_inputs: server, use_nailgun: BTreeSet::new(), }, ) } } impl Default for InputDigests { fn default() -> Self { Self { complete: EMPTY_DIRECTORY_DIGEST.clone(), nailgun: EMPTY_DIRECTORY_DIGEST.clone(), input_files: EMPTY_DIRECTORY_DIGEST.clone(), immutable_inputs: BTreeMap::new(), use_nailgun: BTreeSet::new(), } } } #[derive(DeepSizeOf, Debug, Clone, Hash, PartialEq, Eq, Serialize)] pub enum ProcessExecutionStrategy { Local, /// Stores the platform_properties. RemoteExecution(Vec<(String, String)>), /// Stores the image name. Docker(String), } impl ProcessExecutionStrategy { /// What to insert into the Command proto so that we don't incorrectly cache /// Docker vs remote execution vs local execution. pub fn cache_value(&self) -> String { match self { Self::Local => "local_execution".to_string(), Self::RemoteExecution(_) => "remote_execution".to_string(), // NB: this image will include the container ID, thanks to // https://github.com/pantsbuild/pants/pull/17101. Self::Docker(image) => format!("docker_execution: {image}"), } } } /// /// A process to be executed. /// /// When executing a `Process` using the `local::CommandRunner`, any `{chroot}` placeholders in the /// environment variables are replaced with the temporary sandbox path. /// #[derive(DeepSizeOf, Derivative, Clone, Debug, Eq, Serialize)] #[derivative(PartialEq, Hash)] pub struct Process { /// /// The arguments to execute. /// /// The first argument should be an absolute or relative path to the binary to execute. /// /// No PATH lookup will be performed unless a PATH environment variable is specified. /// /// No shell expansion will take place. /// pub argv: Vec<String>, /// /// The environment variables to set for the execution. /// /// No other environment variables will be set (except possibly for an empty PATH variable). /// pub env: BTreeMap<String, String>, /// /// A relative path to a directory existing in the `input_files` digest to execute the process /// from. Defaults to the `input_files` root. /// pub working_directory: Option<RelativePath>, /// /// All of the input digests for the process. /// pub input_digests: InputDigests, pub output_files: BTreeSet<RelativePath>, pub output_directories: BTreeSet<RelativePath>, pub timeout: Option<std::time::Duration>, /// If not None, then a bounded::CommandRunner executing this Process will set an environment /// variable with this name containing a unique execution slot number. pub execution_slot_variable: Option<String>, /// If non-zero, the amount of parallelism that this process is capable of given its inputs. This /// value does not directly set the number of cores allocated to the process: that is computed /// based on availability, and provided as a template value in the arguments of the process. /// /// When set, a `{pants_concurrency}` variable will be templated into the `argv` of the process. /// /// Processes which set this value may be preempted (i.e. canceled and restarted) for a short /// period after starting if available resources have changed (because other processes have /// started or finished). pub concurrency_available: usize, #[derivative(PartialEq = "ignore", Hash = "ignore")] pub description: String, // NB: We serialize with a function to avoid adding a serde dep to the logging crate. #[serde(serialize_with = "serialize_level")] pub level: log::Level, /// /// Declares that this process uses the given named caches (which might have associated config /// in the future) at the associated relative paths within its workspace. Cache names must /// contain only lowercase ascii characters or underscores. /// /// Caches are exposed to processes within their workspaces at the relative paths represented /// by the values of the dict. A process may optionally check for the existence of the relevant /// directory, and disable use of that cache if it has not been created by the executor /// (indicating a lack of support for this feature). /// /// These caches are globally shared and so must be concurrency safe: a consumer of the cache /// must never assume that it has exclusive access to the provided directory. /// pub append_only_caches: BTreeMap<CacheName, RelativePath>, /// /// If present, a symlink will be created at .jdk which points to this directory for local /// execution, or a system-installed JDK (ignoring the value of the present Some) for remote /// execution. /// /// This is some technical debt we should clean up; /// see <https://github.com/pantsbuild/pants/issues/6416>. /// pub jdk_home: Option<PathBuf>, pub platform: Platform, pub cache_scope: ProcessCacheScope, pub execution_strategy: ProcessExecutionStrategy, pub remote_cache_speculation_delay: std::time::Duration, } impl Process { /// /// Constructs a Process with default values for most fields, after which the builder pattern can /// be used to set values. /// /// We use the more ergonomic (but possibly slightly slower) "move self for each builder method" /// pattern, so this method is only enabled for test usage: production usage should construct the /// Process struct wholesale. We can reconsider this if we end up with more production callsites /// that require partial options. /// #[cfg(test)] pub fn new(argv: Vec<String>) -> Process { Process { argv, env: BTreeMap::new(), working_directory: None, input_digests: InputDigests::default(), output_files: BTreeSet::new(), output_directories: BTreeSet::new(), timeout: None, description: "".to_string(), level: log::Level::Info, append_only_caches: BTreeMap::new(), jdk_home: None, platform: Platform::current().unwrap(), execution_slot_variable: None, concurrency_available: 0, cache_scope: ProcessCacheScope::Successful, execution_strategy: ProcessExecutionStrategy::Local, remote_cache_speculation_delay: std::time::Duration::from_millis(0), } } /// /// Replaces the environment for this process. /// pub fn env(mut self, env: BTreeMap<String, String>) -> Process { self.env = env; self } /// /// Replaces the working_directory for this process. /// pub fn working_directory(mut self, working_directory: Option<RelativePath>) -> Process { self.working_directory = working_directory; self } /// /// Replaces the output files for this process. /// pub fn output_files(mut self, output_files: BTreeSet<RelativePath>) -> Process { self.output_files = output_files; self } /// /// Replaces the output directories for this process. /// pub fn output_directories(mut self, output_directories: BTreeSet<RelativePath>) -> Process { self.output_directories = output_directories; self } /// /// Replaces the append only caches for this process. /// pub fn append_only_caches( mut self, append_only_caches: BTreeMap<CacheName, RelativePath>, ) -> Process { self.append_only_caches = append_only_caches; self } /// /// Set the execution strategy to Docker, with the specified image. /// pub fn docker(mut self, image: String) -> Process { self.execution_strategy = ProcessExecutionStrategy::Docker(image); self } /// /// Set the execution strategy to remote execution with the provided platform properties. /// pub fn remote_execution_platform_properties( mut self, properties: Vec<(String, String)>, ) -> Process { self.execution_strategy = ProcessExecutionStrategy::RemoteExecution(properties); self } pub fn remote_cache_speculation_delay(mut self, delay: std::time::Duration) -> Process { self.remote_cache_speculation_delay = delay; self } pub fn cache_scope(mut self, cache_scope: ProcessCacheScope) -> Process { self.cache_scope = cache_scope; self } } /// /// The result of running a process. /// #[derive(DeepSizeOf, Derivative, Clone, Debug, Eq)] #[derivative(PartialEq, Hash)] pub struct FallibleProcessResultWithPlatform { pub stdout_digest: Digest, pub stderr_digest: Digest, pub exit_code: i32, pub output_directory: DirectoryDigest, pub platform: Platform, #[derivative(PartialEq = "ignore", Hash = "ignore")] pub metadata: ProcessResultMetadata, } /// Metadata for a ProcessResult corresponding to the REAPI `ExecutedActionMetadata` proto. This /// conversion is lossy, but the interesting parts are preserved. #[derive(Clone, Debug, DeepSizeOf, Eq, PartialEq)] pub struct ProcessResultMetadata { /// The time from starting to completion, including preparing the chroot and cleanup. /// Corresponds to `worker_start_timestamp` and `worker_completed_timestamp` from /// `ExecutedActionMetadata`. /// /// NB: This is optional because the REAPI does not guarantee that it is returned. pub total_elapsed: Option<Duration>, /// The source of the result. pub source: ProcessResultSource, /// The RunId of the Session in which the `ProcessResultSource` was accurate. In further runs /// within the same process, the source of the process implicitly becomes memoization. pub source_run_id: RunId, } impl ProcessResultMetadata { pub fn new( total_elapsed: Option<Duration>, source: ProcessResultSource, source_run_id: RunId, ) -> Self { Self { total_elapsed, source, source_run_id, } } pub fn new_from_metadata( metadata: ExecutedActionMetadata, source: ProcessResultSource, source_run_id: RunId, ) -> Self { let total_elapsed = match ( metadata.worker_start_timestamp, metadata.worker_completed_timestamp, ) { (Some(started), Some(completed)) => TimeSpan::from_start_and_end(&started, &completed, "") .map(|span| span.duration) .ok(), _ => None, }; Self { total_elapsed, source, source_run_id, } } /// How much faster a cache hit was than running the process again. /// /// This includes the overhead of setting up and cleaning up the process for execution, and it /// should include all overhead for the cache lookup. /// /// If the cache hit was slower than the original process, we return 0. Note that the cache hit /// may still have been faster than rerunning the process a second time, e.g. if speculation /// is used and the cache hit completed before the rerun; still, we cannot know how long the /// second run would have taken, so the best we can do is report 0. /// /// If the original process's execution time was not recorded, we return None because we /// cannot make a meaningful comparison. pub fn time_saved_from_cache( &self, cache_lookup: std::time::Duration, ) -> Option<std::time::Duration> { self.total_elapsed.and_then(|original_process| { let original_process: std::time::Duration = original_process.into(); original_process .checked_sub(cache_lookup) .or_else(|| Some(std::time::Duration::new(0, 0))) }) } } impl From<ProcessResultMetadata> for ExecutedActionMetadata { fn from(metadata: ProcessResultMetadata) -> ExecutedActionMetadata { let (total_start, total_end) = match metadata.total_elapsed { Some(elapsed) => { // Because we do not have the precise start time, we hardcode to starting at UNIX_EPOCH. We // only care about accurately preserving the duration. let start = prost_types::Timestamp { seconds: 0, nanos: 0, }; let end = prost_types::Timestamp { seconds: elapsed.secs as i64, nanos: elapsed.nanos as i32, }; (Some(start), Some(end)) } None => (None, None), }; ExecutedActionMetadata { worker_start_timestamp: total_start, worker_completed_timestamp: total_end, ..ExecutedActionMetadata::default() } } } #[derive(Clone, Copy, Debug, DeepSizeOf, Eq, PartialEq)] pub enum ProcessResultSource { RanLocally, RanRemotely, HitLocally, HitRemotely, } impl From<ProcessResultSource> for &'static str { fn from(prs: ProcessResultSource) -> &'static str { match prs { ProcessResultSource::RanLocally => "ran_locally", ProcessResultSource::RanRemotely => "ran_remotely", ProcessResultSource::HitLocally => "hit_locally", ProcessResultSource::HitRemotely => "hit_remotely", } } } #[derive(Clone, Copy, Debug, PartialEq, Eq, strum_macros::EnumString)] #[strum(serialize_all = "snake_case")] pub enum CacheContentBehavior { Fetch, Validate, Defer, } /// /// Optionally validate that all digests in the result are loadable, returning false if any are not. /// /// If content loading is deferred, a Digest which is discovered to be missing later on during /// execution will cause backtracking. /// pub(crate) async fn check_cache_content( response: &FallibleProcessResultWithPlatform, store: &Store, cache_content_behavior: CacheContentBehavior, ) -> Result<bool, StoreError> { match cache_content_behavior { CacheContentBehavior::Fetch => { let response = response.clone(); let fetch_result = in_workunit!("eager_fetch_action_cache", Level::Trace, |_workunit| store .ensure_downloaded( HashSet::from([response.stdout_digest, response.stderr_digest]), HashSet::from([response.output_directory]) )) .await; match fetch_result { Err(StoreError::MissingDigest { .. }) => Ok(false), Ok(_) => Ok(true), Err(e) => Err(e), } } CacheContentBehavior::Validate => { let directory_digests = vec![response.output_directory.clone()]; let file_digests = vec![response.stdout_digest, response.stderr_digest]; in_workunit!( "eager_validate_action_cache", Level::Trace, |_workunit| async move { store .exists_recursive(directory_digests, file_digests) .await } ) .await } CacheContentBehavior::Defer => Ok(true), } } #[derive(Clone)] pub struct Context { workunit_store: WorkunitStore, build_id: String, run_id: RunId, tail_tasks: TailTasks, } impl Default for Context { fn default() -> Self { Context { workunit_store: WorkunitStore::new(false, log::Level::Debug), build_id: String::default(), run_id: RunId(0), tail_tasks: TailTasks::new(), } } } impl Context { pub fn new( workunit_store: WorkunitStore, build_id: String, run_id: RunId, tail_tasks: TailTasks, ) -> Context { Context { workunit_store, build_id, run_id, tail_tasks, } } } #[async_trait] pub trait CommandRunner: Send + Sync + Debug { /// /// Submit a request for execution on the underlying runtime, and return /// a future for it. /// async fn run( &self, context: Context, workunit: &mut RunningWorkunit, req: Process, ) -> Result<FallibleProcessResultWithPlatform, ProcessError>; /// Shutdown this CommandRunner cleanly. async fn shutdown(&self) -> Result<(), String>; } #[async_trait] impl<T: CommandRunner + ?Sized> CommandRunner for Box<T> { async fn run( &self, context: Context, workunit: &mut RunningWorkunit, req: Process, ) -> Result<FallibleProcessResultWithPlatform, ProcessError> { (**self).run(context, workunit, req).await } async fn shutdown(&self) -> Result<(), String> { (**self).shutdown().await } } #[async_trait] impl<T: CommandRunner + ?Sized> CommandRunner for Arc<T> { async fn run( &self, context: Context, workunit: &mut RunningWorkunit, req: Process, ) -> Result<FallibleProcessResultWithPlatform, ProcessError> { (**self).run(context, workunit, req).await } async fn shutdown(&self) -> Result<(), String> { (**self).shutdown().await } } // TODO(#8513) possibly move to the MEPR struct, or to the hashing crate? pub async fn digest( process: &Process, instance_name: Option<String>, process_cache_namespace: Option<String>, store: &Store, append_only_caches_base_path: Option<&str>, ) -> Digest { let EntireExecuteRequest { execute_request, .. } = remote::make_execute_request( process, instance_name, process_cache_namespace, store, append_only_caches_base_path, ) .await .unwrap(); execute_request.action_digest.unwrap().try_into().unwrap() } #[cfg(test)] mod tests;
fmt
identifier_name
lib.rs
// Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). #![deny(warnings)] // Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to include inner attributes from a common source. #![deny( clippy::all, clippy::default_trait_access, clippy::expl_impl_clone_on_copy, clippy::if_not_else, clippy::needless_continue, clippy::unseparated_literal_suffix, clippy::used_underscore_binding )] // It is often more clear to show that nothing is being moved. #![allow(clippy::match_ref_pats)] // Subjective style. #![allow( clippy::len_without_is_empty, clippy::redundant_field_names, clippy::too_many_arguments )] // Default isn't as big a deal as people seem to think it is. #![allow(clippy::new_without_default, clippy::new_ret_no_self)] // Arc<Mutex> can be more clear than needing to grok Orderings: #![allow(clippy::mutex_atomic)] #[macro_use] extern crate derivative; use std::collections::{BTreeMap, BTreeSet, HashSet}; use std::convert::{TryFrom, TryInto}; use std::fmt::{self, Debug, Display}; use std::path::PathBuf; use std::sync::Arc; use async_trait::async_trait; use concrete_time::{Duration, TimeSpan}; use deepsize::DeepSizeOf; use fs::{DirectoryDigest, RelativePath, EMPTY_DIRECTORY_DIGEST}; use futures::future::try_join_all; use futures::try_join; use hashing::Digest; use itertools::Itertools; use protos::gen::build::bazel::remote::execution::v2 as remexec; use remexec::ExecutedActionMetadata; use serde::{Deserialize, Serialize}; use store::{SnapshotOps, Store, StoreError}; use task_executor::TailTasks; use workunit_store::{in_workunit, Level, RunId, RunningWorkunit, WorkunitStore}; pub mod bounded; #[cfg(test)] mod bounded_tests; pub mod cache; #[cfg(test)] mod cache_tests; pub mod switched; pub mod children; pub mod docker; #[cfg(test)] mod docker_tests; pub mod local; #[cfg(test)] mod local_tests; pub mod nailgun; pub mod named_caches; pub mod remote; #[cfg(test)] pub mod remote_tests; pub mod remote_cache; #[cfg(test)] mod remote_cache_tests; extern crate uname; pub use crate::children::ManagedChild; pub use crate::named_caches::{CacheName, NamedCaches}; pub use crate::remote_cache::RemoteCacheWarningsBehavior; use crate::remote::EntireExecuteRequest; #[derive(Clone, Debug, PartialEq, Eq)] pub enum ProcessError { /// A Digest was not present in either of the local or remote Stores. MissingDigest(String, Digest), /// All other error types. Unclassified(String), } impl ProcessError { pub fn enrich(self, prefix: &str) -> Self { match self { Self::MissingDigest(s, d) => Self::MissingDigest(format!("{prefix}: {s}"), d), Self::Unclassified(s) => Self::Unclassified(format!("{prefix}: {s}")), } } } impl Display for ProcessError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::MissingDigest(s, d) => { write!(f, "{s}: {d:?}") } Self::Unclassified(s) => write!(f, "{s}"), } } } impl From<StoreError> for ProcessError { fn from(err: StoreError) -> Self { match err { StoreError::MissingDigest(s, d) => Self::MissingDigest(s, d), StoreError::Unclassified(s) => Self::Unclassified(s), } } } impl From<String> for ProcessError { fn from(err: String) -> Self { Self::Unclassified(err) } } #[derive( PartialOrd, Ord, Clone, Copy, Debug, DeepSizeOf, Eq, PartialEq, Hash, Serialize, Deserialize, )] #[allow(non_camel_case_types)] pub enum Platform { Macos_x86_64, Macos_arm64, Linux_x86_64, Linux_arm64, } impl Platform { pub fn current() -> Result<Platform, String> { let platform_info = uname::uname().map_err(|_| "Failed to get local platform info!".to_string())?; match platform_info { uname::Info { ref sysname, ref machine, .. } if sysname.to_lowercase() == "linux" && machine.to_lowercase() == "x86_64" => { Ok(Platform::Linux_x86_64) } uname::Info { ref sysname, ref machine, .. } if sysname.to_lowercase() == "linux" && (machine.to_lowercase() == "arm64" || machine.to_lowercase() == "aarch64") => { Ok(Platform::Linux_arm64) } uname::Info { ref sysname, ref machine, .. } if sysname.to_lowercase() == "darwin" && machine.to_lowercase() == "arm64" => { Ok(Platform::Macos_arm64) } uname::Info { ref sysname, ref machine, .. } if sysname.to_lowercase() == "darwin" && machine.to_lowercase() == "x86_64" => { Ok(Platform::Macos_x86_64) } uname::Info { ref sysname, ref machine, .. } => Err(format!( "Found unknown system/arch name pair {sysname} {machine}" )), } } } impl From<Platform> for String { fn from(platform: Platform) -> String { match platform { Platform::Linux_x86_64 => "linux_x86_64".to_string(), Platform::Linux_arm64 => "linux_arm64".to_string(), Platform::Macos_arm64 => "macos_arm64".to_string(), Platform::Macos_x86_64 => "macos_x86_64".to_string(), } } } impl TryFrom<String> for Platform { type Error = String; fn try_from(variant_candidate: String) -> Result<Self, Self::Error> { match variant_candidate.as_ref() { "macos_arm64" => Ok(Platform::Macos_arm64), "macos_x86_64" => Ok(Platform::Macos_x86_64), "linux_x86_64" => Ok(Platform::Linux_x86_64), "linux_arm64" => Ok(Platform::Linux_arm64), other => Err(format!("Unknown platform {other:?} encountered in parsing")), } } } #[derive(Clone, Copy, Debug, DeepSizeOf, Eq, PartialEq, Hash, Serialize)] pub enum ProcessCacheScope { // Cached in all locations, regardless of success or failure. Always, // Cached in all locations, but only if the process exits successfully. Successful, // Cached only in memory (i.e. memoized in pantsd), but never persistently, regardless of // success vs. failure. PerRestartAlways, // Cached only in memory (i.e. memoized in pantsd), but never persistently, and only if // successful. PerRestartSuccessful, // Will run once per Session, i.e. once per run of Pants. This happens because the engine // de-duplicates identical work; the process is neither memoized in memory nor cached to disk. PerSession, } impl TryFrom<String> for ProcessCacheScope { type Error = String; fn try_from(variant_candidate: String) -> Result<Self, Self::Error> { match variant_candidate.to_lowercase().as_ref() { "always" => Ok(ProcessCacheScope::Always), "successful" => Ok(ProcessCacheScope::Successful), "per_restart_always" => Ok(ProcessCacheScope::PerRestartAlways), "per_restart_successful" => Ok(ProcessCacheScope::PerRestartSuccessful), "per_session" => Ok(ProcessCacheScope::PerSession), other => Err(format!("Unknown Process cache scope: {other:?}")), } } } fn serialize_level<S: serde::Serializer>(level: &log::Level, s: S) -> Result<S::Ok, S::Error> { s.serialize_str(&level.to_string()) } /// Input Digests for a process execution. /// /// The `complete` and `nailgun` Digests are the computed union of various inputs. /// /// TODO: See `crate::local::prepare_workdir` regarding validation of overlapping inputs. #[derive(Clone, Debug, DeepSizeOf, Eq, Hash, PartialEq, Serialize)] pub struct InputDigests { /// All of the input Digests, merged and relativized. Runners without the ability to consume the /// Digests individually should directly consume this value. pub complete: DirectoryDigest, /// The merged Digest of any `use_nailgun`-relevant Digests. pub nailgun: DirectoryDigest, /// The input files for the process execution, which will be materialized as mutable inputs in a /// sandbox for the process. /// /// TODO: Rename to `inputs` for symmetry with `immutable_inputs`. pub input_files: DirectoryDigest, /// Immutable input digests to make available in the input root. /// /// These digests are intended for inputs that will be reused between multiple Process /// invocations, without being mutated. This might be useful to provide the tools being executed, /// but can also be used for tool inputs such as compilation artifacts. /// /// The digests will be mounted at the relative path represented by the `RelativePath` keys. /// The executor may choose how to make the digests available, including by just merging /// the digest normally into the input root, creating a symlink to a persistent cache, /// or bind mounting the directory read-only into a persistent cache. Consequently, the mount /// point of each input must not overlap the `input_files`, even for directory entries. /// /// Assumes the build action does not modify the Digest as made available. This may be /// enforced by an executor, for example by bind mounting the directory read-only. pub immutable_inputs: BTreeMap<RelativePath, DirectoryDigest>, /// If non-empty, use nailgun in supported runners, using the specified `immutable_inputs` keys /// as server inputs. All other keys (and the input_files) will be client inputs. pub use_nailgun: BTreeSet<RelativePath>, } impl InputDigests { pub async fn new( store: &Store, input_files: DirectoryDigest, immutable_inputs: BTreeMap<RelativePath, DirectoryDigest>, use_nailgun: BTreeSet<RelativePath>, ) -> Result<Self, StoreError> { // Collect all digests into `complete`. let mut complete_digests = try_join_all( immutable_inputs .iter() .map(|(path, digest)| store.add_prefix(digest.clone(), path)) .collect::<Vec<_>>(), ) .await?; // And collect only the subset of the Digests which impact nailgun into `nailgun`. let nailgun_digests = immutable_inputs .keys() .zip(complete_digests.iter()) .filter_map(|(path, digest)| { if use_nailgun.contains(path) { Some(digest.clone()) } else { None } }) .collect::<Vec<_>>(); complete_digests.push(input_files.clone()); let (complete, nailgun) = try_join!(store.merge(complete_digests), store.merge(nailgun_digests),)?; Ok(Self { complete: complete, nailgun: nailgun, input_files, immutable_inputs, use_nailgun, }) } pub async fn new_from_merged(store: &Store, from: Vec<InputDigests>) -> Result<Self, StoreError> { let mut merged_immutable_inputs = BTreeMap::new(); for input_digests in from.iter() { let size_before = merged_immutable_inputs.len(); let immutable_inputs = &input_digests.immutable_inputs; merged_immutable_inputs.append(&mut immutable_inputs.clone()); if size_before + immutable_inputs.len() != merged_immutable_inputs.len() { return Err( format!( "Tried to merge two-or-more immutable inputs at the same path with different values! \ The collision involved one of the entries in: {immutable_inputs:?}" ) .into(), ); } } let complete_digests = from .iter() .map(|input_digests| input_digests.complete.clone()) .collect(); let nailgun_digests = from .iter() .map(|input_digests| input_digests.nailgun.clone()) .collect(); let input_files_digests = from .iter() .map(|input_digests| input_digests.input_files.clone()) .collect(); let (complete, nailgun, input_files) = try_join!( store.merge(complete_digests), store.merge(nailgun_digests), store.merge(input_files_digests), )?; Ok(Self { complete: complete, nailgun: nailgun, input_files: input_files, immutable_inputs: merged_immutable_inputs, use_nailgun: Itertools::concat( from .iter() .map(|input_digests| input_digests.use_nailgun.clone()), ) .into_iter() .collect(), }) } pub fn with_input_files(input_files: DirectoryDigest) -> Self { Self { complete: input_files.clone(), nailgun: EMPTY_DIRECTORY_DIGEST.clone(), input_files, immutable_inputs: BTreeMap::new(), use_nailgun: BTreeSet::new(), } } /// Split the InputDigests into client and server subsets. /// /// TODO: The server subset will have an accurate `complete` Digest, but the client will not. /// This is currently safe because the nailgun client code does not consume that field, but it /// would be good to find a better factoring. pub fn nailgun_client_and_server(&self) -> (InputDigests, InputDigests) { let (server, client) = self .immutable_inputs .clone() .into_iter() .partition(|(path, _digest)| self.use_nailgun.contains(path)); ( // Client. InputDigests { // TODO: See method doc. complete: EMPTY_DIRECTORY_DIGEST.clone(), nailgun: EMPTY_DIRECTORY_DIGEST.clone(), input_files: self.input_files.clone(), immutable_inputs: client, use_nailgun: BTreeSet::new(), }, // Server. InputDigests { complete: self.nailgun.clone(), nailgun: EMPTY_DIRECTORY_DIGEST.clone(), input_files: EMPTY_DIRECTORY_DIGEST.clone(), immutable_inputs: server, use_nailgun: BTreeSet::new(), }, ) } } impl Default for InputDigests { fn default() -> Self { Self { complete: EMPTY_DIRECTORY_DIGEST.clone(), nailgun: EMPTY_DIRECTORY_DIGEST.clone(), input_files: EMPTY_DIRECTORY_DIGEST.clone(), immutable_inputs: BTreeMap::new(), use_nailgun: BTreeSet::new(), } } } #[derive(DeepSizeOf, Debug, Clone, Hash, PartialEq, Eq, Serialize)] pub enum ProcessExecutionStrategy { Local, /// Stores the platform_properties. RemoteExecution(Vec<(String, String)>), /// Stores the image name. Docker(String), } impl ProcessExecutionStrategy { /// What to insert into the Command proto so that we don't incorrectly cache /// Docker vs remote execution vs local execution. pub fn cache_value(&self) -> String { match self { Self::Local => "local_execution".to_string(), Self::RemoteExecution(_) => "remote_execution".to_string(), // NB: this image will include the container ID, thanks to // https://github.com/pantsbuild/pants/pull/17101. Self::Docker(image) => format!("docker_execution: {image}"), } } } /// /// A process to be executed. /// /// When executing a `Process` using the `local::CommandRunner`, any `{chroot}` placeholders in the /// environment variables are replaced with the temporary sandbox path. /// #[derive(DeepSizeOf, Derivative, Clone, Debug, Eq, Serialize)] #[derivative(PartialEq, Hash)] pub struct Process { /// /// The arguments to execute. /// /// The first argument should be an absolute or relative path to the binary to execute. /// /// No PATH lookup will be performed unless a PATH environment variable is specified. /// /// No shell expansion will take place. /// pub argv: Vec<String>, /// /// The environment variables to set for the execution. /// /// No other environment variables will be set (except possibly for an empty PATH variable). /// pub env: BTreeMap<String, String>, /// /// A relative path to a directory existing in the `input_files` digest to execute the process /// from. Defaults to the `input_files` root. /// pub working_directory: Option<RelativePath>, /// /// All of the input digests for the process. /// pub input_digests: InputDigests, pub output_files: BTreeSet<RelativePath>, pub output_directories: BTreeSet<RelativePath>, pub timeout: Option<std::time::Duration>, /// If not None, then a bounded::CommandRunner executing this Process will set an environment /// variable with this name containing a unique execution slot number. pub execution_slot_variable: Option<String>, /// If non-zero, the amount of parallelism that this process is capable of given its inputs. This /// value does not directly set the number of cores allocated to the process: that is computed /// based on availability, and provided as a template value in the arguments of the process. /// /// When set, a `{pants_concurrency}` variable will be templated into the `argv` of the process. /// /// Processes which set this value may be preempted (i.e. canceled and restarted) for a short /// period after starting if available resources have changed (because other processes have /// started or finished). pub concurrency_available: usize, #[derivative(PartialEq = "ignore", Hash = "ignore")] pub description: String, // NB: We serialize with a function to avoid adding a serde dep to the logging crate. #[serde(serialize_with = "serialize_level")] pub level: log::Level, /// /// Declares that this process uses the given named caches (which might have associated config /// in the future) at the associated relative paths within its workspace. Cache names must /// contain only lowercase ascii characters or underscores. /// /// Caches are exposed to processes within their workspaces at the relative paths represented /// by the values of the dict. A process may optionally check for the existence of the relevant /// directory, and disable use of that cache if it has not been created by the executor /// (indicating a lack of support for this feature). /// /// These caches are globally shared and so must be concurrency safe: a consumer of the cache /// must never assume that it has exclusive access to the provided directory. /// pub append_only_caches: BTreeMap<CacheName, RelativePath>, /// /// If present, a symlink will be created at .jdk which points to this directory for local /// execution, or a system-installed JDK (ignoring the value of the present Some) for remote /// execution. /// /// This is some technical debt we should clean up; /// see <https://github.com/pantsbuild/pants/issues/6416>. /// pub jdk_home: Option<PathBuf>, pub platform: Platform, pub cache_scope: ProcessCacheScope, pub execution_strategy: ProcessExecutionStrategy, pub remote_cache_speculation_delay: std::time::Duration, } impl Process { /// /// Constructs a Process with default values for most fields, after which the builder pattern can /// be used to set values. /// /// We use the more ergonomic (but possibly slightly slower) "move self for each builder method" /// pattern, so this method is only enabled for test usage: production usage should construct the /// Process struct wholesale. We can reconsider this if we end up with more production callsites /// that require partial options. /// #[cfg(test)] pub fn new(argv: Vec<String>) -> Process { Process { argv, env: BTreeMap::new(), working_directory: None, input_digests: InputDigests::default(), output_files: BTreeSet::new(), output_directories: BTreeSet::new(), timeout: None, description: "".to_string(), level: log::Level::Info, append_only_caches: BTreeMap::new(), jdk_home: None, platform: Platform::current().unwrap(), execution_slot_variable: None, concurrency_available: 0, cache_scope: ProcessCacheScope::Successful, execution_strategy: ProcessExecutionStrategy::Local, remote_cache_speculation_delay: std::time::Duration::from_millis(0), } } /// /// Replaces the environment for this process. /// pub fn env(mut self, env: BTreeMap<String, String>) -> Process { self.env = env; self } /// /// Replaces the working_directory for this process. /// pub fn working_directory(mut self, working_directory: Option<RelativePath>) -> Process { self.working_directory = working_directory; self } /// /// Replaces the output files for this process. /// pub fn output_files(mut self, output_files: BTreeSet<RelativePath>) -> Process { self.output_files = output_files; self } /// /// Replaces the output directories for this process. /// pub fn output_directories(mut self, output_directories: BTreeSet<RelativePath>) -> Process { self.output_directories = output_directories; self } /// /// Replaces the append only caches for this process. /// pub fn append_only_caches( mut self, append_only_caches: BTreeMap<CacheName, RelativePath>, ) -> Process
/// /// Set the execution strategy to Docker, with the specified image. /// pub fn docker(mut self, image: String) -> Process { self.execution_strategy = ProcessExecutionStrategy::Docker(image); self } /// /// Set the execution strategy to remote execution with the provided platform properties. /// pub fn remote_execution_platform_properties( mut self, properties: Vec<(String, String)>, ) -> Process { self.execution_strategy = ProcessExecutionStrategy::RemoteExecution(properties); self } pub fn remote_cache_speculation_delay(mut self, delay: std::time::Duration) -> Process { self.remote_cache_speculation_delay = delay; self } pub fn cache_scope(mut self, cache_scope: ProcessCacheScope) -> Process { self.cache_scope = cache_scope; self } } /// /// The result of running a process. /// #[derive(DeepSizeOf, Derivative, Clone, Debug, Eq)] #[derivative(PartialEq, Hash)] pub struct FallibleProcessResultWithPlatform { pub stdout_digest: Digest, pub stderr_digest: Digest, pub exit_code: i32, pub output_directory: DirectoryDigest, pub platform: Platform, #[derivative(PartialEq = "ignore", Hash = "ignore")] pub metadata: ProcessResultMetadata, } /// Metadata for a ProcessResult corresponding to the REAPI `ExecutedActionMetadata` proto. This /// conversion is lossy, but the interesting parts are preserved. #[derive(Clone, Debug, DeepSizeOf, Eq, PartialEq)] pub struct ProcessResultMetadata { /// The time from starting to completion, including preparing the chroot and cleanup. /// Corresponds to `worker_start_timestamp` and `worker_completed_timestamp` from /// `ExecutedActionMetadata`. /// /// NB: This is optional because the REAPI does not guarantee that it is returned. pub total_elapsed: Option<Duration>, /// The source of the result. pub source: ProcessResultSource, /// The RunId of the Session in which the `ProcessResultSource` was accurate. In further runs /// within the same process, the source of the process implicitly becomes memoization. pub source_run_id: RunId, } impl ProcessResultMetadata { pub fn new( total_elapsed: Option<Duration>, source: ProcessResultSource, source_run_id: RunId, ) -> Self { Self { total_elapsed, source, source_run_id, } } pub fn new_from_metadata( metadata: ExecutedActionMetadata, source: ProcessResultSource, source_run_id: RunId, ) -> Self { let total_elapsed = match ( metadata.worker_start_timestamp, metadata.worker_completed_timestamp, ) { (Some(started), Some(completed)) => TimeSpan::from_start_and_end(&started, &completed, "") .map(|span| span.duration) .ok(), _ => None, }; Self { total_elapsed, source, source_run_id, } } /// How much faster a cache hit was than running the process again. /// /// This includes the overhead of setting up and cleaning up the process for execution, and it /// should include all overhead for the cache lookup. /// /// If the cache hit was slower than the original process, we return 0. Note that the cache hit /// may still have been faster than rerunning the process a second time, e.g. if speculation /// is used and the cache hit completed before the rerun; still, we cannot know how long the /// second run would have taken, so the best we can do is report 0. /// /// If the original process's execution time was not recorded, we return None because we /// cannot make a meaningful comparison. pub fn time_saved_from_cache( &self, cache_lookup: std::time::Duration, ) -> Option<std::time::Duration> { self.total_elapsed.and_then(|original_process| { let original_process: std::time::Duration = original_process.into(); original_process .checked_sub(cache_lookup) .or_else(|| Some(std::time::Duration::new(0, 0))) }) } } impl From<ProcessResultMetadata> for ExecutedActionMetadata { fn from(metadata: ProcessResultMetadata) -> ExecutedActionMetadata { let (total_start, total_end) = match metadata.total_elapsed { Some(elapsed) => { // Because we do not have the precise start time, we hardcode to starting at UNIX_EPOCH. We // only care about accurately preserving the duration. let start = prost_types::Timestamp { seconds: 0, nanos: 0, }; let end = prost_types::Timestamp { seconds: elapsed.secs as i64, nanos: elapsed.nanos as i32, }; (Some(start), Some(end)) } None => (None, None), }; ExecutedActionMetadata { worker_start_timestamp: total_start, worker_completed_timestamp: total_end, ..ExecutedActionMetadata::default() } } } #[derive(Clone, Copy, Debug, DeepSizeOf, Eq, PartialEq)] pub enum ProcessResultSource { RanLocally, RanRemotely, HitLocally, HitRemotely, } impl From<ProcessResultSource> for &'static str { fn from(prs: ProcessResultSource) -> &'static str { match prs { ProcessResultSource::RanLocally => "ran_locally", ProcessResultSource::RanRemotely => "ran_remotely", ProcessResultSource::HitLocally => "hit_locally", ProcessResultSource::HitRemotely => "hit_remotely", } } } #[derive(Clone, Copy, Debug, PartialEq, Eq, strum_macros::EnumString)] #[strum(serialize_all = "snake_case")] pub enum CacheContentBehavior { Fetch, Validate, Defer, } /// /// Optionally validate that all digests in the result are loadable, returning false if any are not. /// /// If content loading is deferred, a Digest which is discovered to be missing later on during /// execution will cause backtracking. /// pub(crate) async fn check_cache_content( response: &FallibleProcessResultWithPlatform, store: &Store, cache_content_behavior: CacheContentBehavior, ) -> Result<bool, StoreError> { match cache_content_behavior { CacheContentBehavior::Fetch => { let response = response.clone(); let fetch_result = in_workunit!("eager_fetch_action_cache", Level::Trace, |_workunit| store .ensure_downloaded( HashSet::from([response.stdout_digest, response.stderr_digest]), HashSet::from([response.output_directory]) )) .await; match fetch_result { Err(StoreError::MissingDigest { .. }) => Ok(false), Ok(_) => Ok(true), Err(e) => Err(e), } } CacheContentBehavior::Validate => { let directory_digests = vec![response.output_directory.clone()]; let file_digests = vec![response.stdout_digest, response.stderr_digest]; in_workunit!( "eager_validate_action_cache", Level::Trace, |_workunit| async move { store .exists_recursive(directory_digests, file_digests) .await } ) .await } CacheContentBehavior::Defer => Ok(true), } } #[derive(Clone)] pub struct Context { workunit_store: WorkunitStore, build_id: String, run_id: RunId, tail_tasks: TailTasks, } impl Default for Context { fn default() -> Self { Context { workunit_store: WorkunitStore::new(false, log::Level::Debug), build_id: String::default(), run_id: RunId(0), tail_tasks: TailTasks::new(), } } } impl Context { pub fn new( workunit_store: WorkunitStore, build_id: String, run_id: RunId, tail_tasks: TailTasks, ) -> Context { Context { workunit_store, build_id, run_id, tail_tasks, } } } #[async_trait] pub trait CommandRunner: Send + Sync + Debug { /// /// Submit a request for execution on the underlying runtime, and return /// a future for it. /// async fn run( &self, context: Context, workunit: &mut RunningWorkunit, req: Process, ) -> Result<FallibleProcessResultWithPlatform, ProcessError>; /// Shutdown this CommandRunner cleanly. async fn shutdown(&self) -> Result<(), String>; } #[async_trait] impl<T: CommandRunner + ?Sized> CommandRunner for Box<T> { async fn run( &self, context: Context, workunit: &mut RunningWorkunit, req: Process, ) -> Result<FallibleProcessResultWithPlatform, ProcessError> { (**self).run(context, workunit, req).await } async fn shutdown(&self) -> Result<(), String> { (**self).shutdown().await } } #[async_trait] impl<T: CommandRunner + ?Sized> CommandRunner for Arc<T> { async fn run( &self, context: Context, workunit: &mut RunningWorkunit, req: Process, ) -> Result<FallibleProcessResultWithPlatform, ProcessError> { (**self).run(context, workunit, req).await } async fn shutdown(&self) -> Result<(), String> { (**self).shutdown().await } } // TODO(#8513) possibly move to the MEPR struct, or to the hashing crate? pub async fn digest( process: &Process, instance_name: Option<String>, process_cache_namespace: Option<String>, store: &Store, append_only_caches_base_path: Option<&str>, ) -> Digest { let EntireExecuteRequest { execute_request, .. } = remote::make_execute_request( process, instance_name, process_cache_namespace, store, append_only_caches_base_path, ) .await .unwrap(); execute_request.action_digest.unwrap().try_into().unwrap() } #[cfg(test)] mod tests;
{ self.append_only_caches = append_only_caches; self }
identifier_body
ptycho-fig5.py
# !/usr/bin/env python # -*- coding: utf-8 -*- """Module for 3D ptychography.""" import dxchange import tomopy import xraylib as xl import numpy as np import scipy as sp import pyfftw import shutil import warnings warnings.filterwarnings("ignore") PLANCK_CONSTANT = 6.58211928e-19 # [keV*s] SPEED_OF_LIGHT = 299792458e+2 # [cm/s] def wavelength(energy): """Calculates the wavelength [cm] given energy [keV]. Parameters ---------- energy : scalar Returns ------- scalar """ return 2 * np.pi * PLANCK_CONSTANT * SPEED_OF_LIGHT / energy def wavenumber(energy): """Calculates the wavenumber [1/cm] given energy [keV]. Parameters ---------- energy : scalar Returns ------- scalar """ return 2 * np.pi / wavelength(energy) class Material(object): """Material property definitions. Attributes ---------- compound : string Molecular formula of the material. density : scalar Density of the compound [g/cm^3]. energy : scalar Illumination energy [keV]. """ def __init__(self, compound, density, energy): self.compound = compound self.density = density self.energy = energy @property def beta(self): """Absorption coefficient.""" return xl.Refractive_Index_Im(self.compound, self.energy, self.density) @property def delta(self): """Decrement of refractive index.""" return 1 - xl.Refractive_Index_Re(self.compound, self.energy, self.density) class Object(object): """Discrete object represented in a 3D regular grid. Attributes ---------- beta : ndarray Absorption index. delta : ndarray Refractive index decrement. voxelsize : scalar [cm] Size of the voxels in the grid. """ def __init__(self, beta, delta, voxelsize): self.beta = beta self.delta = delta self.voxelsize = voxelsize @property def shape(self): return self.beta.shape @property def complexform(self): return self.delta + 1j * self.beta class Detector(object): """A planar area detector. Attributes ---------- numx : int Number of horizontal pixels. numy : int Number of vertical pixels. """ def __init__(self, x, y): self.x = x self.y = y def uniform(size): return np.ones((size, size), dtype='float32') def gaussian(size, rin=0.8, rout=1): r, c = np.mgrid[:size, :size] + 0.5 rs = np.sqrt((r - size/2)**2 + (c - size/2)**2) rmax = np.sqrt(2) * 0.5 * rout * rs.max() + 1.0 rmin = np.sqrt(2) * 0.5 * rin * rs.max() img = np.zeros((size, size), dtype='float32') img[rs < rmin] = 1.0 img[rs > rmax] = 0.0 zone = np.logical_and(rs > rmin, rs < rmax) img[zone] = np.divide(rmax - rs[zone], rmax - rmin) return img class Probe(object): """Illumination probe represented on a 2D regular grid. A finite-extent circular shaped probe is represented as a complex wave. The intensity of the probe is maximum at the center and damps to zero at the borders of the frame. Attributes size : int ---------- Size of the square 2D frame for the probe. rin : float Value between 0 and 1 determining where the dampening of the intensity will start. rout : float Value between 0 and 1 determining where the intensity will reach to zero. maxint : float Maximum intensity of the probe at the center. """ def __init__(self, weights, maxint=1e5): self.weights = weights self.size = weights.shape[0] self.maxint = maxint self.shape = weights.shape @property def amplitude(self): """Amplitude of the probe wave""" return np.sqrt(self.maxint) * self.weights @property def phase(self): """Phase of the probe wave.""" return 0.2 * self.weights @property def intensity(self): """Intensity of the probe wave.""" return np.power(prb.amplitude, 2) @property def complex(self): return self.amplitude * np.exp(1j * self.phase) class Scanner(object): def
(self, shape, sx, sy, margin=[0, 0], offset=[0, 0]): self.shape = shape self.sx = sx self.sy = sy self.margin = margin self.offset = offset @property def x(self): return np.arange(self.offset[0], self.shape[0]-self.margin[0]+1, self.sx) @property def y(self): return np.arange(self.offset[1], self.shape[1]-self.margin[1]+1, self.sy) def scanner3(theta, shape, sx, sy, margin=[0, 0], offset=[0, 0], spiral=0): a = spiral scan = [] for m in range(len(theta)): s = Scanner(shape, sx, sy, margin, offset=[ offset[0], np.mod(offset[1]+a, sy)]) scan.append(s) a += spiral return scan def _pad(phi, det): """Pads phi according to detector size.""" npadx = (det.x - phi.shape[1]) // 2 npady = (det.y - phi.shape[1]) // 2 return np.pad(phi, ((0, 0), (npadx, npadx), (npady, npady)), mode='constant') def project(obj, ang, energy): pb = tomopy.project(obj.beta, ang, pad=False) * obj.voxelsize pd = tomopy.project(obj.delta, ang, pad=False) * obj.voxelsize psi = np.exp(1j * wavenumber(energy) * (pd + 1j * pb)) return psi def exitwave(prb, psi, scan): return np.array([prb.complex * psi[i:i + prb.size, j:j + prb.size] for i in scan.x for j in scan.y], dtype='complex') def propagate2(phi, det): phi = _pad(phi, det) intensity = np.abs(np.fft.fft2(phi)) ** 2 return intensity.astype('float32') def propagate3(prb, psi, scan, theta, det, noise=False): data = [] for m in range(theta.size): phi = exitwave(prb, np.squeeze(psi[m]), scan[m]) dat = propagate2(phi, det) if noise == True: dat = np.random.poisson(dat).astype('float32') data.append(dat) return data def invptycho2(data, prb, scan, init, niter, rho, gamma, hobj, lamd, folder, debug): npadx = (data.shape[1] - prb.size) // 2 npady = (data.shape[2] - prb.size) // 2 psi = init.copy() convpsi = np.zeros(niter, dtype='float32') for i in range(niter): upd = np.zeros(psi.shape, dtype='complex') _psi = np.zeros(psi.shape, dtype='complex') a = 0 for m in range(len(scan.x)): for n in range(len(scan.y)): # Near-plane. phi = np.multiply( prb.complex, psi[scan.x[m]:scan.x[m] + prb.size, scan.y[n]:scan.y[n] + prb.size]) # Go far-plane & Replace the amplitude with the measured amplitude. phi = np.pad( phi, ((npadx, npadx), (npady, npady)), mode='constant') tmp = np.fft.fft2(phi) tmp = np.multiply(np.sqrt(data[a]), np.exp(1j * np.angle(tmp))) # Back to near-plane. iphi = np.fft.ifft2(tmp) # Object update. delphi = (iphi - phi)[npadx:npadx + prb.size, npady:npady+prb.size] num = np.multiply(np.conj(prb.complex), delphi) denum = np.power(np.abs(prb.complex), 2).max() _upd = np.true_divide(num, denum) upd[scan.x[m]:scan.x[m]+prb.size, scan.y[n]:scan.y[n]+prb.size] += _upd a += 1 # psi += upd.copy() # _psi = psi + (gamma / 2) * upd.copy() _psi = (1 - rho*gamma) * psi + rho*gamma * \ (hobj - lamd/rho) + (gamma / 2) * upd.copy() convpsi[i] = np.linalg.norm(psi - _psi, ord='fro') psi = _psi.copy() return psi, convpsi def invptycho3(data, prb, scan, init, theta, niter, rho, gamma, hobj, lamd, folder, debug): psi = np.zeros((init.shape), dtype='complex') convallpsi = np.zeros((theta.size, niter), dtype='float32') for m in range(theta.size): psi[m], convpsi = invptycho2( data[m], prb, scan[m], init[m], niter, rho, gamma, hobj[m], lamd[m], folder, debug) convallpsi[m] = convpsi return psi, convallpsi def invtomo3(data, theta, voxelsize, energy, niter, init, eta): _data = 1 / wavenumber(energy) * np.log(data) / voxelsize pb = tomopy.recon(-np.real(_data), theta, algorithm='grad', num_iter=niter, init_recon=init.beta.copy(), reg_par=eta) pd = tomopy.recon(np.imag(_data), theta, algorithm='grad', num_iter=niter, init_recon=init.delta.copy(), reg_par=eta) obj = Object(pb, pd, 1e-6) return obj folder = 'tmp/lego-joint-noise-1' print(folder) # Parameters. rho = 0.5 gamma = 0.25 eta = 0.25 NITER = 256 piter = 1 titer = 1 maxint = 10 noise = False debug = False # Load a 3D object. beta = dxchange.read_tiff( 'data/test-beta-128.tiff').astype('float32')[::2, ::2, ::2] delta = dxchange.read_tiff( 'data/test-delta-128.tiff').astype('float32')[::2, ::2, ::2] # # Load a 3D object. # beta = dxchange.read_tiff('data/lego-imag.tiff')[::2, ::2, ::2] # delta = dxchange.read_tiff('data/lego-real.tiff')[::2, ::2, ::2] # Create object. obj = Object(beta, delta, 1e-6) dxchange.write_tiff(obj.beta, folder + '/beta') dxchange.write_tiff(obj.delta, folder + '/delta') # Create probe. weights = gaussian(15, rin=0.8, rout=1.0) prb = Probe(weights, maxint=maxint) dxchange.write_tiff(prb.amplitude, folder + '/probe-amplitude') dxchange.write_tiff(prb.phase, folder + '/probe-phase') # Detector parameters. det = Detector(63, 63) # Define rotation angles. theta = np.linspace(0, 2*np.pi, 180) # Raster scan parameters for each rotation angle. scan = scanner3(theta, beta.shape, 12, 12, margin=[ prb.size, prb.size], offset=[0, 0], spiral=1) # Project. psis = project(obj, theta, energy=5) dxchange.write_tiff(np.real(psis), folder + '/psi-amplitude') dxchange.write_tiff(np.imag(psis), folder + '/psi-phase') # Propagate. data0 = propagate3(prb, psis, scan, theta, det, noise=False) data = propagate3(prb, psis, scan, theta, det, noise=noise) print(np.amax(data[3])) print(np.amax(data[3]-data0[3])) dxchange.write_tiff(np.fft.fftshift( np.log(np.array(data[0]))), folder + '/data') # Init. hobj = np.ones(psis.shape, dtype='complex') psi = np.ones(psis.shape, dtype='complex') lamd = np.zeros(psi.shape, dtype='complex') tmp = np.zeros(obj.shape) recobj = Object(tmp, tmp, 1e-6) cp = np.zeros((NITER,)) cl = np.zeros((NITER,)) co = np.zeros((NITER,)) for m in range(NITER): # Ptychography. psi, conv = invptycho3(data, prb, scan, psi, theta, niter=piter, rho=rho, gamma=gamma, hobj=hobj, lamd=lamd, folder=folder, debug=debug) dxchange.write_tiff(np.real(psi[0]).astype( 'float32'), folder + '/psi-amplitude/psi-amplitude') dxchange.write_tiff(np.imag(psi[0]).astype( 'float32'), folder + '/psi-phase/psi-phase') dxchange.write_tiff(np.abs( (psi + lamd/rho)[0]).astype('float32'), folder + '/psilamd-amplitude/psilamd-amplitude') dxchange.write_tiff(np.angle( (psi + lamd/rho)[0]).astype('float32'), folder + '/psilamd-phase/psilamd-phase') cp[m] = np.sqrt(np.sum(np.power(np.abs(hobj-psi), 2))) # Tomography. _recobj = invtomo3(psi + lamd/rho, theta, obj.voxelsize, energy=5, niter=titer, init=recobj, eta=eta) co[m] = np.sqrt( np.sum(np.power(np.abs(recobj.complexform - _recobj.complexform), 2))) recobj = _recobj dxchange.write_tiff( recobj.beta[:, beta.shape[0] // 2], folder + '/beta/beta') dxchange.write_tiff( recobj.delta[:, delta.shape[0] // 2], folder + '/delta/delta') dxchange.write_tiff(recobj.beta, folder + '/beta-full/beta') dxchange.write_tiff(recobj.delta, folder + '/delta-full/delta') # Lambda update. hobj = project(recobj, theta, energy=5) dxchange.write_tiff(np.real(hobj[0]).astype( 'float32'), folder + '/hobj-amplitude/hobj-amplitude') dxchange.write_tiff(np.imag(hobj[0]).astype( 'float32'), folder + '/hobj-phase/hobj-phase') _lamd = lamd + 1 * rho * (psi - hobj) cl[m] = np.sqrt(np.sum(np.power(np.abs(lamd-_lamd), 2))) lamd = _lamd.copy() dxchange.write_tiff(np.abs(lamd[0]).astype( 'float32'), folder + '/lamd-amplitude/lamd-amplitude') dxchange.write_tiff(np.angle(lamd[0]).astype( 'float32'), folder + '/lamd-phase/lamd-phase') print(m, cp[m], co[m], cl[m]) if np.isnan(cp[m]) or np.isnan(co[m]) or np.isnan(cl[m]): break np.save(folder + '/admm-conv-cp.npy', cp) np.save(folder + '/admm-conv-co.npy', co) np.save(folder + '/admm-conv-cl.npy', cl)
__init__
identifier_name
ptycho-fig5.py
# !/usr/bin/env python # -*- coding: utf-8 -*- """Module for 3D ptychography."""
import scipy as sp import pyfftw import shutil import warnings warnings.filterwarnings("ignore") PLANCK_CONSTANT = 6.58211928e-19 # [keV*s] SPEED_OF_LIGHT = 299792458e+2 # [cm/s] def wavelength(energy): """Calculates the wavelength [cm] given energy [keV]. Parameters ---------- energy : scalar Returns ------- scalar """ return 2 * np.pi * PLANCK_CONSTANT * SPEED_OF_LIGHT / energy def wavenumber(energy): """Calculates the wavenumber [1/cm] given energy [keV]. Parameters ---------- energy : scalar Returns ------- scalar """ return 2 * np.pi / wavelength(energy) class Material(object): """Material property definitions. Attributes ---------- compound : string Molecular formula of the material. density : scalar Density of the compound [g/cm^3]. energy : scalar Illumination energy [keV]. """ def __init__(self, compound, density, energy): self.compound = compound self.density = density self.energy = energy @property def beta(self): """Absorption coefficient.""" return xl.Refractive_Index_Im(self.compound, self.energy, self.density) @property def delta(self): """Decrement of refractive index.""" return 1 - xl.Refractive_Index_Re(self.compound, self.energy, self.density) class Object(object): """Discrete object represented in a 3D regular grid. Attributes ---------- beta : ndarray Absorption index. delta : ndarray Refractive index decrement. voxelsize : scalar [cm] Size of the voxels in the grid. """ def __init__(self, beta, delta, voxelsize): self.beta = beta self.delta = delta self.voxelsize = voxelsize @property def shape(self): return self.beta.shape @property def complexform(self): return self.delta + 1j * self.beta class Detector(object): """A planar area detector. Attributes ---------- numx : int Number of horizontal pixels. numy : int Number of vertical pixels. """ def __init__(self, x, y): self.x = x self.y = y def uniform(size): return np.ones((size, size), dtype='float32') def gaussian(size, rin=0.8, rout=1): r, c = np.mgrid[:size, :size] + 0.5 rs = np.sqrt((r - size/2)**2 + (c - size/2)**2) rmax = np.sqrt(2) * 0.5 * rout * rs.max() + 1.0 rmin = np.sqrt(2) * 0.5 * rin * rs.max() img = np.zeros((size, size), dtype='float32') img[rs < rmin] = 1.0 img[rs > rmax] = 0.0 zone = np.logical_and(rs > rmin, rs < rmax) img[zone] = np.divide(rmax - rs[zone], rmax - rmin) return img class Probe(object): """Illumination probe represented on a 2D regular grid. A finite-extent circular shaped probe is represented as a complex wave. The intensity of the probe is maximum at the center and damps to zero at the borders of the frame. Attributes size : int ---------- Size of the square 2D frame for the probe. rin : float Value between 0 and 1 determining where the dampening of the intensity will start. rout : float Value between 0 and 1 determining where the intensity will reach to zero. maxint : float Maximum intensity of the probe at the center. """ def __init__(self, weights, maxint=1e5): self.weights = weights self.size = weights.shape[0] self.maxint = maxint self.shape = weights.shape @property def amplitude(self): """Amplitude of the probe wave""" return np.sqrt(self.maxint) * self.weights @property def phase(self): """Phase of the probe wave.""" return 0.2 * self.weights @property def intensity(self): """Intensity of the probe wave.""" return np.power(prb.amplitude, 2) @property def complex(self): return self.amplitude * np.exp(1j * self.phase) class Scanner(object): def __init__(self, shape, sx, sy, margin=[0, 0], offset=[0, 0]): self.shape = shape self.sx = sx self.sy = sy self.margin = margin self.offset = offset @property def x(self): return np.arange(self.offset[0], self.shape[0]-self.margin[0]+1, self.sx) @property def y(self): return np.arange(self.offset[1], self.shape[1]-self.margin[1]+1, self.sy) def scanner3(theta, shape, sx, sy, margin=[0, 0], offset=[0, 0], spiral=0): a = spiral scan = [] for m in range(len(theta)): s = Scanner(shape, sx, sy, margin, offset=[ offset[0], np.mod(offset[1]+a, sy)]) scan.append(s) a += spiral return scan def _pad(phi, det): """Pads phi according to detector size.""" npadx = (det.x - phi.shape[1]) // 2 npady = (det.y - phi.shape[1]) // 2 return np.pad(phi, ((0, 0), (npadx, npadx), (npady, npady)), mode='constant') def project(obj, ang, energy): pb = tomopy.project(obj.beta, ang, pad=False) * obj.voxelsize pd = tomopy.project(obj.delta, ang, pad=False) * obj.voxelsize psi = np.exp(1j * wavenumber(energy) * (pd + 1j * pb)) return psi def exitwave(prb, psi, scan): return np.array([prb.complex * psi[i:i + prb.size, j:j + prb.size] for i in scan.x for j in scan.y], dtype='complex') def propagate2(phi, det): phi = _pad(phi, det) intensity = np.abs(np.fft.fft2(phi)) ** 2 return intensity.astype('float32') def propagate3(prb, psi, scan, theta, det, noise=False): data = [] for m in range(theta.size): phi = exitwave(prb, np.squeeze(psi[m]), scan[m]) dat = propagate2(phi, det) if noise == True: dat = np.random.poisson(dat).astype('float32') data.append(dat) return data def invptycho2(data, prb, scan, init, niter, rho, gamma, hobj, lamd, folder, debug): npadx = (data.shape[1] - prb.size) // 2 npady = (data.shape[2] - prb.size) // 2 psi = init.copy() convpsi = np.zeros(niter, dtype='float32') for i in range(niter): upd = np.zeros(psi.shape, dtype='complex') _psi = np.zeros(psi.shape, dtype='complex') a = 0 for m in range(len(scan.x)): for n in range(len(scan.y)): # Near-plane. phi = np.multiply( prb.complex, psi[scan.x[m]:scan.x[m] + prb.size, scan.y[n]:scan.y[n] + prb.size]) # Go far-plane & Replace the amplitude with the measured amplitude. phi = np.pad( phi, ((npadx, npadx), (npady, npady)), mode='constant') tmp = np.fft.fft2(phi) tmp = np.multiply(np.sqrt(data[a]), np.exp(1j * np.angle(tmp))) # Back to near-plane. iphi = np.fft.ifft2(tmp) # Object update. delphi = (iphi - phi)[npadx:npadx + prb.size, npady:npady+prb.size] num = np.multiply(np.conj(prb.complex), delphi) denum = np.power(np.abs(prb.complex), 2).max() _upd = np.true_divide(num, denum) upd[scan.x[m]:scan.x[m]+prb.size, scan.y[n]:scan.y[n]+prb.size] += _upd a += 1 # psi += upd.copy() # _psi = psi + (gamma / 2) * upd.copy() _psi = (1 - rho*gamma) * psi + rho*gamma * \ (hobj - lamd/rho) + (gamma / 2) * upd.copy() convpsi[i] = np.linalg.norm(psi - _psi, ord='fro') psi = _psi.copy() return psi, convpsi def invptycho3(data, prb, scan, init, theta, niter, rho, gamma, hobj, lamd, folder, debug): psi = np.zeros((init.shape), dtype='complex') convallpsi = np.zeros((theta.size, niter), dtype='float32') for m in range(theta.size): psi[m], convpsi = invptycho2( data[m], prb, scan[m], init[m], niter, rho, gamma, hobj[m], lamd[m], folder, debug) convallpsi[m] = convpsi return psi, convallpsi def invtomo3(data, theta, voxelsize, energy, niter, init, eta): _data = 1 / wavenumber(energy) * np.log(data) / voxelsize pb = tomopy.recon(-np.real(_data), theta, algorithm='grad', num_iter=niter, init_recon=init.beta.copy(), reg_par=eta) pd = tomopy.recon(np.imag(_data), theta, algorithm='grad', num_iter=niter, init_recon=init.delta.copy(), reg_par=eta) obj = Object(pb, pd, 1e-6) return obj folder = 'tmp/lego-joint-noise-1' print(folder) # Parameters. rho = 0.5 gamma = 0.25 eta = 0.25 NITER = 256 piter = 1 titer = 1 maxint = 10 noise = False debug = False # Load a 3D object. beta = dxchange.read_tiff( 'data/test-beta-128.tiff').astype('float32')[::2, ::2, ::2] delta = dxchange.read_tiff( 'data/test-delta-128.tiff').astype('float32')[::2, ::2, ::2] # # Load a 3D object. # beta = dxchange.read_tiff('data/lego-imag.tiff')[::2, ::2, ::2] # delta = dxchange.read_tiff('data/lego-real.tiff')[::2, ::2, ::2] # Create object. obj = Object(beta, delta, 1e-6) dxchange.write_tiff(obj.beta, folder + '/beta') dxchange.write_tiff(obj.delta, folder + '/delta') # Create probe. weights = gaussian(15, rin=0.8, rout=1.0) prb = Probe(weights, maxint=maxint) dxchange.write_tiff(prb.amplitude, folder + '/probe-amplitude') dxchange.write_tiff(prb.phase, folder + '/probe-phase') # Detector parameters. det = Detector(63, 63) # Define rotation angles. theta = np.linspace(0, 2*np.pi, 180) # Raster scan parameters for each rotation angle. scan = scanner3(theta, beta.shape, 12, 12, margin=[ prb.size, prb.size], offset=[0, 0], spiral=1) # Project. psis = project(obj, theta, energy=5) dxchange.write_tiff(np.real(psis), folder + '/psi-amplitude') dxchange.write_tiff(np.imag(psis), folder + '/psi-phase') # Propagate. data0 = propagate3(prb, psis, scan, theta, det, noise=False) data = propagate3(prb, psis, scan, theta, det, noise=noise) print(np.amax(data[3])) print(np.amax(data[3]-data0[3])) dxchange.write_tiff(np.fft.fftshift( np.log(np.array(data[0]))), folder + '/data') # Init. hobj = np.ones(psis.shape, dtype='complex') psi = np.ones(psis.shape, dtype='complex') lamd = np.zeros(psi.shape, dtype='complex') tmp = np.zeros(obj.shape) recobj = Object(tmp, tmp, 1e-6) cp = np.zeros((NITER,)) cl = np.zeros((NITER,)) co = np.zeros((NITER,)) for m in range(NITER): # Ptychography. psi, conv = invptycho3(data, prb, scan, psi, theta, niter=piter, rho=rho, gamma=gamma, hobj=hobj, lamd=lamd, folder=folder, debug=debug) dxchange.write_tiff(np.real(psi[0]).astype( 'float32'), folder + '/psi-amplitude/psi-amplitude') dxchange.write_tiff(np.imag(psi[0]).astype( 'float32'), folder + '/psi-phase/psi-phase') dxchange.write_tiff(np.abs( (psi + lamd/rho)[0]).astype('float32'), folder + '/psilamd-amplitude/psilamd-amplitude') dxchange.write_tiff(np.angle( (psi + lamd/rho)[0]).astype('float32'), folder + '/psilamd-phase/psilamd-phase') cp[m] = np.sqrt(np.sum(np.power(np.abs(hobj-psi), 2))) # Tomography. _recobj = invtomo3(psi + lamd/rho, theta, obj.voxelsize, energy=5, niter=titer, init=recobj, eta=eta) co[m] = np.sqrt( np.sum(np.power(np.abs(recobj.complexform - _recobj.complexform), 2))) recobj = _recobj dxchange.write_tiff( recobj.beta[:, beta.shape[0] // 2], folder + '/beta/beta') dxchange.write_tiff( recobj.delta[:, delta.shape[0] // 2], folder + '/delta/delta') dxchange.write_tiff(recobj.beta, folder + '/beta-full/beta') dxchange.write_tiff(recobj.delta, folder + '/delta-full/delta') # Lambda update. hobj = project(recobj, theta, energy=5) dxchange.write_tiff(np.real(hobj[0]).astype( 'float32'), folder + '/hobj-amplitude/hobj-amplitude') dxchange.write_tiff(np.imag(hobj[0]).astype( 'float32'), folder + '/hobj-phase/hobj-phase') _lamd = lamd + 1 * rho * (psi - hobj) cl[m] = np.sqrt(np.sum(np.power(np.abs(lamd-_lamd), 2))) lamd = _lamd.copy() dxchange.write_tiff(np.abs(lamd[0]).astype( 'float32'), folder + '/lamd-amplitude/lamd-amplitude') dxchange.write_tiff(np.angle(lamd[0]).astype( 'float32'), folder + '/lamd-phase/lamd-phase') print(m, cp[m], co[m], cl[m]) if np.isnan(cp[m]) or np.isnan(co[m]) or np.isnan(cl[m]): break np.save(folder + '/admm-conv-cp.npy', cp) np.save(folder + '/admm-conv-co.npy', co) np.save(folder + '/admm-conv-cl.npy', cl)
import dxchange import tomopy import xraylib as xl import numpy as np
random_line_split
ptycho-fig5.py
# !/usr/bin/env python # -*- coding: utf-8 -*- """Module for 3D ptychography.""" import dxchange import tomopy import xraylib as xl import numpy as np import scipy as sp import pyfftw import shutil import warnings warnings.filterwarnings("ignore") PLANCK_CONSTANT = 6.58211928e-19 # [keV*s] SPEED_OF_LIGHT = 299792458e+2 # [cm/s] def wavelength(energy): """Calculates the wavelength [cm] given energy [keV]. Parameters ---------- energy : scalar Returns ------- scalar """ return 2 * np.pi * PLANCK_CONSTANT * SPEED_OF_LIGHT / energy def wavenumber(energy): """Calculates the wavenumber [1/cm] given energy [keV]. Parameters ---------- energy : scalar Returns ------- scalar """ return 2 * np.pi / wavelength(energy) class Material(object): """Material property definitions. Attributes ---------- compound : string Molecular formula of the material. density : scalar Density of the compound [g/cm^3]. energy : scalar Illumination energy [keV]. """ def __init__(self, compound, density, energy): self.compound = compound self.density = density self.energy = energy @property def beta(self): """Absorption coefficient.""" return xl.Refractive_Index_Im(self.compound, self.energy, self.density) @property def delta(self): """Decrement of refractive index.""" return 1 - xl.Refractive_Index_Re(self.compound, self.energy, self.density) class Object(object): """Discrete object represented in a 3D regular grid. Attributes ---------- beta : ndarray Absorption index. delta : ndarray Refractive index decrement. voxelsize : scalar [cm] Size of the voxels in the grid. """ def __init__(self, beta, delta, voxelsize): self.beta = beta self.delta = delta self.voxelsize = voxelsize @property def shape(self): return self.beta.shape @property def complexform(self): return self.delta + 1j * self.beta class Detector(object): """A planar area detector. Attributes ---------- numx : int Number of horizontal pixels. numy : int Number of vertical pixels. """ def __init__(self, x, y): self.x = x self.y = y def uniform(size): return np.ones((size, size), dtype='float32') def gaussian(size, rin=0.8, rout=1): r, c = np.mgrid[:size, :size] + 0.5 rs = np.sqrt((r - size/2)**2 + (c - size/2)**2) rmax = np.sqrt(2) * 0.5 * rout * rs.max() + 1.0 rmin = np.sqrt(2) * 0.5 * rin * rs.max() img = np.zeros((size, size), dtype='float32') img[rs < rmin] = 1.0 img[rs > rmax] = 0.0 zone = np.logical_and(rs > rmin, rs < rmax) img[zone] = np.divide(rmax - rs[zone], rmax - rmin) return img class Probe(object): """Illumination probe represented on a 2D regular grid. A finite-extent circular shaped probe is represented as a complex wave. The intensity of the probe is maximum at the center and damps to zero at the borders of the frame. Attributes size : int ---------- Size of the square 2D frame for the probe. rin : float Value between 0 and 1 determining where the dampening of the intensity will start. rout : float Value between 0 and 1 determining where the intensity will reach to zero. maxint : float Maximum intensity of the probe at the center. """ def __init__(self, weights, maxint=1e5): self.weights = weights self.size = weights.shape[0] self.maxint = maxint self.shape = weights.shape @property def amplitude(self): """Amplitude of the probe wave""" return np.sqrt(self.maxint) * self.weights @property def phase(self): """Phase of the probe wave.""" return 0.2 * self.weights @property def intensity(self): """Intensity of the probe wave.""" return np.power(prb.amplitude, 2) @property def complex(self): return self.amplitude * np.exp(1j * self.phase) class Scanner(object): def __init__(self, shape, sx, sy, margin=[0, 0], offset=[0, 0]): self.shape = shape self.sx = sx self.sy = sy self.margin = margin self.offset = offset @property def x(self): return np.arange(self.offset[0], self.shape[0]-self.margin[0]+1, self.sx) @property def y(self): return np.arange(self.offset[1], self.shape[1]-self.margin[1]+1, self.sy) def scanner3(theta, shape, sx, sy, margin=[0, 0], offset=[0, 0], spiral=0): a = spiral scan = [] for m in range(len(theta)): s = Scanner(shape, sx, sy, margin, offset=[ offset[0], np.mod(offset[1]+a, sy)]) scan.append(s) a += spiral return scan def _pad(phi, det): """Pads phi according to detector size.""" npadx = (det.x - phi.shape[1]) // 2 npady = (det.y - phi.shape[1]) // 2 return np.pad(phi, ((0, 0), (npadx, npadx), (npady, npady)), mode='constant') def project(obj, ang, energy): pb = tomopy.project(obj.beta, ang, pad=False) * obj.voxelsize pd = tomopy.project(obj.delta, ang, pad=False) * obj.voxelsize psi = np.exp(1j * wavenumber(energy) * (pd + 1j * pb)) return psi def exitwave(prb, psi, scan): return np.array([prb.complex * psi[i:i + prb.size, j:j + prb.size] for i in scan.x for j in scan.y], dtype='complex') def propagate2(phi, det): phi = _pad(phi, det) intensity = np.abs(np.fft.fft2(phi)) ** 2 return intensity.astype('float32') def propagate3(prb, psi, scan, theta, det, noise=False): data = [] for m in range(theta.size): phi = exitwave(prb, np.squeeze(psi[m]), scan[m]) dat = propagate2(phi, det) if noise == True: dat = np.random.poisson(dat).astype('float32') data.append(dat) return data def invptycho2(data, prb, scan, init, niter, rho, gamma, hobj, lamd, folder, debug): npadx = (data.shape[1] - prb.size) // 2 npady = (data.shape[2] - prb.size) // 2 psi = init.copy() convpsi = np.zeros(niter, dtype='float32') for i in range(niter): upd = np.zeros(psi.shape, dtype='complex') _psi = np.zeros(psi.shape, dtype='complex') a = 0 for m in range(len(scan.x)):
# psi += upd.copy() # _psi = psi + (gamma / 2) * upd.copy() _psi = (1 - rho*gamma) * psi + rho*gamma * \ (hobj - lamd/rho) + (gamma / 2) * upd.copy() convpsi[i] = np.linalg.norm(psi - _psi, ord='fro') psi = _psi.copy() return psi, convpsi def invptycho3(data, prb, scan, init, theta, niter, rho, gamma, hobj, lamd, folder, debug): psi = np.zeros((init.shape), dtype='complex') convallpsi = np.zeros((theta.size, niter), dtype='float32') for m in range(theta.size): psi[m], convpsi = invptycho2( data[m], prb, scan[m], init[m], niter, rho, gamma, hobj[m], lamd[m], folder, debug) convallpsi[m] = convpsi return psi, convallpsi def invtomo3(data, theta, voxelsize, energy, niter, init, eta): _data = 1 / wavenumber(energy) * np.log(data) / voxelsize pb = tomopy.recon(-np.real(_data), theta, algorithm='grad', num_iter=niter, init_recon=init.beta.copy(), reg_par=eta) pd = tomopy.recon(np.imag(_data), theta, algorithm='grad', num_iter=niter, init_recon=init.delta.copy(), reg_par=eta) obj = Object(pb, pd, 1e-6) return obj folder = 'tmp/lego-joint-noise-1' print(folder) # Parameters. rho = 0.5 gamma = 0.25 eta = 0.25 NITER = 256 piter = 1 titer = 1 maxint = 10 noise = False debug = False # Load a 3D object. beta = dxchange.read_tiff( 'data/test-beta-128.tiff').astype('float32')[::2, ::2, ::2] delta = dxchange.read_tiff( 'data/test-delta-128.tiff').astype('float32')[::2, ::2, ::2] # # Load a 3D object. # beta = dxchange.read_tiff('data/lego-imag.tiff')[::2, ::2, ::2] # delta = dxchange.read_tiff('data/lego-real.tiff')[::2, ::2, ::2] # Create object. obj = Object(beta, delta, 1e-6) dxchange.write_tiff(obj.beta, folder + '/beta') dxchange.write_tiff(obj.delta, folder + '/delta') # Create probe. weights = gaussian(15, rin=0.8, rout=1.0) prb = Probe(weights, maxint=maxint) dxchange.write_tiff(prb.amplitude, folder + '/probe-amplitude') dxchange.write_tiff(prb.phase, folder + '/probe-phase') # Detector parameters. det = Detector(63, 63) # Define rotation angles. theta = np.linspace(0, 2*np.pi, 180) # Raster scan parameters for each rotation angle. scan = scanner3(theta, beta.shape, 12, 12, margin=[ prb.size, prb.size], offset=[0, 0], spiral=1) # Project. psis = project(obj, theta, energy=5) dxchange.write_tiff(np.real(psis), folder + '/psi-amplitude') dxchange.write_tiff(np.imag(psis), folder + '/psi-phase') # Propagate. data0 = propagate3(prb, psis, scan, theta, det, noise=False) data = propagate3(prb, psis, scan, theta, det, noise=noise) print(np.amax(data[3])) print(np.amax(data[3]-data0[3])) dxchange.write_tiff(np.fft.fftshift( np.log(np.array(data[0]))), folder + '/data') # Init. hobj = np.ones(psis.shape, dtype='complex') psi = np.ones(psis.shape, dtype='complex') lamd = np.zeros(psi.shape, dtype='complex') tmp = np.zeros(obj.shape) recobj = Object(tmp, tmp, 1e-6) cp = np.zeros((NITER,)) cl = np.zeros((NITER,)) co = np.zeros((NITER,)) for m in range(NITER): # Ptychography. psi, conv = invptycho3(data, prb, scan, psi, theta, niter=piter, rho=rho, gamma=gamma, hobj=hobj, lamd=lamd, folder=folder, debug=debug) dxchange.write_tiff(np.real(psi[0]).astype( 'float32'), folder + '/psi-amplitude/psi-amplitude') dxchange.write_tiff(np.imag(psi[0]).astype( 'float32'), folder + '/psi-phase/psi-phase') dxchange.write_tiff(np.abs( (psi + lamd/rho)[0]).astype('float32'), folder + '/psilamd-amplitude/psilamd-amplitude') dxchange.write_tiff(np.angle( (psi + lamd/rho)[0]).astype('float32'), folder + '/psilamd-phase/psilamd-phase') cp[m] = np.sqrt(np.sum(np.power(np.abs(hobj-psi), 2))) # Tomography. _recobj = invtomo3(psi + lamd/rho, theta, obj.voxelsize, energy=5, niter=titer, init=recobj, eta=eta) co[m] = np.sqrt( np.sum(np.power(np.abs(recobj.complexform - _recobj.complexform), 2))) recobj = _recobj dxchange.write_tiff( recobj.beta[:, beta.shape[0] // 2], folder + '/beta/beta') dxchange.write_tiff( recobj.delta[:, delta.shape[0] // 2], folder + '/delta/delta') dxchange.write_tiff(recobj.beta, folder + '/beta-full/beta') dxchange.write_tiff(recobj.delta, folder + '/delta-full/delta') # Lambda update. hobj = project(recobj, theta, energy=5) dxchange.write_tiff(np.real(hobj[0]).astype( 'float32'), folder + '/hobj-amplitude/hobj-amplitude') dxchange.write_tiff(np.imag(hobj[0]).astype( 'float32'), folder + '/hobj-phase/hobj-phase') _lamd = lamd + 1 * rho * (psi - hobj) cl[m] = np.sqrt(np.sum(np.power(np.abs(lamd-_lamd), 2))) lamd = _lamd.copy() dxchange.write_tiff(np.abs(lamd[0]).astype( 'float32'), folder + '/lamd-amplitude/lamd-amplitude') dxchange.write_tiff(np.angle(lamd[0]).astype( 'float32'), folder + '/lamd-phase/lamd-phase') print(m, cp[m], co[m], cl[m]) if np.isnan(cp[m]) or np.isnan(co[m]) or np.isnan(cl[m]): break np.save(folder + '/admm-conv-cp.npy', cp) np.save(folder + '/admm-conv-co.npy', co) np.save(folder + '/admm-conv-cl.npy', cl)
for n in range(len(scan.y)): # Near-plane. phi = np.multiply( prb.complex, psi[scan.x[m]:scan.x[m] + prb.size, scan.y[n]:scan.y[n] + prb.size]) # Go far-plane & Replace the amplitude with the measured amplitude. phi = np.pad( phi, ((npadx, npadx), (npady, npady)), mode='constant') tmp = np.fft.fft2(phi) tmp = np.multiply(np.sqrt(data[a]), np.exp(1j * np.angle(tmp))) # Back to near-plane. iphi = np.fft.ifft2(tmp) # Object update. delphi = (iphi - phi)[npadx:npadx + prb.size, npady:npady+prb.size] num = np.multiply(np.conj(prb.complex), delphi) denum = np.power(np.abs(prb.complex), 2).max() _upd = np.true_divide(num, denum) upd[scan.x[m]:scan.x[m]+prb.size, scan.y[n]:scan.y[n]+prb.size] += _upd a += 1
conditional_block
ptycho-fig5.py
# !/usr/bin/env python # -*- coding: utf-8 -*- """Module for 3D ptychography.""" import dxchange import tomopy import xraylib as xl import numpy as np import scipy as sp import pyfftw import shutil import warnings warnings.filterwarnings("ignore") PLANCK_CONSTANT = 6.58211928e-19 # [keV*s] SPEED_OF_LIGHT = 299792458e+2 # [cm/s] def wavelength(energy): """Calculates the wavelength [cm] given energy [keV]. Parameters ---------- energy : scalar Returns ------- scalar """ return 2 * np.pi * PLANCK_CONSTANT * SPEED_OF_LIGHT / energy def wavenumber(energy): """Calculates the wavenumber [1/cm] given energy [keV]. Parameters ---------- energy : scalar Returns ------- scalar """ return 2 * np.pi / wavelength(energy) class Material(object): """Material property definitions. Attributes ---------- compound : string Molecular formula of the material. density : scalar Density of the compound [g/cm^3]. energy : scalar Illumination energy [keV]. """ def __init__(self, compound, density, energy): self.compound = compound self.density = density self.energy = energy @property def beta(self): """Absorption coefficient.""" return xl.Refractive_Index_Im(self.compound, self.energy, self.density) @property def delta(self): """Decrement of refractive index.""" return 1 - xl.Refractive_Index_Re(self.compound, self.energy, self.density) class Object(object): """Discrete object represented in a 3D regular grid. Attributes ---------- beta : ndarray Absorption index. delta : ndarray Refractive index decrement. voxelsize : scalar [cm] Size of the voxels in the grid. """ def __init__(self, beta, delta, voxelsize): self.beta = beta self.delta = delta self.voxelsize = voxelsize @property def shape(self): return self.beta.shape @property def complexform(self): return self.delta + 1j * self.beta class Detector(object): """A planar area detector. Attributes ---------- numx : int Number of horizontal pixels. numy : int Number of vertical pixels. """ def __init__(self, x, y): self.x = x self.y = y def uniform(size): return np.ones((size, size), dtype='float32') def gaussian(size, rin=0.8, rout=1): r, c = np.mgrid[:size, :size] + 0.5 rs = np.sqrt((r - size/2)**2 + (c - size/2)**2) rmax = np.sqrt(2) * 0.5 * rout * rs.max() + 1.0 rmin = np.sqrt(2) * 0.5 * rin * rs.max() img = np.zeros((size, size), dtype='float32') img[rs < rmin] = 1.0 img[rs > rmax] = 0.0 zone = np.logical_and(rs > rmin, rs < rmax) img[zone] = np.divide(rmax - rs[zone], rmax - rmin) return img class Probe(object): """Illumination probe represented on a 2D regular grid. A finite-extent circular shaped probe is represented as a complex wave. The intensity of the probe is maximum at the center and damps to zero at the borders of the frame. Attributes size : int ---------- Size of the square 2D frame for the probe. rin : float Value between 0 and 1 determining where the dampening of the intensity will start. rout : float Value between 0 and 1 determining where the intensity will reach to zero. maxint : float Maximum intensity of the probe at the center. """ def __init__(self, weights, maxint=1e5): self.weights = weights self.size = weights.shape[0] self.maxint = maxint self.shape = weights.shape @property def amplitude(self): """Amplitude of the probe wave""" return np.sqrt(self.maxint) * self.weights @property def phase(self): """Phase of the probe wave.""" return 0.2 * self.weights @property def intensity(self): """Intensity of the probe wave.""" return np.power(prb.amplitude, 2) @property def complex(self): return self.amplitude * np.exp(1j * self.phase) class Scanner(object): def __init__(self, shape, sx, sy, margin=[0, 0], offset=[0, 0]):
@property def x(self): return np.arange(self.offset[0], self.shape[0]-self.margin[0]+1, self.sx) @property def y(self): return np.arange(self.offset[1], self.shape[1]-self.margin[1]+1, self.sy) def scanner3(theta, shape, sx, sy, margin=[0, 0], offset=[0, 0], spiral=0): a = spiral scan = [] for m in range(len(theta)): s = Scanner(shape, sx, sy, margin, offset=[ offset[0], np.mod(offset[1]+a, sy)]) scan.append(s) a += spiral return scan def _pad(phi, det): """Pads phi according to detector size.""" npadx = (det.x - phi.shape[1]) // 2 npady = (det.y - phi.shape[1]) // 2 return np.pad(phi, ((0, 0), (npadx, npadx), (npady, npady)), mode='constant') def project(obj, ang, energy): pb = tomopy.project(obj.beta, ang, pad=False) * obj.voxelsize pd = tomopy.project(obj.delta, ang, pad=False) * obj.voxelsize psi = np.exp(1j * wavenumber(energy) * (pd + 1j * pb)) return psi def exitwave(prb, psi, scan): return np.array([prb.complex * psi[i:i + prb.size, j:j + prb.size] for i in scan.x for j in scan.y], dtype='complex') def propagate2(phi, det): phi = _pad(phi, det) intensity = np.abs(np.fft.fft2(phi)) ** 2 return intensity.astype('float32') def propagate3(prb, psi, scan, theta, det, noise=False): data = [] for m in range(theta.size): phi = exitwave(prb, np.squeeze(psi[m]), scan[m]) dat = propagate2(phi, det) if noise == True: dat = np.random.poisson(dat).astype('float32') data.append(dat) return data def invptycho2(data, prb, scan, init, niter, rho, gamma, hobj, lamd, folder, debug): npadx = (data.shape[1] - prb.size) // 2 npady = (data.shape[2] - prb.size) // 2 psi = init.copy() convpsi = np.zeros(niter, dtype='float32') for i in range(niter): upd = np.zeros(psi.shape, dtype='complex') _psi = np.zeros(psi.shape, dtype='complex') a = 0 for m in range(len(scan.x)): for n in range(len(scan.y)): # Near-plane. phi = np.multiply( prb.complex, psi[scan.x[m]:scan.x[m] + prb.size, scan.y[n]:scan.y[n] + prb.size]) # Go far-plane & Replace the amplitude with the measured amplitude. phi = np.pad( phi, ((npadx, npadx), (npady, npady)), mode='constant') tmp = np.fft.fft2(phi) tmp = np.multiply(np.sqrt(data[a]), np.exp(1j * np.angle(tmp))) # Back to near-plane. iphi = np.fft.ifft2(tmp) # Object update. delphi = (iphi - phi)[npadx:npadx + prb.size, npady:npady+prb.size] num = np.multiply(np.conj(prb.complex), delphi) denum = np.power(np.abs(prb.complex), 2).max() _upd = np.true_divide(num, denum) upd[scan.x[m]:scan.x[m]+prb.size, scan.y[n]:scan.y[n]+prb.size] += _upd a += 1 # psi += upd.copy() # _psi = psi + (gamma / 2) * upd.copy() _psi = (1 - rho*gamma) * psi + rho*gamma * \ (hobj - lamd/rho) + (gamma / 2) * upd.copy() convpsi[i] = np.linalg.norm(psi - _psi, ord='fro') psi = _psi.copy() return psi, convpsi def invptycho3(data, prb, scan, init, theta, niter, rho, gamma, hobj, lamd, folder, debug): psi = np.zeros((init.shape), dtype='complex') convallpsi = np.zeros((theta.size, niter), dtype='float32') for m in range(theta.size): psi[m], convpsi = invptycho2( data[m], prb, scan[m], init[m], niter, rho, gamma, hobj[m], lamd[m], folder, debug) convallpsi[m] = convpsi return psi, convallpsi def invtomo3(data, theta, voxelsize, energy, niter, init, eta): _data = 1 / wavenumber(energy) * np.log(data) / voxelsize pb = tomopy.recon(-np.real(_data), theta, algorithm='grad', num_iter=niter, init_recon=init.beta.copy(), reg_par=eta) pd = tomopy.recon(np.imag(_data), theta, algorithm='grad', num_iter=niter, init_recon=init.delta.copy(), reg_par=eta) obj = Object(pb, pd, 1e-6) return obj folder = 'tmp/lego-joint-noise-1' print(folder) # Parameters. rho = 0.5 gamma = 0.25 eta = 0.25 NITER = 256 piter = 1 titer = 1 maxint = 10 noise = False debug = False # Load a 3D object. beta = dxchange.read_tiff( 'data/test-beta-128.tiff').astype('float32')[::2, ::2, ::2] delta = dxchange.read_tiff( 'data/test-delta-128.tiff').astype('float32')[::2, ::2, ::2] # # Load a 3D object. # beta = dxchange.read_tiff('data/lego-imag.tiff')[::2, ::2, ::2] # delta = dxchange.read_tiff('data/lego-real.tiff')[::2, ::2, ::2] # Create object. obj = Object(beta, delta, 1e-6) dxchange.write_tiff(obj.beta, folder + '/beta') dxchange.write_tiff(obj.delta, folder + '/delta') # Create probe. weights = gaussian(15, rin=0.8, rout=1.0) prb = Probe(weights, maxint=maxint) dxchange.write_tiff(prb.amplitude, folder + '/probe-amplitude') dxchange.write_tiff(prb.phase, folder + '/probe-phase') # Detector parameters. det = Detector(63, 63) # Define rotation angles. theta = np.linspace(0, 2*np.pi, 180) # Raster scan parameters for each rotation angle. scan = scanner3(theta, beta.shape, 12, 12, margin=[ prb.size, prb.size], offset=[0, 0], spiral=1) # Project. psis = project(obj, theta, energy=5) dxchange.write_tiff(np.real(psis), folder + '/psi-amplitude') dxchange.write_tiff(np.imag(psis), folder + '/psi-phase') # Propagate. data0 = propagate3(prb, psis, scan, theta, det, noise=False) data = propagate3(prb, psis, scan, theta, det, noise=noise) print(np.amax(data[3])) print(np.amax(data[3]-data0[3])) dxchange.write_tiff(np.fft.fftshift( np.log(np.array(data[0]))), folder + '/data') # Init. hobj = np.ones(psis.shape, dtype='complex') psi = np.ones(psis.shape, dtype='complex') lamd = np.zeros(psi.shape, dtype='complex') tmp = np.zeros(obj.shape) recobj = Object(tmp, tmp, 1e-6) cp = np.zeros((NITER,)) cl = np.zeros((NITER,)) co = np.zeros((NITER,)) for m in range(NITER): # Ptychography. psi, conv = invptycho3(data, prb, scan, psi, theta, niter=piter, rho=rho, gamma=gamma, hobj=hobj, lamd=lamd, folder=folder, debug=debug) dxchange.write_tiff(np.real(psi[0]).astype( 'float32'), folder + '/psi-amplitude/psi-amplitude') dxchange.write_tiff(np.imag(psi[0]).astype( 'float32'), folder + '/psi-phase/psi-phase') dxchange.write_tiff(np.abs( (psi + lamd/rho)[0]).astype('float32'), folder + '/psilamd-amplitude/psilamd-amplitude') dxchange.write_tiff(np.angle( (psi + lamd/rho)[0]).astype('float32'), folder + '/psilamd-phase/psilamd-phase') cp[m] = np.sqrt(np.sum(np.power(np.abs(hobj-psi), 2))) # Tomography. _recobj = invtomo3(psi + lamd/rho, theta, obj.voxelsize, energy=5, niter=titer, init=recobj, eta=eta) co[m] = np.sqrt( np.sum(np.power(np.abs(recobj.complexform - _recobj.complexform), 2))) recobj = _recobj dxchange.write_tiff( recobj.beta[:, beta.shape[0] // 2], folder + '/beta/beta') dxchange.write_tiff( recobj.delta[:, delta.shape[0] // 2], folder + '/delta/delta') dxchange.write_tiff(recobj.beta, folder + '/beta-full/beta') dxchange.write_tiff(recobj.delta, folder + '/delta-full/delta') # Lambda update. hobj = project(recobj, theta, energy=5) dxchange.write_tiff(np.real(hobj[0]).astype( 'float32'), folder + '/hobj-amplitude/hobj-amplitude') dxchange.write_tiff(np.imag(hobj[0]).astype( 'float32'), folder + '/hobj-phase/hobj-phase') _lamd = lamd + 1 * rho * (psi - hobj) cl[m] = np.sqrt(np.sum(np.power(np.abs(lamd-_lamd), 2))) lamd = _lamd.copy() dxchange.write_tiff(np.abs(lamd[0]).astype( 'float32'), folder + '/lamd-amplitude/lamd-amplitude') dxchange.write_tiff(np.angle(lamd[0]).astype( 'float32'), folder + '/lamd-phase/lamd-phase') print(m, cp[m], co[m], cl[m]) if np.isnan(cp[m]) or np.isnan(co[m]) or np.isnan(cl[m]): break np.save(folder + '/admm-conv-cp.npy', cp) np.save(folder + '/admm-conv-co.npy', co) np.save(folder + '/admm-conv-cl.npy', cl)
self.shape = shape self.sx = sx self.sy = sy self.margin = margin self.offset = offset
identifier_body
ec2_vol_management.py
import ast import boto3, botocore from datetime import datetime, timedelta import logging import os import re #setup logger logger = logging.getLogger() logger.setLevel(logging.INFO) def create_snapshot(ec2, reg, filters=[], context={}): result = ec2.describe_volumes(Filters=filters) for volume in result['Volumes']: logger.info("Backing up %s in %s" % (volume['VolumeId'], volume['AvailabilityZone'])) # Create snapshot result = ec2.create_snapshot( VolumeId=volume['VolumeId'], Description='Created by Lambda function %s for backup from %s' % (context.function_name, volume['VolumeId']) ) # Get snapshot resource ec2resource = boto3.resource('ec2', region_name=reg) snapshot = ec2resource.Snapshot(result['SnapshotId']) snapshot_tags = [] # Find name tag for volume if it exists if 'Tags' in volume: for tags in volume['Tags']: snapshot_tags.append({'Key': tags["Key"],'Value': tags["Value"]}) # Add volume name to snapshot for easier identification snapshot.create_tags(Tags=snapshot_tags) def cleanup_detach_snapshot(ec2, aws_account_id, dry_run=True): """This will delete all snapshot that is created automatically by the aws related to ami image but the ami is no longer available (by de-registering) """ images = ec2.images.filter(Owners=[aws_account_id]) images = [image.id for image in images] for snapshot in ec2.snapshots.filter(OwnerIds=[aws_account_id]): r = re.match(r".*for (ami-.*) from.*", snapshot.description) if r: if r.groups()[0] not in images: logger.info("Deleting %s" % snapshot.snapshot_id) if not dry_run: snapshot.delete(DryRun=dry_run) else: logger.info(" skipped as dry_run is true") def cleanup_old_snapshots( ec2resource, retention_days=7, filters=[], keep_at_least=1, dry_run=True): delete_time = int(datetime.now().strftime('%s')) - retention_days * 86400 logger.info('Deleting any snapshots older than {days} days'.format(days=retention_days)) snapshot_iterator = ec2resource.snapshots.filter(Filters=filters) get_last_start_time = lambda obj: int(obj.start_time.strftime('%s')) snapshots = sorted([ x for x in snapshot_iterator ], key=get_last_start_time) deletion_counter = 0 size_counter = 0 total_snapshots = len(snapshots) snapshots_to_delete = snapshots[0:-1 * keep_at_least] for snapshot in snapshots_to_delete: start_time = int(snapshot.start_time.strftime('%s')) if start_time < delete_time: deletion_counter = deletion_counter + 1 size_counter = size_counter + snapshot.volume_size logger.info('Deleting {id}'.format(id=snapshot.snapshot_id)) if not dry_run: snapshot.delete() else: logger.info(" skipped as dry_run is true") logger.info('Deleted {number} snapshots totalling {size} GB'.format( number=deletion_counter, size=size_counter )) def deregister_ami(ec2, aws_account_id, filters=[], retention_days=14, dry_run=True): """Deregister ami if: - No (running/stopped) ec2 instances use it - Matching the filters condition - creation time older than retention_days - Retain at least one ami for safety """ instances = ec2.instances.all() images = ec2.images.filter(Owners=[aws_account_id], Filters=filters) images_in_use = set([instance.image_id for instance in instances]) images_to_deregister_dict = { image.id: image for image in images if image.id not in images_in_use } images_to_deregister_list = images_to_deregister_dict.values() images_to_deregister_list = sorted(images_to_deregister_list, key=lambda x: x.creation_date) # Keep the last one images_to_deregister_list = images_to_deregister_list[0:-1] if len(images_to_deregister_list) == 0: return {} all_snapshots = ec2.snapshots.filter(OwnerIds=[aws_account_id]) # deregister all the AMIs older than retention_days today = datetime.now() date_to_keep = today - timedelta(days=retention_days) for image in images_to_deregister_list: created_date = datetime.strptime(image.creation_date, "%Y-%m-%dT%H:%M:%S.000Z") logger.info(created_date) logger.info(image.creation_date) if created_date < date_to_keep: logger.info("Deregistering %s" % image.id) if not dry_run: image.deregister() for snapshot in all_snapshots: #get the ami id (that the snapshot belongs to) from the snapshot's description
else: logger.info(" skipped as dry_run is true") # Takes a list of EC2 instances with tag 'ami-creation': true - IDs and creates AMIs # Copy from one of my work mate into here with small modification def create_amis(ec2, cycle_tag='daily'): ec2_filter = [{'Name':'tag:ami-creation', 'Values':['true']}] instances = list(ec2.instances.filter(Filters=ec2_filter)) logger.info("create AMIs with cycle_tag: '%s'", cycle_tag) #creat image for each instance for instance in instances: for tag in instance.tags: if tag['Key'] == 'Name': instance_name = tag['Value'] logger.info("creating image for ' %s' with name: %s",instance.id, instance_name) try: utc_now = datetime.utcnow() name = '%s-%s %s/%s/%s %s-%s-%sUTC' % (cycle_tag, instance_name, utc_now.day, utc_now.month, utc_now.year, utc_now.hour, utc_now.minute, utc_now.second) #AMIs names cannot contain ',' name = name.replace(',', '_').replace(':', '_') image = instance.create_image( DryRun=False, Name=name, Description='AMI of ' + instance.id + ' created with Lambda function', NoReboot=True ) logger.info('call to create_image succeeded') #create tag(s) image.create_tags( Tags=[ {'Key': 'ami-cycle', 'Value': cycle_tag}, {'Key': 'Name', 'Value': name} ]) except botocore.exceptions.ClientError as err: logger.info('caught exception: Error message: %s', err) def lambda_handler(event, context): regions = os.environ.get('REGIONS', 'ap-southeast-2').split(',') ses = boto3.session.Session() aws_account_id = os.environ.get('AWS_ACCOUNT_ID') retention_days = int(os.environ.get('RETENTION_DAYS', 14)) # If volume is 'in-use' and having tag:Backup = 'yes' then we create snapshot snapshot_create_filter_default = [ { 'Name': 'status', 'Values': ['in-use'] }, { 'Name': 'tag:Backup', 'Values': ['yes'] } ] snapshot_create_filter = ast.literal_eval( os.environ.get('SNAPSHOT_CREATE_FILTER', "None")) snapshot_create_filter = snapshot_create_filter if snapshot_create_filter else snapshot_create_filter_default # Delete these snapshot created by this script only snapshot_delete_filter_default = [ { 'Name': 'tag:Name', 'Values': ['*'] }, { 'Name': 'tag:Backup', 'Values': ['yes'] } ] snapshot_delete_filter = ast.literal_eval( os.environ.get('SNAPSHOT_DELETE_FILTER', "None")) snapshot_delete_filter = snapshot_delete_filter if snapshot_delete_filter else snapshot_delete_filter_default ami_deregister_filters_default = [ [ { 'Name': 'tag:ami-cycle', 'Values': ['*'] }, { 'Name': 'tag:Application', 'Values': ['ecs-agent'] }, { 'Name': 'tag:Environment', 'Values': ['int'] } ], [ { 'Name': 'tag:Application', 'Values': ['ecs-agent'] }, { 'Name': 'tag:Environment', 'Values': ['qa'] } ], [ { 'Name': 'tag:BuildLayer', 'Values': ['system'] }, { 'Name': 'tag:Version', 'Values': ['ubuntu-1604'] } ], [ { 'Name': 'tag:BuildLayer', 'Values': ['system'] }, { 'Name': 'tag:Version', 'Values': ['ubuntu-1804'] } ], [ { 'Name': 'tag:BuildLayer', 'Values': ['platform'] }, { 'Name': 'tag:Platform', 'Values': ['java'] } ] ] ami_deregister_filters = ast.literal_eval( os.environ.get('AMI_DEREGISTER_FILTER', "None")) ami_deregister_filters = ami_deregister_filters if ami_deregister_filters else ami_deregister_filters_default # Iterate over regions cycle_tag = event.get('cycle_tag', 'daily') for reg in regions: if not reg: continue ec2 = ses.client('ec2', region_name=reg) create_snapshot(ec2, reg, filters=snapshot_create_filter, context=context) ec2resource = ses.resource('ec2', region_name=reg) cleanup_old_snapshots(ec2resource, retention_days=retention_days, filters=snapshot_delete_filter, dry_run=False) cleanup_detach_snapshot(ec2resource, aws_account_id, dry_run=False) create_amis(ec2resource, cycle_tag) for ami_deregister_filter in ami_deregister_filters: deregister_ami(ec2resource, aws_account_id, filters=ami_deregister_filter, dry_run=False) return 'OK'
r = re.match(r".*for (ami-.*) from.*", snapshot.description) if r: #r.groups()[0] will contain the ami id if r.groups()[0] == image.id: logger.info("found snapshot belonging to %s. snapshot with image_id %s will be deleted", image.id, snapshot.snapshot_id) snapshot.delete()
conditional_block
ec2_vol_management.py
import ast import boto3, botocore from datetime import datetime, timedelta import logging import os import re #setup logger logger = logging.getLogger() logger.setLevel(logging.INFO) def create_snapshot(ec2, reg, filters=[], context={}): result = ec2.describe_volumes(Filters=filters) for volume in result['Volumes']: logger.info("Backing up %s in %s" % (volume['VolumeId'], volume['AvailabilityZone'])) # Create snapshot result = ec2.create_snapshot( VolumeId=volume['VolumeId'], Description='Created by Lambda function %s for backup from %s' % (context.function_name, volume['VolumeId']) ) # Get snapshot resource ec2resource = boto3.resource('ec2', region_name=reg) snapshot = ec2resource.Snapshot(result['SnapshotId']) snapshot_tags = [] # Find name tag for volume if it exists if 'Tags' in volume: for tags in volume['Tags']: snapshot_tags.append({'Key': tags["Key"],'Value': tags["Value"]}) # Add volume name to snapshot for easier identification snapshot.create_tags(Tags=snapshot_tags) def cleanup_detach_snapshot(ec2, aws_account_id, dry_run=True): """This will delete all snapshot that is created automatically by the aws related to ami image but the ami is no longer available (by de-registering) """ images = ec2.images.filter(Owners=[aws_account_id]) images = [image.id for image in images] for snapshot in ec2.snapshots.filter(OwnerIds=[aws_account_id]): r = re.match(r".*for (ami-.*) from.*", snapshot.description) if r: if r.groups()[0] not in images: logger.info("Deleting %s" % snapshot.snapshot_id) if not dry_run: snapshot.delete(DryRun=dry_run) else: logger.info(" skipped as dry_run is true") def cleanup_old_snapshots( ec2resource, retention_days=7, filters=[], keep_at_least=1, dry_run=True): delete_time = int(datetime.now().strftime('%s')) - retention_days * 86400 logger.info('Deleting any snapshots older than {days} days'.format(days=retention_days)) snapshot_iterator = ec2resource.snapshots.filter(Filters=filters) get_last_start_time = lambda obj: int(obj.start_time.strftime('%s')) snapshots = sorted([ x for x in snapshot_iterator ], key=get_last_start_time) deletion_counter = 0 size_counter = 0 total_snapshots = len(snapshots) snapshots_to_delete = snapshots[0:-1 * keep_at_least] for snapshot in snapshots_to_delete: start_time = int(snapshot.start_time.strftime('%s')) if start_time < delete_time: deletion_counter = deletion_counter + 1 size_counter = size_counter + snapshot.volume_size logger.info('Deleting {id}'.format(id=snapshot.snapshot_id)) if not dry_run: snapshot.delete() else: logger.info(" skipped as dry_run is true") logger.info('Deleted {number} snapshots totalling {size} GB'.format( number=deletion_counter, size=size_counter )) def deregister_ami(ec2, aws_account_id, filters=[], retention_days=14, dry_run=True): """Deregister ami if: - No (running/stopped) ec2 instances use it - Matching the filters condition - creation time older than retention_days - Retain at least one ami for safety """ instances = ec2.instances.all() images = ec2.images.filter(Owners=[aws_account_id], Filters=filters) images_in_use = set([instance.image_id for instance in instances]) images_to_deregister_dict = { image.id: image for image in images if image.id not in images_in_use } images_to_deregister_list = images_to_deregister_dict.values() images_to_deregister_list = sorted(images_to_deregister_list, key=lambda x: x.creation_date) # Keep the last one images_to_deregister_list = images_to_deregister_list[0:-1] if len(images_to_deregister_list) == 0: return {} all_snapshots = ec2.snapshots.filter(OwnerIds=[aws_account_id]) # deregister all the AMIs older than retention_days today = datetime.now() date_to_keep = today - timedelta(days=retention_days) for image in images_to_deregister_list: created_date = datetime.strptime(image.creation_date, "%Y-%m-%dT%H:%M:%S.000Z") logger.info(created_date) logger.info(image.creation_date) if created_date < date_to_keep: logger.info("Deregistering %s" % image.id) if not dry_run: image.deregister() for snapshot in all_snapshots: #get the ami id (that the snapshot belongs to) from the snapshot's description r = re.match(r".*for (ami-.*) from.*", snapshot.description) if r: #r.groups()[0] will contain the ami id if r.groups()[0] == image.id: logger.info("found snapshot belonging to %s. snapshot with image_id %s will be deleted", image.id, snapshot.snapshot_id) snapshot.delete() else: logger.info(" skipped as dry_run is true") # Takes a list of EC2 instances with tag 'ami-creation': true - IDs and creates AMIs # Copy from one of my work mate into here with small modification def create_amis(ec2, cycle_tag='daily'): ec2_filter = [{'Name':'tag:ami-creation', 'Values':['true']}] instances = list(ec2.instances.filter(Filters=ec2_filter)) logger.info("create AMIs with cycle_tag: '%s'", cycle_tag) #creat image for each instance for instance in instances: for tag in instance.tags: if tag['Key'] == 'Name': instance_name = tag['Value'] logger.info("creating image for ' %s' with name: %s",instance.id, instance_name) try: utc_now = datetime.utcnow() name = '%s-%s %s/%s/%s %s-%s-%sUTC' % (cycle_tag, instance_name, utc_now.day, utc_now.month, utc_now.year, utc_now.hour, utc_now.minute, utc_now.second) #AMIs names cannot contain ',' name = name.replace(',', '_').replace(':', '_') image = instance.create_image( DryRun=False, Name=name, Description='AMI of ' + instance.id + ' created with Lambda function', NoReboot=True ) logger.info('call to create_image succeeded') #create tag(s) image.create_tags( Tags=[ {'Key': 'ami-cycle', 'Value': cycle_tag}, {'Key': 'Name', 'Value': name} ]) except botocore.exceptions.ClientError as err: logger.info('caught exception: Error message: %s', err) def lambda_handler(event, context): regions = os.environ.get('REGIONS', 'ap-southeast-2').split(',') ses = boto3.session.Session() aws_account_id = os.environ.get('AWS_ACCOUNT_ID') retention_days = int(os.environ.get('RETENTION_DAYS', 14)) # If volume is 'in-use' and having tag:Backup = 'yes' then we create snapshot snapshot_create_filter_default = [ { 'Name': 'status', 'Values': ['in-use'] }, { 'Name': 'tag:Backup', 'Values': ['yes'] } ] snapshot_create_filter = ast.literal_eval( os.environ.get('SNAPSHOT_CREATE_FILTER', "None")) snapshot_create_filter = snapshot_create_filter if snapshot_create_filter else snapshot_create_filter_default # Delete these snapshot created by this script only snapshot_delete_filter_default = [ { 'Name': 'tag:Name', 'Values': ['*'] }, { 'Name': 'tag:Backup', 'Values': ['yes'] } ] snapshot_delete_filter = ast.literal_eval( os.environ.get('SNAPSHOT_DELETE_FILTER', "None")) snapshot_delete_filter = snapshot_delete_filter if snapshot_delete_filter else snapshot_delete_filter_default ami_deregister_filters_default = [ [ { 'Name': 'tag:ami-cycle', 'Values': ['*'] }, { 'Name': 'tag:Application', 'Values': ['ecs-agent'] }, { 'Name': 'tag:Environment', 'Values': ['int'] } ], [ { 'Name': 'tag:Application', 'Values': ['ecs-agent'] }, { 'Name': 'tag:Environment', 'Values': ['qa'] } ], [ { 'Name': 'tag:BuildLayer', 'Values': ['system'] }, { 'Name': 'tag:Version', 'Values': ['ubuntu-1604'] } ], [ { 'Name': 'tag:BuildLayer', 'Values': ['system'] }, { 'Name': 'tag:Version', 'Values': ['ubuntu-1804'] } ], [ { 'Name': 'tag:BuildLayer', 'Values': ['platform'] }, {
'Values': ['java'] } ] ] ami_deregister_filters = ast.literal_eval( os.environ.get('AMI_DEREGISTER_FILTER', "None")) ami_deregister_filters = ami_deregister_filters if ami_deregister_filters else ami_deregister_filters_default # Iterate over regions cycle_tag = event.get('cycle_tag', 'daily') for reg in regions: if not reg: continue ec2 = ses.client('ec2', region_name=reg) create_snapshot(ec2, reg, filters=snapshot_create_filter, context=context) ec2resource = ses.resource('ec2', region_name=reg) cleanup_old_snapshots(ec2resource, retention_days=retention_days, filters=snapshot_delete_filter, dry_run=False) cleanup_detach_snapshot(ec2resource, aws_account_id, dry_run=False) create_amis(ec2resource, cycle_tag) for ami_deregister_filter in ami_deregister_filters: deregister_ami(ec2resource, aws_account_id, filters=ami_deregister_filter, dry_run=False) return 'OK'
'Name': 'tag:Platform',
random_line_split
ec2_vol_management.py
import ast import boto3, botocore from datetime import datetime, timedelta import logging import os import re #setup logger logger = logging.getLogger() logger.setLevel(logging.INFO) def create_snapshot(ec2, reg, filters=[], context={}): result = ec2.describe_volumes(Filters=filters) for volume in result['Volumes']: logger.info("Backing up %s in %s" % (volume['VolumeId'], volume['AvailabilityZone'])) # Create snapshot result = ec2.create_snapshot( VolumeId=volume['VolumeId'], Description='Created by Lambda function %s for backup from %s' % (context.function_name, volume['VolumeId']) ) # Get snapshot resource ec2resource = boto3.resource('ec2', region_name=reg) snapshot = ec2resource.Snapshot(result['SnapshotId']) snapshot_tags = [] # Find name tag for volume if it exists if 'Tags' in volume: for tags in volume['Tags']: snapshot_tags.append({'Key': tags["Key"],'Value': tags["Value"]}) # Add volume name to snapshot for easier identification snapshot.create_tags(Tags=snapshot_tags) def cleanup_detach_snapshot(ec2, aws_account_id, dry_run=True): """This will delete all snapshot that is created automatically by the aws related to ami image but the ami is no longer available (by de-registering) """ images = ec2.images.filter(Owners=[aws_account_id]) images = [image.id for image in images] for snapshot in ec2.snapshots.filter(OwnerIds=[aws_account_id]): r = re.match(r".*for (ami-.*) from.*", snapshot.description) if r: if r.groups()[0] not in images: logger.info("Deleting %s" % snapshot.snapshot_id) if not dry_run: snapshot.delete(DryRun=dry_run) else: logger.info(" skipped as dry_run is true") def cleanup_old_snapshots( ec2resource, retention_days=7, filters=[], keep_at_least=1, dry_run=True): delete_time = int(datetime.now().strftime('%s')) - retention_days * 86400 logger.info('Deleting any snapshots older than {days} days'.format(days=retention_days)) snapshot_iterator = ec2resource.snapshots.filter(Filters=filters) get_last_start_time = lambda obj: int(obj.start_time.strftime('%s')) snapshots = sorted([ x for x in snapshot_iterator ], key=get_last_start_time) deletion_counter = 0 size_counter = 0 total_snapshots = len(snapshots) snapshots_to_delete = snapshots[0:-1 * keep_at_least] for snapshot in snapshots_to_delete: start_time = int(snapshot.start_time.strftime('%s')) if start_time < delete_time: deletion_counter = deletion_counter + 1 size_counter = size_counter + snapshot.volume_size logger.info('Deleting {id}'.format(id=snapshot.snapshot_id)) if not dry_run: snapshot.delete() else: logger.info(" skipped as dry_run is true") logger.info('Deleted {number} snapshots totalling {size} GB'.format( number=deletion_counter, size=size_counter )) def deregister_ami(ec2, aws_account_id, filters=[], retention_days=14, dry_run=True): """Deregister ami if: - No (running/stopped) ec2 instances use it - Matching the filters condition - creation time older than retention_days - Retain at least one ami for safety """ instances = ec2.instances.all() images = ec2.images.filter(Owners=[aws_account_id], Filters=filters) images_in_use = set([instance.image_id for instance in instances]) images_to_deregister_dict = { image.id: image for image in images if image.id not in images_in_use } images_to_deregister_list = images_to_deregister_dict.values() images_to_deregister_list = sorted(images_to_deregister_list, key=lambda x: x.creation_date) # Keep the last one images_to_deregister_list = images_to_deregister_list[0:-1] if len(images_to_deregister_list) == 0: return {} all_snapshots = ec2.snapshots.filter(OwnerIds=[aws_account_id]) # deregister all the AMIs older than retention_days today = datetime.now() date_to_keep = today - timedelta(days=retention_days) for image in images_to_deregister_list: created_date = datetime.strptime(image.creation_date, "%Y-%m-%dT%H:%M:%S.000Z") logger.info(created_date) logger.info(image.creation_date) if created_date < date_to_keep: logger.info("Deregistering %s" % image.id) if not dry_run: image.deregister() for snapshot in all_snapshots: #get the ami id (that the snapshot belongs to) from the snapshot's description r = re.match(r".*for (ami-.*) from.*", snapshot.description) if r: #r.groups()[0] will contain the ami id if r.groups()[0] == image.id: logger.info("found snapshot belonging to %s. snapshot with image_id %s will be deleted", image.id, snapshot.snapshot_id) snapshot.delete() else: logger.info(" skipped as dry_run is true") # Takes a list of EC2 instances with tag 'ami-creation': true - IDs and creates AMIs # Copy from one of my work mate into here with small modification def create_amis(ec2, cycle_tag='daily'):
def lambda_handler(event, context): regions = os.environ.get('REGIONS', 'ap-southeast-2').split(',') ses = boto3.session.Session() aws_account_id = os.environ.get('AWS_ACCOUNT_ID') retention_days = int(os.environ.get('RETENTION_DAYS', 14)) # If volume is 'in-use' and having tag:Backup = 'yes' then we create snapshot snapshot_create_filter_default = [ { 'Name': 'status', 'Values': ['in-use'] }, { 'Name': 'tag:Backup', 'Values': ['yes'] } ] snapshot_create_filter = ast.literal_eval( os.environ.get('SNAPSHOT_CREATE_FILTER', "None")) snapshot_create_filter = snapshot_create_filter if snapshot_create_filter else snapshot_create_filter_default # Delete these snapshot created by this script only snapshot_delete_filter_default = [ { 'Name': 'tag:Name', 'Values': ['*'] }, { 'Name': 'tag:Backup', 'Values': ['yes'] } ] snapshot_delete_filter = ast.literal_eval( os.environ.get('SNAPSHOT_DELETE_FILTER', "None")) snapshot_delete_filter = snapshot_delete_filter if snapshot_delete_filter else snapshot_delete_filter_default ami_deregister_filters_default = [ [ { 'Name': 'tag:ami-cycle', 'Values': ['*'] }, { 'Name': 'tag:Application', 'Values': ['ecs-agent'] }, { 'Name': 'tag:Environment', 'Values': ['int'] } ], [ { 'Name': 'tag:Application', 'Values': ['ecs-agent'] }, { 'Name': 'tag:Environment', 'Values': ['qa'] } ], [ { 'Name': 'tag:BuildLayer', 'Values': ['system'] }, { 'Name': 'tag:Version', 'Values': ['ubuntu-1604'] } ], [ { 'Name': 'tag:BuildLayer', 'Values': ['system'] }, { 'Name': 'tag:Version', 'Values': ['ubuntu-1804'] } ], [ { 'Name': 'tag:BuildLayer', 'Values': ['platform'] }, { 'Name': 'tag:Platform', 'Values': ['java'] } ] ] ami_deregister_filters = ast.literal_eval( os.environ.get('AMI_DEREGISTER_FILTER', "None")) ami_deregister_filters = ami_deregister_filters if ami_deregister_filters else ami_deregister_filters_default # Iterate over regions cycle_tag = event.get('cycle_tag', 'daily') for reg in regions: if not reg: continue ec2 = ses.client('ec2', region_name=reg) create_snapshot(ec2, reg, filters=snapshot_create_filter, context=context) ec2resource = ses.resource('ec2', region_name=reg) cleanup_old_snapshots(ec2resource, retention_days=retention_days, filters=snapshot_delete_filter, dry_run=False) cleanup_detach_snapshot(ec2resource, aws_account_id, dry_run=False) create_amis(ec2resource, cycle_tag) for ami_deregister_filter in ami_deregister_filters: deregister_ami(ec2resource, aws_account_id, filters=ami_deregister_filter, dry_run=False) return 'OK'
ec2_filter = [{'Name':'tag:ami-creation', 'Values':['true']}] instances = list(ec2.instances.filter(Filters=ec2_filter)) logger.info("create AMIs with cycle_tag: '%s'", cycle_tag) #creat image for each instance for instance in instances: for tag in instance.tags: if tag['Key'] == 'Name': instance_name = tag['Value'] logger.info("creating image for ' %s' with name: %s",instance.id, instance_name) try: utc_now = datetime.utcnow() name = '%s-%s %s/%s/%s %s-%s-%sUTC' % (cycle_tag, instance_name, utc_now.day, utc_now.month, utc_now.year, utc_now.hour, utc_now.minute, utc_now.second) #AMIs names cannot contain ',' name = name.replace(',', '_').replace(':', '_') image = instance.create_image( DryRun=False, Name=name, Description='AMI of ' + instance.id + ' created with Lambda function', NoReboot=True ) logger.info('call to create_image succeeded') #create tag(s) image.create_tags( Tags=[ {'Key': 'ami-cycle', 'Value': cycle_tag}, {'Key': 'Name', 'Value': name} ]) except botocore.exceptions.ClientError as err: logger.info('caught exception: Error message: %s', err)
identifier_body
ec2_vol_management.py
import ast import boto3, botocore from datetime import datetime, timedelta import logging import os import re #setup logger logger = logging.getLogger() logger.setLevel(logging.INFO) def create_snapshot(ec2, reg, filters=[], context={}): result = ec2.describe_volumes(Filters=filters) for volume in result['Volumes']: logger.info("Backing up %s in %s" % (volume['VolumeId'], volume['AvailabilityZone'])) # Create snapshot result = ec2.create_snapshot( VolumeId=volume['VolumeId'], Description='Created by Lambda function %s for backup from %s' % (context.function_name, volume['VolumeId']) ) # Get snapshot resource ec2resource = boto3.resource('ec2', region_name=reg) snapshot = ec2resource.Snapshot(result['SnapshotId']) snapshot_tags = [] # Find name tag for volume if it exists if 'Tags' in volume: for tags in volume['Tags']: snapshot_tags.append({'Key': tags["Key"],'Value': tags["Value"]}) # Add volume name to snapshot for easier identification snapshot.create_tags(Tags=snapshot_tags) def cleanup_detach_snapshot(ec2, aws_account_id, dry_run=True): """This will delete all snapshot that is created automatically by the aws related to ami image but the ami is no longer available (by de-registering) """ images = ec2.images.filter(Owners=[aws_account_id]) images = [image.id for image in images] for snapshot in ec2.snapshots.filter(OwnerIds=[aws_account_id]): r = re.match(r".*for (ami-.*) from.*", snapshot.description) if r: if r.groups()[0] not in images: logger.info("Deleting %s" % snapshot.snapshot_id) if not dry_run: snapshot.delete(DryRun=dry_run) else: logger.info(" skipped as dry_run is true") def cleanup_old_snapshots( ec2resource, retention_days=7, filters=[], keep_at_least=1, dry_run=True): delete_time = int(datetime.now().strftime('%s')) - retention_days * 86400 logger.info('Deleting any snapshots older than {days} days'.format(days=retention_days)) snapshot_iterator = ec2resource.snapshots.filter(Filters=filters) get_last_start_time = lambda obj: int(obj.start_time.strftime('%s')) snapshots = sorted([ x for x in snapshot_iterator ], key=get_last_start_time) deletion_counter = 0 size_counter = 0 total_snapshots = len(snapshots) snapshots_to_delete = snapshots[0:-1 * keep_at_least] for snapshot in snapshots_to_delete: start_time = int(snapshot.start_time.strftime('%s')) if start_time < delete_time: deletion_counter = deletion_counter + 1 size_counter = size_counter + snapshot.volume_size logger.info('Deleting {id}'.format(id=snapshot.snapshot_id)) if not dry_run: snapshot.delete() else: logger.info(" skipped as dry_run is true") logger.info('Deleted {number} snapshots totalling {size} GB'.format( number=deletion_counter, size=size_counter )) def
(ec2, aws_account_id, filters=[], retention_days=14, dry_run=True): """Deregister ami if: - No (running/stopped) ec2 instances use it - Matching the filters condition - creation time older than retention_days - Retain at least one ami for safety """ instances = ec2.instances.all() images = ec2.images.filter(Owners=[aws_account_id], Filters=filters) images_in_use = set([instance.image_id for instance in instances]) images_to_deregister_dict = { image.id: image for image in images if image.id not in images_in_use } images_to_deregister_list = images_to_deregister_dict.values() images_to_deregister_list = sorted(images_to_deregister_list, key=lambda x: x.creation_date) # Keep the last one images_to_deregister_list = images_to_deregister_list[0:-1] if len(images_to_deregister_list) == 0: return {} all_snapshots = ec2.snapshots.filter(OwnerIds=[aws_account_id]) # deregister all the AMIs older than retention_days today = datetime.now() date_to_keep = today - timedelta(days=retention_days) for image in images_to_deregister_list: created_date = datetime.strptime(image.creation_date, "%Y-%m-%dT%H:%M:%S.000Z") logger.info(created_date) logger.info(image.creation_date) if created_date < date_to_keep: logger.info("Deregistering %s" % image.id) if not dry_run: image.deregister() for snapshot in all_snapshots: #get the ami id (that the snapshot belongs to) from the snapshot's description r = re.match(r".*for (ami-.*) from.*", snapshot.description) if r: #r.groups()[0] will contain the ami id if r.groups()[0] == image.id: logger.info("found snapshot belonging to %s. snapshot with image_id %s will be deleted", image.id, snapshot.snapshot_id) snapshot.delete() else: logger.info(" skipped as dry_run is true") # Takes a list of EC2 instances with tag 'ami-creation': true - IDs and creates AMIs # Copy from one of my work mate into here with small modification def create_amis(ec2, cycle_tag='daily'): ec2_filter = [{'Name':'tag:ami-creation', 'Values':['true']}] instances = list(ec2.instances.filter(Filters=ec2_filter)) logger.info("create AMIs with cycle_tag: '%s'", cycle_tag) #creat image for each instance for instance in instances: for tag in instance.tags: if tag['Key'] == 'Name': instance_name = tag['Value'] logger.info("creating image for ' %s' with name: %s",instance.id, instance_name) try: utc_now = datetime.utcnow() name = '%s-%s %s/%s/%s %s-%s-%sUTC' % (cycle_tag, instance_name, utc_now.day, utc_now.month, utc_now.year, utc_now.hour, utc_now.minute, utc_now.second) #AMIs names cannot contain ',' name = name.replace(',', '_').replace(':', '_') image = instance.create_image( DryRun=False, Name=name, Description='AMI of ' + instance.id + ' created with Lambda function', NoReboot=True ) logger.info('call to create_image succeeded') #create tag(s) image.create_tags( Tags=[ {'Key': 'ami-cycle', 'Value': cycle_tag}, {'Key': 'Name', 'Value': name} ]) except botocore.exceptions.ClientError as err: logger.info('caught exception: Error message: %s', err) def lambda_handler(event, context): regions = os.environ.get('REGIONS', 'ap-southeast-2').split(',') ses = boto3.session.Session() aws_account_id = os.environ.get('AWS_ACCOUNT_ID') retention_days = int(os.environ.get('RETENTION_DAYS', 14)) # If volume is 'in-use' and having tag:Backup = 'yes' then we create snapshot snapshot_create_filter_default = [ { 'Name': 'status', 'Values': ['in-use'] }, { 'Name': 'tag:Backup', 'Values': ['yes'] } ] snapshot_create_filter = ast.literal_eval( os.environ.get('SNAPSHOT_CREATE_FILTER', "None")) snapshot_create_filter = snapshot_create_filter if snapshot_create_filter else snapshot_create_filter_default # Delete these snapshot created by this script only snapshot_delete_filter_default = [ { 'Name': 'tag:Name', 'Values': ['*'] }, { 'Name': 'tag:Backup', 'Values': ['yes'] } ] snapshot_delete_filter = ast.literal_eval( os.environ.get('SNAPSHOT_DELETE_FILTER', "None")) snapshot_delete_filter = snapshot_delete_filter if snapshot_delete_filter else snapshot_delete_filter_default ami_deregister_filters_default = [ [ { 'Name': 'tag:ami-cycle', 'Values': ['*'] }, { 'Name': 'tag:Application', 'Values': ['ecs-agent'] }, { 'Name': 'tag:Environment', 'Values': ['int'] } ], [ { 'Name': 'tag:Application', 'Values': ['ecs-agent'] }, { 'Name': 'tag:Environment', 'Values': ['qa'] } ], [ { 'Name': 'tag:BuildLayer', 'Values': ['system'] }, { 'Name': 'tag:Version', 'Values': ['ubuntu-1604'] } ], [ { 'Name': 'tag:BuildLayer', 'Values': ['system'] }, { 'Name': 'tag:Version', 'Values': ['ubuntu-1804'] } ], [ { 'Name': 'tag:BuildLayer', 'Values': ['platform'] }, { 'Name': 'tag:Platform', 'Values': ['java'] } ] ] ami_deregister_filters = ast.literal_eval( os.environ.get('AMI_DEREGISTER_FILTER', "None")) ami_deregister_filters = ami_deregister_filters if ami_deregister_filters else ami_deregister_filters_default # Iterate over regions cycle_tag = event.get('cycle_tag', 'daily') for reg in regions: if not reg: continue ec2 = ses.client('ec2', region_name=reg) create_snapshot(ec2, reg, filters=snapshot_create_filter, context=context) ec2resource = ses.resource('ec2', region_name=reg) cleanup_old_snapshots(ec2resource, retention_days=retention_days, filters=snapshot_delete_filter, dry_run=False) cleanup_detach_snapshot(ec2resource, aws_account_id, dry_run=False) create_amis(ec2resource, cycle_tag) for ami_deregister_filter in ami_deregister_filters: deregister_ami(ec2resource, aws_account_id, filters=ami_deregister_filter, dry_run=False) return 'OK'
deregister_ami
identifier_name
page.js
// page scroll var sw = $(window).width() var initWidth = 1920; var hd = "easeOutQuad"//缓动 var Speed_ = 400; var box = $("#box"); var page = $(".page"); var pageNum = 7;//总页数 var curPage = 0;//当前页数 var Original = 0;//记录前一帧页数 var isScroll = true;//结束后才能点击 var menu_id = 0; var dir = 1; var Loading = {total: 0, loaded: 0, tl: null}; //load方法 $(function () { adaptive(); //调整元素宽高整屏幕自适应 $(window).resize(adaptive); //窗口调整大小 Loading_Act(); //运行LOAD方法 init(); peizhics() //配置表 yuyue()//预约试驾显示 }); //初始化+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function init() { pageNum = page.length - 1;//总页数赋值 //运行滚动插件jq.mousewheel $(".box").mousewheel(Win_wheel); menu(0); } //菜单+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ var menu_cur = [0, 1, 2, 6, 7, 8] //导航点击跳转页码数组 function menu(n) { if (n > 1 && n < 6) { //判断导航2的页数,如果大于1且小于30,为导航2 n = 2; } if (n > 5) { //判断导航3以下导航的页数,如果大于29,则减去28页。 n = n - 3 } //alert(n) $("#menu ul li").removeClass("cur") $("#menu ul li").eq(n).addClass("cur") for (var i = 0; i < 5; i++) { //导航添加背景置顶 $("#menu ul li").eq(i).css({"background-position": "right bottom"}) } } $("#menu ul li").click(function () { //isScroll 防止点击过快 if (isScroll == true) { var id = $("#menu ul li").index($(this)); menu(menu_cur[id]); Original = menu_id; //$("#shuzitext").text(menu_id) if (menu_cur[id] == Original) { //$("#shuzitext").text("坑爹的!!!") } else { if (id > Original) { dir = 1; } else { dir = -1; } curPage = menu_cur[id]; //$("#shuzitext").text("curPage"+curPage+"上一次值"+Original) Page_inout(curPage, Original) Original = menu_cur[id]; } }//end isScroll }) //卖点菜单点击 function nuin(d) { d = d - 2; $(".innavi_1 a").removeClass("cur") //清空cur for (var i = 0; i <= d; i++) { $(".innavi_1 a").eq(i).addClass("cur").siblings().removeClass("cur") //每个ID添加cur样式 } } $(".innavi_1 a").click(function () { if (isScroll == true) { isScroll = false; var id = $(".innavi_1 a").index($(this)) + 2; //声明ID等于当前值 Original = menu_id; if (id == Original) { // $("#shuzitext").text("坑爹的!!!") } else { nuin(id); //运行方法nuin_cur //fun_into[Math.abs(id)]();//动画进场数组里面放方法 if (id > Original) { dir = 1; } else { dir = -1; } curPage = id //$("#shuzitext").text("curPage"+curPage+"上一次值"+Original) Page_inout(curPage, Original) Original = id; } } }) //配置表限制滚动翻页------------------------------------------ var phototrue = true; /*$('.photo').mouseover(function(){ phototrue=false; }) $('.photo').mouseout(function(){ phototrue=true; })*/ $('#ui-id-1,#ui-id-2,#ui-id-3,.heise,.yysj').mouseover(function () { phototrue = false; }) $('#ui-id-1,#ui-id-2,#ui-id-3,.heise,.yysj').mouseout(function () { phototrue = true; }) //显示预约试驾,关闭预约试驾 function yuyue() { $('.sjbtn').click(function () { $('.heise,.yysj_gb,.yysj').show(); }) $('.yysj_gb').click(function () { $('.heise,.yysj_gb,.yysj').hide(); }) $('.yycg_btn').click(function () { $('.heise_1,.yycg').hide(); }) } //配置参数 function peizhics() { /*$('#dealerMain').touchslider({ scrollObj : '#dealerBox', scrollBarWrap : '#dealerScrollbarWrap', scrollBar :'#dealerScrollbar', onceScrollH :120 });*/ var h = $('#dealerBox').find('img:eq(0)').height(); $('#dealerBox').height(h); var slider = new Slider({ boxObj: '#dealerMain', sliderObj: '#dealerBox', scrollbarWrap: "#dealerScrollbarWrap", scrollBar: "#dealerScrollbar", barFixed: true, //滚动条固定高度 onceScrollHeight: 200, scale: 1, beforeCallback: function () { isScroll = false; }, afterCallback: function () { isScroll = true; } }); } //调整元素宽高整屏幕自适应++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ var adaptive = function () { var width = $(window).width(), winH = $(window).height(); $('.same').each(function (index, element) { var oh = $(this).attr('oh'); var ow = $(this).attr('ow'); var scale = 0; var height; if (width / initWidth > winH / 900) { scale = width / initWidth; } else { scale = winH / 900; } height = scale * oh; var imgWidth = ow * scale; $(this).height(height + 'px').width(imgWidth + 'px'); }); } //鼠标滚动判断上下事件++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function Touch_start(e) { touch.oy = e.pageY; } function Touch_move(e) { e.preventDefault(); touch.move = true; touch.dy = e.pageY; } function Touch_end(e) { if (touch.move) { touch.move = false; var oy = touch.oy; var y = touch.dy; if (y - oy > 40) Win_wheel(e, 1, 0, 0); else if (oy - y > 40) Win_wheel(e, -1, 0, 0); } } /*鼠标滚动事件 delta=-1下 delta=1上*/ function Win_wheel(e, delta, deltaX, deltaY) { if (isScroll == true) { if (phototrue == true) { //pageNum=-(fun.length-1) dir = (delta > 0 ? -1 : 1);//反转delta 向下+1 向上-1 Original = curPage;//记录上次值 //alert(Original); var $this = $('#shuzitext'), timeoutId = $this.data('timeoutId'); if (timeoutId) { clearTimeout(timeoutId); } else { curPage = curPage + dir;
if (curPage < 0) { curPage = 0; return; } if (curPage > pageNum) { curPage = pageNum; return; } Page_inout(curPage, Original) isScroll = false; } //延迟滚动。防止滚动很多次 $this.data('timeoutId', setTimeout(function () { $this.removeData('timeoutId'); $this = null }, 200)); return false; } } } //页面切换方法+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function Page_inout(page_index, page_out) { //page_inde:下页数值,page_out:前面一个 //fun_out[page_out](); //动画出场数组里面放方法 var h = $(window).height() / 900; var dir = page_index > page_out ? 900 : -900; menu_id = page_index; menu(page_index);//菜单传值 //显示卖点导航 if (page_index > 1 && page_index < 6) { nuin(page_index); /*$(".innavi").stop().animate({opacity:"1"},500,hd,function(){});*/ $(".innavi").show(); } else { /*$(".innavi").stop().animate({opacity:"0"},500,hd,function(){});*/ $(".innavi").hide(); } isScroll = false; //eleScrollTop(page_index); //动画进场数组里面放方法 page.eq(page_index).addClass("active").css({ "display": "block", "z-index": "3", "top": dir * h + "px" }).animate({top: "0"}, 800, hd, function () { }); page.eq(page_out).addClass("active_out").css({ "display": "block", "z-index": "1", "top": "0px" }).animate({top: -dir * h + "px"}, 800, hd, function () { //fun_into[Math.abs(page_index)](); //动画进场数组里面放方法 isScroll = true; page.eq(page_out).removeClass("active").css("display", "none"); dh(page_index); //运行动画 }); } //判断滑动时,动画的运行方法 function dh(TextNumber) { switch (TextNumber) { case 0: //首页 into_0(); out_1(); break; case 1: //视频 into_1(); out_0(); break; case 2: //精美车图 out_1(); break; case 3: //精美车图 break; case 4: //精美车图 break; case 5: //精美车图 out_2(); break; case 6: //媒体评测 into_2(); out_3(); break; case 7: //车型配置 into_3(); out_2(); out_4(); break; case 8: //车型配置 into_4(); out_3(); break; } } //首页动画 function into_0() { $(".sy_a1").stop().animate({opacity: "1", left: "15.8%"}, 600, hd, function () { $(".sy_a2").stop().animate({opacity: "1", bottom: "3.22%"}, 600, hd, function () { }).css({flter: "Alpha(Opacity=100)"}); }).css({flter: "Alpha(Opacity=100)"}); $(".sy_a3").stop().delay(300).animate({opacity: "1"}, 600, hd, function () { }).css({flter: "Alpha(Opacity=100)"}); } /* .sy_a1{ position:absolute; top:17.8%; left:20.8%; z-index:1; opacity:0; filter:Alpha(Opacity=0);} .sy_a2{ position:absolute; bottom:5%; left:6.1%; z-index:1; opacity:0; filter:Alpha(Opacity=0);} */ function out_0() { $(".sy_a1").stop().animate({opacity: "0", left: "20.8%"}, 100, hd, function () { }).css({flter: "Alpha(Opacity=0)"}); $(".sy_a2").stop().animate({opacity: "0", bottom: "-1%"}, 100, hd, function () { }).css({flter: "Alpha(Opacity=0)"}); $(".sy_a3").stop().animate({opacity: "0"}, 100, hd, function () { }).css({flter: "Alpha(Opacity=0)"}); } //新车展示 function into_1() { /*$(".xc_zs").stop().animate({opacity: "1", top: "16%"}, 600, hd, function () { $(".hy_ys").stop().animate({opacity: "1", top: "25.2%"}, 600, hd, function () { $(".video_content").stop().animate({opacity: "1", left: "22%"}, 600, hd, function () { }).css({flter: "Alpha(Opacity=100)"}); }).css({flter: "Alpha(Opacity=100)"}); }).css({flter: "Alpha(Opacity=100)"});*/ } /* .xc_zs{ position:absolute; left:0; top:21%; opacity:0; filter:Alpha(Opacity=0);} .hy_ys{position:absolute; left:0; top:30.2%; opacity:0; filter:Alpha(Opacity=0);} .video_content{ position:absolute; top:36.2%; left:27%; z-index:10; opacity:0; filter:Alpha(Opacity=0);} */ function out_1() { /*$(".xc_zs").stop().animate({opacity: "0", top: "21%"}, 100, hd, function () { }).css({flter: "Alpha(Opacity=0)"}); $(".hy_ys").stop().animate({opacity: "0", top: "30.2%"}, 100, hd, function () { }).css({flter: "Alpha(Opacity=0)"}); $(".video_content").stop().animate({opacity: "0", left: "27%"}, 100, hd, function () { }).css({flter: "Alpha(Opacity=0)"});*/ } //媒体评测 function into_2() { $(".ban").stop().animate({opacity: "1", marginTop: "-222.5px"}, 600, hd, function () { }).css({flter: "Alpha(Opacity=100)"}); } /* .ban{ width:1002px; height:445px; position:absolute; overflow:hidden; top:50%; left:50%; margin-left:-501px; margin-top:-122.5px; z-index:5; opacity:0; filter:Alpha(Opacity=0);} */ function out_2() { $(".ban").stop().animate({opacity: "0", marginTop: "-122.5px"}, 100, hd, function () { }).css({flter: "Alpha(Opacity=0)"}); } //车型配置 function into_3() { $(".pzb_2").stop().animate({opacity: "1", marginTop: "-216px"}, 600, hd, function () { }).css({flter: "Alpha(Opacity=100)"}); } /* .pzb_2{position:absolute; top:50%; margin-left:-633.5px; margin-top:-192px; left:50%; z-index:1; width:1267px; height:584px; opacity:0; filter:Alpha(Opacity=0);} */ function out_3() { $(".pzb_2").stop().animate({opacity: "0", marginTop: "-192px"}, 100, hd, function () { }).css({flter: "Alpha(Opacity=0)"}); } //车型配置 function into_4() { $(".dealerInfo").stop().animate({opacity: "1"}, 600, hd, function () { }).css({flter: "Alpha(Opacity=100)"}); } function out_4() { $(".dealerInfo").stop().animate({opacity: "0"}, 100, hd, function () { }).css({flter: "Alpha(Opacity=0)"}); } //loading function Loading_Act() { /* TweenMax.set("#Loading_Rect",{transformOrigin:"0 0"}); var tl=new TimelineMax({repeat:-1,repeatDelay:0.3}); tl.to("#Loading_Rect",0.65,{left:60,top:40,rotation:-90,ease:Cubic.easeInOut},"t1") .to("#Loading_Rect",0.65,{left:100,top:40,rotation:-180,ease:Cubic.easeInOut},"t2") .to("#Loading_c",0.45,{rotation:90,ease:Cubic.easeInOut},"t1+=0.2") .to("#Loading_c",0.45,{rotation:180,ease:Cubic.easeInOut},"t2+=0.2");*/ // $.get("main.html",function(c){ // Stage.me.append(c); // Win.me.resize(Stage_resize); // Stage_resize(); var imgs = $("#box img");//加载资源 Loading.total = imgs.length; imgs.each(function () { if (this.complete) { loading(); } else { $(this).load(loading).error(loading); } }); if (Loading.loaded == Loading.total) { loading_over(); } function loading() { Loading.loaded++; var d = Math.ceil(Loading.loaded * 100 / Loading.total); if (Loading.loaded == Loading.total) { imgs.off("load error"); loading_over(); } else { $("#Loading_num").html(d); } } function loading_over() { $("#Loading_num").html("100"); // tl.tweenTo(tl.duration(),{onComplete:function(){ // tl.clear(); var tl2 = new TimelineMax({ onComplete: function () { $("#Loading").remove(); $("#box").css({"display": "block"}) //$("#box").show(); init(); into_0() //运行动画方法 //Stage.me.removeClass("dn"); //$(".Box:eq(0)").addClass("on"); ////内容事件初始化 //Main_event(); //Home_Act(); } }); tl2.to("#Loading_Rect", 0.6, {opacity: 0, ease: Quad.easeOut}, "t1") .to("#Loading", 0.85, {opacity: 0, ease: Quad.easeInOut}, "t1+=0.2"); // }}); } // }); }
identifier_name
page.js
// page scroll var sw = $(window).width() var initWidth = 1920; var hd = "easeOutQuad"//缓动 var Speed_ = 400; var box = $("#box"); var page = $(".page"); var pageNum = 7;//总页数 var curPage = 0;//当前页数 var Original = 0;//记录前一帧页数 var isScroll = true;//结束后才能点击 var menu_id = 0; var dir = 1; var Loading = {total: 0, loaded: 0, tl: null}; //load方法 $(function () { adaptive(); //调整元素宽高整屏幕自适应 $(window).resize(adaptive); //窗口调整大小 Loading_Act(); //运行LOAD方法 init(); peizhics() //配置表 yuyue()//预约试驾显示 }); //初始化+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function init() { pageNum = page.length - 1;//总页数赋值 //运行滚动插件jq.mousewheel $(".box").mousewheel(Win_wheel); menu(0); } //菜单+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ var menu_cur = [0, 1, 2, 6, 7, 8] //导航点击跳转页码数组 function menu(n) { if (n > 1 && n < 6) { //判断导航2的页数,如果大于1且小于30,为导航2 n = 2; } if (n > 5) { //判断导航3以下导航的页数,如果大于29,则减去28页。 n = n - 3 } //alert(n) $("#menu ul li").removeClass("cur") $("#menu ul li").eq(n).addClass("cur") for (var i = 0; i < 5; i++) { //导航添加背景置顶 $("#menu ul li").eq(i).css({"background-position": "right bottom"}) } } $("#menu ul li").click(function () { //isScroll 防止点击过快 if (isScroll == true) { var id = $("#menu ul li").index($(this)); menu(menu_cur[id]); Original = menu_id; //$("#shuzitext").text(menu_id) if (menu_cur[id] == Original) { //$("#shuzitext").text("坑爹的!!!") } else { if (id > Original) { dir = 1; } else { dir = -1; } curPage = menu_cur[id]; //$("#shuzitext").text("curPage"+curPage+"上一次值"+Original) Page_inout(curPage, Original) Original = menu_cur[id]; } }//end isScroll }) //卖点菜单点击 function nuin(d) { d = d - 2; $(".innavi_1 a").removeClass("cur") //清空cur for (var i = 0; i <= d; i++) { $(".innavi_1 a").eq(i).addClass("cur").siblings().removeClass("cur") //每个ID添加cur样式 } } $(".innavi_1 a").click(function () { if (isScroll == true) { isScroll = false; var id = $(".innavi_1 a").index($(this)) + 2; //声明ID等于当前值 Original = menu_id; if (id == Original) { // $("#shuzitext").text("坑爹的!!!") } else { nuin(id); //运行方法nuin_cur //fun_into[Math.abs(id)]();//动画进场数组里面放方法 if (id > Original) { dir = 1; } else { dir = -1; } curPage = id //$("#shuzitext").text("curPage"+curPage+"上一次值"+Original) Page_inout(curPage, Original) Original = id; } } }) //配置表限制滚动翻页------------------------------------------ var phototrue = true; /*$('.photo').mouseover(function(){ phototrue=false; }) $('.photo').mouseout(function(){ phototrue=true; })*/ $('#ui-id-1,#ui-id-2,#ui-id-3,.heise,.yysj').mouseover(function () { phototrue = false; }) $('#ui-id-1,#ui-id-2,#ui-id-3,.heise,.yysj').mouseout(function () { phototrue = true; }) //显示预约试驾,关闭预约试驾 function yuyue() { $('.sjbtn').click(function () { $('.heise,.yysj_gb,.yysj').show(); }) $('.yysj_gb').click(function () { $('.heise,.yysj_gb,.yysj').hide(); }) $('.yycg_btn').click(function () { $('.heise_1,.yycg').hide(); }) } //配置参数 function peizhics() { /*$('#dealerMain').touchslider({ scrollObj : '#dealerBox', scrollBarWrap : '#dealerScrollbarWrap', scrollBar :'#dealerScrollbar', onceScrollH :120 });*/ var h = $('#dealerBox').find('img:eq(0)').height(); $('#dealerBox').height(h); var slider = new Slider({ boxObj: '#dealerMain', sliderObj: '#dealerBox', scrollbarWrap: "#dealerScrollbarWrap", scrollBar: "#dealerScrollbar", barFixed: true, //滚动条固定高度 onceScrollHeight: 200, scale: 1, beforeCallback: function () { isScroll = false; }, afterCallback: function () { isScroll = true; } }); } //调整元素宽高整屏幕自适应++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ var adaptive = function () { var width = $(window).width(), winH = $(window).height(); $('.same').each(function (index, element) { var oh = $(this).attr('oh'); var ow = $(this).attr('ow'); var scale = 0; var height; if (width / initWidth > winH / 900) { scale = width / initWidth; } else { scale = winH / 900; } height = scale * oh; var imgWidth = ow * scale; $(this).height(height + 'px').width(imgWidth + 'px'); }); } //鼠标滚动判断上下事件++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function Touch_start(e) { touch.oy = e.pageY; } function Touch_move(e) { e.preventDefault();
} function Touch_end(e) { if (touch.move) { touch.move = false; var oy = touch.oy; var y = touch.dy; if (y - oy > 40) Win_wheel(e, 1, 0, 0); else if (oy - y > 40) Win_wheel(e, -1, 0, 0); } } /*鼠标滚动事件 delta=-1下 delta=1上*/ function Win_wheel(e, delta, deltaX, deltaY) { if (isScroll == true) { if (phototrue == true) { //pageNum=-(fun.length-1) dir = (delta > 0 ? -1 : 1);//反转delta 向下+1 向上-1 Original = curPage;//记录上次值 //alert(Original); var $this = $('#shuzitext'), timeoutId = $this.data('timeoutId'); if (timeoutId) { clearTimeout(timeoutId); } else { curPage = curPage + dir; if (curPage < 0) { curPage = 0; return; } if (curPage > pageNum) { curPage = pageNum; return; } Page_inout(curPage, Original) isScroll = false; } //延迟滚动。防止滚动很多次 $this.data('timeoutId', setTimeout(function () { $this.removeData('timeoutId'); $this = null }, 200)); return false; } } } //页面切换方法+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function Page_inout(page_index, page_out) { //page_inde:下页数值,page_out:前面一个 //fun_out[page_out](); //动画出场数组里面放方法 var h = $(window).height() / 900; var dir = page_index > page_out ? 900 : -900; menu_id = page_index; menu(page_index);//菜单传值 //显示卖点导航 if (page_index > 1 && page_index < 6) { nuin(page_index); /*$(".innavi").stop().animate({opacity:"1"},500,hd,function(){});*/ $(".innavi").show(); } else { /*$(".innavi").stop().animate({opacity:"0"},500,hd,function(){});*/ $(".innavi").hide(); } isScroll = false; //eleScrollTop(page_index); //动画进场数组里面放方法 page.eq(page_index).addClass("active").css({ "display": "block", "z-index": "3", "top": dir * h + "px" }).animate({top: "0"}, 800, hd, function () { }); page.eq(page_out).addClass("active_out").css({ "display": "block", "z-index": "1", "top": "0px" }).animate({top: -dir * h + "px"}, 800, hd, function () { //fun_into[Math.abs(page_index)](); //动画进场数组里面放方法 isScroll = true; page.eq(page_out).removeClass("active").css("display", "none"); dh(page_index); //运行动画 }); } //判断滑动时,动画的运行方法 function dh(TextNumber) { switch (TextNumber) { case 0: //首页 into_0(); out_1(); break; case 1: //视频 into_1(); out_0(); break; case 2: //精美车图 out_1(); break; case 3: //精美车图 break; case 4: //精美车图 break; case 5: //精美车图 out_2(); break; case 6: //媒体评测 into_2(); out_3(); break; case 7: //车型配置 into_3(); out_2(); out_4(); break; case 8: //车型配置 into_4(); out_3(); break; } } //首页动画 function into_0() { $(".sy_a1").stop().animate({opacity: "1", left: "15.8%"}, 600, hd, function () { $(".sy_a2").stop().animate({opacity: "1", bottom: "3.22%"}, 600, hd, function () { }).css({flter: "Alpha(Opacity=100)"}); }).css({flter: "Alpha(Opacity=100)"}); $(".sy_a3").stop().delay(300).animate({opacity: "1"}, 600, hd, function () { }).css({flter: "Alpha(Opacity=100)"}); } /* .sy_a1{ position:absolute; top:17.8%; left:20.8%; z-index:1; opacity:0; filter:Alpha(Opacity=0);} .sy_a2{ position:absolute; bottom:5%; left:6.1%; z-index:1; opacity:0; filter:Alpha(Opacity=0);} */ function out_0() { $(".sy_a1").stop().animate({opacity: "0", left: "20.8%"}, 100, hd, function () { }).css({flter: "Alpha(Opacity=0)"}); $(".sy_a2").stop().animate({opacity: "0", bottom: "-1%"}, 100, hd, function () { }).css({flter: "Alpha(Opacity=0)"}); $(".sy_a3").stop().animate({opacity: "0"}, 100, hd, function () { }).css({flter: "Alpha(Opacity=0)"}); } //新车展示 function into_1() { /*$(".xc_zs").stop().animate({opacity: "1", top: "16%"}, 600, hd, function () { $(".hy_ys").stop().animate({opacity: "1", top: "25.2%"}, 600, hd, function () { $(".video_content").stop().animate({opacity: "1", left: "22%"}, 600, hd, function () { }).css({flter: "Alpha(Opacity=100)"}); }).css({flter: "Alpha(Opacity=100)"}); }).css({flter: "Alpha(Opacity=100)"});*/ } /* .xc_zs{ position:absolute; left:0; top:21%; opacity:0; filter:Alpha(Opacity=0);} .hy_ys{position:absolute; left:0; top:30.2%; opacity:0; filter:Alpha(Opacity=0);} .video_content{ position:absolute; top:36.2%; left:27%; z-index:10; opacity:0; filter:Alpha(Opacity=0);} */ function out_1() { /*$(".xc_zs").stop().animate({opacity: "0", top: "21%"}, 100, hd, function () { }).css({flter: "Alpha(Opacity=0)"}); $(".hy_ys").stop().animate({opacity: "0", top: "30.2%"}, 100, hd, function () { }).css({flter: "Alpha(Opacity=0)"}); $(".video_content").stop().animate({opacity: "0", left: "27%"}, 100, hd, function () { }).css({flter: "Alpha(Opacity=0)"});*/ } //媒体评测 function into_2() { $(".ban").stop().animate({opacity: "1", marginTop: "-222.5px"}, 600, hd, function () { }).css({flter: "Alpha(Opacity=100)"}); } /* .ban{ width:1002px; height:445px; position:absolute; overflow:hidden; top:50%; left:50%; margin-left:-501px; margin-top:-122.5px; z-index:5; opacity:0; filter:Alpha(Opacity=0);} */ function out_2() { $(".ban").stop().animate({opacity: "0", marginTop: "-122.5px"}, 100, hd, function () { }).css({flter: "Alpha(Opacity=0)"}); } //车型配置 function into_3() { $(".pzb_2").stop().animate({opacity: "1", marginTop: "-216px"}, 600, hd, function () { }).css({flter: "Alpha(Opacity=100)"}); } /* .pzb_2{position:absolute; top:50%; margin-left:-633.5px; margin-top:-192px; left:50%; z-index:1; width:1267px; height:584px; opacity:0; filter:Alpha(Opacity=0);} */ function out_3() { $(".pzb_2").stop().animate({opacity: "0", marginTop: "-192px"}, 100, hd, function () { }).css({flter: "Alpha(Opacity=0)"}); } //车型配置 function into_4() { $(".dealerInfo").stop().animate({opacity: "1"}, 600, hd, function () { }).css({flter: "Alpha(Opacity=100)"}); } function out_4() { $(".dealerInfo").stop().animate({opacity: "0"}, 100, hd, function () { }).css({flter: "Alpha(Opacity=0)"}); } //loading function Loading_Act() { /* TweenMax.set("#Loading_Rect",{transformOrigin:"0 0"}); var tl=new TimelineMax({repeat:-1,repeatDelay:0.3}); tl.to("#Loading_Rect",0.65,{left:60,top:40,rotation:-90,ease:Cubic.easeInOut},"t1") .to("#Loading_Rect",0.65,{left:100,top:40,rotation:-180,ease:Cubic.easeInOut},"t2") .to("#Loading_c",0.45,{rotation:90,ease:Cubic.easeInOut},"t1+=0.2") .to("#Loading_c",0.45,{rotation:180,ease:Cubic.easeInOut},"t2+=0.2");*/ // $.get("main.html",function(c){ // Stage.me.append(c); // Win.me.resize(Stage_resize); // Stage_resize(); var imgs = $("#box img");//加载资源 Loading.total = imgs.length; imgs.each(function () { if (this.complete) { loading(); } else { $(this).load(loading).error(loading); } }); if (Loading.loaded == Loading.total) { loading_over(); } function loading() { Loading.loaded++; var d = Math.ceil(Loading.loaded * 100 / Loading.total); if (Loading.loaded == Loading.total) { imgs.off("load error"); loading_over(); } else { $("#Loading_num").html(d); } } function loading_over() { $("#Loading_num").html("100"); // tl.tweenTo(tl.duration(),{onComplete:function(){ // tl.clear(); var tl2 = new TimelineMax({ onComplete: function () { $("#Loading").remove(); $("#box").css({"display": "block"}) //$("#box").show(); init(); into_0() //运行动画方法 //Stage.me.removeClass("dn"); //$(".Box:eq(0)").addClass("on"); ////内容事件初始化 //Main_event(); //Home_Act(); } }); tl2.to("#Loading_Rect", 0.6, {opacity: 0, ease: Quad.easeOut}, "t1") .to("#Loading", 0.85, {opacity: 0, ease: Quad.easeInOut}, "t1+=0.2"); // }}); } // }); }
touch.move = true; touch.dy = e.pageY;
random_line_split
page.js
// page scroll var sw = $(window).width() var initWidth = 1920; var hd = "easeOutQuad"//缓动 var Speed_ = 400; var box = $("#box"); var page = $(".page"); var pageNum = 7;//总页数 var curPage = 0;//当前页数 var Original = 0;//记录前一帧页数 var isScroll = true;//结束后才能点击 var menu_id = 0; var dir = 1; var Loading = {total: 0, loaded: 0, tl: null}; //load方法 $(function () { adaptive(); //调整元素宽高整屏幕自适应 $(window).resize(adaptive); //窗口调整大小 Loading_Act(); //运行LOAD方法 init(); peizhics() //配置表 yuyue()//预约试驾显示 }); //初始化+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function init() { pageNum = page.length - 1;//总页数赋值 //运行滚动插件jq.mousewheel $(".box").mousewheel(Win_wheel); menu(0); } //菜单+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ var menu_cur = [0, 1, 2, 6, 7, 8] //导航点击跳转页码数组 function menu(n) { if (n > 1 && n < 6) { //判断导航2的页数,如果大于1且小于30,为导航2 n = 2; } if (n > 5) { //判断导航3以下导航的页数,如果大于29,则减去28页。 n = n - 3 } //
Original) { //$("#shuzitext").text("坑爹的!!!") } else { if (id > Original) { dir = 1; } else { dir = -1; } curPage = menu_cur[id]; //$("#shuzitext").text("curPage"+curPage+"上一次值"+Original) Page_inout(curPage, Original) Original = menu_cur[id]; } }//end isScroll }) //卖点菜单点击 function nuin(d) { d = d - 2; $(".innavi_1 a").removeClass("cur") //清空cur for (var i = 0; i <= d; i++) { $(".innavi_1 a").eq(i).addClass("cur").siblings().removeClass("cur") //每个ID添加cur样式 } } $(".innavi_1 a").click(function () { if (isScroll == true) { isScroll = false; var id = $(".innavi_1 a").index($(this)) + 2; //声明ID等于当前值 Original = menu_id; if (id == Original) { // $("#shuzitext").text("坑爹的!!!") } else { nuin(id); //运行方法nuin_cur //fun_into[Math.abs(id)]();//动画进场数组里面放方法 if (id > Original) { dir = 1; } else { dir = -1; } curPage = id //$("#shuzitext").text("curPage"+curPage+"上一次值"+Original) Page_inout(curPage, Original) Original = id; } } }) //配置表限制滚动翻页------------------------------------------ var phototrue = true; /*$('.photo').mouseover(function(){ phototrue=false; }) $('.photo').mouseout(function(){ phototrue=true; })*/ $('#ui-id-1,#ui-id-2,#ui-id-3,.heise,.yysj').mouseover(function () { phototrue = false; }) $('#ui-id-1,#ui-id-2,#ui-id-3,.heise,.yysj').mouseout(function () { phototrue = true; }) //显示预约试驾,关闭预约试驾 function yuyue() { $('.sjbtn').click(function () { $('.heise,.yysj_gb,.yysj').show(); }) $('.yysj_gb').click(function () { $('.heise,.yysj_gb,.yysj').hide(); }) $('.yycg_btn').click(function () { $('.heise_1,.yycg').hide(); }) } //配置参数 function peizhics() { /*$('#dealerMain').touchslider({ scrollObj : '#dealerBox', scrollBarWrap : '#dealerScrollbarWrap', scrollBar :'#dealerScrollbar', onceScrollH :120 });*/ var h = $('#dealerBox').find('img:eq(0)').height(); $('#dealerBox').height(h); var slider = new Slider({ boxObj: '#dealerMain', sliderObj: '#dealerBox', scrollbarWrap: "#dealerScrollbarWrap", scrollBar: "#dealerScrollbar", barFixed: true, //滚动条固定高度 onceScrollHeight: 200, scale: 1, beforeCallback: function () { isScroll = false; }, afterCallback: function () { isScroll = true; } }); } //调整元素宽高整屏幕自适应++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ var adaptive = function () { var width = $(window).width(), winH = $(window).height(); $('.same').each(function (index, element) { var oh = $(this).attr('oh'); var ow = $(this).attr('ow'); var scale = 0; var height; if (width / initWidth > winH / 900) { scale = width / initWidth; } else { scale = winH / 900; } height = scale * oh; var imgWidth = ow * scale; $(this).height(height + 'px').width(imgWidth + 'px'); }); } //鼠标滚动判断上下事件++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function Touch_start(e) { touch.oy = e.pageY; } function Touch_move(e) { e.preventDefault(); touch.move = true; touch.dy = e.pageY; } function Touch_end(e) { if (touch.move) { touch.move = false; var oy = touch.oy; var y = touch.dy; if (y - oy > 40) Win_wheel(e, 1, 0, 0); else if (oy - y > 40) Win_wheel(e, -1, 0, 0); } } /*鼠标滚动事件 delta=-1下 delta=1上*/ function Win_wheel(e, delta, deltaX, deltaY) { if (isScroll == true) { if (phototrue == true) { //pageNum=-(fun.length-1) dir = (delta > 0 ? -1 : 1);//反转delta 向下+1 向上-1 Original = curPage;//记录上次值 //alert(Original); var $this = $('#shuzitext'), timeoutId = $this.data('timeoutId'); if (timeoutId) { clearTimeout(timeoutId); } else { curPage = curPage + dir; if (curPage < 0) { curPage = 0; return; } if (curPage > pageNum) { curPage = pageNum; return; } Page_inout(curPage, Original) isScroll = false; } //延迟滚动。防止滚动很多次 $this.data('timeoutId', setTimeout(function () { $this.removeData('timeoutId'); $this = null }, 200)); return false; } } } //页面切换方法+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function Page_inout(page_index, page_out) { //page_inde:下页数值,page_out:前面一个 //fun_out[page_out](); //动画出场数组里面放方法 var h = $(window).height() / 900; var dir = page_index > page_out ? 900 : -900; menu_id = page_index; menu(page_index);//菜单传值 //显示卖点导航 if (page_index > 1 && page_index < 6) { nuin(page_index); /*$(".innavi").stop().animate({opacity:"1"},500,hd,function(){});*/ $(".innavi").show(); } else { /*$(".innavi").stop().animate({opacity:"0"},500,hd,function(){});*/ $(".innavi").hide(); } isScroll = false; //eleScrollTop(page_index); //动画进场数组里面放方法 page.eq(page_index).addClass("active").css({ "display": "block", "z-index": "3", "top": dir * h + "px" }).animate({top: "0"}, 800, hd, function () { }); page.eq(page_out).addClass("active_out").css({ "display": "block", "z-index": "1", "top": "0px" }).animate({top: -dir * h + "px"}, 800, hd, function () { //fun_into[Math.abs(page_index)](); //动画进场数组里面放方法 isScroll = true; page.eq(page_out).removeClass("active").css("display", "none"); dh(page_index); //运行动画 }); } //判断滑动时,动画的运行方法 function dh(TextNumber) { switch (TextNumber) { case 0: //首页 into_0(); out_1(); break; case 1: //视频 into_1(); out_0(); break; case 2: //精美车图 out_1(); break; case 3: //精美车图 break; case 4: //精美车图 break; case 5: //精美车图 out_2(); break; case 6: //媒体评测 into_2(); out_3(); break; case 7: //车型配置 into_3(); out_2(); out_4(); break; case 8: //车型配置 into_4(); out_3(); break; } } //首页动画 function into_0() { $(".sy_a1").stop().animate({opacity: "1", left: "15.8%"}, 600, hd, function () { $(".sy_a2").stop().animate({opacity: "1", bottom: "3.22%"}, 600, hd, function () { }).css({flter: "Alpha(Opacity=100)"}); }).css({flter: "Alpha(Opacity=100)"}); $(".sy_a3").stop().delay(300).animate({opacity: "1"}, 600, hd, function () { }).css({flter: "Alpha(Opacity=100)"}); } /* .sy_a1{ position:absolute; top:17.8%; left:20.8%; z-index:1; opacity:0; filter:Alpha(Opacity=0);} .sy_a2{ position:absolute; bottom:5%; left:6.1%; z-index:1; opacity:0; filter:Alpha(Opacity=0);} */ function out_0() { $(".sy_a1").stop().animate({opacity: "0", left: "20.8%"}, 100, hd, function () { }).css({flter: "Alpha(Opacity=0)"}); $(".sy_a2").stop().animate({opacity: "0", bottom: "-1%"}, 100, hd, function () { }).css({flter: "Alpha(Opacity=0)"}); $(".sy_a3").stop().animate({opacity: "0"}, 100, hd, function () { }).css({flter: "Alpha(Opacity=0)"}); } //新车展示 function into_1() { /*$(".xc_zs").stop().animate({opacity: "1", top: "16%"}, 600, hd, function () { $(".hy_ys").stop().animate({opacity: "1", top: "25.2%"}, 600, hd, function () { $(".video_content").stop().animate({opacity: "1", left: "22%"}, 600, hd, function () { }).css({flter: "Alpha(Opacity=100)"}); }).css({flter: "Alpha(Opacity=100)"}); }).css({flter: "Alpha(Opacity=100)"});*/ } /* .xc_zs{ position:absolute; left:0; top:21%; opacity:0; filter:Alpha(Opacity=0);} .hy_ys{position:absolute; left:0; top:30.2%; opacity:0; filter:Alpha(Opacity=0);} .video_content{ position:absolute; top:36.2%; left:27%; z-index:10; opacity:0; filter:Alpha(Opacity=0);} */ function out_1() { /*$(".xc_zs").stop().animate({opacity: "0", top: "21%"}, 100, hd, function () { }).css({flter: "Alpha(Opacity=0)"}); $(".hy_ys").stop().animate({opacity: "0", top: "30.2%"}, 100, hd, function () { }).css({flter: "Alpha(Opacity=0)"}); $(".video_content").stop().animate({opacity: "0", left: "27%"}, 100, hd, function () { }).css({flter: "Alpha(Opacity=0)"});*/ } //媒体评测 function into_2() { $(".ban").stop().animate({opacity: "1", marginTop: "-222.5px"}, 600, hd, function () { }).css({flter: "Alpha(Opacity=100)"}); } /* .ban{ width:1002px; height:445px; position:absolute; overflow:hidden; top:50%; left:50%; margin-left:-501px; margin-top:-122.5px; z-index:5; opacity:0; filter:Alpha(Opacity=0);} */ function out_2() { $(".ban").stop().animate({opacity: "0", marginTop: "-122.5px"}, 100, hd, function () { }).css({flter: "Alpha(Opacity=0)"}); } //车型配置 function into_3() { $(".pzb_2").stop().animate({opacity: "1", marginTop: "-216px"}, 600, hd, function () { }).css({flter: "Alpha(Opacity=100)"}); } /* .pzb_2{position:absolute; top:50%; margin-left:-633.5px; margin-top:-192px; left:50%; z-index:1; width:1267px; height:584px; opacity:0; filter:Alpha(Opacity=0);} */ function out_3() { $(".pzb_2").stop().animate({opacity: "0", marginTop: "-192px"}, 100, hd, function () { }).css({flter: "Alpha(Opacity=0)"}); } //车型配置 function into_4() { $(".dealerInfo").stop().animate({opacity: "1"}, 600, hd, function () { }).css({flter: "Alpha(Opacity=100)"}); } function out_4() { $(".dealerInfo").stop().animate({opacity: "0"}, 100, hd, function () { }).css({flter: "Alpha(Opacity=0)"}); } //loading function Loading_Act() { /* TweenMax.set("#Loading_Rect",{transformOrigin:"0 0"}); var tl=new TimelineMax({repeat:-1,repeatDelay:0.3}); tl.to("#Loading_Rect",0.65,{left:60,top:40,rotation:-90,ease:Cubic.easeInOut},"t1") .to("#Loading_Rect",0.65,{left:100,top:40,rotation:-180,ease:Cubic.easeInOut},"t2") .to("#Loading_c",0.45,{rotation:90,ease:Cubic.easeInOut},"t1+=0.2") .to("#Loading_c",0.45,{rotation:180,ease:Cubic.easeInOut},"t2+=0.2");*/ // $.get("main.html",function(c){ // Stage.me.append(c); // Win.me.resize(Stage_resize); // Stage_resize(); var imgs = $("#box img");//加载资源 Loading.total = imgs.length; imgs.each(function () { if (this.complete) { loading(); } else { $(this).load(loading).error(loading); } }); if (Loading.loaded == Loading.total) { loading_over(); } function loading() { Loading.loaded++; var d = Math.ceil(Loading.loaded * 100 / Loading.total); if (Loading.loaded == Loading.total) { imgs.off("load error"); loading_over(); } else { $("#Loading_num").html(d); } } function loading_over() { $("#Loading_num").html("100"); // tl.tweenTo(tl.duration(),{onComplete:function(){ // tl.clear(); var tl2 = new TimelineMax({ onComplete: function () { $("#Loading").remove(); $("#box").css({"display": "block"}) //$("#box").show(); init(); into_0() //运行动画方法 //Stage.me.removeClass("dn"); //$(".Box:eq(0)").addClass("on"); ////内容事件初始化 //Main_event(); //Home_Act(); } }); tl2.to("#Loading_Rect", 0.6, {opacity: 0, ease: Quad.easeOut}, "t1") .to("#Loading", 0.85, {opacity: 0, ease: Quad.easeInOut}, "t1+=0.2"); // }}); } // }); }
alert(n) $("#menu ul li").removeClass("cur") $("#menu ul li").eq(n).addClass("cur") for (var i = 0; i < 5; i++) { //导航添加背景置顶 $("#menu ul li").eq(i).css({"background-position": "right bottom"}) } } $("#menu ul li").click(function () { //isScroll 防止点击过快 if (isScroll == true) { var id = $("#menu ul li").index($(this)); menu(menu_cur[id]); Original = menu_id; //$("#shuzitext").text(menu_id) if (menu_cur[id] ==
identifier_body
page.js
// page scroll var sw = $(window).width() var initWidth = 1920; var hd = "easeOutQuad"//缓动 var Speed_ = 400; var box = $("#box"); var page = $(".page"); var pageNum = 7;//总页数 var curPage = 0;//当前页数 var Original = 0;//记录前一帧页数 var isScroll = true;//结束后才能点击 var menu_id = 0; var dir = 1; var Loading = {total: 0, loaded: 0, tl: null}; //load方法 $(function () { adaptive(); //调整元素宽高整屏幕自适应 $(window).resize(adaptive); //窗口调整大小 Loading_Act(); //运行LOAD方法 init(); peizhics() //配置表 yuyue()//预约试驾显示 }); //初始化+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function init() { pageNum = page.length - 1;//总页数赋值 //运行滚动插件jq.mousewheel $(".box").mousewheel(Win_wheel); menu(0); } //菜单+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ var menu_cur = [0, 1, 2, 6, 7, 8] //导航点击跳转页码数组 function menu(n) { if (n > 1 && n < 6) { //判断导航2的页数,如果大于1且小于30,为导航2 n = 2; } if (n > 5) { //判断导航3以下导航的页数,如果大于29,则减去28页。 n = n - 3 } //alert(n) $("#menu ul li").removeClass("cur") $("#menu ul li").eq(n).addClass("cur") for (var i = 0; i < 5; i++) { //导航添加背景置顶 $("#menu ul li").eq(i).css({"background-position": "right bottom"}) } } $("#menu ul li").click(function () { //isScroll 防止点击过快 if (isScroll == true) { var id = $("#menu ul li").index($(this)); menu(menu_cur[id]); Original = menu_id; //$("#shuzitext").text(menu_id) if (menu_cur[id] == Original) { //$("#shuzitext").text("坑爹的!!!") } else { if (id > Original) { dir = 1; } else { dir = -1; } curPage = menu_cur[id]; //$("#shuzitext").text("curPage"+curPage+"上一次值"+Original) Page_inout(curPage, Original) Original = menu_cur[id]; } }//end isScroll }) //卖点菜单点击 function nuin(d) { d = d - 2; $(".innavi_1 a").removeClass("cur") //清空cur for (var i = 0; i <= d; i++) { $(".innavi_1 a").eq(i).addClass("cur").siblings().removeClass("cur") //每个ID添加cur样式 } } $(".innavi_1 a").click(function () { if (isScroll == true) { isScroll = false; var id = $(".innavi_1 a").index($(this)) + 2; //声明ID等于当前值 Original = menu_id; if (id == Original) { // $("#shuzitext").text("坑爹的!!!") } else { nuin(id); //运行方法nuin_cur //fun_into[Math.abs(id)]();//动画进场数组里面放方法 if (id > Original) { dir = 1; } else { dir = -1; } curPage = id //$("#shuzitext").text("curPage"+curPage+"上一次值"+Original) Page_inout(curPage, Original) Original = id; } } }) //配置表限制滚动翻页------------------------------------------ var phototrue = true; /*$('.photo').mouseover(function(){ phototrue=false; }) $('.photo').mouseout(function(){ phototrue=true; })*/ $('#ui-id-1,#ui-id-2,#ui-id-3,.heise,.yysj').mouseover(function () { phototrue = false; }) $('#ui-id-1,#ui-id-2,#ui-id-3,.heise,.yysj').mouseout(function () { phototrue = true; }) //显示预约试驾,关闭预约试驾 function yuyue() { $('.sjbtn').click(function () { $('.heise,.yysj_gb,.yysj').show(); }) $('.yysj_gb').click(function () { $('.heise,.yysj_gb,.yysj').hide(); }) $('.yycg_btn').click(function () { $('.heise_1,.yycg').hide(); }) } //配置参数 function peizhics() { /*$('#dealerMain').touchslider({ scrollObj : '#dealerBox', scrollBarWrap : '#dealerScrollbarWrap', scrollBar :'#dealerScrollbar', onceScrollH :120 });*/ var h = $('#dealerBox').find('img:eq(0)').height(); $('#dealerBox').height(h); var slider = new Slider({ boxObj: '#dealerMain', sliderObj: '#dealerBox', scrollbarWrap: "#dealerScrollbarWrap", scrollBar: "#dealerScrollbar", barFixed: true, //滚动条固定高度 onceScrollHeight: 200, scale: 1, beforeCallback: function () { isScroll = false; }, afterCallback: function () { isScroll = true; } }); } //调整元素宽高整屏幕自适应++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ var adaptive = function () { var width = $(window).width(), winH = $(window).height(); $('.same').each(function (index, element) { var oh = $(this).attr('oh'); var ow = $(this).attr('ow'); var scale = 0; var height; if (width / initWidth > winH / 900) { scale = width / initWidth; } else { scale = winH / 900; } height = scale * oh; var imgWidth = ow * scale; $(this).height(height + 'px').width(imgWidth + 'px'); }); } //鼠标滚动判断上下事件++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function Touch_start(e) { touch.oy = e.pageY; } function Touch_move(e) { e.preventDefault(); touch.move = true; touch.dy = e.pageY; } function Touch_end(e) { if (touch.move) { touch.move = false; var oy = touch.oy; var y = touch.dy; if (y - oy > 40) Win_wheel(e, 1, 0, 0); else if (oy - y > 40) Win_wheel(e, -1, 0, 0); } } /*鼠标滚动事件 delta=-1下 delta=1上*/ function Win_wheel(e, delta, deltaX, deltaY) { if (isScroll == true) { if (phototrue == true) { //pageNum=-(fun.length-1) dir = (delta > 0 ? -1 : 1);//反转delta 向下+1 向上-1 Original = curPage;//记录上次值 //alert(Original); var $this = $('#shuzitext'), timeoutId = $this.data('timeoutId'); if (timeoutId) { clearTimeout(timeoutId); } else { curPage = curPage + dir; if (curPage < 0) { curPage = 0; return;
,function(){});*/ $(".innavi").show(); } else { /*$(".innavi").stop().animate({opacity:"0"},500,hd,function(){});*/ $(".innavi").hide(); } isScroll = false; //eleScrollTop(page_index); //动画进场数组里面放方法 page.eq(page_index).addClass("active").css({ "display": "block", "z-index": "3", "top": dir * h + "px" }).animate({top: "0"}, 800, hd, function () { }); page.eq(page_out).addClass("active_out").css({ "display": "block", "z-index": "1", "top": "0px" }).animate({top: -dir * h + "px"}, 800, hd, function () { //fun_into[Math.abs(page_index)](); //动画进场数组里面放方法 isScroll = true; page.eq(page_out).removeClass("active").css("display", "none"); dh(page_index); //运行动画 }); } //判断滑动时,动画的运行方法 function dh(TextNumber) { switch (TextNumber) { case 0: //首页 into_0(); out_1(); break; case 1: //视频 into_1(); out_0(); break; case 2: //精美车图 out_1(); break; case 3: //精美车图 break; case 4: //精美车图 break; case 5: //精美车图 out_2(); break; case 6: //媒体评测 into_2(); out_3(); break; case 7: //车型配置 into_3(); out_2(); out_4(); break; case 8: //车型配置 into_4(); out_3(); break; } } //首页动画 function into_0() { $(".sy_a1").stop().animate({opacity: "1", left: "15.8%"}, 600, hd, function () { $(".sy_a2").stop().animate({opacity: "1", bottom: "3.22%"}, 600, hd, function () { }).css({flter: "Alpha(Opacity=100)"}); }).css({flter: "Alpha(Opacity=100)"}); $(".sy_a3").stop().delay(300).animate({opacity: "1"}, 600, hd, function () { }).css({flter: "Alpha(Opacity=100)"}); } /* .sy_a1{ position:absolute; top:17.8%; left:20.8%; z-index:1; opacity:0; filter:Alpha(Opacity=0);} .sy_a2{ position:absolute; bottom:5%; left:6.1%; z-index:1; opacity:0; filter:Alpha(Opacity=0);} */ function out_0() { $(".sy_a1").stop().animate({opacity: "0", left: "20.8%"}, 100, hd, function () { }).css({flter: "Alpha(Opacity=0)"}); $(".sy_a2").stop().animate({opacity: "0", bottom: "-1%"}, 100, hd, function () { }).css({flter: "Alpha(Opacity=0)"}); $(".sy_a3").stop().animate({opacity: "0"}, 100, hd, function () { }).css({flter: "Alpha(Opacity=0)"}); } //新车展示 function into_1() { /*$(".xc_zs").stop().animate({opacity: "1", top: "16%"}, 600, hd, function () { $(".hy_ys").stop().animate({opacity: "1", top: "25.2%"}, 600, hd, function () { $(".video_content").stop().animate({opacity: "1", left: "22%"}, 600, hd, function () { }).css({flter: "Alpha(Opacity=100)"}); }).css({flter: "Alpha(Opacity=100)"}); }).css({flter: "Alpha(Opacity=100)"});*/ } /* .xc_zs{ position:absolute; left:0; top:21%; opacity:0; filter:Alpha(Opacity=0);} .hy_ys{position:absolute; left:0; top:30.2%; opacity:0; filter:Alpha(Opacity=0);} .video_content{ position:absolute; top:36.2%; left:27%; z-index:10; opacity:0; filter:Alpha(Opacity=0);} */ function out_1() { /*$(".xc_zs").stop().animate({opacity: "0", top: "21%"}, 100, hd, function () { }).css({flter: "Alpha(Opacity=0)"}); $(".hy_ys").stop().animate({opacity: "0", top: "30.2%"}, 100, hd, function () { }).css({flter: "Alpha(Opacity=0)"}); $(".video_content").stop().animate({opacity: "0", left: "27%"}, 100, hd, function () { }).css({flter: "Alpha(Opacity=0)"});*/ } //媒体评测 function into_2() { $(".ban").stop().animate({opacity: "1", marginTop: "-222.5px"}, 600, hd, function () { }).css({flter: "Alpha(Opacity=100)"}); } /* .ban{ width:1002px; height:445px; position:absolute; overflow:hidden; top:50%; left:50%; margin-left:-501px; margin-top:-122.5px; z-index:5; opacity:0; filter:Alpha(Opacity=0);} */ function out_2() { $(".ban").stop().animate({opacity: "0", marginTop: "-122.5px"}, 100, hd, function () { }).css({flter: "Alpha(Opacity=0)"}); } //车型配置 function into_3() { $(".pzb_2").stop().animate({opacity: "1", marginTop: "-216px"}, 600, hd, function () { }).css({flter: "Alpha(Opacity=100)"}); } /* .pzb_2{position:absolute; top:50%; margin-left:-633.5px; margin-top:-192px; left:50%; z-index:1; width:1267px; height:584px; opacity:0; filter:Alpha(Opacity=0);} */ function out_3() { $(".pzb_2").stop().animate({opacity: "0", marginTop: "-192px"}, 100, hd, function () { }).css({flter: "Alpha(Opacity=0)"}); } //车型配置 function into_4() { $(".dealerInfo").stop().animate({opacity: "1"}, 600, hd, function () { }).css({flter: "Alpha(Opacity=100)"}); } function out_4() { $(".dealerInfo").stop().animate({opacity: "0"}, 100, hd, function () { }).css({flter: "Alpha(Opacity=0)"}); } //loading function Loading_Act() { /* TweenMax.set("#Loading_Rect",{transformOrigin:"0 0"}); var tl=new TimelineMax({repeat:-1,repeatDelay:0.3}); tl.to("#Loading_Rect",0.65,{left:60,top:40,rotation:-90,ease:Cubic.easeInOut},"t1") .to("#Loading_Rect",0.65,{left:100,top:40,rotation:-180,ease:Cubic.easeInOut},"t2") .to("#Loading_c",0.45,{rotation:90,ease:Cubic.easeInOut},"t1+=0.2") .to("#Loading_c",0.45,{rotation:180,ease:Cubic.easeInOut},"t2+=0.2");*/ // $.get("main.html",function(c){ // Stage.me.append(c); // Win.me.resize(Stage_resize); // Stage_resize(); var imgs = $("#box img");//加载资源 Loading.total = imgs.length; imgs.each(function () { if (this.complete) { loading(); } else { $(this).load(loading).error(loading); } }); if (Loading.loaded == Loading.total) { loading_over(); } function loading() { Loading.loaded++; var d = Math.ceil(Loading.loaded * 100 / Loading.total); if (Loading.loaded == Loading.total) { imgs.off("load error"); loading_over(); } else { $("#Loading_num").html(d); } } function loading_over() { $("#Loading_num").html("100"); // tl.tweenTo(tl.duration(),{onComplete:function(){ // tl.clear(); var tl2 = new TimelineMax({ onComplete: function () { $("#Loading").remove(); $("#box").css({"display": "block"}) //$("#box").show(); init(); into_0() //运行动画方法 //Stage.me.removeClass("dn"); //$(".Box:eq(0)").addClass("on"); ////内容事件初始化 //Main_event(); //Home_Act(); } }); tl2.to("#Loading_Rect", 0.6, {opacity: 0, ease: Quad.easeOut}, "t1") .to("#Loading", 0.85, {opacity: 0, ease: Quad.easeInOut}, "t1+=0.2"); // }}); } // }); }
} if (curPage > pageNum) { curPage = pageNum; return; } Page_inout(curPage, Original) isScroll = false; } //延迟滚动。防止滚动很多次 $this.data('timeoutId', setTimeout(function () { $this.removeData('timeoutId'); $this = null }, 200)); return false; } } } //页面切换方法+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ function Page_inout(page_index, page_out) { //page_inde:下页数值,page_out:前面一个 //fun_out[page_out](); //动画出场数组里面放方法 var h = $(window).height() / 900; var dir = page_index > page_out ? 900 : -900; menu_id = page_index; menu(page_index);//菜单传值 //显示卖点导航 if (page_index > 1 && page_index < 6) { nuin(page_index); /*$(".innavi").stop().animate({opacity:"1"},500,hd
conditional_block
index.js
function createXmlForQuestions() { var doc = document.implementation.createDocument("", "", null); var quiz = doc.createElement("quiz"); // Create initial category to make sure we're in the right place. // If wildcards are used, we need to order those questions last for processing. createCategory(quiz, doc, $('#category').val()); // Order by if wildcards are used (put last). var questionElems = $('#questions').children(); var noWildcardQuestions = []; var wildcardQuestions = []; questionElems.each(function () { var qid = $(this).find('.col-md-12').attr('data-qid'); if (qid === "NUMBER") { return; } var text = $(this).find('#question-text-' + qid).data('editor').getContents(); // If it has wildcards... if (/{.*}/gi.test(text)) { wildcardQuestions.push($(this)); } else { noWildcardQuestions.push($(this)); } }); // Concat the wildcard at the end. noWildcardQuestions.concat(wildcardQuestions).forEach(function(elem) { getQuestion(quiz, doc, $(elem)) }); doc.appendChild(quiz); var serializer = new XMLSerializer(); var xmlString = serializer.serializeToString(doc); $('#delete-me').remove(); var filename = "Moodle EQG Questions.xml"; var pom = document.createElement('a'); var bb = new Blob(['<?xml version="1.0" encoding="UTF-8"?>'+xmlString], {type: 'text/plain'}); pom.setAttribute('href', window.URL.createObjectURL(bb)); pom.setAttribute('download', filename); pom.setAttribute('id', 'delete-me'); pom.dataset.downloadurl = ['text/plain', pom.download, pom.href].join(':'); pom.draggable = true; pom.classList.add('dragout'); pom.click(); //$('#dump').text('<?xml version="1.0" encoding="UTF-8"?>' + xmlString); } function getQuestion(quiz, doc, qElem) { // Takes in the XML creator and adds to it for the question. var qid = qElem.find('.col-md-12').attr('data-qid'); if (qid === 'NUMBER') { return; } var name = qElem.find('#question-name-' + qid).val(); var text = qElem.find('#question-text-' + qid).data('editor').getContents(); var hasWildcards = /{.*}/gi.test(text); var mark = qElem.find('#question-default-mark-' + qid).val(); var genFeed = qElem.find('#question-general-feedback-' + qid).data('editor').getContents(); var format = qElem.find('#question-response-format-' + qid).val(); var reqText = qElem.find('#question-require-text-' + qid).val(); var boxSize = qElem.find('#question-input-box-' + qid).val(); var graderInfo = qElem.find('#question-grader-info-' + qid).data('editor').getContents(); var responseTemplate = qElem.find('#question-response-template-' + qid).data('editor').getContents(); if (!hasWildcards) { createXmlForQuestion(quiz, doc, qid, name, text, mark, genFeed, format, reqText, boxSize, graderInfo, responseTemplate); } else { var orWildcards = Array.from(text.matchAll(/{.*?[\|].*?}/gi)); var rangeWildcards = Array.from(text.matchAll(/{[\d-]+}/gi)); var orWildcardsFiltered = []; // Filter out duplicate wildcard matches (when a user uses multiple of the same wildcard we treat them as one). var matchedVals = []; orWildcards.forEach(function (wildcard) { // Not present so push to filtered. if (matchedVals.indexOf(wildcard[0]) === -1) { matchedVals.push(wildcard[0]); orWildcardsFiltered.push(wildcard); } }); // Create a category for this question, it will not have a single question but many, many questions. createCategory(quiz, doc, name + '-' + qid, $('#category').val()) var wildcardValues = []; // Process all or wildcards together, adding to the wildcard values array of arrays. orWildcardsFiltered.forEach(function (wildcard) { var possibleValues = wildcard[0].replace('{', '').replace('}', '').split('|'); wildcardValues.push(possibleValues); }); console.log(wildcardValues); // Boom, generate all combinations possible with the wildcards given for the supplied text. var questionsToCreate = generateAllCombinationsOfText(wildcardValues, matchedVals, text); console.log(questionsToCreate); // Create questions for all. questionsToCreate.forEach(function (val, idx) { createXmlForQuestion(quiz, doc, qid, name + idx, val, mark, genFeed, format, reqText, boxSize, graderInfo, responseTemplate); }); } } function
(quiz, doc, qid, name, text, mark, genFeed, format, reqText, boxSize, graderInfo, responseTemplate) { console.log(qid, name, text, mark, genFeed, format, reqText, boxSize, graderInfo, responseTemplate); var q = doc.createElement('question'); q.setAttribute('type', 'essay'); // Question Name. var qName = doc.createElement('name'); createTextElementWithValue(doc, qName, name, false); q.appendChild(qName); // Question Text. var qText = doc.createElement('questiontext'); qText.setAttribute('format', 'html'); createTextElementWithValue(doc, qText, text, true); q.appendChild(qText); // General Feedback. var qGeneralFeedback = doc.createElement('generalfeedback'); qGeneralFeedback.setAttribute('format', 'html'); createTextElementWithValue(doc, qGeneralFeedback, genFeed, true); q.appendChild(qGeneralFeedback); // Default Grade createTextElementWithValue(doc, q, parseFloat(mark), false, 'defaultgrade'); // Penalty: unimplemented. createTextElementWithValue(doc, q, parseFloat(0), false, 'penalty'); // Hidden: unimplemented. createTextElementWithValue(doc, q, '0', false, 'hidden'); // ID Number: unimplemented. createTextElementWithValue(doc, q, '', false, 'idnumber'); // Response Format createTextElementWithValue(doc, q, format, false, 'responseformat'); // Response Required createTextElementWithValue(doc, q, reqText, false, 'responserequired'); // Input box size createTextElementWithValue(doc, q, boxSize, false, 'responsefieldlines'); // Attachments: unimplemented. var attachments = format === 'editorfilepicker' ? 1 : 0; createTextElementWithValue(doc, q, attachments, false, 'attachments'); // Attachments required: unimplemented. createTextElementWithValue(doc, q, '0', false, 'attachmentsrequired'); // Grader feedback/info. var qGraderInfo = doc.createElement('graderinfo'); qGraderInfo.setAttribute('format', 'html'); createTextElementWithValue(doc, qGraderInfo, graderInfo, true); q.appendChild(qGraderInfo); // Response Template. var qRespTemplate = doc.createElement('responsetemplate'); qRespTemplate.setAttribute('format', 'html'); createTextElementWithValue(doc, qRespTemplate, responseTemplate, true); q.appendChild(qRespTemplate); quiz.appendChild(q); } function createTextElementWithValue(doc, appender, value, isCDATA, elemName) { var textNode = doc.createElement(elemName || 'text'); var v = isCDATA ? doc.createCDATASection(value) : doc.createTextNode(value); textNode.appendChild(v); appender.appendChild(textNode); } function createCategory(quiz, doc, categoryName, previousCategory) { if (previousCategory === undefined) { previousCategory = ''; } else { previousCategory += '/'; } var q = doc.createElement('question'); q.setAttribute('type', 'category'); var qCat = doc.createElement('category'); createTextElementWithValue(doc, qCat, '$course$/top/' + previousCategory + categoryName, false); q.appendChild(qCat); var qInfo = doc.createElement('info'); qInfo.setAttribute('format', 'html'); createTextElementWithValue(doc, qInfo, 'Category for ' + previousCategory + categoryName, false); q.appendChild(qInfo); createTextElementWithValue(doc, q, '', false, 'idnumber'); quiz.appendChild(q); } var kothingEditorOptions = { display: "block", width: "100%", height: "200px", popupDisplay: "full", toolbarItem: [ ["undo", "redo"], ["formatBlock"], [ "bold", "underline", "italic", "strike", "subscript", "superscript", "fontColor", "hiliteColor", ], ["outdent", "indent", "align", "list", "horizontalRule"], ["link", "table", "image"], ["lineHeight", "paragraphStyle", "textStyle"], ["showBlocks", "codeView"], ["preview", "fullScreen"], ["removeFormat"], ], charCounter: true, }; $(document).ready(function () { $('#add-question').click(function () { var template = $('#question-template').clone(); var appendTo = $('#questions'); var newQuestionNumber = appendTo.children().length; template.css('display', 'block'); template.removeAttr('id'); template.html(function() { return $(this).html().replace(/NUMBER/g, newQuestionNumber); }); appendTo.append(template); $('#question-general-feedback-' + newQuestionNumber).data('editor', KothingEditor.create('question-general-feedback-' + newQuestionNumber, kothingEditorOptions)); $('#question-grader-info-' + newQuestionNumber).data('editor', KothingEditor.create('question-grader-info-' + newQuestionNumber, kothingEditorOptions)); $('#question-response-template-' + newQuestionNumber).data('editor', KothingEditor.create('question-response-template-' + newQuestionNumber, kothingEditorOptions)); $('#question-text-' + newQuestionNumber).data('editor', KothingEditor.create('question-text-' + newQuestionNumber, kothingEditorOptions)); }); $('#generate').click(createXmlForQuestions); });
createXmlForQuestion
identifier_name
index.js
function createXmlForQuestions() { var doc = document.implementation.createDocument("", "", null); var quiz = doc.createElement("quiz"); // Create initial category to make sure we're in the right place. // If wildcards are used, we need to order those questions last for processing. createCategory(quiz, doc, $('#category').val()); // Order by if wildcards are used (put last). var questionElems = $('#questions').children(); var noWildcardQuestions = []; var wildcardQuestions = []; questionElems.each(function () { var qid = $(this).find('.col-md-12').attr('data-qid'); if (qid === "NUMBER") { return; } var text = $(this).find('#question-text-' + qid).data('editor').getContents(); // If it has wildcards... if (/{.*}/gi.test(text)) { wildcardQuestions.push($(this)); } else { noWildcardQuestions.push($(this)); } }); // Concat the wildcard at the end. noWildcardQuestions.concat(wildcardQuestions).forEach(function(elem) { getQuestion(quiz, doc, $(elem)) }); doc.appendChild(quiz); var serializer = new XMLSerializer(); var xmlString = serializer.serializeToString(doc); $('#delete-me').remove(); var filename = "Moodle EQG Questions.xml"; var pom = document.createElement('a'); var bb = new Blob(['<?xml version="1.0" encoding="UTF-8"?>'+xmlString], {type: 'text/plain'}); pom.setAttribute('href', window.URL.createObjectURL(bb)); pom.setAttribute('download', filename); pom.setAttribute('id', 'delete-me'); pom.dataset.downloadurl = ['text/plain', pom.download, pom.href].join(':'); pom.draggable = true; pom.classList.add('dragout'); pom.click(); //$('#dump').text('<?xml version="1.0" encoding="UTF-8"?>' + xmlString); } function getQuestion(quiz, doc, qElem) { // Takes in the XML creator and adds to it for the question. var qid = qElem.find('.col-md-12').attr('data-qid'); if (qid === 'NUMBER') { return; } var name = qElem.find('#question-name-' + qid).val(); var text = qElem.find('#question-text-' + qid).data('editor').getContents(); var hasWildcards = /{.*}/gi.test(text); var mark = qElem.find('#question-default-mark-' + qid).val(); var genFeed = qElem.find('#question-general-feedback-' + qid).data('editor').getContents(); var format = qElem.find('#question-response-format-' + qid).val(); var reqText = qElem.find('#question-require-text-' + qid).val(); var boxSize = qElem.find('#question-input-box-' + qid).val(); var graderInfo = qElem.find('#question-grader-info-' + qid).data('editor').getContents(); var responseTemplate = qElem.find('#question-response-template-' + qid).data('editor').getContents(); if (!hasWildcards) { createXmlForQuestion(quiz, doc, qid, name, text, mark, genFeed, format, reqText, boxSize, graderInfo, responseTemplate); } else { var orWildcards = Array.from(text.matchAll(/{.*?[\|].*?}/gi)); var rangeWildcards = Array.from(text.matchAll(/{[\d-]+}/gi)); var orWildcardsFiltered = []; // Filter out duplicate wildcard matches (when a user uses multiple of the same wildcard we treat them as one). var matchedVals = []; orWildcards.forEach(function (wildcard) { // Not present so push to filtered. if (matchedVals.indexOf(wildcard[0]) === -1) { matchedVals.push(wildcard[0]); orWildcardsFiltered.push(wildcard); } }); // Create a category for this question, it will not have a single question but many, many questions. createCategory(quiz, doc, name + '-' + qid, $('#category').val()) var wildcardValues = []; // Process all or wildcards together, adding to the wildcard values array of arrays. orWildcardsFiltered.forEach(function (wildcard) { var possibleValues = wildcard[0].replace('{', '').replace('}', '').split('|'); wildcardValues.push(possibleValues); }); console.log(wildcardValues); // Boom, generate all combinations possible with the wildcards given for the supplied text. var questionsToCreate = generateAllCombinationsOfText(wildcardValues, matchedVals, text); console.log(questionsToCreate); // Create questions for all. questionsToCreate.forEach(function (val, idx) { createXmlForQuestion(quiz, doc, qid, name + idx, val, mark, genFeed, format, reqText, boxSize, graderInfo, responseTemplate); }); } } function createXmlForQuestion(quiz, doc, qid, name, text, mark, genFeed, format, reqText, boxSize, graderInfo, responseTemplate) { console.log(qid, name, text, mark, genFeed, format, reqText, boxSize, graderInfo, responseTemplate); var q = doc.createElement('question'); q.setAttribute('type', 'essay'); // Question Name. var qName = doc.createElement('name'); createTextElementWithValue(doc, qName, name, false); q.appendChild(qName); // Question Text. var qText = doc.createElement('questiontext'); qText.setAttribute('format', 'html'); createTextElementWithValue(doc, qText, text, true); q.appendChild(qText); // General Feedback. var qGeneralFeedback = doc.createElement('generalfeedback'); qGeneralFeedback.setAttribute('format', 'html'); createTextElementWithValue(doc, qGeneralFeedback, genFeed, true); q.appendChild(qGeneralFeedback); // Default Grade createTextElementWithValue(doc, q, parseFloat(mark), false, 'defaultgrade'); // Penalty: unimplemented. createTextElementWithValue(doc, q, parseFloat(0), false, 'penalty'); // Hidden: unimplemented. createTextElementWithValue(doc, q, '0', false, 'hidden'); // ID Number: unimplemented. createTextElementWithValue(doc, q, '', false, 'idnumber'); // Response Format createTextElementWithValue(doc, q, format, false, 'responseformat'); // Response Required createTextElementWithValue(doc, q, reqText, false, 'responserequired'); // Input box size createTextElementWithValue(doc, q, boxSize, false, 'responsefieldlines'); // Attachments: unimplemented. var attachments = format === 'editorfilepicker' ? 1 : 0; createTextElementWithValue(doc, q, attachments, false, 'attachments'); // Attachments required: unimplemented. createTextElementWithValue(doc, q, '0', false, 'attachmentsrequired'); // Grader feedback/info. var qGraderInfo = doc.createElement('graderinfo'); qGraderInfo.setAttribute('format', 'html'); createTextElementWithValue(doc, qGraderInfo, graderInfo, true); q.appendChild(qGraderInfo); // Response Template. var qRespTemplate = doc.createElement('responsetemplate'); qRespTemplate.setAttribute('format', 'html'); createTextElementWithValue(doc, qRespTemplate, responseTemplate, true); q.appendChild(qRespTemplate); quiz.appendChild(q); } function createTextElementWithValue(doc, appender, value, isCDATA, elemName) { var textNode = doc.createElement(elemName || 'text'); var v = isCDATA ? doc.createCDATASection(value) : doc.createTextNode(value); textNode.appendChild(v); appender.appendChild(textNode); } function createCategory(quiz, doc, categoryName, previousCategory) { if (previousCategory === undefined) { previousCategory = ''; } else { previousCategory += '/'; } var q = doc.createElement('question'); q.setAttribute('type', 'category'); var qCat = doc.createElement('category'); createTextElementWithValue(doc, qCat, '$course$/top/' + previousCategory + categoryName, false); q.appendChild(qCat); var qInfo = doc.createElement('info'); qInfo.setAttribute('format', 'html'); createTextElementWithValue(doc, qInfo, 'Category for ' + previousCategory + categoryName, false); q.appendChild(qInfo); createTextElementWithValue(doc, q, '', false, 'idnumber'); quiz.appendChild(q); } var kothingEditorOptions = { display: "block", width: "100%", height: "200px", popupDisplay: "full", toolbarItem: [ ["undo", "redo"], ["formatBlock"], [ "bold", "underline", "italic", "strike", "subscript", "superscript", "fontColor", "hiliteColor", ], ["outdent", "indent", "align", "list", "horizontalRule"], ["link", "table", "image"], ["lineHeight", "paragraphStyle", "textStyle"], ["showBlocks", "codeView"], ["preview", "fullScreen"], ["removeFormat"], ], charCounter: true, }; $(document).ready(function () { $('#add-question').click(function () { var template = $('#question-template').clone(); var appendTo = $('#questions'); var newQuestionNumber = appendTo.children().length; template.css('display', 'block');
return $(this).html().replace(/NUMBER/g, newQuestionNumber); }); appendTo.append(template); $('#question-general-feedback-' + newQuestionNumber).data('editor', KothingEditor.create('question-general-feedback-' + newQuestionNumber, kothingEditorOptions)); $('#question-grader-info-' + newQuestionNumber).data('editor', KothingEditor.create('question-grader-info-' + newQuestionNumber, kothingEditorOptions)); $('#question-response-template-' + newQuestionNumber).data('editor', KothingEditor.create('question-response-template-' + newQuestionNumber, kothingEditorOptions)); $('#question-text-' + newQuestionNumber).data('editor', KothingEditor.create('question-text-' + newQuestionNumber, kothingEditorOptions)); }); $('#generate').click(createXmlForQuestions); });
template.removeAttr('id'); template.html(function() {
random_line_split
index.js
function createXmlForQuestions() { var doc = document.implementation.createDocument("", "", null); var quiz = doc.createElement("quiz"); // Create initial category to make sure we're in the right place. // If wildcards are used, we need to order those questions last for processing. createCategory(quiz, doc, $('#category').val()); // Order by if wildcards are used (put last). var questionElems = $('#questions').children(); var noWildcardQuestions = []; var wildcardQuestions = []; questionElems.each(function () { var qid = $(this).find('.col-md-12').attr('data-qid'); if (qid === "NUMBER") { return; } var text = $(this).find('#question-text-' + qid).data('editor').getContents(); // If it has wildcards... if (/{.*}/gi.test(text)) { wildcardQuestions.push($(this)); } else { noWildcardQuestions.push($(this)); } }); // Concat the wildcard at the end. noWildcardQuestions.concat(wildcardQuestions).forEach(function(elem) { getQuestion(quiz, doc, $(elem)) }); doc.appendChild(quiz); var serializer = new XMLSerializer(); var xmlString = serializer.serializeToString(doc); $('#delete-me').remove(); var filename = "Moodle EQG Questions.xml"; var pom = document.createElement('a'); var bb = new Blob(['<?xml version="1.0" encoding="UTF-8"?>'+xmlString], {type: 'text/plain'}); pom.setAttribute('href', window.URL.createObjectURL(bb)); pom.setAttribute('download', filename); pom.setAttribute('id', 'delete-me'); pom.dataset.downloadurl = ['text/plain', pom.download, pom.href].join(':'); pom.draggable = true; pom.classList.add('dragout'); pom.click(); //$('#dump').text('<?xml version="1.0" encoding="UTF-8"?>' + xmlString); } function getQuestion(quiz, doc, qElem)
function createXmlForQuestion(quiz, doc, qid, name, text, mark, genFeed, format, reqText, boxSize, graderInfo, responseTemplate) { console.log(qid, name, text, mark, genFeed, format, reqText, boxSize, graderInfo, responseTemplate); var q = doc.createElement('question'); q.setAttribute('type', 'essay'); // Question Name. var qName = doc.createElement('name'); createTextElementWithValue(doc, qName, name, false); q.appendChild(qName); // Question Text. var qText = doc.createElement('questiontext'); qText.setAttribute('format', 'html'); createTextElementWithValue(doc, qText, text, true); q.appendChild(qText); // General Feedback. var qGeneralFeedback = doc.createElement('generalfeedback'); qGeneralFeedback.setAttribute('format', 'html'); createTextElementWithValue(doc, qGeneralFeedback, genFeed, true); q.appendChild(qGeneralFeedback); // Default Grade createTextElementWithValue(doc, q, parseFloat(mark), false, 'defaultgrade'); // Penalty: unimplemented. createTextElementWithValue(doc, q, parseFloat(0), false, 'penalty'); // Hidden: unimplemented. createTextElementWithValue(doc, q, '0', false, 'hidden'); // ID Number: unimplemented. createTextElementWithValue(doc, q, '', false, 'idnumber'); // Response Format createTextElementWithValue(doc, q, format, false, 'responseformat'); // Response Required createTextElementWithValue(doc, q, reqText, false, 'responserequired'); // Input box size createTextElementWithValue(doc, q, boxSize, false, 'responsefieldlines'); // Attachments: unimplemented. var attachments = format === 'editorfilepicker' ? 1 : 0; createTextElementWithValue(doc, q, attachments, false, 'attachments'); // Attachments required: unimplemented. createTextElementWithValue(doc, q, '0', false, 'attachmentsrequired'); // Grader feedback/info. var qGraderInfo = doc.createElement('graderinfo'); qGraderInfo.setAttribute('format', 'html'); createTextElementWithValue(doc, qGraderInfo, graderInfo, true); q.appendChild(qGraderInfo); // Response Template. var qRespTemplate = doc.createElement('responsetemplate'); qRespTemplate.setAttribute('format', 'html'); createTextElementWithValue(doc, qRespTemplate, responseTemplate, true); q.appendChild(qRespTemplate); quiz.appendChild(q); } function createTextElementWithValue(doc, appender, value, isCDATA, elemName) { var textNode = doc.createElement(elemName || 'text'); var v = isCDATA ? doc.createCDATASection(value) : doc.createTextNode(value); textNode.appendChild(v); appender.appendChild(textNode); } function createCategory(quiz, doc, categoryName, previousCategory) { if (previousCategory === undefined) { previousCategory = ''; } else { previousCategory += '/'; } var q = doc.createElement('question'); q.setAttribute('type', 'category'); var qCat = doc.createElement('category'); createTextElementWithValue(doc, qCat, '$course$/top/' + previousCategory + categoryName, false); q.appendChild(qCat); var qInfo = doc.createElement('info'); qInfo.setAttribute('format', 'html'); createTextElementWithValue(doc, qInfo, 'Category for ' + previousCategory + categoryName, false); q.appendChild(qInfo); createTextElementWithValue(doc, q, '', false, 'idnumber'); quiz.appendChild(q); } var kothingEditorOptions = { display: "block", width: "100%", height: "200px", popupDisplay: "full", toolbarItem: [ ["undo", "redo"], ["formatBlock"], [ "bold", "underline", "italic", "strike", "subscript", "superscript", "fontColor", "hiliteColor", ], ["outdent", "indent", "align", "list", "horizontalRule"], ["link", "table", "image"], ["lineHeight", "paragraphStyle", "textStyle"], ["showBlocks", "codeView"], ["preview", "fullScreen"], ["removeFormat"], ], charCounter: true, }; $(document).ready(function () { $('#add-question').click(function () { var template = $('#question-template').clone(); var appendTo = $('#questions'); var newQuestionNumber = appendTo.children().length; template.css('display', 'block'); template.removeAttr('id'); template.html(function() { return $(this).html().replace(/NUMBER/g, newQuestionNumber); }); appendTo.append(template); $('#question-general-feedback-' + newQuestionNumber).data('editor', KothingEditor.create('question-general-feedback-' + newQuestionNumber, kothingEditorOptions)); $('#question-grader-info-' + newQuestionNumber).data('editor', KothingEditor.create('question-grader-info-' + newQuestionNumber, kothingEditorOptions)); $('#question-response-template-' + newQuestionNumber).data('editor', KothingEditor.create('question-response-template-' + newQuestionNumber, kothingEditorOptions)); $('#question-text-' + newQuestionNumber).data('editor', KothingEditor.create('question-text-' + newQuestionNumber, kothingEditorOptions)); }); $('#generate').click(createXmlForQuestions); });
{ // Takes in the XML creator and adds to it for the question. var qid = qElem.find('.col-md-12').attr('data-qid'); if (qid === 'NUMBER') { return; } var name = qElem.find('#question-name-' + qid).val(); var text = qElem.find('#question-text-' + qid).data('editor').getContents(); var hasWildcards = /{.*}/gi.test(text); var mark = qElem.find('#question-default-mark-' + qid).val(); var genFeed = qElem.find('#question-general-feedback-' + qid).data('editor').getContents(); var format = qElem.find('#question-response-format-' + qid).val(); var reqText = qElem.find('#question-require-text-' + qid).val(); var boxSize = qElem.find('#question-input-box-' + qid).val(); var graderInfo = qElem.find('#question-grader-info-' + qid).data('editor').getContents(); var responseTemplate = qElem.find('#question-response-template-' + qid).data('editor').getContents(); if (!hasWildcards) { createXmlForQuestion(quiz, doc, qid, name, text, mark, genFeed, format, reqText, boxSize, graderInfo, responseTemplate); } else { var orWildcards = Array.from(text.matchAll(/{.*?[\|].*?}/gi)); var rangeWildcards = Array.from(text.matchAll(/{[\d-]+}/gi)); var orWildcardsFiltered = []; // Filter out duplicate wildcard matches (when a user uses multiple of the same wildcard we treat them as one). var matchedVals = []; orWildcards.forEach(function (wildcard) { // Not present so push to filtered. if (matchedVals.indexOf(wildcard[0]) === -1) { matchedVals.push(wildcard[0]); orWildcardsFiltered.push(wildcard); } }); // Create a category for this question, it will not have a single question but many, many questions. createCategory(quiz, doc, name + '-' + qid, $('#category').val()) var wildcardValues = []; // Process all or wildcards together, adding to the wildcard values array of arrays. orWildcardsFiltered.forEach(function (wildcard) { var possibleValues = wildcard[0].replace('{', '').replace('}', '').split('|'); wildcardValues.push(possibleValues); }); console.log(wildcardValues); // Boom, generate all combinations possible with the wildcards given for the supplied text. var questionsToCreate = generateAllCombinationsOfText(wildcardValues, matchedVals, text); console.log(questionsToCreate); // Create questions for all. questionsToCreate.forEach(function (val, idx) { createXmlForQuestion(quiz, doc, qid, name + idx, val, mark, genFeed, format, reqText, boxSize, graderInfo, responseTemplate); }); } }
identifier_body
index.js
function createXmlForQuestions() { var doc = document.implementation.createDocument("", "", null); var quiz = doc.createElement("quiz"); // Create initial category to make sure we're in the right place. // If wildcards are used, we need to order those questions last for processing. createCategory(quiz, doc, $('#category').val()); // Order by if wildcards are used (put last). var questionElems = $('#questions').children(); var noWildcardQuestions = []; var wildcardQuestions = []; questionElems.each(function () { var qid = $(this).find('.col-md-12').attr('data-qid'); if (qid === "NUMBER") { return; } var text = $(this).find('#question-text-' + qid).data('editor').getContents(); // If it has wildcards... if (/{.*}/gi.test(text))
else { noWildcardQuestions.push($(this)); } }); // Concat the wildcard at the end. noWildcardQuestions.concat(wildcardQuestions).forEach(function(elem) { getQuestion(quiz, doc, $(elem)) }); doc.appendChild(quiz); var serializer = new XMLSerializer(); var xmlString = serializer.serializeToString(doc); $('#delete-me').remove(); var filename = "Moodle EQG Questions.xml"; var pom = document.createElement('a'); var bb = new Blob(['<?xml version="1.0" encoding="UTF-8"?>'+xmlString], {type: 'text/plain'}); pom.setAttribute('href', window.URL.createObjectURL(bb)); pom.setAttribute('download', filename); pom.setAttribute('id', 'delete-me'); pom.dataset.downloadurl = ['text/plain', pom.download, pom.href].join(':'); pom.draggable = true; pom.classList.add('dragout'); pom.click(); //$('#dump').text('<?xml version="1.0" encoding="UTF-8"?>' + xmlString); } function getQuestion(quiz, doc, qElem) { // Takes in the XML creator and adds to it for the question. var qid = qElem.find('.col-md-12').attr('data-qid'); if (qid === 'NUMBER') { return; } var name = qElem.find('#question-name-' + qid).val(); var text = qElem.find('#question-text-' + qid).data('editor').getContents(); var hasWildcards = /{.*}/gi.test(text); var mark = qElem.find('#question-default-mark-' + qid).val(); var genFeed = qElem.find('#question-general-feedback-' + qid).data('editor').getContents(); var format = qElem.find('#question-response-format-' + qid).val(); var reqText = qElem.find('#question-require-text-' + qid).val(); var boxSize = qElem.find('#question-input-box-' + qid).val(); var graderInfo = qElem.find('#question-grader-info-' + qid).data('editor').getContents(); var responseTemplate = qElem.find('#question-response-template-' + qid).data('editor').getContents(); if (!hasWildcards) { createXmlForQuestion(quiz, doc, qid, name, text, mark, genFeed, format, reqText, boxSize, graderInfo, responseTemplate); } else { var orWildcards = Array.from(text.matchAll(/{.*?[\|].*?}/gi)); var rangeWildcards = Array.from(text.matchAll(/{[\d-]+}/gi)); var orWildcardsFiltered = []; // Filter out duplicate wildcard matches (when a user uses multiple of the same wildcard we treat them as one). var matchedVals = []; orWildcards.forEach(function (wildcard) { // Not present so push to filtered. if (matchedVals.indexOf(wildcard[0]) === -1) { matchedVals.push(wildcard[0]); orWildcardsFiltered.push(wildcard); } }); // Create a category for this question, it will not have a single question but many, many questions. createCategory(quiz, doc, name + '-' + qid, $('#category').val()) var wildcardValues = []; // Process all or wildcards together, adding to the wildcard values array of arrays. orWildcardsFiltered.forEach(function (wildcard) { var possibleValues = wildcard[0].replace('{', '').replace('}', '').split('|'); wildcardValues.push(possibleValues); }); console.log(wildcardValues); // Boom, generate all combinations possible with the wildcards given for the supplied text. var questionsToCreate = generateAllCombinationsOfText(wildcardValues, matchedVals, text); console.log(questionsToCreate); // Create questions for all. questionsToCreate.forEach(function (val, idx) { createXmlForQuestion(quiz, doc, qid, name + idx, val, mark, genFeed, format, reqText, boxSize, graderInfo, responseTemplate); }); } } function createXmlForQuestion(quiz, doc, qid, name, text, mark, genFeed, format, reqText, boxSize, graderInfo, responseTemplate) { console.log(qid, name, text, mark, genFeed, format, reqText, boxSize, graderInfo, responseTemplate); var q = doc.createElement('question'); q.setAttribute('type', 'essay'); // Question Name. var qName = doc.createElement('name'); createTextElementWithValue(doc, qName, name, false); q.appendChild(qName); // Question Text. var qText = doc.createElement('questiontext'); qText.setAttribute('format', 'html'); createTextElementWithValue(doc, qText, text, true); q.appendChild(qText); // General Feedback. var qGeneralFeedback = doc.createElement('generalfeedback'); qGeneralFeedback.setAttribute('format', 'html'); createTextElementWithValue(doc, qGeneralFeedback, genFeed, true); q.appendChild(qGeneralFeedback); // Default Grade createTextElementWithValue(doc, q, parseFloat(mark), false, 'defaultgrade'); // Penalty: unimplemented. createTextElementWithValue(doc, q, parseFloat(0), false, 'penalty'); // Hidden: unimplemented. createTextElementWithValue(doc, q, '0', false, 'hidden'); // ID Number: unimplemented. createTextElementWithValue(doc, q, '', false, 'idnumber'); // Response Format createTextElementWithValue(doc, q, format, false, 'responseformat'); // Response Required createTextElementWithValue(doc, q, reqText, false, 'responserequired'); // Input box size createTextElementWithValue(doc, q, boxSize, false, 'responsefieldlines'); // Attachments: unimplemented. var attachments = format === 'editorfilepicker' ? 1 : 0; createTextElementWithValue(doc, q, attachments, false, 'attachments'); // Attachments required: unimplemented. createTextElementWithValue(doc, q, '0', false, 'attachmentsrequired'); // Grader feedback/info. var qGraderInfo = doc.createElement('graderinfo'); qGraderInfo.setAttribute('format', 'html'); createTextElementWithValue(doc, qGraderInfo, graderInfo, true); q.appendChild(qGraderInfo); // Response Template. var qRespTemplate = doc.createElement('responsetemplate'); qRespTemplate.setAttribute('format', 'html'); createTextElementWithValue(doc, qRespTemplate, responseTemplate, true); q.appendChild(qRespTemplate); quiz.appendChild(q); } function createTextElementWithValue(doc, appender, value, isCDATA, elemName) { var textNode = doc.createElement(elemName || 'text'); var v = isCDATA ? doc.createCDATASection(value) : doc.createTextNode(value); textNode.appendChild(v); appender.appendChild(textNode); } function createCategory(quiz, doc, categoryName, previousCategory) { if (previousCategory === undefined) { previousCategory = ''; } else { previousCategory += '/'; } var q = doc.createElement('question'); q.setAttribute('type', 'category'); var qCat = doc.createElement('category'); createTextElementWithValue(doc, qCat, '$course$/top/' + previousCategory + categoryName, false); q.appendChild(qCat); var qInfo = doc.createElement('info'); qInfo.setAttribute('format', 'html'); createTextElementWithValue(doc, qInfo, 'Category for ' + previousCategory + categoryName, false); q.appendChild(qInfo); createTextElementWithValue(doc, q, '', false, 'idnumber'); quiz.appendChild(q); } var kothingEditorOptions = { display: "block", width: "100%", height: "200px", popupDisplay: "full", toolbarItem: [ ["undo", "redo"], ["formatBlock"], [ "bold", "underline", "italic", "strike", "subscript", "superscript", "fontColor", "hiliteColor", ], ["outdent", "indent", "align", "list", "horizontalRule"], ["link", "table", "image"], ["lineHeight", "paragraphStyle", "textStyle"], ["showBlocks", "codeView"], ["preview", "fullScreen"], ["removeFormat"], ], charCounter: true, }; $(document).ready(function () { $('#add-question').click(function () { var template = $('#question-template').clone(); var appendTo = $('#questions'); var newQuestionNumber = appendTo.children().length; template.css('display', 'block'); template.removeAttr('id'); template.html(function() { return $(this).html().replace(/NUMBER/g, newQuestionNumber); }); appendTo.append(template); $('#question-general-feedback-' + newQuestionNumber).data('editor', KothingEditor.create('question-general-feedback-' + newQuestionNumber, kothingEditorOptions)); $('#question-grader-info-' + newQuestionNumber).data('editor', KothingEditor.create('question-grader-info-' + newQuestionNumber, kothingEditorOptions)); $('#question-response-template-' + newQuestionNumber).data('editor', KothingEditor.create('question-response-template-' + newQuestionNumber, kothingEditorOptions)); $('#question-text-' + newQuestionNumber).data('editor', KothingEditor.create('question-text-' + newQuestionNumber, kothingEditorOptions)); }); $('#generate').click(createXmlForQuestions); });
{ wildcardQuestions.push($(this)); }
conditional_block
main.rs
#![no_std] #![no_main] #![feature(global_asm, asm, naked_functions)] #![feature(panic_info_message)] #[macro_use] extern crate bitflags; use volatile::Volatile; use lcd::*; use gpu::FramebufferConfig; use core::ptr::{read_volatile, write_volatile}; use core::{str, fmt, cmp, mem}; use core::fmt::{Write, UpperHex, Binary}; use common::input::GamePad; use common::util::reg::*; use common::Console; use common::mem::arm11::*; use num_traits::PrimInt; mod lcd; mod gpu; mod panic; mod mpcore; mod boot11; mod exceptions; const SCREEN_TOP_WIDTH: usize = 400; const SCREEN_BOTTOM_WIDTH: usize = 320; const SCREEN_HEIGHT: usize = 240; const SCREEN_TOP_FBSIZE: usize = (3 * SCREEN_TOP_WIDTH * SCREEN_HEIGHT); const SCREEN_BOTTOM_FBSIZE: usize = (3 * SCREEN_BOTTOM_WIDTH * SCREEN_HEIGHT); global_asm!(r#" .section .text.start .global _start .align 4 .arm _start: cpsid aif, #0x13 ldr r0, =0x24000000 mov sp, r0 blx _rust_start .pool "#); const FERRIS: &[u8] = include_bytes!("../../ferris.data"); #[no_mangle] pub unsafe extern "C" fn _rust_start() -> ! { exceptions::install_handlers(); // mpcore::enable_scu(); // mpcore::enable_smp_mode(); // mpcore::disable_interrupts(); // mpcore::clean_and_invalidate_data_cache(); // if mpcore::cpu_id() == 0 { // boot11::start_cpu(1, _start); // loop {} // } common::start(); busy_sleep(1000); let fb_top = core::slice::from_raw_parts_mut::<[u8; 3]>(0x18000000 as *mut _, SCREEN_TOP_FBSIZE / 3); init_screens(fb_top); { for (pixel, ferris_pixel) in fb_top.iter_mut().zip(FERRIS.chunks(3)) { write_volatile(&mut pixel[0], ferris_pixel[2]); write_volatile(&mut pixel[1], ferris_pixel[1]); write_volatile(&mut pixel[2], ferris_pixel[0]); } } let ref mut console = Console::new(fb_top, 400, 240); let mut pad = GamePad::new(); let mut bg_color = U32HexEditor::new(0); let mut fg_color = U32HexEditor::new(0xFFFFFF00); let mut fg_selected = false; loop { console.go_to(0, 0); let base = AXI_WRAM.end - 0x60; print_addr::<u32>(console, base + 0x10, "svc vector instr"); print_addr::<u32>(console, base + 0x10, "svc vector addr"); print_addr_bin::<u16>(console, 0x10146000, "pad"); writeln!(console, "cpsr = 0b{:032b}", mpcore::cpu_status_reg()).ok(); static mut N: u32 = 0; writeln!(console, "frame {}", N).ok(); N = N.wrapping_add(1); if !pad.l() && pad.y_once() { fg_selected = !fg_selected; } console.set_bg(u32_to_rgb(bg_color.value())); console.set_fg(u32_to_rgb(fg_color.value())); { if !fg_selected { bg_color.manipulate(&pad); } write!(console, "bg_color = ").ok(); bg_color.render_with_cursor(console, !fg_selected); writeln!(console, "").ok(); } { if fg_selected { fg_color.manipulate(&pad); } write!(console, "fg_color = ").ok(); fg_color.render_with_cursor(console, fg_selected); writeln!(console, "").ok(); } // trigger svc if pad.l() && pad.a() { asm!("svc 42"); } // trigger data abort if pad.l() && pad.b() { RW::<usize>::new(0).write(42); } // trigger prefetch abort if pad.l() && pad.y() { asm!("bkpt"); } // trigger undefined instruction if pad.l() && pad.x() { asm!(".word 0xFFFFFFFF"); } pad.poll(); } } struct U32HexEditor { cursor_pos: usize, value: u32, } impl U32HexEditor { const fn new(value: u32) -> Self { Self { cursor_pos: 0, value, } } fn cursor_left(&mut self) { self.cursor_pos += 1; self.cursor_pos %= 8; } fn cursor_right(&mut self) { self.cursor_pos += 8 - 1; self.cursor_pos %= 8; } fn increment(&mut self) { self.modify(|digit| { *digit += 1; *digit %= 16; }) } fn decrement(&mut self) { self.modify(|digit| { *digit += 16 - 1; *digit %= 16; }) } fn modify(&mut self, f: impl FnOnce(&mut u32)) { let pos = self.cursor_pos * 4; // Extract digit let mut digit = (self.value >> pos) & 0xF; f(&mut digit); digit &= 0xF; // Clear digit self.value &= !(0xF << pos); // Insert digit self.value |= digit << pos; } fn render(&self, console: &mut Console) { self.render_with_cursor(console, true); } fn render_with_cursor(&self, console: &mut Console, with_cursor: bool) { write!(console, "0x").ok(); for cursor_pos in (0..8).rev() { let pos = cursor_pos * 4; let digit = (self.value >> pos) & 0xF; if with_cursor && cursor_pos == self.cursor_pos { console.swap_colors(); } write!(console, "{:X}", digit).ok(); if with_cursor && cursor_pos == self.cursor_pos { console.swap_colors(); } } } fn manipulate(&mut self, pad: &GamePad) { if pad.left_once() { self.cursor_left(); } if pad.right_once() { self.cursor_right(); } if pad.up_once()
if pad.down_once() { self.decrement(); } } fn set_value(&mut self, value: u32) { self.value = value; } fn value(&self) -> u32 { self.value } } pub unsafe fn init_screens(top_fb: &mut [[u8; 3]]) { let brightness_level = 0xFEFE; (*(0x10141200 as *mut Volatile<u32>)).write(0x1007F); (*(0x10202204 as *mut Volatile<u32>)).write(0x01000000); //set LCD fill black to hide potential garbage -- NFIRM does it before firmlaunching (*(0x10202A04 as *mut Volatile<u32>)).write(0x01000000); (*(0x10202014 as *mut Volatile<u32>)).write(0x00000001); (*(0x1020200C as *mut Volatile<u32>)).update(|v| *v &= 0xFFFEFFFE); (*(0x10202240 as *mut Volatile<u32>)).write(brightness_level); (*(0x10202A40 as *mut Volatile<u32>)).write(brightness_level); (*(0x10202244 as *mut Volatile<u32>)).write(0x1023E); (*(0x10202A44 as *mut Volatile<u32>)).write(0x1023E); //Top screen let mut top_fb_conf = gpu::FramebufferConfig::top(); top_fb_conf.set_pixel_clock(0x1c2); top_fb_conf.set_hblank_timer(0xd1); top_fb_conf.reg(0x08).write(0x1c1); top_fb_conf.reg(0x0c).write(0x1c1); top_fb_conf.set_window_x_start(0); top_fb_conf.set_window_x_end(0xcf); top_fb_conf.set_window_y_start(0xd1); top_fb_conf.reg(0x1c).write(0x01c501c1); top_fb_conf.set_window_y_end(0x10000); top_fb_conf.set_vblank_timer(0x19d); top_fb_conf.reg(0x28).write(0x2); top_fb_conf.reg(0x2c).write(0x192); top_fb_conf.set_vtotal(0x192); top_fb_conf.set_vdisp(0x192); top_fb_conf.set_vertical_data_offset(0x1); top_fb_conf.reg(0x3c).write(0x2); top_fb_conf.reg(0x40).write(0x01960192); top_fb_conf.reg(0x44).write(0); top_fb_conf.reg(0x48).write(0); top_fb_conf.reg(0x5C).write(0x00f00190); top_fb_conf.reg(0x60).write(0x01c100d1); top_fb_conf.reg(0x64).write(0x01920002); top_fb_conf.set_buffer0(top_fb.as_ptr() as _); top_fb_conf.set_buffer1(top_fb.as_ptr() as _); top_fb_conf.set_buffer_format(0x80341); top_fb_conf.reg(0x74).write(0x10501); top_fb_conf.set_shown_buffer(0); top_fb_conf.set_alt_buffer0(top_fb.as_ptr() as _); top_fb_conf.set_alt_buffer1(top_fb.as_ptr() as _); top_fb_conf.set_buffer_stride(0x2D0); top_fb_conf.reg(0x9C).write(0); // Set up color LUT top_fb_conf.set_color_lut_index(0); for i in 0 ..= 255 { top_fb_conf.set_color_lut_color(0x10101 * i); } setup_framebuffers(top_fb.as_ptr() as _); } unsafe fn setup_framebuffers(addr: u32) { (*(0x10202204 as *mut Volatile<u32>)).write(0x01000000); //set LCD fill black to hide potential garbage -- NFIRM does it before firmlaunching (*(0x10202A04 as *mut Volatile<u32>)).write(0x01000000); let mut top_fb_conf = gpu::FramebufferConfig::top(); top_fb_conf.reg(0x68).write(addr); top_fb_conf.reg(0x6c).write(addr); top_fb_conf.reg(0x94).write(addr); top_fb_conf.reg(0x98).write(addr); // (*(0x10400568 as *mut Volatile<u32>)).write((u32)fbs[0].bottom); // (*(0x1040056c as *mut Volatile<u32>)).write((u32)fbs[1].bottom); //Set framebuffer format, framebuffer select and stride top_fb_conf.reg(0x70).write(0x80341); top_fb_conf.reg(0x78).write(0); top_fb_conf.reg(0x90).write(0x2D0); (*(0x10400570 as *mut Volatile<u32>)).write(0x80301); (*(0x10400578 as *mut Volatile<u32>)).write(0); (*(0x10400590 as *mut Volatile<u32>)).write(0x2D0); (*(0x10202204 as *mut Volatile<u32>)).write(0x00000000); //unset LCD fill (*(0x10202A04 as *mut Volatile<u32>)).write(0x00000000); } unsafe fn print_addr<T: PrimInt + UpperHex>(console: &mut Console, addr: usize, label: &'static str) { writeln!(console, "[0x{addr:08X}] = 0x{value:0width$X} {label}", addr = addr, value = RO::<T>::new(addr).read(), width = 2 * mem::size_of::<T>(), label = label, ).ok(); } unsafe fn print_addr_bin<T: PrimInt + Binary>(console: &mut Console, addr: usize, label: &'static str) { writeln!(console, "[0x{addr:08X}] = 0b{value:0width$b} {label}", addr = addr, value = RO::<T>::new(addr).read(), width = 8 * mem::size_of::<T>(), label = label, ).ok(); } fn busy_sleep(iterations: usize) { let n = 42; for _ in 0 .. 15 * iterations { unsafe { read_volatile(&n); } } } fn u32_to_rgb(n: u32) -> [u8; 3] { let c = n.to_be_bytes(); [c[0], c[1], c[2]] }
{ self.increment(); }
conditional_block
main.rs
#![no_std] #![no_main] #![feature(global_asm, asm, naked_functions)] #![feature(panic_info_message)] #[macro_use] extern crate bitflags; use volatile::Volatile; use lcd::*; use gpu::FramebufferConfig; use core::ptr::{read_volatile, write_volatile}; use core::{str, fmt, cmp, mem}; use core::fmt::{Write, UpperHex, Binary}; use common::input::GamePad; use common::util::reg::*; use common::Console; use common::mem::arm11::*; use num_traits::PrimInt; mod lcd; mod gpu; mod panic; mod mpcore; mod boot11; mod exceptions; const SCREEN_TOP_WIDTH: usize = 400; const SCREEN_BOTTOM_WIDTH: usize = 320; const SCREEN_HEIGHT: usize = 240; const SCREEN_TOP_FBSIZE: usize = (3 * SCREEN_TOP_WIDTH * SCREEN_HEIGHT); const SCREEN_BOTTOM_FBSIZE: usize = (3 * SCREEN_BOTTOM_WIDTH * SCREEN_HEIGHT); global_asm!(r#" .section .text.start .global _start .align 4 .arm _start: cpsid aif, #0x13 ldr r0, =0x24000000 mov sp, r0 blx _rust_start .pool "#); const FERRIS: &[u8] = include_bytes!("../../ferris.data"); #[no_mangle] pub unsafe extern "C" fn _rust_start() -> ! { exceptions::install_handlers(); // mpcore::enable_scu(); // mpcore::enable_smp_mode(); // mpcore::disable_interrupts(); // mpcore::clean_and_invalidate_data_cache(); // if mpcore::cpu_id() == 0 { // boot11::start_cpu(1, _start); // loop {} // } common::start(); busy_sleep(1000); let fb_top = core::slice::from_raw_parts_mut::<[u8; 3]>(0x18000000 as *mut _, SCREEN_TOP_FBSIZE / 3); init_screens(fb_top); { for (pixel, ferris_pixel) in fb_top.iter_mut().zip(FERRIS.chunks(3)) { write_volatile(&mut pixel[0], ferris_pixel[2]); write_volatile(&mut pixel[1], ferris_pixel[1]); write_volatile(&mut pixel[2], ferris_pixel[0]); } } let ref mut console = Console::new(fb_top, 400, 240); let mut pad = GamePad::new(); let mut bg_color = U32HexEditor::new(0); let mut fg_color = U32HexEditor::new(0xFFFFFF00); let mut fg_selected = false; loop { console.go_to(0, 0); let base = AXI_WRAM.end - 0x60; print_addr::<u32>(console, base + 0x10, "svc vector instr"); print_addr::<u32>(console, base + 0x10, "svc vector addr"); print_addr_bin::<u16>(console, 0x10146000, "pad"); writeln!(console, "cpsr = 0b{:032b}", mpcore::cpu_status_reg()).ok(); static mut N: u32 = 0; writeln!(console, "frame {}", N).ok(); N = N.wrapping_add(1); if !pad.l() && pad.y_once() { fg_selected = !fg_selected; } console.set_bg(u32_to_rgb(bg_color.value())); console.set_fg(u32_to_rgb(fg_color.value())); { if !fg_selected { bg_color.manipulate(&pad); } write!(console, "bg_color = ").ok(); bg_color.render_with_cursor(console, !fg_selected); writeln!(console, "").ok(); } { if fg_selected { fg_color.manipulate(&pad); } write!(console, "fg_color = ").ok(); fg_color.render_with_cursor(console, fg_selected); writeln!(console, "").ok(); } // trigger svc if pad.l() && pad.a() { asm!("svc 42"); } // trigger data abort if pad.l() && pad.b() { RW::<usize>::new(0).write(42); } // trigger prefetch abort if pad.l() && pad.y() { asm!("bkpt"); } // trigger undefined instruction if pad.l() && pad.x() { asm!(".word 0xFFFFFFFF"); } pad.poll(); } } struct U32HexEditor { cursor_pos: usize, value: u32, } impl U32HexEditor { const fn new(value: u32) -> Self { Self { cursor_pos: 0, value, } } fn cursor_left(&mut self) { self.cursor_pos += 1; self.cursor_pos %= 8; } fn cursor_right(&mut self) { self.cursor_pos += 8 - 1; self.cursor_pos %= 8; } fn increment(&mut self) { self.modify(|digit| { *digit += 1; *digit %= 16; }) } fn decrement(&mut self) { self.modify(|digit| { *digit += 16 - 1; *digit %= 16; }) } fn modify(&mut self, f: impl FnOnce(&mut u32)) { let pos = self.cursor_pos * 4; // Extract digit let mut digit = (self.value >> pos) & 0xF; f(&mut digit); digit &= 0xF; // Clear digit self.value &= !(0xF << pos); // Insert digit self.value |= digit << pos; } fn render(&self, console: &mut Console) { self.render_with_cursor(console, true); } fn render_with_cursor(&self, console: &mut Console, with_cursor: bool) { write!(console, "0x").ok(); for cursor_pos in (0..8).rev() { let pos = cursor_pos * 4; let digit = (self.value >> pos) & 0xF; if with_cursor && cursor_pos == self.cursor_pos { console.swap_colors(); } write!(console, "{:X}", digit).ok(); if with_cursor && cursor_pos == self.cursor_pos { console.swap_colors(); } } } fn manipulate(&mut self, pad: &GamePad) { if pad.left_once() { self.cursor_left(); } if pad.right_once() { self.cursor_right(); } if pad.up_once() { self.increment(); } if pad.down_once() { self.decrement(); } } fn set_value(&mut self, value: u32) { self.value = value; } fn value(&self) -> u32 { self.value } } pub unsafe fn init_screens(top_fb: &mut [[u8; 3]]) { let brightness_level = 0xFEFE; (*(0x10141200 as *mut Volatile<u32>)).write(0x1007F); (*(0x10202204 as *mut Volatile<u32>)).write(0x01000000); //set LCD fill black to hide potential garbage -- NFIRM does it before firmlaunching (*(0x10202A04 as *mut Volatile<u32>)).write(0x01000000); (*(0x10202014 as *mut Volatile<u32>)).write(0x00000001); (*(0x1020200C as *mut Volatile<u32>)).update(|v| *v &= 0xFFFEFFFE); (*(0x10202240 as *mut Volatile<u32>)).write(brightness_level); (*(0x10202A40 as *mut Volatile<u32>)).write(brightness_level); (*(0x10202244 as *mut Volatile<u32>)).write(0x1023E); (*(0x10202A44 as *mut Volatile<u32>)).write(0x1023E); //Top screen let mut top_fb_conf = gpu::FramebufferConfig::top(); top_fb_conf.set_pixel_clock(0x1c2); top_fb_conf.set_hblank_timer(0xd1); top_fb_conf.reg(0x08).write(0x1c1); top_fb_conf.reg(0x0c).write(0x1c1); top_fb_conf.set_window_x_start(0); top_fb_conf.set_window_x_end(0xcf); top_fb_conf.set_window_y_start(0xd1); top_fb_conf.reg(0x1c).write(0x01c501c1); top_fb_conf.set_window_y_end(0x10000); top_fb_conf.set_vblank_timer(0x19d); top_fb_conf.reg(0x28).write(0x2); top_fb_conf.reg(0x2c).write(0x192); top_fb_conf.set_vtotal(0x192); top_fb_conf.set_vdisp(0x192); top_fb_conf.set_vertical_data_offset(0x1); top_fb_conf.reg(0x3c).write(0x2); top_fb_conf.reg(0x40).write(0x01960192); top_fb_conf.reg(0x44).write(0); top_fb_conf.reg(0x48).write(0); top_fb_conf.reg(0x5C).write(0x00f00190); top_fb_conf.reg(0x60).write(0x01c100d1); top_fb_conf.reg(0x64).write(0x01920002); top_fb_conf.set_buffer0(top_fb.as_ptr() as _); top_fb_conf.set_buffer1(top_fb.as_ptr() as _); top_fb_conf.set_buffer_format(0x80341); top_fb_conf.reg(0x74).write(0x10501); top_fb_conf.set_shown_buffer(0); top_fb_conf.set_alt_buffer0(top_fb.as_ptr() as _); top_fb_conf.set_alt_buffer1(top_fb.as_ptr() as _);
// Set up color LUT top_fb_conf.set_color_lut_index(0); for i in 0 ..= 255 { top_fb_conf.set_color_lut_color(0x10101 * i); } setup_framebuffers(top_fb.as_ptr() as _); } unsafe fn setup_framebuffers(addr: u32) { (*(0x10202204 as *mut Volatile<u32>)).write(0x01000000); //set LCD fill black to hide potential garbage -- NFIRM does it before firmlaunching (*(0x10202A04 as *mut Volatile<u32>)).write(0x01000000); let mut top_fb_conf = gpu::FramebufferConfig::top(); top_fb_conf.reg(0x68).write(addr); top_fb_conf.reg(0x6c).write(addr); top_fb_conf.reg(0x94).write(addr); top_fb_conf.reg(0x98).write(addr); // (*(0x10400568 as *mut Volatile<u32>)).write((u32)fbs[0].bottom); // (*(0x1040056c as *mut Volatile<u32>)).write((u32)fbs[1].bottom); //Set framebuffer format, framebuffer select and stride top_fb_conf.reg(0x70).write(0x80341); top_fb_conf.reg(0x78).write(0); top_fb_conf.reg(0x90).write(0x2D0); (*(0x10400570 as *mut Volatile<u32>)).write(0x80301); (*(0x10400578 as *mut Volatile<u32>)).write(0); (*(0x10400590 as *mut Volatile<u32>)).write(0x2D0); (*(0x10202204 as *mut Volatile<u32>)).write(0x00000000); //unset LCD fill (*(0x10202A04 as *mut Volatile<u32>)).write(0x00000000); } unsafe fn print_addr<T: PrimInt + UpperHex>(console: &mut Console, addr: usize, label: &'static str) { writeln!(console, "[0x{addr:08X}] = 0x{value:0width$X} {label}", addr = addr, value = RO::<T>::new(addr).read(), width = 2 * mem::size_of::<T>(), label = label, ).ok(); } unsafe fn print_addr_bin<T: PrimInt + Binary>(console: &mut Console, addr: usize, label: &'static str) { writeln!(console, "[0x{addr:08X}] = 0b{value:0width$b} {label}", addr = addr, value = RO::<T>::new(addr).read(), width = 8 * mem::size_of::<T>(), label = label, ).ok(); } fn busy_sleep(iterations: usize) { let n = 42; for _ in 0 .. 15 * iterations { unsafe { read_volatile(&n); } } } fn u32_to_rgb(n: u32) -> [u8; 3] { let c = n.to_be_bytes(); [c[0], c[1], c[2]] }
top_fb_conf.set_buffer_stride(0x2D0); top_fb_conf.reg(0x9C).write(0);
random_line_split
main.rs
#![no_std] #![no_main] #![feature(global_asm, asm, naked_functions)] #![feature(panic_info_message)] #[macro_use] extern crate bitflags; use volatile::Volatile; use lcd::*; use gpu::FramebufferConfig; use core::ptr::{read_volatile, write_volatile}; use core::{str, fmt, cmp, mem}; use core::fmt::{Write, UpperHex, Binary}; use common::input::GamePad; use common::util::reg::*; use common::Console; use common::mem::arm11::*; use num_traits::PrimInt; mod lcd; mod gpu; mod panic; mod mpcore; mod boot11; mod exceptions; const SCREEN_TOP_WIDTH: usize = 400; const SCREEN_BOTTOM_WIDTH: usize = 320; const SCREEN_HEIGHT: usize = 240; const SCREEN_TOP_FBSIZE: usize = (3 * SCREEN_TOP_WIDTH * SCREEN_HEIGHT); const SCREEN_BOTTOM_FBSIZE: usize = (3 * SCREEN_BOTTOM_WIDTH * SCREEN_HEIGHT); global_asm!(r#" .section .text.start .global _start .align 4 .arm _start: cpsid aif, #0x13 ldr r0, =0x24000000 mov sp, r0 blx _rust_start .pool "#); const FERRIS: &[u8] = include_bytes!("../../ferris.data"); #[no_mangle] pub unsafe extern "C" fn _rust_start() -> ! { exceptions::install_handlers(); // mpcore::enable_scu(); // mpcore::enable_smp_mode(); // mpcore::disable_interrupts(); // mpcore::clean_and_invalidate_data_cache(); // if mpcore::cpu_id() == 0 { // boot11::start_cpu(1, _start); // loop {} // } common::start(); busy_sleep(1000); let fb_top = core::slice::from_raw_parts_mut::<[u8; 3]>(0x18000000 as *mut _, SCREEN_TOP_FBSIZE / 3); init_screens(fb_top); { for (pixel, ferris_pixel) in fb_top.iter_mut().zip(FERRIS.chunks(3)) { write_volatile(&mut pixel[0], ferris_pixel[2]); write_volatile(&mut pixel[1], ferris_pixel[1]); write_volatile(&mut pixel[2], ferris_pixel[0]); } } let ref mut console = Console::new(fb_top, 400, 240); let mut pad = GamePad::new(); let mut bg_color = U32HexEditor::new(0); let mut fg_color = U32HexEditor::new(0xFFFFFF00); let mut fg_selected = false; loop { console.go_to(0, 0); let base = AXI_WRAM.end - 0x60; print_addr::<u32>(console, base + 0x10, "svc vector instr"); print_addr::<u32>(console, base + 0x10, "svc vector addr"); print_addr_bin::<u16>(console, 0x10146000, "pad"); writeln!(console, "cpsr = 0b{:032b}", mpcore::cpu_status_reg()).ok(); static mut N: u32 = 0; writeln!(console, "frame {}", N).ok(); N = N.wrapping_add(1); if !pad.l() && pad.y_once() { fg_selected = !fg_selected; } console.set_bg(u32_to_rgb(bg_color.value())); console.set_fg(u32_to_rgb(fg_color.value())); { if !fg_selected { bg_color.manipulate(&pad); } write!(console, "bg_color = ").ok(); bg_color.render_with_cursor(console, !fg_selected); writeln!(console, "").ok(); } { if fg_selected { fg_color.manipulate(&pad); } write!(console, "fg_color = ").ok(); fg_color.render_with_cursor(console, fg_selected); writeln!(console, "").ok(); } // trigger svc if pad.l() && pad.a() { asm!("svc 42"); } // trigger data abort if pad.l() && pad.b() { RW::<usize>::new(0).write(42); } // trigger prefetch abort if pad.l() && pad.y() { asm!("bkpt"); } // trigger undefined instruction if pad.l() && pad.x() { asm!(".word 0xFFFFFFFF"); } pad.poll(); } } struct U32HexEditor { cursor_pos: usize, value: u32, } impl U32HexEditor { const fn new(value: u32) -> Self { Self { cursor_pos: 0, value, } } fn cursor_left(&mut self) { self.cursor_pos += 1; self.cursor_pos %= 8; } fn cursor_right(&mut self) { self.cursor_pos += 8 - 1; self.cursor_pos %= 8; } fn increment(&mut self) { self.modify(|digit| { *digit += 1; *digit %= 16; }) } fn decrement(&mut self) { self.modify(|digit| { *digit += 16 - 1; *digit %= 16; }) } fn
(&mut self, f: impl FnOnce(&mut u32)) { let pos = self.cursor_pos * 4; // Extract digit let mut digit = (self.value >> pos) & 0xF; f(&mut digit); digit &= 0xF; // Clear digit self.value &= !(0xF << pos); // Insert digit self.value |= digit << pos; } fn render(&self, console: &mut Console) { self.render_with_cursor(console, true); } fn render_with_cursor(&self, console: &mut Console, with_cursor: bool) { write!(console, "0x").ok(); for cursor_pos in (0..8).rev() { let pos = cursor_pos * 4; let digit = (self.value >> pos) & 0xF; if with_cursor && cursor_pos == self.cursor_pos { console.swap_colors(); } write!(console, "{:X}", digit).ok(); if with_cursor && cursor_pos == self.cursor_pos { console.swap_colors(); } } } fn manipulate(&mut self, pad: &GamePad) { if pad.left_once() { self.cursor_left(); } if pad.right_once() { self.cursor_right(); } if pad.up_once() { self.increment(); } if pad.down_once() { self.decrement(); } } fn set_value(&mut self, value: u32) { self.value = value; } fn value(&self) -> u32 { self.value } } pub unsafe fn init_screens(top_fb: &mut [[u8; 3]]) { let brightness_level = 0xFEFE; (*(0x10141200 as *mut Volatile<u32>)).write(0x1007F); (*(0x10202204 as *mut Volatile<u32>)).write(0x01000000); //set LCD fill black to hide potential garbage -- NFIRM does it before firmlaunching (*(0x10202A04 as *mut Volatile<u32>)).write(0x01000000); (*(0x10202014 as *mut Volatile<u32>)).write(0x00000001); (*(0x1020200C as *mut Volatile<u32>)).update(|v| *v &= 0xFFFEFFFE); (*(0x10202240 as *mut Volatile<u32>)).write(brightness_level); (*(0x10202A40 as *mut Volatile<u32>)).write(brightness_level); (*(0x10202244 as *mut Volatile<u32>)).write(0x1023E); (*(0x10202A44 as *mut Volatile<u32>)).write(0x1023E); //Top screen let mut top_fb_conf = gpu::FramebufferConfig::top(); top_fb_conf.set_pixel_clock(0x1c2); top_fb_conf.set_hblank_timer(0xd1); top_fb_conf.reg(0x08).write(0x1c1); top_fb_conf.reg(0x0c).write(0x1c1); top_fb_conf.set_window_x_start(0); top_fb_conf.set_window_x_end(0xcf); top_fb_conf.set_window_y_start(0xd1); top_fb_conf.reg(0x1c).write(0x01c501c1); top_fb_conf.set_window_y_end(0x10000); top_fb_conf.set_vblank_timer(0x19d); top_fb_conf.reg(0x28).write(0x2); top_fb_conf.reg(0x2c).write(0x192); top_fb_conf.set_vtotal(0x192); top_fb_conf.set_vdisp(0x192); top_fb_conf.set_vertical_data_offset(0x1); top_fb_conf.reg(0x3c).write(0x2); top_fb_conf.reg(0x40).write(0x01960192); top_fb_conf.reg(0x44).write(0); top_fb_conf.reg(0x48).write(0); top_fb_conf.reg(0x5C).write(0x00f00190); top_fb_conf.reg(0x60).write(0x01c100d1); top_fb_conf.reg(0x64).write(0x01920002); top_fb_conf.set_buffer0(top_fb.as_ptr() as _); top_fb_conf.set_buffer1(top_fb.as_ptr() as _); top_fb_conf.set_buffer_format(0x80341); top_fb_conf.reg(0x74).write(0x10501); top_fb_conf.set_shown_buffer(0); top_fb_conf.set_alt_buffer0(top_fb.as_ptr() as _); top_fb_conf.set_alt_buffer1(top_fb.as_ptr() as _); top_fb_conf.set_buffer_stride(0x2D0); top_fb_conf.reg(0x9C).write(0); // Set up color LUT top_fb_conf.set_color_lut_index(0); for i in 0 ..= 255 { top_fb_conf.set_color_lut_color(0x10101 * i); } setup_framebuffers(top_fb.as_ptr() as _); } unsafe fn setup_framebuffers(addr: u32) { (*(0x10202204 as *mut Volatile<u32>)).write(0x01000000); //set LCD fill black to hide potential garbage -- NFIRM does it before firmlaunching (*(0x10202A04 as *mut Volatile<u32>)).write(0x01000000); let mut top_fb_conf = gpu::FramebufferConfig::top(); top_fb_conf.reg(0x68).write(addr); top_fb_conf.reg(0x6c).write(addr); top_fb_conf.reg(0x94).write(addr); top_fb_conf.reg(0x98).write(addr); // (*(0x10400568 as *mut Volatile<u32>)).write((u32)fbs[0].bottom); // (*(0x1040056c as *mut Volatile<u32>)).write((u32)fbs[1].bottom); //Set framebuffer format, framebuffer select and stride top_fb_conf.reg(0x70).write(0x80341); top_fb_conf.reg(0x78).write(0); top_fb_conf.reg(0x90).write(0x2D0); (*(0x10400570 as *mut Volatile<u32>)).write(0x80301); (*(0x10400578 as *mut Volatile<u32>)).write(0); (*(0x10400590 as *mut Volatile<u32>)).write(0x2D0); (*(0x10202204 as *mut Volatile<u32>)).write(0x00000000); //unset LCD fill (*(0x10202A04 as *mut Volatile<u32>)).write(0x00000000); } unsafe fn print_addr<T: PrimInt + UpperHex>(console: &mut Console, addr: usize, label: &'static str) { writeln!(console, "[0x{addr:08X}] = 0x{value:0width$X} {label}", addr = addr, value = RO::<T>::new(addr).read(), width = 2 * mem::size_of::<T>(), label = label, ).ok(); } unsafe fn print_addr_bin<T: PrimInt + Binary>(console: &mut Console, addr: usize, label: &'static str) { writeln!(console, "[0x{addr:08X}] = 0b{value:0width$b} {label}", addr = addr, value = RO::<T>::new(addr).read(), width = 8 * mem::size_of::<T>(), label = label, ).ok(); } fn busy_sleep(iterations: usize) { let n = 42; for _ in 0 .. 15 * iterations { unsafe { read_volatile(&n); } } } fn u32_to_rgb(n: u32) -> [u8; 3] { let c = n.to_be_bytes(); [c[0], c[1], c[2]] }
modify
identifier_name
main.rs
#![no_std] #![no_main] #![feature(global_asm, asm, naked_functions)] #![feature(panic_info_message)] #[macro_use] extern crate bitflags; use volatile::Volatile; use lcd::*; use gpu::FramebufferConfig; use core::ptr::{read_volatile, write_volatile}; use core::{str, fmt, cmp, mem}; use core::fmt::{Write, UpperHex, Binary}; use common::input::GamePad; use common::util::reg::*; use common::Console; use common::mem::arm11::*; use num_traits::PrimInt; mod lcd; mod gpu; mod panic; mod mpcore; mod boot11; mod exceptions; const SCREEN_TOP_WIDTH: usize = 400; const SCREEN_BOTTOM_WIDTH: usize = 320; const SCREEN_HEIGHT: usize = 240; const SCREEN_TOP_FBSIZE: usize = (3 * SCREEN_TOP_WIDTH * SCREEN_HEIGHT); const SCREEN_BOTTOM_FBSIZE: usize = (3 * SCREEN_BOTTOM_WIDTH * SCREEN_HEIGHT); global_asm!(r#" .section .text.start .global _start .align 4 .arm _start: cpsid aif, #0x13 ldr r0, =0x24000000 mov sp, r0 blx _rust_start .pool "#); const FERRIS: &[u8] = include_bytes!("../../ferris.data"); #[no_mangle] pub unsafe extern "C" fn _rust_start() -> ! { exceptions::install_handlers(); // mpcore::enable_scu(); // mpcore::enable_smp_mode(); // mpcore::disable_interrupts(); // mpcore::clean_and_invalidate_data_cache(); // if mpcore::cpu_id() == 0 { // boot11::start_cpu(1, _start); // loop {} // } common::start(); busy_sleep(1000); let fb_top = core::slice::from_raw_parts_mut::<[u8; 3]>(0x18000000 as *mut _, SCREEN_TOP_FBSIZE / 3); init_screens(fb_top); { for (pixel, ferris_pixel) in fb_top.iter_mut().zip(FERRIS.chunks(3)) { write_volatile(&mut pixel[0], ferris_pixel[2]); write_volatile(&mut pixel[1], ferris_pixel[1]); write_volatile(&mut pixel[2], ferris_pixel[0]); } } let ref mut console = Console::new(fb_top, 400, 240); let mut pad = GamePad::new(); let mut bg_color = U32HexEditor::new(0); let mut fg_color = U32HexEditor::new(0xFFFFFF00); let mut fg_selected = false; loop { console.go_to(0, 0); let base = AXI_WRAM.end - 0x60; print_addr::<u32>(console, base + 0x10, "svc vector instr"); print_addr::<u32>(console, base + 0x10, "svc vector addr"); print_addr_bin::<u16>(console, 0x10146000, "pad"); writeln!(console, "cpsr = 0b{:032b}", mpcore::cpu_status_reg()).ok(); static mut N: u32 = 0; writeln!(console, "frame {}", N).ok(); N = N.wrapping_add(1); if !pad.l() && pad.y_once() { fg_selected = !fg_selected; } console.set_bg(u32_to_rgb(bg_color.value())); console.set_fg(u32_to_rgb(fg_color.value())); { if !fg_selected { bg_color.manipulate(&pad); } write!(console, "bg_color = ").ok(); bg_color.render_with_cursor(console, !fg_selected); writeln!(console, "").ok(); } { if fg_selected { fg_color.manipulate(&pad); } write!(console, "fg_color = ").ok(); fg_color.render_with_cursor(console, fg_selected); writeln!(console, "").ok(); } // trigger svc if pad.l() && pad.a() { asm!("svc 42"); } // trigger data abort if pad.l() && pad.b() { RW::<usize>::new(0).write(42); } // trigger prefetch abort if pad.l() && pad.y() { asm!("bkpt"); } // trigger undefined instruction if pad.l() && pad.x() { asm!(".word 0xFFFFFFFF"); } pad.poll(); } } struct U32HexEditor { cursor_pos: usize, value: u32, } impl U32HexEditor { const fn new(value: u32) -> Self { Self { cursor_pos: 0, value, } } fn cursor_left(&mut self) { self.cursor_pos += 1; self.cursor_pos %= 8; } fn cursor_right(&mut self) { self.cursor_pos += 8 - 1; self.cursor_pos %= 8; } fn increment(&mut self) { self.modify(|digit| { *digit += 1; *digit %= 16; }) } fn decrement(&mut self) { self.modify(|digit| { *digit += 16 - 1; *digit %= 16; }) } fn modify(&mut self, f: impl FnOnce(&mut u32)) { let pos = self.cursor_pos * 4; // Extract digit let mut digit = (self.value >> pos) & 0xF; f(&mut digit); digit &= 0xF; // Clear digit self.value &= !(0xF << pos); // Insert digit self.value |= digit << pos; } fn render(&self, console: &mut Console) { self.render_with_cursor(console, true); } fn render_with_cursor(&self, console: &mut Console, with_cursor: bool) { write!(console, "0x").ok(); for cursor_pos in (0..8).rev() { let pos = cursor_pos * 4; let digit = (self.value >> pos) & 0xF; if with_cursor && cursor_pos == self.cursor_pos { console.swap_colors(); } write!(console, "{:X}", digit).ok(); if with_cursor && cursor_pos == self.cursor_pos { console.swap_colors(); } } } fn manipulate(&mut self, pad: &GamePad) { if pad.left_once() { self.cursor_left(); } if pad.right_once() { self.cursor_right(); } if pad.up_once() { self.increment(); } if pad.down_once() { self.decrement(); } } fn set_value(&mut self, value: u32) { self.value = value; } fn value(&self) -> u32 { self.value } } pub unsafe fn init_screens(top_fb: &mut [[u8; 3]]) { let brightness_level = 0xFEFE; (*(0x10141200 as *mut Volatile<u32>)).write(0x1007F); (*(0x10202204 as *mut Volatile<u32>)).write(0x01000000); //set LCD fill black to hide potential garbage -- NFIRM does it before firmlaunching (*(0x10202A04 as *mut Volatile<u32>)).write(0x01000000); (*(0x10202014 as *mut Volatile<u32>)).write(0x00000001); (*(0x1020200C as *mut Volatile<u32>)).update(|v| *v &= 0xFFFEFFFE); (*(0x10202240 as *mut Volatile<u32>)).write(brightness_level); (*(0x10202A40 as *mut Volatile<u32>)).write(brightness_level); (*(0x10202244 as *mut Volatile<u32>)).write(0x1023E); (*(0x10202A44 as *mut Volatile<u32>)).write(0x1023E); //Top screen let mut top_fb_conf = gpu::FramebufferConfig::top(); top_fb_conf.set_pixel_clock(0x1c2); top_fb_conf.set_hblank_timer(0xd1); top_fb_conf.reg(0x08).write(0x1c1); top_fb_conf.reg(0x0c).write(0x1c1); top_fb_conf.set_window_x_start(0); top_fb_conf.set_window_x_end(0xcf); top_fb_conf.set_window_y_start(0xd1); top_fb_conf.reg(0x1c).write(0x01c501c1); top_fb_conf.set_window_y_end(0x10000); top_fb_conf.set_vblank_timer(0x19d); top_fb_conf.reg(0x28).write(0x2); top_fb_conf.reg(0x2c).write(0x192); top_fb_conf.set_vtotal(0x192); top_fb_conf.set_vdisp(0x192); top_fb_conf.set_vertical_data_offset(0x1); top_fb_conf.reg(0x3c).write(0x2); top_fb_conf.reg(0x40).write(0x01960192); top_fb_conf.reg(0x44).write(0); top_fb_conf.reg(0x48).write(0); top_fb_conf.reg(0x5C).write(0x00f00190); top_fb_conf.reg(0x60).write(0x01c100d1); top_fb_conf.reg(0x64).write(0x01920002); top_fb_conf.set_buffer0(top_fb.as_ptr() as _); top_fb_conf.set_buffer1(top_fb.as_ptr() as _); top_fb_conf.set_buffer_format(0x80341); top_fb_conf.reg(0x74).write(0x10501); top_fb_conf.set_shown_buffer(0); top_fb_conf.set_alt_buffer0(top_fb.as_ptr() as _); top_fb_conf.set_alt_buffer1(top_fb.as_ptr() as _); top_fb_conf.set_buffer_stride(0x2D0); top_fb_conf.reg(0x9C).write(0); // Set up color LUT top_fb_conf.set_color_lut_index(0); for i in 0 ..= 255 { top_fb_conf.set_color_lut_color(0x10101 * i); } setup_framebuffers(top_fb.as_ptr() as _); } unsafe fn setup_framebuffers(addr: u32) { (*(0x10202204 as *mut Volatile<u32>)).write(0x01000000); //set LCD fill black to hide potential garbage -- NFIRM does it before firmlaunching (*(0x10202A04 as *mut Volatile<u32>)).write(0x01000000); let mut top_fb_conf = gpu::FramebufferConfig::top(); top_fb_conf.reg(0x68).write(addr); top_fb_conf.reg(0x6c).write(addr); top_fb_conf.reg(0x94).write(addr); top_fb_conf.reg(0x98).write(addr); // (*(0x10400568 as *mut Volatile<u32>)).write((u32)fbs[0].bottom); // (*(0x1040056c as *mut Volatile<u32>)).write((u32)fbs[1].bottom); //Set framebuffer format, framebuffer select and stride top_fb_conf.reg(0x70).write(0x80341); top_fb_conf.reg(0x78).write(0); top_fb_conf.reg(0x90).write(0x2D0); (*(0x10400570 as *mut Volatile<u32>)).write(0x80301); (*(0x10400578 as *mut Volatile<u32>)).write(0); (*(0x10400590 as *mut Volatile<u32>)).write(0x2D0); (*(0x10202204 as *mut Volatile<u32>)).write(0x00000000); //unset LCD fill (*(0x10202A04 as *mut Volatile<u32>)).write(0x00000000); } unsafe fn print_addr<T: PrimInt + UpperHex>(console: &mut Console, addr: usize, label: &'static str) { writeln!(console, "[0x{addr:08X}] = 0x{value:0width$X} {label}", addr = addr, value = RO::<T>::new(addr).read(), width = 2 * mem::size_of::<T>(), label = label, ).ok(); } unsafe fn print_addr_bin<T: PrimInt + Binary>(console: &mut Console, addr: usize, label: &'static str) { writeln!(console, "[0x{addr:08X}] = 0b{value:0width$b} {label}", addr = addr, value = RO::<T>::new(addr).read(), width = 8 * mem::size_of::<T>(), label = label, ).ok(); } fn busy_sleep(iterations: usize) { let n = 42; for _ in 0 .. 15 * iterations { unsafe { read_volatile(&n); } } } fn u32_to_rgb(n: u32) -> [u8; 3]
{ let c = n.to_be_bytes(); [c[0], c[1], c[2]] }
identifier_body
call.rs
use super::arch::*; use super::data::{Map, SigAction, Stat, StatVfs, TimeSpec}; use super::error::Result; use super::flag::*; use super::number::*; use core::{mem, ptr}; // Signal restorer extern "C" fn restorer() -> ! { sigreturn().unwrap(); unreachable!(); } /// Close a file pub fn
(fd: usize) -> Result<usize> { unsafe { syscall1(SYS_CLOSE, fd) } } /// Get the current system time pub fn clock_gettime(clock: usize, tp: &mut TimeSpec) -> Result<usize> { unsafe { syscall2(SYS_CLOCK_GETTIME, clock, tp as *mut TimeSpec as usize) } } /// Copy and transform a file descriptor pub fn dup(fd: usize, buf: &[u8]) -> Result<usize> { unsafe { syscall3(SYS_DUP, fd, buf.as_ptr() as usize, buf.len()) } } /// Copy and transform a file descriptor pub fn dup2(fd: usize, newfd: usize, buf: &[u8]) -> Result<usize> { unsafe { syscall4(SYS_DUP2, fd, newfd, buf.as_ptr() as usize, buf.len()) } } /// Exit the current process pub fn exit(status: usize) -> Result<usize> { unsafe { syscall1(SYS_EXIT, status) } } /// Change file permissions pub fn fchmod(fd: usize, mode: u16) -> Result<usize> { unsafe { syscall2(SYS_FCHMOD, fd, mode as usize) } } /// Change file ownership pub fn fchown(fd: usize, uid: u32, gid: u32) -> Result<usize> { unsafe { syscall3(SYS_FCHOWN, fd, uid as usize, gid as usize) } } /// Change file descriptor flags pub fn fcntl(fd: usize, cmd: usize, arg: usize) -> Result<usize> { unsafe { syscall3(SYS_FCNTL, fd, cmd, arg) } } /// Map a file into memory, but with the ability to set the address to map into, either as a hint /// or as a requirement of the map. /// /// # Errors /// `EACCES` - the file descriptor was not open for reading /// `EBADF` - if the file descriptor was invalid /// `ENODEV` - mmapping was not supported /// `EINVAL` - invalid combination of flags /// `EEXIST` - if [`MapFlags::MAP_FIXED`] was set, and the address specified was already in use. /// pub unsafe fn fmap(fd: usize, map: &Map) -> Result<usize> { syscall3(SYS_FMAP, fd, map as *const Map as usize, mem::size_of::<Map>()) } /// Unmap whole (or partial) continous memory-mapped files pub unsafe fn funmap(addr: usize, len: usize) -> Result<usize> { syscall2(SYS_FUNMAP, addr, len) } /// Retrieve the canonical path of a file pub fn fpath(fd: usize, buf: &mut [u8]) -> Result<usize> { unsafe { syscall3(SYS_FPATH, fd, buf.as_mut_ptr() as usize, buf.len()) } } /// Rename a file pub fn frename<T: AsRef<str>>(fd: usize, path: T) -> Result<usize> { unsafe { syscall3(SYS_FRENAME, fd, path.as_ref().as_ptr() as usize, path.as_ref().len()) } } /// Get metadata about a file pub fn fstat(fd: usize, stat: &mut Stat) -> Result<usize> { unsafe { syscall3(SYS_FSTAT, fd, stat as *mut Stat as usize, mem::size_of::<Stat>()) } } /// Get metadata about a filesystem pub fn fstatvfs(fd: usize, stat: &mut StatVfs) -> Result<usize> { unsafe { syscall3(SYS_FSTATVFS, fd, stat as *mut StatVfs as usize, mem::size_of::<StatVfs>()) } } /// Sync a file descriptor to its underlying medium pub fn fsync(fd: usize) -> Result<usize> { unsafe { syscall1(SYS_FSYNC, fd) } } /// Truncate or extend a file to a specified length pub fn ftruncate(fd: usize, len: usize) -> Result<usize> { unsafe { syscall2(SYS_FTRUNCATE, fd, len) } } // Change modify and/or access times pub fn futimens(fd: usize, times: &[TimeSpec]) -> Result<usize> { unsafe { syscall3(SYS_FUTIMENS, fd, times.as_ptr() as usize, times.len() * mem::size_of::<TimeSpec>()) } } /// Fast userspace mutex pub unsafe fn futex(addr: *mut i32, op: usize, val: i32, val2: usize, addr2: *mut i32) -> Result<usize> { syscall5(SYS_FUTEX, addr as usize, op, (val as isize) as usize, val2, addr2 as usize) } /// Get the effective group ID pub fn getegid() -> Result<usize> { unsafe { syscall0(SYS_GETEGID) } } /// Get the effective namespace pub fn getens() -> Result<usize> { unsafe { syscall0(SYS_GETENS) } } /// Get the effective user ID pub fn geteuid() -> Result<usize> { unsafe { syscall0(SYS_GETEUID) } } /// Get the current group ID pub fn getgid() -> Result<usize> { unsafe { syscall0(SYS_GETGID) } } /// Get the current namespace pub fn getns() -> Result<usize> { unsafe { syscall0(SYS_GETNS) } } /// Get the current process ID pub fn getpid() -> Result<usize> { unsafe { syscall0(SYS_GETPID) } } /// Get the process group ID pub fn getpgid(pid: usize) -> Result<usize> { unsafe { syscall1(SYS_GETPGID, pid) } } /// Get the parent process ID pub fn getppid() -> Result<usize> { unsafe { syscall0(SYS_GETPPID) } } /// Get the current user ID pub fn getuid() -> Result<usize> { unsafe { syscall0(SYS_GETUID) } } /// Set the I/O privilege level /// /// # Errors /// /// * `EPERM` - `uid != 0` /// * `EINVAL` - `level > 3` pub unsafe fn iopl(level: usize) -> Result<usize> { syscall1(SYS_IOPL, level) } /// Send a signal `sig` to the process identified by `pid` pub fn kill(pid: usize, sig: usize) -> Result<usize> { unsafe { syscall2(SYS_KILL, pid, sig) } } /// Create a link to a file pub unsafe fn link(old: *const u8, new: *const u8) -> Result<usize> { syscall2(SYS_LINK, old as usize, new as usize) } /// Seek to `offset` bytes in a file descriptor pub fn lseek(fd: usize, offset: isize, whence: usize) -> Result<usize> { unsafe { syscall3(SYS_LSEEK, fd, offset as usize, whence) } } /// Make a new scheme namespace pub fn mkns(schemes: &[[usize; 2]]) -> Result<usize> { unsafe { syscall2(SYS_MKNS, schemes.as_ptr() as usize, schemes.len()) } } /// Change mapping flags pub unsafe fn mprotect(addr: usize, size: usize, flags: MapFlags) -> Result<usize> { syscall3(SYS_MPROTECT, addr, size, flags.bits()) } /// Sleep for the time specified in `req` pub fn nanosleep(req: &TimeSpec, rem: &mut TimeSpec) -> Result<usize> { unsafe { syscall2(SYS_NANOSLEEP, req as *const TimeSpec as usize, rem as *mut TimeSpec as usize) } } /// Open a file pub fn open<T: AsRef<str>>(path: T, flags: usize) -> Result<usize> { unsafe { syscall3(SYS_OPEN, path.as_ref().as_ptr() as usize, path.as_ref().len(), flags) } } /// Allocate frames, linearly in physical memory. /// /// # Errors /// /// * `EPERM` - `uid != 0` /// * `ENOMEM` - the system has run out of available memory pub unsafe fn physalloc(size: usize) -> Result<usize> { syscall1(SYS_PHYSALLOC, size) } /// Allocate frames, linearly in physical memory, with an extra set of flags. If the flags contain /// [`PARTIAL_ALLOC`], this will result in `physalloc3` with `min = 1`. /// /// Refer to the simpler [`physalloc`] and the more complex [`physalloc3`], that this convenience /// function is based on. /// /// # Errors /// /// * `EPERM` - `uid != 0` /// * `ENOMEM` - the system has run out of available memory pub unsafe fn physalloc2(size: usize, flags: usize) -> Result<usize> { let mut ret = 1usize; physalloc3(size, flags, &mut ret) } /// Allocate frames, linearly in physical memory, with an extra set of flags. If the flags contain /// [`PARTIAL_ALLOC`], the `min` parameter specifies the number of frames that have to be allocated /// for this operation to succeed. The return value is the offset of the first frame, and `min` is /// overwritten with the number of frames actually allocated. /// /// Refer to the simpler [`physalloc`] and the simpler library function [`physalloc2`]. /// /// # Errors /// /// * `EPERM` - `uid != 0` /// * `ENOMEM` - the system has run out of available memory /// * `EINVAL` - `min = 0` pub unsafe fn physalloc3(size: usize, flags: usize, min: &mut usize) -> Result<usize> { syscall3(SYS_PHYSALLOC3, size, flags, min as *mut usize as usize) } /// Free physically allocated pages /// /// # Errors /// /// * `EPERM` - `uid != 0` pub unsafe fn physfree(physical_address: usize, size: usize) -> Result<usize> { syscall2(SYS_PHYSFREE, physical_address, size) } /// Map physical memory to virtual memory /// /// # Errors /// /// * `EPERM` - `uid != 0` pub unsafe fn physmap(physical_address: usize, size: usize, flags: PhysmapFlags) -> Result<usize> { syscall3(SYS_PHYSMAP, physical_address, size, flags.bits()) } /// Create a pair of file descriptors referencing the read and write ends of a pipe pub fn pipe2(fds: &mut [usize; 2], flags: usize) -> Result<usize> { unsafe { syscall2(SYS_PIPE2, fds.as_ptr() as usize, flags) } } /// Read from a file descriptor into a buffer pub fn read(fd: usize, buf: &mut [u8]) -> Result<usize> { unsafe { syscall3(SYS_READ, fd, buf.as_mut_ptr() as usize, buf.len()) } } /// Remove a directory pub fn rmdir<T: AsRef<str>>(path: T) -> Result<usize> { unsafe { syscall2(SYS_RMDIR, path.as_ref().as_ptr() as usize, path.as_ref().len()) } } /// Set the process group ID pub fn setpgid(pid: usize, pgid: usize) -> Result<usize> { unsafe { syscall2(SYS_SETPGID, pid, pgid) } } /// Set the current process group IDs pub fn setregid(rgid: usize, egid: usize) -> Result<usize> { unsafe { syscall2(SYS_SETREGID, rgid, egid) } } /// Make a new scheme namespace pub fn setrens(rns: usize, ens: usize) -> Result<usize> { unsafe { syscall2(SYS_SETRENS, rns, ens) } } /// Set the current process user IDs pub fn setreuid(ruid: usize, euid: usize) -> Result<usize> { unsafe { syscall2(SYS_SETREUID, ruid, euid) } } /// Set up a signal handler pub fn sigaction(sig: usize, act: Option<&SigAction>, oldact: Option<&mut SigAction>) -> Result<usize> { unsafe { syscall4(SYS_SIGACTION, sig, act.map(|x| x as *const _).unwrap_or_else(ptr::null) as usize, oldact.map(|x| x as *mut _).unwrap_or_else(ptr::null_mut) as usize, restorer as usize) } } /// Get and/or set signal masks pub fn sigprocmask(how: usize, set: Option<&[u64; 2]>, oldset: Option<&mut [u64; 2]>) -> Result<usize> { unsafe { syscall3(SYS_SIGPROCMASK, how, set.map(|x| x as *const _).unwrap_or_else(ptr::null) as usize, oldset.map(|x| x as *mut _).unwrap_or_else(ptr::null_mut) as usize) } } // Return from signal handler pub fn sigreturn() -> Result<usize> { unsafe { syscall0(SYS_SIGRETURN) } } /// Set the file mode creation mask pub fn umask(mask: usize) -> Result<usize> { unsafe { syscall1(SYS_UMASK, mask) } } /// Remove a file pub fn unlink<T: AsRef<str>>(path: T) -> Result<usize> { unsafe { syscall2(SYS_UNLINK, path.as_ref().as_ptr() as usize, path.as_ref().len()) } } /// Convert a virtual address to a physical one /// /// # Errors /// /// * `EPERM` - `uid != 0` pub unsafe fn virttophys(virtual_address: usize) -> Result<usize> { syscall1(SYS_VIRTTOPHYS, virtual_address) } /// Check if a child process has exited or received a signal pub fn waitpid(pid: usize, status: &mut usize, options: WaitFlags) -> Result<usize> { unsafe { syscall3(SYS_WAITPID, pid, status as *mut usize as usize, options.bits()) } } /// Write a buffer to a file descriptor /// /// The kernel will attempt to write the bytes in `buf` to the file descriptor `fd`, returning /// either an `Err`, explained below, or `Ok(count)` where `count` is the number of bytes which /// were written. /// /// # Errors /// /// * `EAGAIN` - the file descriptor was opened with `O_NONBLOCK` and writing would block /// * `EBADF` - the file descriptor is not valid or is not open for writing /// * `EFAULT` - `buf` does not point to the process's addressible memory /// * `EIO` - an I/O error occurred /// * `ENOSPC` - the device containing the file descriptor has no room for data /// * `EPIPE` - the file descriptor refers to a pipe or socket whose reading end is closed pub fn write(fd: usize, buf: &[u8]) -> Result<usize> { unsafe { syscall3(SYS_WRITE, fd, buf.as_ptr() as usize, buf.len()) } } /// Yield the process's time slice to the kernel /// /// This function will return Ok(0) on success pub fn sched_yield() -> Result<usize> { unsafe { syscall0(SYS_YIELD) } }
close
identifier_name
call.rs
use super::arch::*; use super::data::{Map, SigAction, Stat, StatVfs, TimeSpec}; use super::error::Result; use super::flag::*; use super::number::*; use core::{mem, ptr}; // Signal restorer extern "C" fn restorer() -> ! { sigreturn().unwrap(); unreachable!(); } /// Close a file pub fn close(fd: usize) -> Result<usize> { unsafe { syscall1(SYS_CLOSE, fd) } } /// Get the current system time pub fn clock_gettime(clock: usize, tp: &mut TimeSpec) -> Result<usize> { unsafe { syscall2(SYS_CLOCK_GETTIME, clock, tp as *mut TimeSpec as usize) } } /// Copy and transform a file descriptor pub fn dup(fd: usize, buf: &[u8]) -> Result<usize> { unsafe { syscall3(SYS_DUP, fd, buf.as_ptr() as usize, buf.len()) } } /// Copy and transform a file descriptor pub fn dup2(fd: usize, newfd: usize, buf: &[u8]) -> Result<usize> { unsafe { syscall4(SYS_DUP2, fd, newfd, buf.as_ptr() as usize, buf.len()) } } /// Exit the current process pub fn exit(status: usize) -> Result<usize> { unsafe { syscall1(SYS_EXIT, status) } } /// Change file permissions pub fn fchmod(fd: usize, mode: u16) -> Result<usize> { unsafe { syscall2(SYS_FCHMOD, fd, mode as usize) } } /// Change file ownership pub fn fchown(fd: usize, uid: u32, gid: u32) -> Result<usize> { unsafe { syscall3(SYS_FCHOWN, fd, uid as usize, gid as usize) } } /// Change file descriptor flags pub fn fcntl(fd: usize, cmd: usize, arg: usize) -> Result<usize> { unsafe { syscall3(SYS_FCNTL, fd, cmd, arg) } } /// Map a file into memory, but with the ability to set the address to map into, either as a hint /// or as a requirement of the map. /// /// # Errors /// `EACCES` - the file descriptor was not open for reading /// `EBADF` - if the file descriptor was invalid /// `ENODEV` - mmapping was not supported /// `EINVAL` - invalid combination of flags /// `EEXIST` - if [`MapFlags::MAP_FIXED`] was set, and the address specified was already in use. /// pub unsafe fn fmap(fd: usize, map: &Map) -> Result<usize> { syscall3(SYS_FMAP, fd, map as *const Map as usize, mem::size_of::<Map>()) } /// Unmap whole (or partial) continous memory-mapped files pub unsafe fn funmap(addr: usize, len: usize) -> Result<usize> { syscall2(SYS_FUNMAP, addr, len) } /// Retrieve the canonical path of a file pub fn fpath(fd: usize, buf: &mut [u8]) -> Result<usize> { unsafe { syscall3(SYS_FPATH, fd, buf.as_mut_ptr() as usize, buf.len()) } } /// Rename a file pub fn frename<T: AsRef<str>>(fd: usize, path: T) -> Result<usize> { unsafe { syscall3(SYS_FRENAME, fd, path.as_ref().as_ptr() as usize, path.as_ref().len()) } } /// Get metadata about a file pub fn fstat(fd: usize, stat: &mut Stat) -> Result<usize> { unsafe { syscall3(SYS_FSTAT, fd, stat as *mut Stat as usize, mem::size_of::<Stat>()) } } /// Get metadata about a filesystem pub fn fstatvfs(fd: usize, stat: &mut StatVfs) -> Result<usize> { unsafe { syscall3(SYS_FSTATVFS, fd, stat as *mut StatVfs as usize, mem::size_of::<StatVfs>()) } } /// Sync a file descriptor to its underlying medium pub fn fsync(fd: usize) -> Result<usize> { unsafe { syscall1(SYS_FSYNC, fd) } } /// Truncate or extend a file to a specified length pub fn ftruncate(fd: usize, len: usize) -> Result<usize> { unsafe { syscall2(SYS_FTRUNCATE, fd, len) } } // Change modify and/or access times pub fn futimens(fd: usize, times: &[TimeSpec]) -> Result<usize> { unsafe { syscall3(SYS_FUTIMENS, fd, times.as_ptr() as usize, times.len() * mem::size_of::<TimeSpec>()) } } /// Fast userspace mutex pub unsafe fn futex(addr: *mut i32, op: usize, val: i32, val2: usize, addr2: *mut i32) -> Result<usize> { syscall5(SYS_FUTEX, addr as usize, op, (val as isize) as usize, val2, addr2 as usize) } /// Get the effective group ID pub fn getegid() -> Result<usize> { unsafe { syscall0(SYS_GETEGID) } } /// Get the effective namespace pub fn getens() -> Result<usize> { unsafe { syscall0(SYS_GETENS) } } /// Get the effective user ID pub fn geteuid() -> Result<usize> { unsafe { syscall0(SYS_GETEUID) } } /// Get the current group ID pub fn getgid() -> Result<usize> { unsafe { syscall0(SYS_GETGID) } } /// Get the current namespace pub fn getns() -> Result<usize> { unsafe { syscall0(SYS_GETNS) } } /// Get the current process ID pub fn getpid() -> Result<usize> { unsafe { syscall0(SYS_GETPID) } } /// Get the process group ID pub fn getpgid(pid: usize) -> Result<usize> { unsafe { syscall1(SYS_GETPGID, pid) } } /// Get the parent process ID pub fn getppid() -> Result<usize> { unsafe { syscall0(SYS_GETPPID) } } /// Get the current user ID pub fn getuid() -> Result<usize> { unsafe { syscall0(SYS_GETUID) } } /// Set the I/O privilege level /// /// # Errors /// /// * `EPERM` - `uid != 0` /// * `EINVAL` - `level > 3` pub unsafe fn iopl(level: usize) -> Result<usize> { syscall1(SYS_IOPL, level) } /// Send a signal `sig` to the process identified by `pid` pub fn kill(pid: usize, sig: usize) -> Result<usize> { unsafe { syscall2(SYS_KILL, pid, sig) } } /// Create a link to a file pub unsafe fn link(old: *const u8, new: *const u8) -> Result<usize> { syscall2(SYS_LINK, old as usize, new as usize) } /// Seek to `offset` bytes in a file descriptor pub fn lseek(fd: usize, offset: isize, whence: usize) -> Result<usize> { unsafe { syscall3(SYS_LSEEK, fd, offset as usize, whence) } } /// Make a new scheme namespace pub fn mkns(schemes: &[[usize; 2]]) -> Result<usize> { unsafe { syscall2(SYS_MKNS, schemes.as_ptr() as usize, schemes.len()) } } /// Change mapping flags pub unsafe fn mprotect(addr: usize, size: usize, flags: MapFlags) -> Result<usize> { syscall3(SYS_MPROTECT, addr, size, flags.bits()) } /// Sleep for the time specified in `req` pub fn nanosleep(req: &TimeSpec, rem: &mut TimeSpec) -> Result<usize> { unsafe { syscall2(SYS_NANOSLEEP, req as *const TimeSpec as usize, rem as *mut TimeSpec as usize) } } /// Open a file pub fn open<T: AsRef<str>>(path: T, flags: usize) -> Result<usize> { unsafe { syscall3(SYS_OPEN, path.as_ref().as_ptr() as usize, path.as_ref().len(), flags) } } /// Allocate frames, linearly in physical memory. /// /// # Errors /// /// * `EPERM` - `uid != 0` /// * `ENOMEM` - the system has run out of available memory pub unsafe fn physalloc(size: usize) -> Result<usize> { syscall1(SYS_PHYSALLOC, size) } /// Allocate frames, linearly in physical memory, with an extra set of flags. If the flags contain /// [`PARTIAL_ALLOC`], this will result in `physalloc3` with `min = 1`. /// /// Refer to the simpler [`physalloc`] and the more complex [`physalloc3`], that this convenience /// function is based on. /// /// # Errors /// /// * `EPERM` - `uid != 0` /// * `ENOMEM` - the system has run out of available memory pub unsafe fn physalloc2(size: usize, flags: usize) -> Result<usize> { let mut ret = 1usize; physalloc3(size, flags, &mut ret) } /// Allocate frames, linearly in physical memory, with an extra set of flags. If the flags contain /// [`PARTIAL_ALLOC`], the `min` parameter specifies the number of frames that have to be allocated /// for this operation to succeed. The return value is the offset of the first frame, and `min` is /// overwritten with the number of frames actually allocated. /// /// Refer to the simpler [`physalloc`] and the simpler library function [`physalloc2`]. /// /// # Errors /// /// * `EPERM` - `uid != 0` /// * `ENOMEM` - the system has run out of available memory /// * `EINVAL` - `min = 0` pub unsafe fn physalloc3(size: usize, flags: usize, min: &mut usize) -> Result<usize> { syscall3(SYS_PHYSALLOC3, size, flags, min as *mut usize as usize) } /// Free physically allocated pages /// /// # Errors /// /// * `EPERM` - `uid != 0` pub unsafe fn physfree(physical_address: usize, size: usize) -> Result<usize> { syscall2(SYS_PHYSFREE, physical_address, size) } /// Map physical memory to virtual memory /// /// # Errors /// /// * `EPERM` - `uid != 0` pub unsafe fn physmap(physical_address: usize, size: usize, flags: PhysmapFlags) -> Result<usize> { syscall3(SYS_PHYSMAP, physical_address, size, flags.bits()) } /// Create a pair of file descriptors referencing the read and write ends of a pipe pub fn pipe2(fds: &mut [usize; 2], flags: usize) -> Result<usize> { unsafe { syscall2(SYS_PIPE2, fds.as_ptr() as usize, flags) } } /// Read from a file descriptor into a buffer pub fn read(fd: usize, buf: &mut [u8]) -> Result<usize> { unsafe { syscall3(SYS_READ, fd, buf.as_mut_ptr() as usize, buf.len()) } } /// Remove a directory pub fn rmdir<T: AsRef<str>>(path: T) -> Result<usize> { unsafe { syscall2(SYS_RMDIR, path.as_ref().as_ptr() as usize, path.as_ref().len()) } } /// Set the process group ID pub fn setpgid(pid: usize, pgid: usize) -> Result<usize> { unsafe { syscall2(SYS_SETPGID, pid, pgid) } } /// Set the current process group IDs pub fn setregid(rgid: usize, egid: usize) -> Result<usize> { unsafe { syscall2(SYS_SETREGID, rgid, egid) } } /// Make a new scheme namespace pub fn setrens(rns: usize, ens: usize) -> Result<usize>
/// Set the current process user IDs pub fn setreuid(ruid: usize, euid: usize) -> Result<usize> { unsafe { syscall2(SYS_SETREUID, ruid, euid) } } /// Set up a signal handler pub fn sigaction(sig: usize, act: Option<&SigAction>, oldact: Option<&mut SigAction>) -> Result<usize> { unsafe { syscall4(SYS_SIGACTION, sig, act.map(|x| x as *const _).unwrap_or_else(ptr::null) as usize, oldact.map(|x| x as *mut _).unwrap_or_else(ptr::null_mut) as usize, restorer as usize) } } /// Get and/or set signal masks pub fn sigprocmask(how: usize, set: Option<&[u64; 2]>, oldset: Option<&mut [u64; 2]>) -> Result<usize> { unsafe { syscall3(SYS_SIGPROCMASK, how, set.map(|x| x as *const _).unwrap_or_else(ptr::null) as usize, oldset.map(|x| x as *mut _).unwrap_or_else(ptr::null_mut) as usize) } } // Return from signal handler pub fn sigreturn() -> Result<usize> { unsafe { syscall0(SYS_SIGRETURN) } } /// Set the file mode creation mask pub fn umask(mask: usize) -> Result<usize> { unsafe { syscall1(SYS_UMASK, mask) } } /// Remove a file pub fn unlink<T: AsRef<str>>(path: T) -> Result<usize> { unsafe { syscall2(SYS_UNLINK, path.as_ref().as_ptr() as usize, path.as_ref().len()) } } /// Convert a virtual address to a physical one /// /// # Errors /// /// * `EPERM` - `uid != 0` pub unsafe fn virttophys(virtual_address: usize) -> Result<usize> { syscall1(SYS_VIRTTOPHYS, virtual_address) } /// Check if a child process has exited or received a signal pub fn waitpid(pid: usize, status: &mut usize, options: WaitFlags) -> Result<usize> { unsafe { syscall3(SYS_WAITPID, pid, status as *mut usize as usize, options.bits()) } } /// Write a buffer to a file descriptor /// /// The kernel will attempt to write the bytes in `buf` to the file descriptor `fd`, returning /// either an `Err`, explained below, or `Ok(count)` where `count` is the number of bytes which /// were written. /// /// # Errors /// /// * `EAGAIN` - the file descriptor was opened with `O_NONBLOCK` and writing would block /// * `EBADF` - the file descriptor is not valid or is not open for writing /// * `EFAULT` - `buf` does not point to the process's addressible memory /// * `EIO` - an I/O error occurred /// * `ENOSPC` - the device containing the file descriptor has no room for data /// * `EPIPE` - the file descriptor refers to a pipe or socket whose reading end is closed pub fn write(fd: usize, buf: &[u8]) -> Result<usize> { unsafe { syscall3(SYS_WRITE, fd, buf.as_ptr() as usize, buf.len()) } } /// Yield the process's time slice to the kernel /// /// This function will return Ok(0) on success pub fn sched_yield() -> Result<usize> { unsafe { syscall0(SYS_YIELD) } }
{ unsafe { syscall2(SYS_SETRENS, rns, ens) } }
identifier_body
call.rs
use super::arch::*; use super::data::{Map, SigAction, Stat, StatVfs, TimeSpec}; use super::error::Result; use super::flag::*; use super::number::*; use core::{mem, ptr}; // Signal restorer extern "C" fn restorer() -> ! { sigreturn().unwrap(); unreachable!(); } /// Close a file pub fn close(fd: usize) -> Result<usize> { unsafe { syscall1(SYS_CLOSE, fd) }
unsafe { syscall2(SYS_CLOCK_GETTIME, clock, tp as *mut TimeSpec as usize) } } /// Copy and transform a file descriptor pub fn dup(fd: usize, buf: &[u8]) -> Result<usize> { unsafe { syscall3(SYS_DUP, fd, buf.as_ptr() as usize, buf.len()) } } /// Copy and transform a file descriptor pub fn dup2(fd: usize, newfd: usize, buf: &[u8]) -> Result<usize> { unsafe { syscall4(SYS_DUP2, fd, newfd, buf.as_ptr() as usize, buf.len()) } } /// Exit the current process pub fn exit(status: usize) -> Result<usize> { unsafe { syscall1(SYS_EXIT, status) } } /// Change file permissions pub fn fchmod(fd: usize, mode: u16) -> Result<usize> { unsafe { syscall2(SYS_FCHMOD, fd, mode as usize) } } /// Change file ownership pub fn fchown(fd: usize, uid: u32, gid: u32) -> Result<usize> { unsafe { syscall3(SYS_FCHOWN, fd, uid as usize, gid as usize) } } /// Change file descriptor flags pub fn fcntl(fd: usize, cmd: usize, arg: usize) -> Result<usize> { unsafe { syscall3(SYS_FCNTL, fd, cmd, arg) } } /// Map a file into memory, but with the ability to set the address to map into, either as a hint /// or as a requirement of the map. /// /// # Errors /// `EACCES` - the file descriptor was not open for reading /// `EBADF` - if the file descriptor was invalid /// `ENODEV` - mmapping was not supported /// `EINVAL` - invalid combination of flags /// `EEXIST` - if [`MapFlags::MAP_FIXED`] was set, and the address specified was already in use. /// pub unsafe fn fmap(fd: usize, map: &Map) -> Result<usize> { syscall3(SYS_FMAP, fd, map as *const Map as usize, mem::size_of::<Map>()) } /// Unmap whole (or partial) continous memory-mapped files pub unsafe fn funmap(addr: usize, len: usize) -> Result<usize> { syscall2(SYS_FUNMAP, addr, len) } /// Retrieve the canonical path of a file pub fn fpath(fd: usize, buf: &mut [u8]) -> Result<usize> { unsafe { syscall3(SYS_FPATH, fd, buf.as_mut_ptr() as usize, buf.len()) } } /// Rename a file pub fn frename<T: AsRef<str>>(fd: usize, path: T) -> Result<usize> { unsafe { syscall3(SYS_FRENAME, fd, path.as_ref().as_ptr() as usize, path.as_ref().len()) } } /// Get metadata about a file pub fn fstat(fd: usize, stat: &mut Stat) -> Result<usize> { unsafe { syscall3(SYS_FSTAT, fd, stat as *mut Stat as usize, mem::size_of::<Stat>()) } } /// Get metadata about a filesystem pub fn fstatvfs(fd: usize, stat: &mut StatVfs) -> Result<usize> { unsafe { syscall3(SYS_FSTATVFS, fd, stat as *mut StatVfs as usize, mem::size_of::<StatVfs>()) } } /// Sync a file descriptor to its underlying medium pub fn fsync(fd: usize) -> Result<usize> { unsafe { syscall1(SYS_FSYNC, fd) } } /// Truncate or extend a file to a specified length pub fn ftruncate(fd: usize, len: usize) -> Result<usize> { unsafe { syscall2(SYS_FTRUNCATE, fd, len) } } // Change modify and/or access times pub fn futimens(fd: usize, times: &[TimeSpec]) -> Result<usize> { unsafe { syscall3(SYS_FUTIMENS, fd, times.as_ptr() as usize, times.len() * mem::size_of::<TimeSpec>()) } } /// Fast userspace mutex pub unsafe fn futex(addr: *mut i32, op: usize, val: i32, val2: usize, addr2: *mut i32) -> Result<usize> { syscall5(SYS_FUTEX, addr as usize, op, (val as isize) as usize, val2, addr2 as usize) } /// Get the effective group ID pub fn getegid() -> Result<usize> { unsafe { syscall0(SYS_GETEGID) } } /// Get the effective namespace pub fn getens() -> Result<usize> { unsafe { syscall0(SYS_GETENS) } } /// Get the effective user ID pub fn geteuid() -> Result<usize> { unsafe { syscall0(SYS_GETEUID) } } /// Get the current group ID pub fn getgid() -> Result<usize> { unsafe { syscall0(SYS_GETGID) } } /// Get the current namespace pub fn getns() -> Result<usize> { unsafe { syscall0(SYS_GETNS) } } /// Get the current process ID pub fn getpid() -> Result<usize> { unsafe { syscall0(SYS_GETPID) } } /// Get the process group ID pub fn getpgid(pid: usize) -> Result<usize> { unsafe { syscall1(SYS_GETPGID, pid) } } /// Get the parent process ID pub fn getppid() -> Result<usize> { unsafe { syscall0(SYS_GETPPID) } } /// Get the current user ID pub fn getuid() -> Result<usize> { unsafe { syscall0(SYS_GETUID) } } /// Set the I/O privilege level /// /// # Errors /// /// * `EPERM` - `uid != 0` /// * `EINVAL` - `level > 3` pub unsafe fn iopl(level: usize) -> Result<usize> { syscall1(SYS_IOPL, level) } /// Send a signal `sig` to the process identified by `pid` pub fn kill(pid: usize, sig: usize) -> Result<usize> { unsafe { syscall2(SYS_KILL, pid, sig) } } /// Create a link to a file pub unsafe fn link(old: *const u8, new: *const u8) -> Result<usize> { syscall2(SYS_LINK, old as usize, new as usize) } /// Seek to `offset` bytes in a file descriptor pub fn lseek(fd: usize, offset: isize, whence: usize) -> Result<usize> { unsafe { syscall3(SYS_LSEEK, fd, offset as usize, whence) } } /// Make a new scheme namespace pub fn mkns(schemes: &[[usize; 2]]) -> Result<usize> { unsafe { syscall2(SYS_MKNS, schemes.as_ptr() as usize, schemes.len()) } } /// Change mapping flags pub unsafe fn mprotect(addr: usize, size: usize, flags: MapFlags) -> Result<usize> { syscall3(SYS_MPROTECT, addr, size, flags.bits()) } /// Sleep for the time specified in `req` pub fn nanosleep(req: &TimeSpec, rem: &mut TimeSpec) -> Result<usize> { unsafe { syscall2(SYS_NANOSLEEP, req as *const TimeSpec as usize, rem as *mut TimeSpec as usize) } } /// Open a file pub fn open<T: AsRef<str>>(path: T, flags: usize) -> Result<usize> { unsafe { syscall3(SYS_OPEN, path.as_ref().as_ptr() as usize, path.as_ref().len(), flags) } } /// Allocate frames, linearly in physical memory. /// /// # Errors /// /// * `EPERM` - `uid != 0` /// * `ENOMEM` - the system has run out of available memory pub unsafe fn physalloc(size: usize) -> Result<usize> { syscall1(SYS_PHYSALLOC, size) } /// Allocate frames, linearly in physical memory, with an extra set of flags. If the flags contain /// [`PARTIAL_ALLOC`], this will result in `physalloc3` with `min = 1`. /// /// Refer to the simpler [`physalloc`] and the more complex [`physalloc3`], that this convenience /// function is based on. /// /// # Errors /// /// * `EPERM` - `uid != 0` /// * `ENOMEM` - the system has run out of available memory pub unsafe fn physalloc2(size: usize, flags: usize) -> Result<usize> { let mut ret = 1usize; physalloc3(size, flags, &mut ret) } /// Allocate frames, linearly in physical memory, with an extra set of flags. If the flags contain /// [`PARTIAL_ALLOC`], the `min` parameter specifies the number of frames that have to be allocated /// for this operation to succeed. The return value is the offset of the first frame, and `min` is /// overwritten with the number of frames actually allocated. /// /// Refer to the simpler [`physalloc`] and the simpler library function [`physalloc2`]. /// /// # Errors /// /// * `EPERM` - `uid != 0` /// * `ENOMEM` - the system has run out of available memory /// * `EINVAL` - `min = 0` pub unsafe fn physalloc3(size: usize, flags: usize, min: &mut usize) -> Result<usize> { syscall3(SYS_PHYSALLOC3, size, flags, min as *mut usize as usize) } /// Free physically allocated pages /// /// # Errors /// /// * `EPERM` - `uid != 0` pub unsafe fn physfree(physical_address: usize, size: usize) -> Result<usize> { syscall2(SYS_PHYSFREE, physical_address, size) } /// Map physical memory to virtual memory /// /// # Errors /// /// * `EPERM` - `uid != 0` pub unsafe fn physmap(physical_address: usize, size: usize, flags: PhysmapFlags) -> Result<usize> { syscall3(SYS_PHYSMAP, physical_address, size, flags.bits()) } /// Create a pair of file descriptors referencing the read and write ends of a pipe pub fn pipe2(fds: &mut [usize; 2], flags: usize) -> Result<usize> { unsafe { syscall2(SYS_PIPE2, fds.as_ptr() as usize, flags) } } /// Read from a file descriptor into a buffer pub fn read(fd: usize, buf: &mut [u8]) -> Result<usize> { unsafe { syscall3(SYS_READ, fd, buf.as_mut_ptr() as usize, buf.len()) } } /// Remove a directory pub fn rmdir<T: AsRef<str>>(path: T) -> Result<usize> { unsafe { syscall2(SYS_RMDIR, path.as_ref().as_ptr() as usize, path.as_ref().len()) } } /// Set the process group ID pub fn setpgid(pid: usize, pgid: usize) -> Result<usize> { unsafe { syscall2(SYS_SETPGID, pid, pgid) } } /// Set the current process group IDs pub fn setregid(rgid: usize, egid: usize) -> Result<usize> { unsafe { syscall2(SYS_SETREGID, rgid, egid) } } /// Make a new scheme namespace pub fn setrens(rns: usize, ens: usize) -> Result<usize> { unsafe { syscall2(SYS_SETRENS, rns, ens) } } /// Set the current process user IDs pub fn setreuid(ruid: usize, euid: usize) -> Result<usize> { unsafe { syscall2(SYS_SETREUID, ruid, euid) } } /// Set up a signal handler pub fn sigaction(sig: usize, act: Option<&SigAction>, oldact: Option<&mut SigAction>) -> Result<usize> { unsafe { syscall4(SYS_SIGACTION, sig, act.map(|x| x as *const _).unwrap_or_else(ptr::null) as usize, oldact.map(|x| x as *mut _).unwrap_or_else(ptr::null_mut) as usize, restorer as usize) } } /// Get and/or set signal masks pub fn sigprocmask(how: usize, set: Option<&[u64; 2]>, oldset: Option<&mut [u64; 2]>) -> Result<usize> { unsafe { syscall3(SYS_SIGPROCMASK, how, set.map(|x| x as *const _).unwrap_or_else(ptr::null) as usize, oldset.map(|x| x as *mut _).unwrap_or_else(ptr::null_mut) as usize) } } // Return from signal handler pub fn sigreturn() -> Result<usize> { unsafe { syscall0(SYS_SIGRETURN) } } /// Set the file mode creation mask pub fn umask(mask: usize) -> Result<usize> { unsafe { syscall1(SYS_UMASK, mask) } } /// Remove a file pub fn unlink<T: AsRef<str>>(path: T) -> Result<usize> { unsafe { syscall2(SYS_UNLINK, path.as_ref().as_ptr() as usize, path.as_ref().len()) } } /// Convert a virtual address to a physical one /// /// # Errors /// /// * `EPERM` - `uid != 0` pub unsafe fn virttophys(virtual_address: usize) -> Result<usize> { syscall1(SYS_VIRTTOPHYS, virtual_address) } /// Check if a child process has exited or received a signal pub fn waitpid(pid: usize, status: &mut usize, options: WaitFlags) -> Result<usize> { unsafe { syscall3(SYS_WAITPID, pid, status as *mut usize as usize, options.bits()) } } /// Write a buffer to a file descriptor /// /// The kernel will attempt to write the bytes in `buf` to the file descriptor `fd`, returning /// either an `Err`, explained below, or `Ok(count)` where `count` is the number of bytes which /// were written. /// /// # Errors /// /// * `EAGAIN` - the file descriptor was opened with `O_NONBLOCK` and writing would block /// * `EBADF` - the file descriptor is not valid or is not open for writing /// * `EFAULT` - `buf` does not point to the process's addressible memory /// * `EIO` - an I/O error occurred /// * `ENOSPC` - the device containing the file descriptor has no room for data /// * `EPIPE` - the file descriptor refers to a pipe or socket whose reading end is closed pub fn write(fd: usize, buf: &[u8]) -> Result<usize> { unsafe { syscall3(SYS_WRITE, fd, buf.as_ptr() as usize, buf.len()) } } /// Yield the process's time slice to the kernel /// /// This function will return Ok(0) on success pub fn sched_yield() -> Result<usize> { unsafe { syscall0(SYS_YIELD) } }
} /// Get the current system time pub fn clock_gettime(clock: usize, tp: &mut TimeSpec) -> Result<usize> {
random_line_split
frame_info.rs
//! This module is used for having backtraces in the Wasm runtime. //! Once the Compiler has compiled the ModuleInfo, and we have a set of //! compiled functions (addresses and function index) and a module, //! then we can use this to set a backtrace for that module. //! //! # Example //! ```ignore //! use wasmer_vm::{ModuleInfo, FRAME_INFO}; //! //! let module: ModuleInfo = ...; //! FRAME_INFO.register(module, compiled_functions); //! ``` use crate::serialize::SerializableFunctionFrameInfo; use std::cmp; use std::collections::BTreeMap; use std::sync::{Arc, RwLock}; use wasmer_compiler::{CompiledFunctionFrameInfo, SourceLoc, TrapInformation}; use wasmer_types::entity::{BoxedSlice, EntityRef, PrimaryMap}; use wasmer_types::LocalFunctionIndex; use wasmer_vm::{FunctionBodyPtr, ModuleInfo}; lazy_static::lazy_static! { /// This is a global cache of backtrace frame information for all active /// /// This global cache is used during `Trap` creation to symbolicate frames. /// This is populated on module compilation, and it is cleared out whenever /// all references to a module are dropped. pub static ref FRAME_INFO: RwLock<GlobalFrameInfo> = Default::default(); } #[derive(Default)] pub struct GlobalFrameInfo { /// An internal map that keeps track of backtrace frame information for /// each module. /// /// This map is morally a map of ranges to a map of information for that /// module. Each module is expected to reside in a disjoint section of /// contiguous memory. No modules can overlap. /// /// The key of this map is the highest address in the module and the value /// is the module's information, which also contains the start address. ranges: BTreeMap<usize, ModuleInfoFrameInfo>, } /// An RAII structure used to unregister a module's frame information when the /// module is destroyed. pub struct GlobalFrameInfoRegistration { /// The key that will be removed from the global `ranges` map when this is /// dropped. key: usize, } struct ModuleInfoFrameInfo { start: usize, functions: BTreeMap<usize, FunctionInfo>, module: Arc<ModuleInfo>, frame_infos: PrimaryMap<LocalFunctionIndex, SerializableFunctionFrameInfo>, } impl ModuleInfoFrameInfo { fn function_debug_info( &self, local_index: LocalFunctionIndex, ) -> &SerializableFunctionFrameInfo { &self.frame_infos.get(local_index).unwrap() } fn process_function_debug_info(&mut self, local_index: LocalFunctionIndex) { let func = self.frame_infos.get_mut(local_index).unwrap(); let processed: CompiledFunctionFrameInfo = match func { SerializableFunctionFrameInfo::Processed(_) => { // This should be a no-op on processed info return; } SerializableFunctionFrameInfo::Unprocessed(unprocessed) => unprocessed.deserialize(), }; *func = SerializableFunctionFrameInfo::Processed(processed) } fn processed_function_frame_info( &self, local_index: LocalFunctionIndex, ) -> &CompiledFunctionFrameInfo { match self.function_debug_info(local_index) { SerializableFunctionFrameInfo::Processed(di) => &di, _ => unreachable!("frame info should already be processed"), } } /// Gets a function given a pc fn function_info(&self, pc: usize) -> Option<&FunctionInfo> { let (end, func) = self.functions.range(pc..).next()?; if pc < func.start || *end < pc { return None; } Some(func) } } struct FunctionInfo { start: usize, local_index: LocalFunctionIndex, } impl GlobalFrameInfo { /// Fetches frame information about a program counter in a backtrace. /// /// Returns an object if this `pc` is known to some previously registered /// module, or returns `None` if no information can be found. pub fn lookup_frame_info(&self, pc: usize) -> Option<FrameInfo> { let module = self.module_info(pc)?; let func = module.function_info(pc)?; // Use our relative position from the start of the function to find the // machine instruction that corresponds to `pc`, which then allows us to // map that to a wasm original source location. let rel_pos = pc - func.start; let instr_map = &module .processed_function_frame_info(func.local_index) .address_map; let pos = match instr_map .instructions .binary_search_by_key(&rel_pos, |map| map.code_offset) { // Exact hit! Ok(pos) => Some(pos), // This *would* be at the first slot in the array, so no // instructions cover `pc`. Err(0) => None, // This would be at the `nth` slot, so check `n-1` to see if we're // part of that instruction. This happens due to the minus one when // this function is called form trap symbolication, where we don't // always get called with a `pc` that's an exact instruction // boundary. Err(n) => { let instr = &instr_map.instructions[n - 1]; if instr.code_offset <= rel_pos && rel_pos < instr.code_offset + instr.code_len { Some(n - 1) } else
} }; // In debug mode for now assert that we found a mapping for `pc` within // the function, because otherwise something is buggy along the way and // not accounting for all the instructions. This isn't super critical // though so we can omit this check in release mode. debug_assert!(pos.is_some(), "failed to find instruction for {:x}", pc); let instr = match pos { Some(pos) => instr_map.instructions[pos].srcloc, None => instr_map.start_srcloc, }; let func_index = module.module.func_index(func.local_index); Some(FrameInfo { module_name: module.module.name(), func_index: func_index.index() as u32, function_name: module.module.function_names.get(&func_index).cloned(), instr, func_start: instr_map.start_srcloc, }) } /// Fetches trap information about a program counter in a backtrace. pub fn lookup_trap_info(&self, pc: usize) -> Option<&TrapInformation> { let module = self.module_info(pc)?; let func = module.function_info(pc)?; let traps = &module.processed_function_frame_info(func.local_index).traps; let idx = traps .binary_search_by_key(&((pc - func.start) as u32), |info| info.code_offset) .ok()?; Some(&traps[idx]) } /// Should process the frame before anything? pub fn should_process_frame(&self, pc: usize) -> Option<bool> { let module = self.module_info(pc)?; let func = module.function_info(pc)?; let extra_func_info = module.function_debug_info(func.local_index); Some(extra_func_info.is_unprocessed()) } /// Process the frame info in case is not yet processed pub fn maybe_process_frame(&mut self, pc: usize) -> Option<()> { let module = self.module_info_mut(pc)?; let func = module.function_info(pc)?; let func_local_index = func.local_index; module.process_function_debug_info(func_local_index); Some(()) } /// Gets a module given a pc fn module_info(&self, pc: usize) -> Option<&ModuleInfoFrameInfo> { let (end, module_info) = self.ranges.range(pc..).next()?; if pc < module_info.start || *end < pc { return None; } Some(module_info) } /// Gets a module given a pc fn module_info_mut(&mut self, pc: usize) -> Option<&mut ModuleInfoFrameInfo> { let (end, module_info) = self.ranges.range_mut(pc..).next()?; if pc < module_info.start || *end < pc { return None; } Some(module_info) } } impl Drop for GlobalFrameInfoRegistration { fn drop(&mut self) { if let Ok(mut info) = FRAME_INFO.write() { info.ranges.remove(&self.key); } } } /// Registers a new compiled module's frame information. /// /// This function will register the `names` information for all of the /// compiled functions within `module`. If the `module` has no functions /// then `None` will be returned. Otherwise the returned object, when /// dropped, will be used to unregister all name information from this map. pub fn register( module: Arc<ModuleInfo>, finished_functions: &BoxedSlice<LocalFunctionIndex, FunctionBodyPtr>, frame_infos: PrimaryMap<LocalFunctionIndex, SerializableFunctionFrameInfo>, ) -> Option<GlobalFrameInfoRegistration> { let mut min = usize::max_value(); let mut max = 0; let mut functions = BTreeMap::new(); for (i, allocated) in finished_functions.iter() { let (start, end) = unsafe { let ptr = (***allocated).as_ptr(); let len = (***allocated).len(); (ptr as usize, ptr as usize + len) }; min = cmp::min(min, start); max = cmp::max(max, end); let func = FunctionInfo { start, local_index: i, }; assert!(functions.insert(end, func).is_none()); } if functions.is_empty() { return None; } let mut info = FRAME_INFO.write().unwrap(); // First up assert that our chunk of jit functions doesn't collide with // any other known chunks of jit functions... if let Some((_, prev)) = info.ranges.range(max..).next() { assert!(prev.start > max); } if let Some((prev_end, _)) = info.ranges.range(..=min).next_back() { assert!(*prev_end < min); } // ... then insert our range and assert nothing was there previously let prev = info.ranges.insert( max, ModuleInfoFrameInfo { start: min, functions, module, frame_infos, }, ); assert!(prev.is_none()); Some(GlobalFrameInfoRegistration { key: max }) } /// Description of a frame in a backtrace for a [`Trap`]. /// /// Whenever a WebAssembly trap occurs an instance of [`Trap`] is created. Each /// [`Trap`] has a backtrace of the WebAssembly frames that led to the trap, and /// each frame is described by this structure. /// /// [`Trap`]: crate::Trap #[derive(Debug, Clone)] pub struct FrameInfo { module_name: String, func_index: u32, function_name: Option<String>, func_start: SourceLoc, instr: SourceLoc, } impl FrameInfo { /// Returns the WebAssembly function index for this frame. /// /// This function index is the index in the function index space of the /// WebAssembly module that this frame comes from. pub fn func_index(&self) -> u32 { self.func_index } /// Returns the identifer of the module that this frame is for. /// /// ModuleInfo identifiers are present in the `name` section of a WebAssembly /// binary, but this may not return the exact item in the `name` section. /// ModuleInfo names can be overwritten at construction time or perhaps inferred /// from file names. The primary purpose of this function is to assist in /// debugging and therefore may be tweaked over time. /// /// This function returns `None` when no name can be found or inferred. pub fn module_name(&self) -> &str { &self.module_name } /// Returns a descriptive name of the function for this frame, if one is /// available. /// /// The name of this function may come from the `name` section of the /// WebAssembly binary, or wasmer may try to infer a better name for it if /// not available, for example the name of the export if it's exported. /// /// This return value is primarily used for debugging and human-readable /// purposes for things like traps. Note that the exact return value may be /// tweaked over time here and isn't guaranteed to be something in /// particular about a wasm module due to its primary purpose of assisting /// in debugging. /// /// This function returns `None` when no name could be inferred. pub fn function_name(&self) -> Option<&str> { self.function_name.as_deref() } /// Returns the offset within the original wasm module this frame's program /// counter was at. /// /// The offset here is the offset from the beginning of the original wasm /// module to the instruction that this frame points to. pub fn module_offset(&self) -> usize { self.instr.bits() as usize } /// Returns the offset from the original wasm module's function to this /// frame's program counter. /// /// The offset here is the offset from the beginning of the defining /// function of this frame (within the wasm module) to the instruction this /// frame points to. pub fn func_offset(&self) -> usize { (self.instr.bits() - self.func_start.bits()) as usize } }
{ None }
conditional_block
frame_info.rs
//! This module is used for having backtraces in the Wasm runtime. //! Once the Compiler has compiled the ModuleInfo, and we have a set of //! compiled functions (addresses and function index) and a module, //! then we can use this to set a backtrace for that module. //! //! # Example //! ```ignore //! use wasmer_vm::{ModuleInfo, FRAME_INFO}; //! //! let module: ModuleInfo = ...; //! FRAME_INFO.register(module, compiled_functions); //! ``` use crate::serialize::SerializableFunctionFrameInfo; use std::cmp; use std::collections::BTreeMap; use std::sync::{Arc, RwLock}; use wasmer_compiler::{CompiledFunctionFrameInfo, SourceLoc, TrapInformation}; use wasmer_types::entity::{BoxedSlice, EntityRef, PrimaryMap}; use wasmer_types::LocalFunctionIndex; use wasmer_vm::{FunctionBodyPtr, ModuleInfo}; lazy_static::lazy_static! { /// This is a global cache of backtrace frame information for all active /// /// This global cache is used during `Trap` creation to symbolicate frames. /// This is populated on module compilation, and it is cleared out whenever /// all references to a module are dropped. pub static ref FRAME_INFO: RwLock<GlobalFrameInfo> = Default::default(); } #[derive(Default)] pub struct GlobalFrameInfo { /// An internal map that keeps track of backtrace frame information for /// each module. /// /// This map is morally a map of ranges to a map of information for that /// module. Each module is expected to reside in a disjoint section of /// contiguous memory. No modules can overlap. /// /// The key of this map is the highest address in the module and the value /// is the module's information, which also contains the start address. ranges: BTreeMap<usize, ModuleInfoFrameInfo>, } /// An RAII structure used to unregister a module's frame information when the /// module is destroyed. pub struct GlobalFrameInfoRegistration { /// The key that will be removed from the global `ranges` map when this is /// dropped. key: usize, } struct ModuleInfoFrameInfo { start: usize, functions: BTreeMap<usize, FunctionInfo>, module: Arc<ModuleInfo>, frame_infos: PrimaryMap<LocalFunctionIndex, SerializableFunctionFrameInfo>, } impl ModuleInfoFrameInfo { fn function_debug_info( &self, local_index: LocalFunctionIndex, ) -> &SerializableFunctionFrameInfo { &self.frame_infos.get(local_index).unwrap() } fn process_function_debug_info(&mut self, local_index: LocalFunctionIndex) { let func = self.frame_infos.get_mut(local_index).unwrap(); let processed: CompiledFunctionFrameInfo = match func { SerializableFunctionFrameInfo::Processed(_) => { // This should be a no-op on processed info return; } SerializableFunctionFrameInfo::Unprocessed(unprocessed) => unprocessed.deserialize(), }; *func = SerializableFunctionFrameInfo::Processed(processed) } fn processed_function_frame_info( &self, local_index: LocalFunctionIndex, ) -> &CompiledFunctionFrameInfo { match self.function_debug_info(local_index) { SerializableFunctionFrameInfo::Processed(di) => &di, _ => unreachable!("frame info should already be processed"), } } /// Gets a function given a pc fn function_info(&self, pc: usize) -> Option<&FunctionInfo> { let (end, func) = self.functions.range(pc..).next()?; if pc < func.start || *end < pc { return None; } Some(func) } } struct FunctionInfo { start: usize, local_index: LocalFunctionIndex, } impl GlobalFrameInfo { /// Fetches frame information about a program counter in a backtrace. /// /// Returns an object if this `pc` is known to some previously registered /// module, or returns `None` if no information can be found. pub fn lookup_frame_info(&self, pc: usize) -> Option<FrameInfo> { let module = self.module_info(pc)?; let func = module.function_info(pc)?; // Use our relative position from the start of the function to find the // machine instruction that corresponds to `pc`, which then allows us to // map that to a wasm original source location. let rel_pos = pc - func.start; let instr_map = &module .processed_function_frame_info(func.local_index) .address_map; let pos = match instr_map .instructions .binary_search_by_key(&rel_pos, |map| map.code_offset) { // Exact hit! Ok(pos) => Some(pos), // This *would* be at the first slot in the array, so no // instructions cover `pc`. Err(0) => None, // This would be at the `nth` slot, so check `n-1` to see if we're // part of that instruction. This happens due to the minus one when // this function is called form trap symbolication, where we don't // always get called with a `pc` that's an exact instruction // boundary. Err(n) => { let instr = &instr_map.instructions[n - 1]; if instr.code_offset <= rel_pos && rel_pos < instr.code_offset + instr.code_len { Some(n - 1) } else { None } } }; // In debug mode for now assert that we found a mapping for `pc` within // the function, because otherwise something is buggy along the way and // not accounting for all the instructions. This isn't super critical // though so we can omit this check in release mode. debug_assert!(pos.is_some(), "failed to find instruction for {:x}", pc); let instr = match pos { Some(pos) => instr_map.instructions[pos].srcloc, None => instr_map.start_srcloc, }; let func_index = module.module.func_index(func.local_index); Some(FrameInfo { module_name: module.module.name(), func_index: func_index.index() as u32, function_name: module.module.function_names.get(&func_index).cloned(), instr, func_start: instr_map.start_srcloc, }) } /// Fetches trap information about a program counter in a backtrace. pub fn lookup_trap_info(&self, pc: usize) -> Option<&TrapInformation> { let module = self.module_info(pc)?; let func = module.function_info(pc)?; let traps = &module.processed_function_frame_info(func.local_index).traps; let idx = traps .binary_search_by_key(&((pc - func.start) as u32), |info| info.code_offset) .ok()?; Some(&traps[idx]) } /// Should process the frame before anything? pub fn should_process_frame(&self, pc: usize) -> Option<bool>
/// Process the frame info in case is not yet processed pub fn maybe_process_frame(&mut self, pc: usize) -> Option<()> { let module = self.module_info_mut(pc)?; let func = module.function_info(pc)?; let func_local_index = func.local_index; module.process_function_debug_info(func_local_index); Some(()) } /// Gets a module given a pc fn module_info(&self, pc: usize) -> Option<&ModuleInfoFrameInfo> { let (end, module_info) = self.ranges.range(pc..).next()?; if pc < module_info.start || *end < pc { return None; } Some(module_info) } /// Gets a module given a pc fn module_info_mut(&mut self, pc: usize) -> Option<&mut ModuleInfoFrameInfo> { let (end, module_info) = self.ranges.range_mut(pc..).next()?; if pc < module_info.start || *end < pc { return None; } Some(module_info) } } impl Drop for GlobalFrameInfoRegistration { fn drop(&mut self) { if let Ok(mut info) = FRAME_INFO.write() { info.ranges.remove(&self.key); } } } /// Registers a new compiled module's frame information. /// /// This function will register the `names` information for all of the /// compiled functions within `module`. If the `module` has no functions /// then `None` will be returned. Otherwise the returned object, when /// dropped, will be used to unregister all name information from this map. pub fn register( module: Arc<ModuleInfo>, finished_functions: &BoxedSlice<LocalFunctionIndex, FunctionBodyPtr>, frame_infos: PrimaryMap<LocalFunctionIndex, SerializableFunctionFrameInfo>, ) -> Option<GlobalFrameInfoRegistration> { let mut min = usize::max_value(); let mut max = 0; let mut functions = BTreeMap::new(); for (i, allocated) in finished_functions.iter() { let (start, end) = unsafe { let ptr = (***allocated).as_ptr(); let len = (***allocated).len(); (ptr as usize, ptr as usize + len) }; min = cmp::min(min, start); max = cmp::max(max, end); let func = FunctionInfo { start, local_index: i, }; assert!(functions.insert(end, func).is_none()); } if functions.is_empty() { return None; } let mut info = FRAME_INFO.write().unwrap(); // First up assert that our chunk of jit functions doesn't collide with // any other known chunks of jit functions... if let Some((_, prev)) = info.ranges.range(max..).next() { assert!(prev.start > max); } if let Some((prev_end, _)) = info.ranges.range(..=min).next_back() { assert!(*prev_end < min); } // ... then insert our range and assert nothing was there previously let prev = info.ranges.insert( max, ModuleInfoFrameInfo { start: min, functions, module, frame_infos, }, ); assert!(prev.is_none()); Some(GlobalFrameInfoRegistration { key: max }) } /// Description of a frame in a backtrace for a [`Trap`]. /// /// Whenever a WebAssembly trap occurs an instance of [`Trap`] is created. Each /// [`Trap`] has a backtrace of the WebAssembly frames that led to the trap, and /// each frame is described by this structure. /// /// [`Trap`]: crate::Trap #[derive(Debug, Clone)] pub struct FrameInfo { module_name: String, func_index: u32, function_name: Option<String>, func_start: SourceLoc, instr: SourceLoc, } impl FrameInfo { /// Returns the WebAssembly function index for this frame. /// /// This function index is the index in the function index space of the /// WebAssembly module that this frame comes from. pub fn func_index(&self) -> u32 { self.func_index } /// Returns the identifer of the module that this frame is for. /// /// ModuleInfo identifiers are present in the `name` section of a WebAssembly /// binary, but this may not return the exact item in the `name` section. /// ModuleInfo names can be overwritten at construction time or perhaps inferred /// from file names. The primary purpose of this function is to assist in /// debugging and therefore may be tweaked over time. /// /// This function returns `None` when no name can be found or inferred. pub fn module_name(&self) -> &str { &self.module_name } /// Returns a descriptive name of the function for this frame, if one is /// available. /// /// The name of this function may come from the `name` section of the /// WebAssembly binary, or wasmer may try to infer a better name for it if /// not available, for example the name of the export if it's exported. /// /// This return value is primarily used for debugging and human-readable /// purposes for things like traps. Note that the exact return value may be /// tweaked over time here and isn't guaranteed to be something in /// particular about a wasm module due to its primary purpose of assisting /// in debugging. /// /// This function returns `None` when no name could be inferred. pub fn function_name(&self) -> Option<&str> { self.function_name.as_deref() } /// Returns the offset within the original wasm module this frame's program /// counter was at. /// /// The offset here is the offset from the beginning of the original wasm /// module to the instruction that this frame points to. pub fn module_offset(&self) -> usize { self.instr.bits() as usize } /// Returns the offset from the original wasm module's function to this /// frame's program counter. /// /// The offset here is the offset from the beginning of the defining /// function of this frame (within the wasm module) to the instruction this /// frame points to. pub fn func_offset(&self) -> usize { (self.instr.bits() - self.func_start.bits()) as usize } }
{ let module = self.module_info(pc)?; let func = module.function_info(pc)?; let extra_func_info = module.function_debug_info(func.local_index); Some(extra_func_info.is_unprocessed()) }
identifier_body
frame_info.rs
//! This module is used for having backtraces in the Wasm runtime. //! Once the Compiler has compiled the ModuleInfo, and we have a set of //! compiled functions (addresses and function index) and a module, //! then we can use this to set a backtrace for that module. //! //! # Example //! ```ignore //! use wasmer_vm::{ModuleInfo, FRAME_INFO}; //! //! let module: ModuleInfo = ...; //! FRAME_INFO.register(module, compiled_functions); //! ``` use crate::serialize::SerializableFunctionFrameInfo; use std::cmp; use std::collections::BTreeMap; use std::sync::{Arc, RwLock}; use wasmer_compiler::{CompiledFunctionFrameInfo, SourceLoc, TrapInformation}; use wasmer_types::entity::{BoxedSlice, EntityRef, PrimaryMap}; use wasmer_types::LocalFunctionIndex; use wasmer_vm::{FunctionBodyPtr, ModuleInfo}; lazy_static::lazy_static! { /// This is a global cache of backtrace frame information for all active /// /// This global cache is used during `Trap` creation to symbolicate frames. /// This is populated on module compilation, and it is cleared out whenever /// all references to a module are dropped. pub static ref FRAME_INFO: RwLock<GlobalFrameInfo> = Default::default(); } #[derive(Default)] pub struct GlobalFrameInfo { /// An internal map that keeps track of backtrace frame information for /// each module. /// /// This map is morally a map of ranges to a map of information for that /// module. Each module is expected to reside in a disjoint section of /// contiguous memory. No modules can overlap. /// /// The key of this map is the highest address in the module and the value /// is the module's information, which also contains the start address. ranges: BTreeMap<usize, ModuleInfoFrameInfo>, } /// An RAII structure used to unregister a module's frame information when the /// module is destroyed. pub struct GlobalFrameInfoRegistration { /// The key that will be removed from the global `ranges` map when this is /// dropped. key: usize, } struct ModuleInfoFrameInfo { start: usize, functions: BTreeMap<usize, FunctionInfo>, module: Arc<ModuleInfo>, frame_infos: PrimaryMap<LocalFunctionIndex, SerializableFunctionFrameInfo>, } impl ModuleInfoFrameInfo { fn function_debug_info( &self, local_index: LocalFunctionIndex, ) -> &SerializableFunctionFrameInfo { &self.frame_infos.get(local_index).unwrap() } fn process_function_debug_info(&mut self, local_index: LocalFunctionIndex) { let func = self.frame_infos.get_mut(local_index).unwrap(); let processed: CompiledFunctionFrameInfo = match func { SerializableFunctionFrameInfo::Processed(_) => { // This should be a no-op on processed info return; } SerializableFunctionFrameInfo::Unprocessed(unprocessed) => unprocessed.deserialize(), }; *func = SerializableFunctionFrameInfo::Processed(processed) } fn processed_function_frame_info( &self, local_index: LocalFunctionIndex, ) -> &CompiledFunctionFrameInfo { match self.function_debug_info(local_index) { SerializableFunctionFrameInfo::Processed(di) => &di, _ => unreachable!("frame info should already be processed"), } } /// Gets a function given a pc fn function_info(&self, pc: usize) -> Option<&FunctionInfo> { let (end, func) = self.functions.range(pc..).next()?; if pc < func.start || *end < pc { return None; } Some(func) } } struct FunctionInfo { start: usize, local_index: LocalFunctionIndex, } impl GlobalFrameInfo { /// Fetches frame information about a program counter in a backtrace. /// /// Returns an object if this `pc` is known to some previously registered /// module, or returns `None` if no information can be found. pub fn lookup_frame_info(&self, pc: usize) -> Option<FrameInfo> { let module = self.module_info(pc)?; let func = module.function_info(pc)?; // Use our relative position from the start of the function to find the // machine instruction that corresponds to `pc`, which then allows us to // map that to a wasm original source location. let rel_pos = pc - func.start; let instr_map = &module .processed_function_frame_info(func.local_index) .address_map; let pos = match instr_map .instructions .binary_search_by_key(&rel_pos, |map| map.code_offset) { // Exact hit! Ok(pos) => Some(pos), // This *would* be at the first slot in the array, so no // instructions cover `pc`. Err(0) => None, // This would be at the `nth` slot, so check `n-1` to see if we're // part of that instruction. This happens due to the minus one when // this function is called form trap symbolication, where we don't // always get called with a `pc` that's an exact instruction // boundary. Err(n) => { let instr = &instr_map.instructions[n - 1]; if instr.code_offset <= rel_pos && rel_pos < instr.code_offset + instr.code_len { Some(n - 1) } else { None } } }; // In debug mode for now assert that we found a mapping for `pc` within // the function, because otherwise something is buggy along the way and // not accounting for all the instructions. This isn't super critical // though so we can omit this check in release mode. debug_assert!(pos.is_some(), "failed to find instruction for {:x}", pc); let instr = match pos { Some(pos) => instr_map.instructions[pos].srcloc, None => instr_map.start_srcloc, }; let func_index = module.module.func_index(func.local_index); Some(FrameInfo { module_name: module.module.name(), func_index: func_index.index() as u32, function_name: module.module.function_names.get(&func_index).cloned(), instr, func_start: instr_map.start_srcloc, }) } /// Fetches trap information about a program counter in a backtrace. pub fn lookup_trap_info(&self, pc: usize) -> Option<&TrapInformation> { let module = self.module_info(pc)?; let func = module.function_info(pc)?; let traps = &module.processed_function_frame_info(func.local_index).traps; let idx = traps .binary_search_by_key(&((pc - func.start) as u32), |info| info.code_offset) .ok()?; Some(&traps[idx]) } /// Should process the frame before anything? pub fn should_process_frame(&self, pc: usize) -> Option<bool> { let module = self.module_info(pc)?; let func = module.function_info(pc)?; let extra_func_info = module.function_debug_info(func.local_index); Some(extra_func_info.is_unprocessed()) } /// Process the frame info in case is not yet processed pub fn maybe_process_frame(&mut self, pc: usize) -> Option<()> { let module = self.module_info_mut(pc)?; let func = module.function_info(pc)?; let func_local_index = func.local_index; module.process_function_debug_info(func_local_index); Some(()) } /// Gets a module given a pc fn module_info(&self, pc: usize) -> Option<&ModuleInfoFrameInfo> { let (end, module_info) = self.ranges.range(pc..).next()?; if pc < module_info.start || *end < pc { return None; } Some(module_info) } /// Gets a module given a pc fn module_info_mut(&mut self, pc: usize) -> Option<&mut ModuleInfoFrameInfo> { let (end, module_info) = self.ranges.range_mut(pc..).next()?; if pc < module_info.start || *end < pc { return None; } Some(module_info) } } impl Drop for GlobalFrameInfoRegistration { fn drop(&mut self) { if let Ok(mut info) = FRAME_INFO.write() { info.ranges.remove(&self.key); } } } /// Registers a new compiled module's frame information. /// /// This function will register the `names` information for all of the /// compiled functions within `module`. If the `module` has no functions /// then `None` will be returned. Otherwise the returned object, when /// dropped, will be used to unregister all name information from this map. pub fn register( module: Arc<ModuleInfo>, finished_functions: &BoxedSlice<LocalFunctionIndex, FunctionBodyPtr>, frame_infos: PrimaryMap<LocalFunctionIndex, SerializableFunctionFrameInfo>, ) -> Option<GlobalFrameInfoRegistration> { let mut min = usize::max_value(); let mut max = 0; let mut functions = BTreeMap::new(); for (i, allocated) in finished_functions.iter() { let (start, end) = unsafe { let ptr = (***allocated).as_ptr(); let len = (***allocated).len(); (ptr as usize, ptr as usize + len) }; min = cmp::min(min, start); max = cmp::max(max, end); let func = FunctionInfo { start, local_index: i, }; assert!(functions.insert(end, func).is_none()); } if functions.is_empty() { return None; } let mut info = FRAME_INFO.write().unwrap(); // First up assert that our chunk of jit functions doesn't collide with // any other known chunks of jit functions... if let Some((_, prev)) = info.ranges.range(max..).next() { assert!(prev.start > max); } if let Some((prev_end, _)) = info.ranges.range(..=min).next_back() { assert!(*prev_end < min); } // ... then insert our range and assert nothing was there previously let prev = info.ranges.insert( max, ModuleInfoFrameInfo { start: min, functions, module, frame_infos, }, ); assert!(prev.is_none()); Some(GlobalFrameInfoRegistration { key: max }) } /// Description of a frame in a backtrace for a [`Trap`]. /// /// Whenever a WebAssembly trap occurs an instance of [`Trap`] is created. Each /// [`Trap`] has a backtrace of the WebAssembly frames that led to the trap, and /// each frame is described by this structure. /// /// [`Trap`]: crate::Trap #[derive(Debug, Clone)] pub struct FrameInfo { module_name: String, func_index: u32, function_name: Option<String>, func_start: SourceLoc, instr: SourceLoc, } impl FrameInfo { /// Returns the WebAssembly function index for this frame. /// /// This function index is the index in the function index space of the /// WebAssembly module that this frame comes from. pub fn func_index(&self) -> u32 { self.func_index } /// Returns the identifer of the module that this frame is for. /// /// ModuleInfo identifiers are present in the `name` section of a WebAssembly /// binary, but this may not return the exact item in the `name` section. /// ModuleInfo names can be overwritten at construction time or perhaps inferred /// from file names. The primary purpose of this function is to assist in /// debugging and therefore may be tweaked over time. /// /// This function returns `None` when no name can be found or inferred. pub fn module_name(&self) -> &str { &self.module_name } /// Returns a descriptive name of the function for this frame, if one is /// available. /// /// The name of this function may come from the `name` section of the /// WebAssembly binary, or wasmer may try to infer a better name for it if /// not available, for example the name of the export if it's exported. /// /// This return value is primarily used for debugging and human-readable /// purposes for things like traps. Note that the exact return value may be /// tweaked over time here and isn't guaranteed to be something in /// particular about a wasm module due to its primary purpose of assisting /// in debugging. /// /// This function returns `None` when no name could be inferred. pub fn function_name(&self) -> Option<&str> { self.function_name.as_deref() } /// Returns the offset within the original wasm module this frame's program /// counter was at.
/// /// The offset here is the offset from the beginning of the original wasm /// module to the instruction that this frame points to. pub fn module_offset(&self) -> usize { self.instr.bits() as usize } /// Returns the offset from the original wasm module's function to this /// frame's program counter. /// /// The offset here is the offset from the beginning of the defining /// function of this frame (within the wasm module) to the instruction this /// frame points to. pub fn func_offset(&self) -> usize { (self.instr.bits() - self.func_start.bits()) as usize } }
random_line_split
frame_info.rs
//! This module is used for having backtraces in the Wasm runtime. //! Once the Compiler has compiled the ModuleInfo, and we have a set of //! compiled functions (addresses and function index) and a module, //! then we can use this to set a backtrace for that module. //! //! # Example //! ```ignore //! use wasmer_vm::{ModuleInfo, FRAME_INFO}; //! //! let module: ModuleInfo = ...; //! FRAME_INFO.register(module, compiled_functions); //! ``` use crate::serialize::SerializableFunctionFrameInfo; use std::cmp; use std::collections::BTreeMap; use std::sync::{Arc, RwLock}; use wasmer_compiler::{CompiledFunctionFrameInfo, SourceLoc, TrapInformation}; use wasmer_types::entity::{BoxedSlice, EntityRef, PrimaryMap}; use wasmer_types::LocalFunctionIndex; use wasmer_vm::{FunctionBodyPtr, ModuleInfo}; lazy_static::lazy_static! { /// This is a global cache of backtrace frame information for all active /// /// This global cache is used during `Trap` creation to symbolicate frames. /// This is populated on module compilation, and it is cleared out whenever /// all references to a module are dropped. pub static ref FRAME_INFO: RwLock<GlobalFrameInfo> = Default::default(); } #[derive(Default)] pub struct
{ /// An internal map that keeps track of backtrace frame information for /// each module. /// /// This map is morally a map of ranges to a map of information for that /// module. Each module is expected to reside in a disjoint section of /// contiguous memory. No modules can overlap. /// /// The key of this map is the highest address in the module and the value /// is the module's information, which also contains the start address. ranges: BTreeMap<usize, ModuleInfoFrameInfo>, } /// An RAII structure used to unregister a module's frame information when the /// module is destroyed. pub struct GlobalFrameInfoRegistration { /// The key that will be removed from the global `ranges` map when this is /// dropped. key: usize, } struct ModuleInfoFrameInfo { start: usize, functions: BTreeMap<usize, FunctionInfo>, module: Arc<ModuleInfo>, frame_infos: PrimaryMap<LocalFunctionIndex, SerializableFunctionFrameInfo>, } impl ModuleInfoFrameInfo { fn function_debug_info( &self, local_index: LocalFunctionIndex, ) -> &SerializableFunctionFrameInfo { &self.frame_infos.get(local_index).unwrap() } fn process_function_debug_info(&mut self, local_index: LocalFunctionIndex) { let func = self.frame_infos.get_mut(local_index).unwrap(); let processed: CompiledFunctionFrameInfo = match func { SerializableFunctionFrameInfo::Processed(_) => { // This should be a no-op on processed info return; } SerializableFunctionFrameInfo::Unprocessed(unprocessed) => unprocessed.deserialize(), }; *func = SerializableFunctionFrameInfo::Processed(processed) } fn processed_function_frame_info( &self, local_index: LocalFunctionIndex, ) -> &CompiledFunctionFrameInfo { match self.function_debug_info(local_index) { SerializableFunctionFrameInfo::Processed(di) => &di, _ => unreachable!("frame info should already be processed"), } } /// Gets a function given a pc fn function_info(&self, pc: usize) -> Option<&FunctionInfo> { let (end, func) = self.functions.range(pc..).next()?; if pc < func.start || *end < pc { return None; } Some(func) } } struct FunctionInfo { start: usize, local_index: LocalFunctionIndex, } impl GlobalFrameInfo { /// Fetches frame information about a program counter in a backtrace. /// /// Returns an object if this `pc` is known to some previously registered /// module, or returns `None` if no information can be found. pub fn lookup_frame_info(&self, pc: usize) -> Option<FrameInfo> { let module = self.module_info(pc)?; let func = module.function_info(pc)?; // Use our relative position from the start of the function to find the // machine instruction that corresponds to `pc`, which then allows us to // map that to a wasm original source location. let rel_pos = pc - func.start; let instr_map = &module .processed_function_frame_info(func.local_index) .address_map; let pos = match instr_map .instructions .binary_search_by_key(&rel_pos, |map| map.code_offset) { // Exact hit! Ok(pos) => Some(pos), // This *would* be at the first slot in the array, so no // instructions cover `pc`. Err(0) => None, // This would be at the `nth` slot, so check `n-1` to see if we're // part of that instruction. This happens due to the minus one when // this function is called form trap symbolication, where we don't // always get called with a `pc` that's an exact instruction // boundary. Err(n) => { let instr = &instr_map.instructions[n - 1]; if instr.code_offset <= rel_pos && rel_pos < instr.code_offset + instr.code_len { Some(n - 1) } else { None } } }; // In debug mode for now assert that we found a mapping for `pc` within // the function, because otherwise something is buggy along the way and // not accounting for all the instructions. This isn't super critical // though so we can omit this check in release mode. debug_assert!(pos.is_some(), "failed to find instruction for {:x}", pc); let instr = match pos { Some(pos) => instr_map.instructions[pos].srcloc, None => instr_map.start_srcloc, }; let func_index = module.module.func_index(func.local_index); Some(FrameInfo { module_name: module.module.name(), func_index: func_index.index() as u32, function_name: module.module.function_names.get(&func_index).cloned(), instr, func_start: instr_map.start_srcloc, }) } /// Fetches trap information about a program counter in a backtrace. pub fn lookup_trap_info(&self, pc: usize) -> Option<&TrapInformation> { let module = self.module_info(pc)?; let func = module.function_info(pc)?; let traps = &module.processed_function_frame_info(func.local_index).traps; let idx = traps .binary_search_by_key(&((pc - func.start) as u32), |info| info.code_offset) .ok()?; Some(&traps[idx]) } /// Should process the frame before anything? pub fn should_process_frame(&self, pc: usize) -> Option<bool> { let module = self.module_info(pc)?; let func = module.function_info(pc)?; let extra_func_info = module.function_debug_info(func.local_index); Some(extra_func_info.is_unprocessed()) } /// Process the frame info in case is not yet processed pub fn maybe_process_frame(&mut self, pc: usize) -> Option<()> { let module = self.module_info_mut(pc)?; let func = module.function_info(pc)?; let func_local_index = func.local_index; module.process_function_debug_info(func_local_index); Some(()) } /// Gets a module given a pc fn module_info(&self, pc: usize) -> Option<&ModuleInfoFrameInfo> { let (end, module_info) = self.ranges.range(pc..).next()?; if pc < module_info.start || *end < pc { return None; } Some(module_info) } /// Gets a module given a pc fn module_info_mut(&mut self, pc: usize) -> Option<&mut ModuleInfoFrameInfo> { let (end, module_info) = self.ranges.range_mut(pc..).next()?; if pc < module_info.start || *end < pc { return None; } Some(module_info) } } impl Drop for GlobalFrameInfoRegistration { fn drop(&mut self) { if let Ok(mut info) = FRAME_INFO.write() { info.ranges.remove(&self.key); } } } /// Registers a new compiled module's frame information. /// /// This function will register the `names` information for all of the /// compiled functions within `module`. If the `module` has no functions /// then `None` will be returned. Otherwise the returned object, when /// dropped, will be used to unregister all name information from this map. pub fn register( module: Arc<ModuleInfo>, finished_functions: &BoxedSlice<LocalFunctionIndex, FunctionBodyPtr>, frame_infos: PrimaryMap<LocalFunctionIndex, SerializableFunctionFrameInfo>, ) -> Option<GlobalFrameInfoRegistration> { let mut min = usize::max_value(); let mut max = 0; let mut functions = BTreeMap::new(); for (i, allocated) in finished_functions.iter() { let (start, end) = unsafe { let ptr = (***allocated).as_ptr(); let len = (***allocated).len(); (ptr as usize, ptr as usize + len) }; min = cmp::min(min, start); max = cmp::max(max, end); let func = FunctionInfo { start, local_index: i, }; assert!(functions.insert(end, func).is_none()); } if functions.is_empty() { return None; } let mut info = FRAME_INFO.write().unwrap(); // First up assert that our chunk of jit functions doesn't collide with // any other known chunks of jit functions... if let Some((_, prev)) = info.ranges.range(max..).next() { assert!(prev.start > max); } if let Some((prev_end, _)) = info.ranges.range(..=min).next_back() { assert!(*prev_end < min); } // ... then insert our range and assert nothing was there previously let prev = info.ranges.insert( max, ModuleInfoFrameInfo { start: min, functions, module, frame_infos, }, ); assert!(prev.is_none()); Some(GlobalFrameInfoRegistration { key: max }) } /// Description of a frame in a backtrace for a [`Trap`]. /// /// Whenever a WebAssembly trap occurs an instance of [`Trap`] is created. Each /// [`Trap`] has a backtrace of the WebAssembly frames that led to the trap, and /// each frame is described by this structure. /// /// [`Trap`]: crate::Trap #[derive(Debug, Clone)] pub struct FrameInfo { module_name: String, func_index: u32, function_name: Option<String>, func_start: SourceLoc, instr: SourceLoc, } impl FrameInfo { /// Returns the WebAssembly function index for this frame. /// /// This function index is the index in the function index space of the /// WebAssembly module that this frame comes from. pub fn func_index(&self) -> u32 { self.func_index } /// Returns the identifer of the module that this frame is for. /// /// ModuleInfo identifiers are present in the `name` section of a WebAssembly /// binary, but this may not return the exact item in the `name` section. /// ModuleInfo names can be overwritten at construction time or perhaps inferred /// from file names. The primary purpose of this function is to assist in /// debugging and therefore may be tweaked over time. /// /// This function returns `None` when no name can be found or inferred. pub fn module_name(&self) -> &str { &self.module_name } /// Returns a descriptive name of the function for this frame, if one is /// available. /// /// The name of this function may come from the `name` section of the /// WebAssembly binary, or wasmer may try to infer a better name for it if /// not available, for example the name of the export if it's exported. /// /// This return value is primarily used for debugging and human-readable /// purposes for things like traps. Note that the exact return value may be /// tweaked over time here and isn't guaranteed to be something in /// particular about a wasm module due to its primary purpose of assisting /// in debugging. /// /// This function returns `None` when no name could be inferred. pub fn function_name(&self) -> Option<&str> { self.function_name.as_deref() } /// Returns the offset within the original wasm module this frame's program /// counter was at. /// /// The offset here is the offset from the beginning of the original wasm /// module to the instruction that this frame points to. pub fn module_offset(&self) -> usize { self.instr.bits() as usize } /// Returns the offset from the original wasm module's function to this /// frame's program counter. /// /// The offset here is the offset from the beginning of the defining /// function of this frame (within the wasm module) to the instruction this /// frame points to. pub fn func_offset(&self) -> usize { (self.instr.bits() - self.func_start.bits()) as usize } }
GlobalFrameInfo
identifier_name
simpletree.component.ts
import { Component, OnInit, OnChanges, ViewChild, ElementRef, Input, ViewEncapsulation, ViewContainerRef } from '@angular/core'; import { D3Service, D3, Selection } from 'd3-ng2-service'; import {WorkflowService} from '../workflow.service'; import {WorkflowMeta} from '../workflow-meta'; import {State} from '../state'; import {Tree} from '../tree'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/do'; import {BackendRequestClass} from '../backend.request'; import { Overlay } from 'angular2-modal'; import { Modal } from 'angular2-modal/plugins/bootstrap'; @Component({ selector: 'app-simpletree', templateUrl: './simpletree.component.html', styleUrls: ['./simpletree.component.css'] }) export class SimpletreeComponent implements OnInit { @ViewChild('tree') private treeContainer: ElementRef; @Input() private data: any; private d3: D3; // private member let to hold d3 reference private margin; private parentNativeElement: any; private svg: any; private width: number; private height: number; private root: any; private duration: 750; private treemap: any; private currentState: any; private nWidth: any; private nHeight: any; tooltip: any; tree: any; errorMessage: string; meta: WorkflowMeta; states: State[]; colors = { indigo: '#14143e', pink: '#fd1c49', orange: '#ff6e00', yellow: '#f0c800', mint: '#00efab', cyan: '#05d1ff', purple: '#841386', white: '#fff' }; constructor(element: ElementRef, d3service: D3Service, private workflowService: WorkflowService, private backend: BackendRequestClass, overlay: Overlay, vcRef: ViewContainerRef, public modal: Modal) { this.d3 = d3service.getD3(); this.parentNativeElement = element.nativeElement; overlay.defaultViewContainer = vcRef; } ngOnInit() { // gets and sets data from data service this.getWorkflowMeta(); this.getStates(); this.initDimensions(); // this.setDimensions(); this.createSVG(); this.declareTreeLayout(); this.assignRootPositions(); this.updateTree(this.root); } getWorkflowMeta() { this.workflowService.getWorkflowMeta() .subscribe( meta => { this.meta = meta; }, error => this.errorMessage = <any>error); } getStates() { this.workflowService.getStates() .subscribe( states => { this.states = states; }, error => this.errorMessage = <any>error); } extractTree(res: any): Tree { const states = res[0].workflow.states; console.log(res[0].workflow.state.id); const treearray = []; this.currentState = res[0].workflow.state.id; let previous, current, tree; for (let i = 0, len = states.length; i < len ; i++) { current = states[i]; // tree is empty push root node if (treearray.length === 0) { current.children = []; treearray.push(current); previous = current; continue; } // if id is 1 more than the previous then parent child relationship is assumed if (current.id === previous.id + 1) { current.children = []; previous.children.push(current); previous = current; } else { current.children = []; previous = current; treearray[0].children.push(current); } } tree = Object.assign({}, treearray[0]); // console.log(tree); return tree; } /* Method initializes dimensions for the svg object * Params: none */ initDimensions()
/* Sets new dimensions for tree * Params: (all optional) height and width of window and node object after window resize */ setDimensions(newHeight?, newWidth?, nodeH?, nodeW?) { // this.margin = {top: 20, right: 20, bottom: 20, left: 20}; newHeight != null ? this.height = newHeight - this.margin.top - this.margin.bottom : this.height = 1000 - this.margin.top - this.margin.bottom; newWidth != null ? this.width = newWidth - this.margin.right - this.margin.left : this.width = 1400 - this.margin.right - this.margin.left; // console.log(this.height); this.nWidth = nodeW; this.nHeight = nodeH; } onResize(event) { const d3 = this.d3; let nodeH = 0, nodeW; const newHeight = event.target.innerHeight - 50; console.log('newHeight %i', newHeight); const newWidth = event.target.innerWidth - 50; console.log('newWidth %i', newWidth); (newHeight < 740) ? nodeH = newHeight / 18 : nodeH = 40; (newWidth < 1500) ? nodeW = newWidth / 7 : nodeW = 220; // clears svg element for new tree d3.select('svg').remove(); // need to update dimensions after getting these new sizes this.getWorkflowMeta(); this.getStates(); this.setDimensions(newHeight, newWidth, nodeH, nodeW); this.createSVG(); this.declareTreeLayout(); this.assignRootPositions(); this.updateTree(this.root); } createSVG() { const d3 = this.d3; const width = this.width; const height = this.height; console.log(height); // let element = this.parentNativeElement; const element = this.treeContainer.nativeElement; this.svg = d3.select(element).append('svg') .attr('width', this.width + this.margin.right + this.margin.left) .attr('height', this.height + this.margin.top + this.margin.bottom) .append('g') .attr('transform', 'translate(' + this.margin.left + ',' + this.margin.top + ')'); // declares tooltip element this.tooltip = d3.select(element).append('div').attr('class', 'toolTip'); } declareTreeLayout() { console.log(this.height); const d3 = this.d3; this.treemap = d3.tree().size([this.height, this.width]); } assignRootPositions() { // console.log(this.height); const d3 = this.d3; this.tree = this.extractTree(this.data); // console.log(this.data); // this.tree = this.data; this.root = d3.hierarchy(this.tree); this.root.x0 = this.height / 2; // console.log(this.root.x0); this.root.y0 = 0; } diagonal(source, destination) { console.log(source); console.log(destination); var x = destination.x + 150 / 2; var y = destination.y; var px = source.x + 40 / 2; var py = source.y + 40; return 'M' + x + ',' + y + 'C' + x + ',' + (y + py) / 2 + ' ' + x + ',' + (y + py) / 2 + ' ' + px + ',' + py; } updateTree(source) { const modal = this.modal; let nodeHeight = this.nHeight; let nodeWidth = this.nWidth; const d3 = this.d3; const costOffset = 18; // offset in px for the cost symbol based on symbol size let currentState = this.currentState; let i = 0; // Assigns the x and y position for the nodes let treeData = this.treemap(this.root); // Compute the new tree layout let nodes = treeData.descendants(), links = treeData.descendants().slice(1); // Normalize for fixed-depth nodes.forEach(function(d) { d.y = d.depth * (nodeWidth + 25); }); // Nodes section // let node = this.svg.selectAll('g.node') .data(nodes, function(d) { return d.id || (d.id = ++i); }); // Enter any new modes at the parent's previous position. let nodeEnter = node.enter().append('g') .attr('class', 'node') .attr('transform', function(d) { return 'translate(' + source.y0 + ',' + source.x0 + ')'; }); nodeEnter.append('rect') .attr('width', 1e-6) .attr('height', 1e-6) .on('mouseover', function(d) { const xPosition = this.getBoundingClientRect().left + (nodeWidth / 10); const yPosition = (this.getBoundingClientRect().top - (nodeHeight * 2.5)); // console.log(this.getBoundingClientRect()); // console.log(this.getBoundingClientRect().top); // console.log(yPosition); d3.select('#tooltip') .style('left', xPosition + 'px') .style('top', yPosition + 'px') .select('#value') .text(d.data.desc); d3.select('#tooltip') .select('#progress') .text(d.data.percentcomplete); d3.select('#tooltip').classed('hidden', false); }) .on('mouseout', function() { d3.select('#tooltip').classed('hidden', true); }) .on('click', function(d){ d3.select('#tooltip').classed('hidden', true); modal.alert() .size('lg') .showClose(true) .titleHtml(`State ID: ` + d.data.id) .body(`<!--<h4>State Details:</h4>--> <div class="description-container"> <span class="modal-stateID"> State ID: ` + ' ' + d.data.id + `</span> <span class="modal-stateName">` + ' ' + d.data.name + `</span> <span class="modal-description">` + ' ' + d.data.desc + `</span> </div> <div class="stateMeta"> <ul class="first-col"> <li>Status:` + ' ' + d.data.status + `</li> <li>Rev:` + ' ' + d.data.rev + `</li> <li>Iteration:` + ' ' + d.data.iteration + `</li> <li>Percent Complete:` + ' ' + d.data.percentcomplete + `</li> <!--<li>Participants:` + ' ' + d.data.participants + `</li>--> </ul> <ul class="second-col"> <li>Actual Hours:` + ' ' + d.data.actualhours + `</li> <li>Planned Hours:` + ' ' + d.data.plannedhours + `</li> <li>Start:` + ' ' + d.data.start + `</li> <li>End:` + ' ' + d.data.end + `</li> </ul> </div> `) .open(); }) .on('dblclick', function(d) { if (d.children) { d._children = d.children; d.children = null; } else { d.children = d._children; d._children = null; } this.update(d); }); nodeEnter.append('text') .attr("id", "state-name") .attr('x', 10) //.attr('y', -8) .attr('y', function (d){ return nodeHeight / 12; }) .attr('dy', '.35em') .text(function(d) { return d.data.name; }); // UPDATE Nodes let nodeUpdate = nodeEnter.merge(node); // Transition to the proper position for the node nodeUpdate.transition() .duration(this.duration) .attr('transform', function(d) { return 'translate(' + d.y + ',' + d.x + ')'; }); nodeUpdate.selectAll('rect') .attr('rx', 6) .attr('ry', 6) .attr('y', -(nodeHeight / 2)) .attr('width', nodeWidth) .attr('height', nodeHeight) .style('fill', function(d) { if (d.data.quality == 'Q1') {return '#7F90FC'; } else if (d.data.quality == 'Q2') {return '#7FFD7F'; } else if (d.data.quality == 'Q3') {return '#FFFE70'; } else if (d.data.quality == 'Q4') {return '#FC6668'; } else {return '#FFF'; } }) .style('stroke', function (d){ return (d.data.id === currentState) ? '#05d1ff' : '#636363'; }) .style('stroke-width', function (d){ return (d.data.id === currentState) ? '5px' : '2.5px'; }); nodeUpdate.select('text') .style('fill-opacity', 1); // Node exit let nodeExit = node.exit().transition() .duration(this.duration) .attr('transform', function(d) { return 'translate(' + source.y + ',' + source.x + ')'; }) .remove(); nodeExit.select('rect') .attr('width', 1e-6) .attr('height', 1e-6); nodeExit.select('text') .style('fill-opacity', 1e-6); // Update the links… let link = this.svg.selectAll('.link') .data(links); // Enter any new links at the parent's previous position. // ** I dont know if this is correct, but it compiles let linkEnter = link.enter().insert('path', 'g') .attr('class', 'link') .attr('d', function(d){ // let o = {x: source.x0, y: source.y0}; // return this.diagonal(o, o); return 'M' + d.y + ',' + d.x + 'C' + (d.y + d.parent.y) / 2 + ',' + d.x + ' ' + (d.y + d.parent.y) / 2 + ',' + d.parent.x + ' ' + d.parent.y + ',' + d.parent.x; }); // Transition links to their new position. link.transition() .duration(this.duration) .attr('d', function(d){ var o = {x: d.x0, y: d.parent.y0}; // return this.diagonal(d, d.parent); return 'M' + d.y + ',' + d.x + 'C' + (d.y + d.parent.y) / 2 + ',' + d.x + ' ' + (d.y + d.parent.y) / 2 + ',' + d.parent.x + ' ' + d.parent.y + ',' + d.parent.x; }); // Transition exiting nodes to the parent's new position. link.exit().transition() .duration(this.duration) .attr('d', function(d) { // var o = {x: source.x, y: source.y}; // return this.diagonal(o, o); return 'M' + d.y + ',' + d.x + 'C' + (d.y + d.parent.y) / 2 + ',' + d.x + ' ' + (d.y + d.parent.y) / 2 + ',' + d.parent.x + ' ' + d.parent.y + ',' + d.parent.x; }) .remove(); // Stash the old positions for transition. nodes.forEach(function(d) { d.x0 = d.x; d.y0 = d.y; }); } // Toggle children on click. click(d) { console.log(this.root); if (d.children) { d._children = d.children; d.children = null; } else { d.children = d._children; d._children = null; } console.log(d); this.updateTree(d); } collapse(d) { if (d.children) { d._children = d.children; d._children.forEach(this.collapse); d.children = null; } } }
{ this.margin = {top: 20, right: 20, bottom: 20, left: 20}; this.height = window.innerHeight - 50 - this.margin.top - this.margin.bottom; this.width = window.innerWidth - this.margin.right - this.margin.left; // this.nHeight = 40; // this.nWidth = 220; this.nHeight = window.innerHeight / 18; this.nWidth = window.innerWidth / 7; }
identifier_body
simpletree.component.ts
import { Component, OnInit, OnChanges, ViewChild, ElementRef, Input, ViewEncapsulation, ViewContainerRef } from '@angular/core'; import { D3Service, D3, Selection } from 'd3-ng2-service'; import {WorkflowService} from '../workflow.service'; import {WorkflowMeta} from '../workflow-meta'; import {State} from '../state'; import {Tree} from '../tree'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/do'; import {BackendRequestClass} from '../backend.request'; import { Overlay } from 'angular2-modal'; import { Modal } from 'angular2-modal/plugins/bootstrap'; @Component({ selector: 'app-simpletree', templateUrl: './simpletree.component.html', styleUrls: ['./simpletree.component.css'] }) export class SimpletreeComponent implements OnInit { @ViewChild('tree') private treeContainer: ElementRef; @Input() private data: any; private d3: D3; // private member let to hold d3 reference private margin; private parentNativeElement: any; private svg: any; private width: number; private height: number; private root: any; private duration: 750; private treemap: any; private currentState: any; private nWidth: any; private nHeight: any; tooltip: any; tree: any; errorMessage: string; meta: WorkflowMeta; states: State[]; colors = { indigo: '#14143e', pink: '#fd1c49', orange: '#ff6e00', yellow: '#f0c800', mint: '#00efab', cyan: '#05d1ff', purple: '#841386', white: '#fff' }; constructor(element: ElementRef, d3service: D3Service, private workflowService: WorkflowService, private backend: BackendRequestClass, overlay: Overlay, vcRef: ViewContainerRef, public modal: Modal) { this.d3 = d3service.getD3(); this.parentNativeElement = element.nativeElement; overlay.defaultViewContainer = vcRef; } ngOnInit() { // gets and sets data from data service this.getWorkflowMeta(); this.getStates(); this.initDimensions(); // this.setDimensions(); this.createSVG(); this.declareTreeLayout(); this.assignRootPositions(); this.updateTree(this.root); } getWorkflowMeta() { this.workflowService.getWorkflowMeta() .subscribe( meta => { this.meta = meta; }, error => this.errorMessage = <any>error); } getStates() { this.workflowService.getStates() .subscribe( states => { this.states = states; }, error => this.errorMessage = <any>error); } extractTree(res: any): Tree { const states = res[0].workflow.states; console.log(res[0].workflow.state.id); const treearray = []; this.currentState = res[0].workflow.state.id; let previous, current, tree; for (let i = 0, len = states.length; i < len ; i++) { current = states[i]; // tree is empty push root node if (treearray.length === 0) { current.children = []; treearray.push(current); previous = current; continue; } // if id is 1 more than the previous then parent child relationship is assumed if (current.id === previous.id + 1) { current.children = []; previous.children.push(current); previous = current; } else { current.children = []; previous = current; treearray[0].children.push(current); } } tree = Object.assign({}, treearray[0]); // console.log(tree); return tree; } /* Method initializes dimensions for the svg object * Params: none */ initDimensions() { this.margin = {top: 20, right: 20, bottom: 20, left: 20}; this.height = window.innerHeight - 50 - this.margin.top - this.margin.bottom; this.width = window.innerWidth - this.margin.right - this.margin.left; // this.nHeight = 40; // this.nWidth = 220; this.nHeight = window.innerHeight / 18; this.nWidth = window.innerWidth / 7; } /* Sets new dimensions for tree * Params: (all optional) height and width of window and node object after window resize */ setDimensions(newHeight?, newWidth?, nodeH?, nodeW?) { // this.margin = {top: 20, right: 20, bottom: 20, left: 20}; newHeight != null ? this.height = newHeight - this.margin.top - this.margin.bottom : this.height = 1000 - this.margin.top - this.margin.bottom; newWidth != null ? this.width = newWidth - this.margin.right - this.margin.left : this.width = 1400 - this.margin.right - this.margin.left; // console.log(this.height); this.nWidth = nodeW; this.nHeight = nodeH; } onResize(event) { const d3 = this.d3; let nodeH = 0, nodeW; const newHeight = event.target.innerHeight - 50; console.log('newHeight %i', newHeight); const newWidth = event.target.innerWidth - 50; console.log('newWidth %i', newWidth); (newHeight < 740) ? nodeH = newHeight / 18 : nodeH = 40; (newWidth < 1500) ? nodeW = newWidth / 7 : nodeW = 220; // clears svg element for new tree d3.select('svg').remove(); // need to update dimensions after getting these new sizes this.getWorkflowMeta(); this.getStates(); this.setDimensions(newHeight, newWidth, nodeH, nodeW); this.createSVG(); this.declareTreeLayout(); this.assignRootPositions(); this.updateTree(this.root); } createSVG() { const d3 = this.d3; const width = this.width; const height = this.height; console.log(height); // let element = this.parentNativeElement; const element = this.treeContainer.nativeElement; this.svg = d3.select(element).append('svg') .attr('width', this.width + this.margin.right + this.margin.left) .attr('height', this.height + this.margin.top + this.margin.bottom) .append('g') .attr('transform', 'translate(' + this.margin.left + ',' + this.margin.top + ')'); // declares tooltip element this.tooltip = d3.select(element).append('div').attr('class', 'toolTip'); } declareTreeLayout() { console.log(this.height); const d3 = this.d3; this.treemap = d3.tree().size([this.height, this.width]); } assignRootPositions() { // console.log(this.height); const d3 = this.d3; this.tree = this.extractTree(this.data); // console.log(this.data); // this.tree = this.data; this.root = d3.hierarchy(this.tree); this.root.x0 = this.height / 2; // console.log(this.root.x0); this.root.y0 = 0; } diagonal(source, destination) { console.log(source); console.log(destination); var x = destination.x + 150 / 2; var y = destination.y; var px = source.x + 40 / 2; var py = source.y + 40; return 'M' + x + ',' + y + 'C' + x + ',' + (y + py) / 2 + ' ' + x + ',' + (y + py) / 2 + ' ' + px + ',' + py; } updateTree(source) { const modal = this.modal; let nodeHeight = this.nHeight; let nodeWidth = this.nWidth; const d3 = this.d3; const costOffset = 18; // offset in px for the cost symbol based on symbol size let currentState = this.currentState; let i = 0; // Assigns the x and y position for the nodes let treeData = this.treemap(this.root); // Compute the new tree layout let nodes = treeData.descendants(), links = treeData.descendants().slice(1); // Normalize for fixed-depth nodes.forEach(function(d) { d.y = d.depth * (nodeWidth + 25); }); // Nodes section // let node = this.svg.selectAll('g.node') .data(nodes, function(d) { return d.id || (d.id = ++i); }); // Enter any new modes at the parent's previous position. let nodeEnter = node.enter().append('g') .attr('class', 'node') .attr('transform', function(d) { return 'translate(' + source.y0 + ',' + source.x0 + ')'; }); nodeEnter.append('rect') .attr('width', 1e-6) .attr('height', 1e-6) .on('mouseover', function(d) { const xPosition = this.getBoundingClientRect().left + (nodeWidth / 10); const yPosition = (this.getBoundingClientRect().top - (nodeHeight * 2.5)); // console.log(this.getBoundingClientRect()); // console.log(this.getBoundingClientRect().top); // console.log(yPosition); d3.select('#tooltip') .style('left', xPosition + 'px') .style('top', yPosition + 'px') .select('#value') .text(d.data.desc); d3.select('#tooltip') .select('#progress') .text(d.data.percentcomplete); d3.select('#tooltip').classed('hidden', false); }) .on('mouseout', function() { d3.select('#tooltip').classed('hidden', true); }) .on('click', function(d){ d3.select('#tooltip').classed('hidden', true); modal.alert() .size('lg') .showClose(true) .titleHtml(`State ID: ` + d.data.id) .body(`<!--<h4>State Details:</h4>--> <div class="description-container"> <span class="modal-stateID"> State ID: ` + ' ' + d.data.id + `</span> <span class="modal-stateName">` + ' ' + d.data.name + `</span> <span class="modal-description">` + ' ' + d.data.desc + `</span> </div> <div class="stateMeta"> <ul class="first-col"> <li>Status:` + ' ' + d.data.status + `</li> <li>Rev:` + ' ' + d.data.rev + `</li> <li>Iteration:` + ' ' + d.data.iteration + `</li> <li>Percent Complete:` + ' ' + d.data.percentcomplete + `</li> <!--<li>Participants:` + ' ' + d.data.participants + `</li>--> </ul> <ul class="second-col"> <li>Actual Hours:` + ' ' + d.data.actualhours + `</li> <li>Planned Hours:` + ' ' + d.data.plannedhours + `</li> <li>Start:` + ' ' + d.data.start + `</li> <li>End:` + ' ' + d.data.end + `</li> </ul> </div> `) .open(); }) .on('dblclick', function(d) { if (d.children) { d._children = d.children; d.children = null; } else { d.children = d._children; d._children = null; } this.update(d); }); nodeEnter.append('text') .attr("id", "state-name") .attr('x', 10) //.attr('y', -8) .attr('y', function (d){ return nodeHeight / 12; }) .attr('dy', '.35em') .text(function(d) { return d.data.name; }); // UPDATE Nodes let nodeUpdate = nodeEnter.merge(node); // Transition to the proper position for the node nodeUpdate.transition() .duration(this.duration) .attr('transform', function(d) { return 'translate(' + d.y + ',' + d.x + ')'; }); nodeUpdate.selectAll('rect') .attr('rx', 6) .attr('ry', 6) .attr('y', -(nodeHeight / 2)) .attr('width', nodeWidth) .attr('height', nodeHeight) .style('fill', function(d) { if (d.data.quality == 'Q1') {return '#7F90FC'; } else if (d.data.quality == 'Q2') {return '#7FFD7F'; } else if (d.data.quality == 'Q3') {return '#FFFE70'; } else if (d.data.quality == 'Q4') {return '#FC6668'; } else {return '#FFF'; } }) .style('stroke', function (d){ return (d.data.id === currentState) ? '#05d1ff' : '#636363'; }) .style('stroke-width', function (d){ return (d.data.id === currentState) ? '5px' : '2.5px'; }); nodeUpdate.select('text') .style('fill-opacity', 1); // Node exit let nodeExit = node.exit().transition() .duration(this.duration) .attr('transform', function(d) { return 'translate(' + source.y + ',' + source.x + ')'; }) .remove(); nodeExit.select('rect') .attr('width', 1e-6) .attr('height', 1e-6); nodeExit.select('text') .style('fill-opacity', 1e-6); // Update the links…
.data(links); // Enter any new links at the parent's previous position. // ** I dont know if this is correct, but it compiles let linkEnter = link.enter().insert('path', 'g') .attr('class', 'link') .attr('d', function(d){ // let o = {x: source.x0, y: source.y0}; // return this.diagonal(o, o); return 'M' + d.y + ',' + d.x + 'C' + (d.y + d.parent.y) / 2 + ',' + d.x + ' ' + (d.y + d.parent.y) / 2 + ',' + d.parent.x + ' ' + d.parent.y + ',' + d.parent.x; }); // Transition links to their new position. link.transition() .duration(this.duration) .attr('d', function(d){ var o = {x: d.x0, y: d.parent.y0}; // return this.diagonal(d, d.parent); return 'M' + d.y + ',' + d.x + 'C' + (d.y + d.parent.y) / 2 + ',' + d.x + ' ' + (d.y + d.parent.y) / 2 + ',' + d.parent.x + ' ' + d.parent.y + ',' + d.parent.x; }); // Transition exiting nodes to the parent's new position. link.exit().transition() .duration(this.duration) .attr('d', function(d) { // var o = {x: source.x, y: source.y}; // return this.diagonal(o, o); return 'M' + d.y + ',' + d.x + 'C' + (d.y + d.parent.y) / 2 + ',' + d.x + ' ' + (d.y + d.parent.y) / 2 + ',' + d.parent.x + ' ' + d.parent.y + ',' + d.parent.x; }) .remove(); // Stash the old positions for transition. nodes.forEach(function(d) { d.x0 = d.x; d.y0 = d.y; }); } // Toggle children on click. click(d) { console.log(this.root); if (d.children) { d._children = d.children; d.children = null; } else { d.children = d._children; d._children = null; } console.log(d); this.updateTree(d); } collapse(d) { if (d.children) { d._children = d.children; d._children.forEach(this.collapse); d.children = null; } } }
let link = this.svg.selectAll('.link')
random_line_split
simpletree.component.ts
import { Component, OnInit, OnChanges, ViewChild, ElementRef, Input, ViewEncapsulation, ViewContainerRef } from '@angular/core'; import { D3Service, D3, Selection } from 'd3-ng2-service'; import {WorkflowService} from '../workflow.service'; import {WorkflowMeta} from '../workflow-meta'; import {State} from '../state'; import {Tree} from '../tree'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/do'; import {BackendRequestClass} from '../backend.request'; import { Overlay } from 'angular2-modal'; import { Modal } from 'angular2-modal/plugins/bootstrap'; @Component({ selector: 'app-simpletree', templateUrl: './simpletree.component.html', styleUrls: ['./simpletree.component.css'] }) export class SimpletreeComponent implements OnInit { @ViewChild('tree') private treeContainer: ElementRef; @Input() private data: any; private d3: D3; // private member let to hold d3 reference private margin; private parentNativeElement: any; private svg: any; private width: number; private height: number; private root: any; private duration: 750; private treemap: any; private currentState: any; private nWidth: any; private nHeight: any; tooltip: any; tree: any; errorMessage: string; meta: WorkflowMeta; states: State[]; colors = { indigo: '#14143e', pink: '#fd1c49', orange: '#ff6e00', yellow: '#f0c800', mint: '#00efab', cyan: '#05d1ff', purple: '#841386', white: '#fff' }; constructor(element: ElementRef, d3service: D3Service, private workflowService: WorkflowService, private backend: BackendRequestClass, overlay: Overlay, vcRef: ViewContainerRef, public modal: Modal) { this.d3 = d3service.getD3(); this.parentNativeElement = element.nativeElement; overlay.defaultViewContainer = vcRef; } ngOnInit() { // gets and sets data from data service this.getWorkflowMeta(); this.getStates(); this.initDimensions(); // this.setDimensions(); this.createSVG(); this.declareTreeLayout(); this.assignRootPositions(); this.updateTree(this.root); } getWorkflowMeta() { this.workflowService.getWorkflowMeta() .subscribe( meta => { this.meta = meta; }, error => this.errorMessage = <any>error); } getStates() { this.workflowService.getStates() .subscribe( states => { this.states = states; }, error => this.errorMessage = <any>error); } extractTree(res: any): Tree { const states = res[0].workflow.states; console.log(res[0].workflow.state.id); const treearray = []; this.currentState = res[0].workflow.state.id; let previous, current, tree; for (let i = 0, len = states.length; i < len ; i++) { current = states[i]; // tree is empty push root node if (treearray.length === 0) { current.children = []; treearray.push(current); previous = current; continue; } // if id is 1 more than the previous then parent child relationship is assumed if (current.id === previous.id + 1) { current.children = []; previous.children.push(current); previous = current; } else { current.children = []; previous = current; treearray[0].children.push(current); } } tree = Object.assign({}, treearray[0]); // console.log(tree); return tree; } /* Method initializes dimensions for the svg object * Params: none */ initDimensions() { this.margin = {top: 20, right: 20, bottom: 20, left: 20}; this.height = window.innerHeight - 50 - this.margin.top - this.margin.bottom; this.width = window.innerWidth - this.margin.right - this.margin.left; // this.nHeight = 40; // this.nWidth = 220; this.nHeight = window.innerHeight / 18; this.nWidth = window.innerWidth / 7; } /* Sets new dimensions for tree * Params: (all optional) height and width of window and node object after window resize */ setDimensions(newHeight?, newWidth?, nodeH?, nodeW?) { // this.margin = {top: 20, right: 20, bottom: 20, left: 20}; newHeight != null ? this.height = newHeight - this.margin.top - this.margin.bottom : this.height = 1000 - this.margin.top - this.margin.bottom; newWidth != null ? this.width = newWidth - this.margin.right - this.margin.left : this.width = 1400 - this.margin.right - this.margin.left; // console.log(this.height); this.nWidth = nodeW; this.nHeight = nodeH; } onResize(event) { const d3 = this.d3; let nodeH = 0, nodeW; const newHeight = event.target.innerHeight - 50; console.log('newHeight %i', newHeight); const newWidth = event.target.innerWidth - 50; console.log('newWidth %i', newWidth); (newHeight < 740) ? nodeH = newHeight / 18 : nodeH = 40; (newWidth < 1500) ? nodeW = newWidth / 7 : nodeW = 220; // clears svg element for new tree d3.select('svg').remove(); // need to update dimensions after getting these new sizes this.getWorkflowMeta(); this.getStates(); this.setDimensions(newHeight, newWidth, nodeH, nodeW); this.createSVG(); this.declareTreeLayout(); this.assignRootPositions(); this.updateTree(this.root); } createSVG() { const d3 = this.d3; const width = this.width; const height = this.height; console.log(height); // let element = this.parentNativeElement; const element = this.treeContainer.nativeElement; this.svg = d3.select(element).append('svg') .attr('width', this.width + this.margin.right + this.margin.left) .attr('height', this.height + this.margin.top + this.margin.bottom) .append('g') .attr('transform', 'translate(' + this.margin.left + ',' + this.margin.top + ')'); // declares tooltip element this.tooltip = d3.select(element).append('div').attr('class', 'toolTip'); } declareTreeLayout() { console.log(this.height); const d3 = this.d3; this.treemap = d3.tree().size([this.height, this.width]); } assignRootPositions() { // console.log(this.height); const d3 = this.d3; this.tree = this.extractTree(this.data); // console.log(this.data); // this.tree = this.data; this.root = d3.hierarchy(this.tree); this.root.x0 = this.height / 2; // console.log(this.root.x0); this.root.y0 = 0; }
(source, destination) { console.log(source); console.log(destination); var x = destination.x + 150 / 2; var y = destination.y; var px = source.x + 40 / 2; var py = source.y + 40; return 'M' + x + ',' + y + 'C' + x + ',' + (y + py) / 2 + ' ' + x + ',' + (y + py) / 2 + ' ' + px + ',' + py; } updateTree(source) { const modal = this.modal; let nodeHeight = this.nHeight; let nodeWidth = this.nWidth; const d3 = this.d3; const costOffset = 18; // offset in px for the cost symbol based on symbol size let currentState = this.currentState; let i = 0; // Assigns the x and y position for the nodes let treeData = this.treemap(this.root); // Compute the new tree layout let nodes = treeData.descendants(), links = treeData.descendants().slice(1); // Normalize for fixed-depth nodes.forEach(function(d) { d.y = d.depth * (nodeWidth + 25); }); // Nodes section // let node = this.svg.selectAll('g.node') .data(nodes, function(d) { return d.id || (d.id = ++i); }); // Enter any new modes at the parent's previous position. let nodeEnter = node.enter().append('g') .attr('class', 'node') .attr('transform', function(d) { return 'translate(' + source.y0 + ',' + source.x0 + ')'; }); nodeEnter.append('rect') .attr('width', 1e-6) .attr('height', 1e-6) .on('mouseover', function(d) { const xPosition = this.getBoundingClientRect().left + (nodeWidth / 10); const yPosition = (this.getBoundingClientRect().top - (nodeHeight * 2.5)); // console.log(this.getBoundingClientRect()); // console.log(this.getBoundingClientRect().top); // console.log(yPosition); d3.select('#tooltip') .style('left', xPosition + 'px') .style('top', yPosition + 'px') .select('#value') .text(d.data.desc); d3.select('#tooltip') .select('#progress') .text(d.data.percentcomplete); d3.select('#tooltip').classed('hidden', false); }) .on('mouseout', function() { d3.select('#tooltip').classed('hidden', true); }) .on('click', function(d){ d3.select('#tooltip').classed('hidden', true); modal.alert() .size('lg') .showClose(true) .titleHtml(`State ID: ` + d.data.id) .body(`<!--<h4>State Details:</h4>--> <div class="description-container"> <span class="modal-stateID"> State ID: ` + ' ' + d.data.id + `</span> <span class="modal-stateName">` + ' ' + d.data.name + `</span> <span class="modal-description">` + ' ' + d.data.desc + `</span> </div> <div class="stateMeta"> <ul class="first-col"> <li>Status:` + ' ' + d.data.status + `</li> <li>Rev:` + ' ' + d.data.rev + `</li> <li>Iteration:` + ' ' + d.data.iteration + `</li> <li>Percent Complete:` + ' ' + d.data.percentcomplete + `</li> <!--<li>Participants:` + ' ' + d.data.participants + `</li>--> </ul> <ul class="second-col"> <li>Actual Hours:` + ' ' + d.data.actualhours + `</li> <li>Planned Hours:` + ' ' + d.data.plannedhours + `</li> <li>Start:` + ' ' + d.data.start + `</li> <li>End:` + ' ' + d.data.end + `</li> </ul> </div> `) .open(); }) .on('dblclick', function(d) { if (d.children) { d._children = d.children; d.children = null; } else { d.children = d._children; d._children = null; } this.update(d); }); nodeEnter.append('text') .attr("id", "state-name") .attr('x', 10) //.attr('y', -8) .attr('y', function (d){ return nodeHeight / 12; }) .attr('dy', '.35em') .text(function(d) { return d.data.name; }); // UPDATE Nodes let nodeUpdate = nodeEnter.merge(node); // Transition to the proper position for the node nodeUpdate.transition() .duration(this.duration) .attr('transform', function(d) { return 'translate(' + d.y + ',' + d.x + ')'; }); nodeUpdate.selectAll('rect') .attr('rx', 6) .attr('ry', 6) .attr('y', -(nodeHeight / 2)) .attr('width', nodeWidth) .attr('height', nodeHeight) .style('fill', function(d) { if (d.data.quality == 'Q1') {return '#7F90FC'; } else if (d.data.quality == 'Q2') {return '#7FFD7F'; } else if (d.data.quality == 'Q3') {return '#FFFE70'; } else if (d.data.quality == 'Q4') {return '#FC6668'; } else {return '#FFF'; } }) .style('stroke', function (d){ return (d.data.id === currentState) ? '#05d1ff' : '#636363'; }) .style('stroke-width', function (d){ return (d.data.id === currentState) ? '5px' : '2.5px'; }); nodeUpdate.select('text') .style('fill-opacity', 1); // Node exit let nodeExit = node.exit().transition() .duration(this.duration) .attr('transform', function(d) { return 'translate(' + source.y + ',' + source.x + ')'; }) .remove(); nodeExit.select('rect') .attr('width', 1e-6) .attr('height', 1e-6); nodeExit.select('text') .style('fill-opacity', 1e-6); // Update the links… let link = this.svg.selectAll('.link') .data(links); // Enter any new links at the parent's previous position. // ** I dont know if this is correct, but it compiles let linkEnter = link.enter().insert('path', 'g') .attr('class', 'link') .attr('d', function(d){ // let o = {x: source.x0, y: source.y0}; // return this.diagonal(o, o); return 'M' + d.y + ',' + d.x + 'C' + (d.y + d.parent.y) / 2 + ',' + d.x + ' ' + (d.y + d.parent.y) / 2 + ',' + d.parent.x + ' ' + d.parent.y + ',' + d.parent.x; }); // Transition links to their new position. link.transition() .duration(this.duration) .attr('d', function(d){ var o = {x: d.x0, y: d.parent.y0}; // return this.diagonal(d, d.parent); return 'M' + d.y + ',' + d.x + 'C' + (d.y + d.parent.y) / 2 + ',' + d.x + ' ' + (d.y + d.parent.y) / 2 + ',' + d.parent.x + ' ' + d.parent.y + ',' + d.parent.x; }); // Transition exiting nodes to the parent's new position. link.exit().transition() .duration(this.duration) .attr('d', function(d) { // var o = {x: source.x, y: source.y}; // return this.diagonal(o, o); return 'M' + d.y + ',' + d.x + 'C' + (d.y + d.parent.y) / 2 + ',' + d.x + ' ' + (d.y + d.parent.y) / 2 + ',' + d.parent.x + ' ' + d.parent.y + ',' + d.parent.x; }) .remove(); // Stash the old positions for transition. nodes.forEach(function(d) { d.x0 = d.x; d.y0 = d.y; }); } // Toggle children on click. click(d) { console.log(this.root); if (d.children) { d._children = d.children; d.children = null; } else { d.children = d._children; d._children = null; } console.log(d); this.updateTree(d); } collapse(d) { if (d.children) { d._children = d.children; d._children.forEach(this.collapse); d.children = null; } } }
diagonal
identifier_name
dataCreationHelpers.js
/** * Created by Andy Likuski on 2017.02.23 * Copyright (c) 2017 Andy Likuski * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import * as R from 'ramda'; import moment from 'moment'; import {fromImmutable, toTimeString, calculateDistance} from 'rescape-helpers'; const { capitalize, compact, compactJoin, emptyToNull, idOrIdFromObj } = require('rescape-ramda'); // Direction ids for typical Trip pairs export const FROM_TO_DIRECTION = { id: '0', resolveToStop: route => route.places.to, resolveTripSymbol: route => `${route.places.from.id}->${route.via ? `(${route.via})->` : ''}${route.places.to.id}` }; export const TO_FROM_DIRECTION = { id: '1', resolveToStop: route => route.places.from, resolveTripSymbol: route => `${route.places.to.id}->${route.via ? `(${route.via})->` : ''}${route.places.from.id}` }; const tripHeadSign = (to, via) => compact([to.label, via]).join(' via '); /** * Forms a unique stop id based on the place id and which station/stop of that place it is * @param {Place|id} place The Place object or its id * @param {string} place.id The id of the Place used to create the Stop id * @param {string|null} [which] Which station/stop (e.g. Union, Airport) * @returns {string} A stop id */ export const createStopId = (place, which = null) => compact([idOrIdFromObj(place), which]).join('-'); /** * @typedef {Object} Location * @property {number} lon The longitude * @property {number} lat The latitude **/ /** * @typedef {Object} Stop * @property {string} id The X Coordinate * @property {Place} place The Place of the Stop * @property {string} which Which Stop/Station of the Place (e.g. Central or Airport) * @property {stopName} the name of the Stop * @property {Location} the lon/lat of the Stop */ /** * Creates a GTFS compatible stop definition * @param {Place} place Place object representing a city or town * @param {string} place.id The 3 letter code of the city or town main station, based on train station codes * @param {string} place.label Label describing the place * @param {string} which Label representing the specific stop, such as 'Amtrak', 'Central', 'Arena', or 'Airport'. * @param {Location} location: lon/lat pair * @param {number} location.lon The longitude * @param {number} location.lat The latitude * @param {Object} [options] Options * @param {string|null} [options.stopName] label describing the stop. Defaults to `${place}[ ${where}] ${stopType}` * @param {string|null} [options.stopType] label describing the stop type if stopName is not used, defaults to 'Station' * @returns {Map} A Stop object */ export const createStop = (place, which, location, options = {}) => { const id = createStopId(place, which); return { id: id, place: place, which: which, stopName: options.stopName || `${place.label} ${which} ${options.stopType || 'Station'}`, location }; }; /** * @ * @property {string} id The id of the Route * @property {[Place]} places The two end Places of the Route * @property {string} routeLongName The full name of the Route * @property {string} routeShortName The short name of the Route * @property {string} routeType The id of the RouteType * @property {string} [via] The optional intermediate Region of the Route */ /** * Forms a unique Route id based on the place id and which station/stop of that place it is. * @param {Place|id} from The start/end Place or its id * @param {Place|id} to The other start/end Place or its id * @param {string} [via] Optional pass through Region to distinguish the route * @returns {string} A Route id */ export const createRouteId = (from, to, via) => { const fromId = idOrIdFromObj(from); const toId = idOrIdFromObj(to); return via ? `${ fromId }<-${ via }->${ toId }` : `${ fromId }<->${ toId }`; }; /** * Generates a non-directional Route between two stops. specs.via allows a distinguishing label for routes * that have the same two stops but use different tracks * @param {Place} from - the general Place of one end of the Route * @param {string} from.id - used for route id * @param {string} from.label - used for route long name * @param {Place} to - the general Place of one end of the Route * @param {string} to.id - used for route id * @param {string} to.label - used for route long name * @param {Object} specs - Mostly required additional values * @param {string} [specs.via] - Optional label of via region or city of the Route. * @param {string} specs.routeType - GTFS extended RouteType (see routes.json) * @returns {Route} An object representing the Route */ export const createRoute = (from, to, specs = {}) => { // The id is from the place ids with an optional via // (e.g. 'SFC-REN via Altamont') const id = createRouteId(from, to, specs.via); // Made from the from and to stop names and the optional specs.via // (e.g. 'San Francisco/Reno via Altamont const routeLongName = compact([ [from.label, to.label].join('/'), specs.via]).join(' via '); // Made from the route type and id // (e.g. 'IRRS SFC-REN via Altamont' for inter regional rail service between SFC and RENO via Altamont const routeShortName = compact([id, specs.via]).join(' via '); return { id: id, places: {from, to}, via: specs.via, routeLongName, routeShortName, routeType: specs.routeType }; }; /** * @typedef {Object} Service * @property {string} id The id of the Service * @property {[string]} days Days of service * @property {[string]} seasons Seasons of service * @property {[string]} label Friendly label of based on the parameters */ /** * Creates a Service is based on the given days and season. In the GTSF spec this file is calendar * @param {string|null} startDate The startDate of the service in the form YYYYMMDD. * If null then the start date is the 'beginning of time' * @param {string|null} endDate The endDate of the service in the form YYYYMMDD * If null then the end date is the 'end of time' * @param {[string]} [days] Default ['everyday'] Days of the week, 'everyday', 'weekday', 'weekend', 'blue moons', etc * @param {[string]} [seasons] Default ['yearlong'] Seasons of the year: 'Winter', 'School Year', 'Tourist Season' * @returns {Service} A Service object with an id based on days and seasons */ export const createService = (startDate, endDate, days = ['everyday'], seasons = ['yearlong']) => { return { id: R.join('_', R.concat(seasons, days)), days, seasons, startDate, endDate, label: // '[startDate-endDate] Day, Day Season, Season' compactJoin(' ', [ compactJoin('-', [startDate, endDate]), R.pipe( R.map( R.pipe(R.map(capitalize), R.join(', '), emptyToNull) ), R.join(' '), emptyToNull )([days, seasons]) ]) }; }; /** * Creates a Trip id * @param {Route|String} route The Route or Route id of the Trip * @param {Direction} direction Direction or Direction id for the Trip (from -> to vs to -> from) * @param {callback} direction.resolveTripSymbol Takes the route to create a directional Trip symbol * (e.g. to->[(via)]->from or from->[(via)]->to * @param {Service|String} service The Service or Service id of the Trip * @returns {String} The trip id */ export const createTripId = (route, direction, service) => { return [ direction.resolveTripSymbol(route), service.label ].join(' '); }; /** * @typedef {Object} Trip * @property {Route} route The Route of the Trip * @property {Stop} from The from Stop * @property {Place} from.place The Place of the Stop, used for the Route id * @property {Stop} to The to Stop * @property {Place} to.place The Place of the Stop, used for the Route id * @property {Direction} Direction or Direction id of the Trip * @property {Service} service The Service of the Trip */ /** * @typedef {Object} TripWithStopTimes * @property {Route} route The Route of the Trip * @property {Stop} from The from Stop * @property {Place} from.place The Place of the Stop, used for the Route id * @property {Stop} to The to Stop * @property {Place} to.place The Place of the Stop, used for the Route id * @property {Trip} directionId The Direction or Direction id of the Trip * @property {Service} service The Service of the Trip * @property {[StopTime]} StopTimes for the Trip */ /** * @callback resolveToStop * @param {Route} Route to resolve a Stop from * @returns {Stop} The to Stop of the Trip */ /** * @typedef {Object} Direction * @property {Number} id The Direction id * @property {resolveToStop} resolve Resolve the Route to the to Stop of the Trip */ /** * Creates a Trip * @param {Route} route The Route of the Trip * @param {Direction} direction The Direction of the Trip * @param {Service} service The Service of the Trip * @returns {Object} The Trip */ export const createTrip = (route, direction, service) => { const id = createTripId(route, direction, service); return { id: id, route: route, service: service, direction: direction, tripHeadsign: tripHeadSign(direction.resolveToStop(route), route.via) }; }; /** * @callback stopTimeCallback * @param {Trip} trip The Trip * @returns {Trip} The Trip augmented with StopTimes */ /** * Generates a to and from trip definition for the given trip ids and other required specs * @param {Route} route - the Route used by the trip * @param {Object} route.stops - object with Stops used for naming the tripHeadsigns * @param {Place} route.places.from - The Place at one end of the Route * @param {string} route.places.from.label - used for the tripHeadSign * @param {Place} route.places.to - The Place at the other end of the Route * @param {string} route.places.to.id - used for trip id * @param {string} route.places.to.label - used for the tripHeadSign * @param {string} [route.via] Optional label of via region or city of the trip * @param {Service} service - The Service of the Trip * @param {stopTimeCallback} stopTimeCallback - Called with each trip to generate StopTimes. * This is * @returns {[TripWithStopTimes]} A two-item array containing with each result of stopTimeCallback. */ export const createTripWithStopTimesPair = (route, service, stopTimeCallback) => [ createTrip(route, FROM_TO_DIRECTION, service), createTrip(route, TO_FROM_DIRECTION, service) ].map(trip => R.merge(trip, {stopTimes: stopTimeCallback(trip)})); /** * @typedef {Object} StopTime * @property {string} tripId The id of the Trip * @property {string} stopSequence The stop number in sequence (e.g. 1 is the first stop, 2 the second stop) * @property {Stop} stop The Stop * @property {string} arrivalTime The arrival time in format 23:59[:59] * @property {string} departureTime The departure time in format 23:59[:59] */ /** * Creates A StopTime * @param {Trip} trip The Trip * @param {number} stopSequence The stop number, 1 based * @param {Stop} stop The Stop * @param {string|null} [arrivalTime] The optional arrival time in format 23:59:59 * @param {string|null} [departureTime] The optional departure time in format 23:59:59 * @returns {StopTime} The StopTime */ export const createStopTime = (trip, stopSequence, stop, arrivalTime = null, departureTime = null) => { return R.mergeAll([ { trip, stopSequence, stop }, compact({arrivalTime, departureTime}) ]); }; /** * Returns the standard ordering for stops. If the trip directionId == '0', stops are returned in order. * If the trip directionId == TO_FROM_DIRECTION, stops are returned in reverse. A different function could be used * if the stops were not consistent for both directions of the trip * @param {Trip} trip The Trip * @param {[Stop]} stops The Stops * @returns {[Stop]} The ordered Stops */ export const orderStops = (trip, stops) => { switch (trip.direction) { case FROM_TO_DIRECTION: return stops; case TO_FROM_DIRECTION: return stops.reverse(); default: throw new Error(`Unknown direction id ${trip.directionId}`); } }; /** * Creates a StopTime generator. The generator uses the startTime and EndTime to * estimate where each Stop is based on the location of each Stop * @param {Trip} trip: A Trip to which the stopTimes apply * @param {string} trip.id: The id of the Trip * @param {[Stop]} stops: A Stop, optionally augmented with an arrivalTime and/or dwellTime * Adding the arrivalTime causes all stations up to that Stop to be estimated based on that time * and that of the startTime or last explicit arrivalTime+dwellTime. Adding the dwellTime adjusts * the dwellTime of just that Stop * @param {string} startTime Time of departure of trip in format 23:59:59. * @param {string} endTime Time of arrival of trip in format 23:59:59. If it surpasses 23:59:59, uses * 24 + time for arrival the next day, 48 + time for arrival the subsequent day, etc. * (According to https://developers.google.com/transit/gtfs/reference/stop_times-file) * @param {number} dwellTime Number of seconds of dwell time * @yields {StopTime} each Stop Time * @returns {StopTime} WTF eslint */ export const stopTimeGenerator = function *(trip, stops, startTime, endTime, dwellTime) { const imStops = fromImmutable(stops); // The duration of the endTime const endDuration = moment.duration(endTime); // Zip the imStops together so we can access it in overlapping pairs const pairs = R.zip(R.slice(0, -1, imStops), R.slice(1, Infinity, imStops)); // The total distance between stops const totalDistance = R.reduce( (total, [current, next]) => total + calculateDistance(current.location, next.location), 0, pairs ); /** * Given the previous StopTime, use its departureTime, the endTime, and the * percent distance of Stop between the previous Stop and the final Stop * * @param {Stop} stop The Stop * @param {string} [stop.arrivalTime] Optional augmentation to Stop to give an explicit arrival time * Otherwise the arrivalTime is calculated * @param {Location} stop.location Used with previousStopTime.stop.location and endTime * to calculate what percentage to the end this location is * @param {StopTime} previousStopTime The previous StopTime. * @param {StopTime} previousStopTime.stop The previous StopTime Stop * @param {Location} previousStopTime.stop.location The previous StopTime Location * @param {string} previousStopTime.departureTime The timeString of the previous departure * @param {Number} previousStopTime.totalDistance The distance in km since the start of the trip * @param {Number} distanceFromPreviousStop The distance in km from the previous stop or 0 at the start
return stop.arrivalTime; } const totalRemainingDistance = totalDistance - (previousStopTime.totalDistance + distanceFromPreviousStop); // If there is no remaining distance we are at the last stop if (totalRemainingDistance === 0) { return moment.duration(endDuration); } // Calculate the fraction of distance to stop over the total remainingDistance const distanceFraction = distanceFromPreviousStop / totalRemainingDistance; const remainingDuration = moment.duration(endDuration).subtract(moment.duration(previousStopTime.departureTime)); // Calculate the elapsed time as a percentage of the total distance and add it to the last departure time return moment.duration(previousStopTime.departureTime).add( moment.duration(remainingDuration.asMilliseconds() * distanceFraction) ); }; /** * Calculates the departure time based on the arrivalTime and dwellTime * @param {Duration} arrivalDuration Duration of the arrival time (relative to 00:00:00) * @param {number} [customDwellTime] Number of seconds of dwellTime. Defaults to dwellTime * @returns {Duration} The Duration of the departure time (relative to 00:00:00) */ const calculateDepartureDuration = (arrivalDuration, customDwellTime = dwellTime) => { return moment.duration(arrivalDuration).add(customDwellTime, 's'); }; // Reduce the stops in order to combine the previousStopTime with the current Stop. // In the initial case the previousStopTime will be the first Stop, so it must be augmented // with the startTime yield* [ [{stop: R.head(imStops), totalDistance: 0, departureTime: startTime}], ...R.tail(imStops) ].reduce((previousStopTimes, stop, index) => { const previousStopTime = R.last(previousStopTimes); const previousStop = previousStopTime.stop; const distanceFromPreviousStop = calculateDistance(previousStop.location, stop.location); // Calculate the arrivalTime of the next stop based on distance or stop.arrivalTime. const arrivalDuration = calculateArrivalDuration(stop, previousStopTime, distanceFromPreviousStop); return previousStopTimes.concat(R.merge( createStopTime( trip, index + 1, stop, toTimeString(arrivalDuration), toTimeString(arrivalDuration) === toTimeString(endDuration) ? null : toTimeString(calculateDepartureDuration(arrivalDuration, stop.dwellTime || dwellTime)) ), { totalDistance: previousStopTime.totalDistance + distanceFromPreviousStop } )); }); }; /** * Invokes the stopTimeGenerator to get all Stops * @param {Array} args See stopTimeGenerator * @returns {[Stop]} All of the Stops */ export const createStopTimes = (...args) => Array.from(stopTimeGenerator(...args));
* @returns {Duration} The calculated arrival Duration relative to 00:00:00 */ const calculateArrivalDuration = (stop, previousStopTime, distanceFromPreviousStop) => { if (stop.arrivalTime) {
random_line_split
dataCreationHelpers.js
/** * Created by Andy Likuski on 2017.02.23 * Copyright (c) 2017 Andy Likuski * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import * as R from 'ramda'; import moment from 'moment'; import {fromImmutable, toTimeString, calculateDistance} from 'rescape-helpers'; const { capitalize, compact, compactJoin, emptyToNull, idOrIdFromObj } = require('rescape-ramda'); // Direction ids for typical Trip pairs export const FROM_TO_DIRECTION = { id: '0', resolveToStop: route => route.places.to, resolveTripSymbol: route => `${route.places.from.id}->${route.via ? `(${route.via})->` : ''}${route.places.to.id}` }; export const TO_FROM_DIRECTION = { id: '1', resolveToStop: route => route.places.from, resolveTripSymbol: route => `${route.places.to.id}->${route.via ? `(${route.via})->` : ''}${route.places.from.id}` }; const tripHeadSign = (to, via) => compact([to.label, via]).join(' via '); /** * Forms a unique stop id based on the place id and which station/stop of that place it is * @param {Place|id} place The Place object or its id * @param {string} place.id The id of the Place used to create the Stop id * @param {string|null} [which] Which station/stop (e.g. Union, Airport) * @returns {string} A stop id */ export const createStopId = (place, which = null) => compact([idOrIdFromObj(place), which]).join('-'); /** * @typedef {Object} Location * @property {number} lon The longitude * @property {number} lat The latitude **/ /** * @typedef {Object} Stop * @property {string} id The X Coordinate * @property {Place} place The Place of the Stop * @property {string} which Which Stop/Station of the Place (e.g. Central or Airport) * @property {stopName} the name of the Stop * @property {Location} the lon/lat of the Stop */ /** * Creates a GTFS compatible stop definition * @param {Place} place Place object representing a city or town * @param {string} place.id The 3 letter code of the city or town main station, based on train station codes * @param {string} place.label Label describing the place * @param {string} which Label representing the specific stop, such as 'Amtrak', 'Central', 'Arena', or 'Airport'. * @param {Location} location: lon/lat pair * @param {number} location.lon The longitude * @param {number} location.lat The latitude * @param {Object} [options] Options * @param {string|null} [options.stopName] label describing the stop. Defaults to `${place}[ ${where}] ${stopType}` * @param {string|null} [options.stopType] label describing the stop type if stopName is not used, defaults to 'Station' * @returns {Map} A Stop object */ export const createStop = (place, which, location, options = {}) => { const id = createStopId(place, which); return { id: id, place: place, which: which, stopName: options.stopName || `${place.label} ${which} ${options.stopType || 'Station'}`, location }; }; /** * @ * @property {string} id The id of the Route * @property {[Place]} places The two end Places of the Route * @property {string} routeLongName The full name of the Route * @property {string} routeShortName The short name of the Route * @property {string} routeType The id of the RouteType * @property {string} [via] The optional intermediate Region of the Route */ /** * Forms a unique Route id based on the place id and which station/stop of that place it is. * @param {Place|id} from The start/end Place or its id * @param {Place|id} to The other start/end Place or its id * @param {string} [via] Optional pass through Region to distinguish the route * @returns {string} A Route id */ export const createRouteId = (from, to, via) => { const fromId = idOrIdFromObj(from); const toId = idOrIdFromObj(to); return via ? `${ fromId }<-${ via }->${ toId }` : `${ fromId }<->${ toId }`; }; /** * Generates a non-directional Route between two stops. specs.via allows a distinguishing label for routes * that have the same two stops but use different tracks * @param {Place} from - the general Place of one end of the Route * @param {string} from.id - used for route id * @param {string} from.label - used for route long name * @param {Place} to - the general Place of one end of the Route * @param {string} to.id - used for route id * @param {string} to.label - used for route long name * @param {Object} specs - Mostly required additional values * @param {string} [specs.via] - Optional label of via region or city of the Route. * @param {string} specs.routeType - GTFS extended RouteType (see routes.json) * @returns {Route} An object representing the Route */ export const createRoute = (from, to, specs = {}) => { // The id is from the place ids with an optional via // (e.g. 'SFC-REN via Altamont') const id = createRouteId(from, to, specs.via); // Made from the from and to stop names and the optional specs.via // (e.g. 'San Francisco/Reno via Altamont const routeLongName = compact([ [from.label, to.label].join('/'), specs.via]).join(' via '); // Made from the route type and id // (e.g. 'IRRS SFC-REN via Altamont' for inter regional rail service between SFC and RENO via Altamont const routeShortName = compact([id, specs.via]).join(' via '); return { id: id, places: {from, to}, via: specs.via, routeLongName, routeShortName, routeType: specs.routeType }; }; /** * @typedef {Object} Service * @property {string} id The id of the Service * @property {[string]} days Days of service * @property {[string]} seasons Seasons of service * @property {[string]} label Friendly label of based on the parameters */ /** * Creates a Service is based on the given days and season. In the GTSF spec this file is calendar * @param {string|null} startDate The startDate of the service in the form YYYYMMDD. * If null then the start date is the 'beginning of time' * @param {string|null} endDate The endDate of the service in the form YYYYMMDD * If null then the end date is the 'end of time' * @param {[string]} [days] Default ['everyday'] Days of the week, 'everyday', 'weekday', 'weekend', 'blue moons', etc * @param {[string]} [seasons] Default ['yearlong'] Seasons of the year: 'Winter', 'School Year', 'Tourist Season' * @returns {Service} A Service object with an id based on days and seasons */ export const createService = (startDate, endDate, days = ['everyday'], seasons = ['yearlong']) => { return { id: R.join('_', R.concat(seasons, days)), days, seasons, startDate, endDate, label: // '[startDate-endDate] Day, Day Season, Season' compactJoin(' ', [ compactJoin('-', [startDate, endDate]), R.pipe( R.map( R.pipe(R.map(capitalize), R.join(', '), emptyToNull) ), R.join(' '), emptyToNull )([days, seasons]) ]) }; }; /** * Creates a Trip id * @param {Route|String} route The Route or Route id of the Trip * @param {Direction} direction Direction or Direction id for the Trip (from -> to vs to -> from) * @param {callback} direction.resolveTripSymbol Takes the route to create a directional Trip symbol * (e.g. to->[(via)]->from or from->[(via)]->to * @param {Service|String} service The Service or Service id of the Trip * @returns {String} The trip id */ export const createTripId = (route, direction, service) => { return [ direction.resolveTripSymbol(route), service.label ].join(' '); }; /** * @typedef {Object} Trip * @property {Route} route The Route of the Trip * @property {Stop} from The from Stop * @property {Place} from.place The Place of the Stop, used for the Route id * @property {Stop} to The to Stop * @property {Place} to.place The Place of the Stop, used for the Route id * @property {Direction} Direction or Direction id of the Trip * @property {Service} service The Service of the Trip */ /** * @typedef {Object} TripWithStopTimes * @property {Route} route The Route of the Trip * @property {Stop} from The from Stop * @property {Place} from.place The Place of the Stop, used for the Route id * @property {Stop} to The to Stop * @property {Place} to.place The Place of the Stop, used for the Route id * @property {Trip} directionId The Direction or Direction id of the Trip * @property {Service} service The Service of the Trip * @property {[StopTime]} StopTimes for the Trip */ /** * @callback resolveToStop * @param {Route} Route to resolve a Stop from * @returns {Stop} The to Stop of the Trip */ /** * @typedef {Object} Direction * @property {Number} id The Direction id * @property {resolveToStop} resolve Resolve the Route to the to Stop of the Trip */ /** * Creates a Trip * @param {Route} route The Route of the Trip * @param {Direction} direction The Direction of the Trip * @param {Service} service The Service of the Trip * @returns {Object} The Trip */ export const createTrip = (route, direction, service) => { const id = createTripId(route, direction, service); return { id: id, route: route, service: service, direction: direction, tripHeadsign: tripHeadSign(direction.resolveToStop(route), route.via) }; }; /** * @callback stopTimeCallback * @param {Trip} trip The Trip * @returns {Trip} The Trip augmented with StopTimes */ /** * Generates a to and from trip definition for the given trip ids and other required specs * @param {Route} route - the Route used by the trip * @param {Object} route.stops - object with Stops used for naming the tripHeadsigns * @param {Place} route.places.from - The Place at one end of the Route * @param {string} route.places.from.label - used for the tripHeadSign * @param {Place} route.places.to - The Place at the other end of the Route * @param {string} route.places.to.id - used for trip id * @param {string} route.places.to.label - used for the tripHeadSign * @param {string} [route.via] Optional label of via region or city of the trip * @param {Service} service - The Service of the Trip * @param {stopTimeCallback} stopTimeCallback - Called with each trip to generate StopTimes. * This is * @returns {[TripWithStopTimes]} A two-item array containing with each result of stopTimeCallback. */ export const createTripWithStopTimesPair = (route, service, stopTimeCallback) => [ createTrip(route, FROM_TO_DIRECTION, service), createTrip(route, TO_FROM_DIRECTION, service) ].map(trip => R.merge(trip, {stopTimes: stopTimeCallback(trip)})); /** * @typedef {Object} StopTime * @property {string} tripId The id of the Trip * @property {string} stopSequence The stop number in sequence (e.g. 1 is the first stop, 2 the second stop) * @property {Stop} stop The Stop * @property {string} arrivalTime The arrival time in format 23:59[:59] * @property {string} departureTime The departure time in format 23:59[:59] */ /** * Creates A StopTime * @param {Trip} trip The Trip * @param {number} stopSequence The stop number, 1 based * @param {Stop} stop The Stop * @param {string|null} [arrivalTime] The optional arrival time in format 23:59:59 * @param {string|null} [departureTime] The optional departure time in format 23:59:59 * @returns {StopTime} The StopTime */ export const createStopTime = (trip, stopSequence, stop, arrivalTime = null, departureTime = null) => { return R.mergeAll([ { trip, stopSequence, stop }, compact({arrivalTime, departureTime}) ]); }; /** * Returns the standard ordering for stops. If the trip directionId == '0', stops are returned in order. * If the trip directionId == TO_FROM_DIRECTION, stops are returned in reverse. A different function could be used * if the stops were not consistent for both directions of the trip * @param {Trip} trip The Trip * @param {[Stop]} stops The Stops * @returns {[Stop]} The ordered Stops */ export const orderStops = (trip, stops) => { switch (trip.direction) { case FROM_TO_DIRECTION: return stops; case TO_FROM_DIRECTION: return stops.reverse(); default: throw new Error(`Unknown direction id ${trip.directionId}`); } }; /** * Creates a StopTime generator. The generator uses the startTime and EndTime to * estimate where each Stop is based on the location of each Stop * @param {Trip} trip: A Trip to which the stopTimes apply * @param {string} trip.id: The id of the Trip * @param {[Stop]} stops: A Stop, optionally augmented with an arrivalTime and/or dwellTime * Adding the arrivalTime causes all stations up to that Stop to be estimated based on that time * and that of the startTime or last explicit arrivalTime+dwellTime. Adding the dwellTime adjusts * the dwellTime of just that Stop * @param {string} startTime Time of departure of trip in format 23:59:59. * @param {string} endTime Time of arrival of trip in format 23:59:59. If it surpasses 23:59:59, uses * 24 + time for arrival the next day, 48 + time for arrival the subsequent day, etc. * (According to https://developers.google.com/transit/gtfs/reference/stop_times-file) * @param {number} dwellTime Number of seconds of dwell time * @yields {StopTime} each Stop Time * @returns {StopTime} WTF eslint */ export const stopTimeGenerator = function *(trip, stops, startTime, endTime, dwellTime) { const imStops = fromImmutable(stops); // The duration of the endTime const endDuration = moment.duration(endTime); // Zip the imStops together so we can access it in overlapping pairs const pairs = R.zip(R.slice(0, -1, imStops), R.slice(1, Infinity, imStops)); // The total distance between stops const totalDistance = R.reduce( (total, [current, next]) => total + calculateDistance(current.location, next.location), 0, pairs ); /** * Given the previous StopTime, use its departureTime, the endTime, and the * percent distance of Stop between the previous Stop and the final Stop * * @param {Stop} stop The Stop * @param {string} [stop.arrivalTime] Optional augmentation to Stop to give an explicit arrival time * Otherwise the arrivalTime is calculated * @param {Location} stop.location Used with previousStopTime.stop.location and endTime * to calculate what percentage to the end this location is * @param {StopTime} previousStopTime The previous StopTime. * @param {StopTime} previousStopTime.stop The previous StopTime Stop * @param {Location} previousStopTime.stop.location The previous StopTime Location * @param {string} previousStopTime.departureTime The timeString of the previous departure * @param {Number} previousStopTime.totalDistance The distance in km since the start of the trip * @param {Number} distanceFromPreviousStop The distance in km from the previous stop or 0 at the start * @returns {Duration} The calculated arrival Duration relative to 00:00:00 */ const calculateArrivalDuration = (stop, previousStopTime, distanceFromPreviousStop) => { if (stop.arrivalTime) { return stop.arrivalTime; } const totalRemainingDistance = totalDistance - (previousStopTime.totalDistance + distanceFromPreviousStop); // If there is no remaining distance we are at the last stop if (totalRemainingDistance === 0)
// Calculate the fraction of distance to stop over the total remainingDistance const distanceFraction = distanceFromPreviousStop / totalRemainingDistance; const remainingDuration = moment.duration(endDuration).subtract(moment.duration(previousStopTime.departureTime)); // Calculate the elapsed time as a percentage of the total distance and add it to the last departure time return moment.duration(previousStopTime.departureTime).add( moment.duration(remainingDuration.asMilliseconds() * distanceFraction) ); }; /** * Calculates the departure time based on the arrivalTime and dwellTime * @param {Duration} arrivalDuration Duration of the arrival time (relative to 00:00:00) * @param {number} [customDwellTime] Number of seconds of dwellTime. Defaults to dwellTime * @returns {Duration} The Duration of the departure time (relative to 00:00:00) */ const calculateDepartureDuration = (arrivalDuration, customDwellTime = dwellTime) => { return moment.duration(arrivalDuration).add(customDwellTime, 's'); }; // Reduce the stops in order to combine the previousStopTime with the current Stop. // In the initial case the previousStopTime will be the first Stop, so it must be augmented // with the startTime yield* [ [{stop: R.head(imStops), totalDistance: 0, departureTime: startTime}], ...R.tail(imStops) ].reduce((previousStopTimes, stop, index) => { const previousStopTime = R.last(previousStopTimes); const previousStop = previousStopTime.stop; const distanceFromPreviousStop = calculateDistance(previousStop.location, stop.location); // Calculate the arrivalTime of the next stop based on distance or stop.arrivalTime. const arrivalDuration = calculateArrivalDuration(stop, previousStopTime, distanceFromPreviousStop); return previousStopTimes.concat(R.merge( createStopTime( trip, index + 1, stop, toTimeString(arrivalDuration), toTimeString(arrivalDuration) === toTimeString(endDuration) ? null : toTimeString(calculateDepartureDuration(arrivalDuration, stop.dwellTime || dwellTime)) ), { totalDistance: previousStopTime.totalDistance + distanceFromPreviousStop } )); }); }; /** * Invokes the stopTimeGenerator to get all Stops * @param {Array} args See stopTimeGenerator * @returns {[Stop]} All of the Stops */ export const createStopTimes = (...args) => Array.from(stopTimeGenerator(...args));
{ return moment.duration(endDuration); }
conditional_block
config.go
package eudore import ( "encoding/json" "fmt" "os" "reflect" "runtime" "strings" "sync" ) // ConfigParseFunc 定义配置解析函数。 // // Config 默认解析函数为eudore.ConfigAllParseFunc type ConfigParseFunc func(Config) error /* Config defines configuration management and uses configuration read-write and analysis functions. Get/Set read and write data implementation: Use custom map or struct as data storage Support Lock concurrency safety Access attributes based on string path hierarchy The default analysis function implementation: Custom configuration analysis function Parse multiple json files Parse the length and short parameters of the command line Parse Env environment variables Configuration differentiation Generate help information based on the structure Switch working directory Config 定义配置管理,使用配置读写和解析功能。 Get/Set读写数据实现下列功能: 使用自定义map或struct作为数据存储 支持Lock并发安全 基于字符串路径层次访问属性 默认解析函数实现下列功能: 自定义配置解析函数 解析多json文件 解析命令行长短参数 解析Env环境变量 配置差异化 根据结构体生成帮助信息 切换工作目录 */ type Config interface { Get(string) interface{} Set(string, interface{}) error ParseOption([]ConfigParseFunc) []ConfigParseFunc Parse() error } // configMap 使用map保存配置。 type configMap struct { Keys map[string]interface{} `alias:"keys"` Print func(...interface{}) `alias:"print"` funcs []ConfigParseFunc `alias:"-"` Locker sync.RWMutex `alias:"-"` } // configEudore 使用结构体或map保存配置,通过属性或反射来读写属性。 type configEudore struct { Keys interface{} `alias:"keys"` Print func(...interface{}) `alias:"print"` funcs []ConfigParseFunc `alias:"-"` configRLocker `alias:"-"` } type configRLocker interface { sync.Locker RLock() RUnlock() } // NewConfigMap 创建一个ConfigMap,如果传入参数为map[string]interface{},则作为初始化数据。 // // ConfigMap将使用传入的map作为配置存储去Get/Set一个键值。 // // ConfigMap已实现json.Marshaler和json.Unmarshaler接口. func NewConfigMap(arg interface{}) Config { var keys map[string]interface{} if ks, ok := arg.(map[string]interface{}); ok { keys = ks } else { keys = make(map[string]interface{}) } return &configMap{ Keys: keys, Print: printEmpty, funcs: ConfigAllParseFunc, } } // Get 方法获取一个属性,如果键为空字符串,返回保存全部数据的map对象。 func (c *configMap) Get(key string) interface{} { c.Locker.RLock() defer c.Locker.RUnlock() if len(key) == 0 { return c.Keys } return c.Keys[key] } // Set 方法设置一个属性,如果键为空字符串且值类型是map[string]interface{},则替换保存全部数据的map对象。 func (c *configMap) Set(key string, val interface{}) error { c.Locker.Lock() if len(key) == 0 { keys, ok := val.(map[string]interface{}) if ok { c.Keys = keys } } else if key == "print" { fn, ok := val.(func(...interface{})) if ok { c.Print = fn } else { c.Print(val) } } else { c.Keys[key] = val } c.Locker.Unlock() return nil } // ParseOption 执行一个配置解析函数选项。 func (c *configMap) ParseOption(fn []ConfigParseFunc) []ConfigParseFunc { c.funcs, fn = fn, c.funcs return fn } // Parse 方法执行全部配置解析函数,如果其中解析函数返回err,则停止解析并返回err。 func (c *configMap) Parse() (err error) { for _, fn := range c.funcs { err = fn(c) if err != nil { c.Print(err) return } } return nil } // MarshalJSON 实现json.Marshaler接口,试json序列化直接操作保存的数据。 func (c *configMap) MarshalJSON() ([]byte, error) { c.Locker.RLock() defer c.Locker.RUnlock() return json.Marshal(c.Keys) } // UnmarshalJSON 实现json.Unmarshaler接口,试json反序列化直接操作保存的数据。 func (c *configMap) UnmarshalJSON(data []byte) error { c.Locker.Lock() defer c.Locker.Unlock() return json.Unmarshal(data, &c.Keys) } // NewConfigEudore 创建一个ConfigEudore,如果传入参数为空,使用空map[string]interface{}作为初始化数据。 // // ConfigEduoew允许传入一个map或struct作为配置存储,使用eudore.Set和eudore.Get方法去读写数据。 // // 如果传入的配置对象实现sync.RLock一样的读写锁,则使用配置的读写锁,否则会创建一个sync.RWMutex锁。 // // ConfigEduoe已实现json.Marshaler和json.Unmarshaler接口. func NewConfigEudore(i interface{}) Config { if i == nil { i = make(map[string]interface{}) } mu, ok := i.(configRLocker) if !ok { mu = new(sync.RWMutex) } return &configEudore{ Keys: i, Print: printEmpty, funcs: ConfigAllParseFunc, configRLocker: mu, } } // Get 方法实现读取数据属性的一个属性。 func (c *configEudore) Get(key string) (i interface{}) { if len(key) == 0 { return c.Keys } c.RLock() i = Get(c.Keys, key) c.RUnlock() return } // Set 方法实现设置数据的一个属性。 func (c *configEudore) Set(key string, val interface{}) (err error) { c.Lock() if len(key) == 0 { c.Keys = val } else if key == "print" { fn, ok := val.(func(...interface{})) if ok { c.Print = fn } else { c.Print(val) } } else { err = Set(c.Keys, key, val) } c.Unlock() return } // ParseOption 执行一个配置解析函数选项。 func (c *configEudore) ParseOption(fn []ConfigParseFunc) []ConfigParseFunc { c.funcs, fn = fn, c.funcs return fn } // Parse 方法执行全部配置解析函数,如果其中解析函数返回err,则停止解析并返回err。 func (c *configEudore) Parse() (err error) { for _, fn := range c.funcs { err = fn(c) if err != nil { c.Print(err) return } } return nil } // MarshalJSON 实现json.Marshaler接口,试json序列化直接操作保存的数据。 func (c *configEudore) MarshalJSON() ([]byte, error) { c.RLock() defer c.RUnlock() return json.Marshal(c.Keys) } // UnmarshalJSON 实现json.Unmarshaler接口,试json反序列化直接操作保存的数据。 func (c *configEudore) UnmarshalJSON(data []byte) error { c.Lock() defer c.Unlock() return json.Unmarshal(data, &c.Keys) } func configPrint(c Config, args ...interface{}) { c.Set("print", fmt.Sprint(args...)) } // ConfigParseJSON 方法解析json文件配置。 func ConfigParseJSON(c Config) error { configPrint(c, "config read paths: ", c.Get("config")) for _, path := range GetStrings(c.Get("config")) { file, err := os.Open(path) if err == nil { err = json.NewDecoder(file).Decode(c) file.Close() } if err == nil { configPrint(c, "config load path: ", path) return nil } if !os.IsNotExist(err) { return fmt.Errorf("config load %s error: %s", path, err.Error()) } } return nil } // ConfigParseArgs 函数使用参数设置配置,参数使用'--'为前缀。 // // 如果结构体存在flag tag将作为该路径的缩写,tag长度小于5使用'-'为前缀。 func ConfigParseArgs(c Config) (err error) { flag := &eachTags{tag: "flag", Repeat: make(map[uintptr]string)} flag.Each("", reflect.ValueOf(c.Get(""))) short := make(map[string][]string) for i, tag := range flag.Tags { short[flag.Vals[i]] = append(short[flag.Vals[i]], tag[1:]) } for _, str := range os.Args[1:] { key, val := split2byte(str, '=') if len(key) > 1 && key[0] == '-' && key[1] != '-' { for _, lkey := range short[key[1:]] { val := val if val == "" && reflect.ValueOf(c.Get(lkey)).Kind() == reflect.Bool { val = "true" } configPrint(c, fmt.Sprintf("config set short arg %s: --%s=%s", key[1:], lkey, val)) c.Set(lkey, val) } } else if strings.HasPrefix(key, "--") { if val == "" && reflect.ValueOf(c.Get(key[2:])).Kind() == reflect.Bool { val = "true" } configPrint(c, "config set arg: ", str) c.Set(key[2:], val) } } return } // ConfigParseEnvs 函数使用环境变量设置配置,环境变量使用'ENV_'为前缀,'_'下划线相当于'.'的作用。 func ConfigParseEnvs(c Config) error { for _, value := range os.Environ() { if strings.HasPrefix(value, "ENV_") { configPrint(c, "config set env: ", value) k, v := split2byte(value, '=') k = strings.ToLower(strings.Replace(k, "_", ".", -1))[4:] c.Set(k, v) } } return nil } // ConfigParseMods 函数从'enable'项获得使用的模式的数组字符串,从'mods.xxx'加载配置。 // // 默认会加载OS mod,如果是docker环境下使用docker模式。 func ConfigParseMods(c Config) error { mod := GetStrings(c.Get("enable")) mod = append([]string{getOS()}, mod...) for _, i := range mod { m := c.Get("mods." + i) if m != nil { configPrint(c, "config load mod "+i) ConvertTo(m, c.Get("")) } } return nil } func getOS() string { // check docker _, err := os.Stat("/.dockerenv") if err == nil || !os.IsNotExist(err) { return "docker" } // 返回默认OS return runtime.GOOS } // ConfigParseWorkdir 函数初始化工作空间,从config获取workdir的值为工作空间,然后切换目录。 func ConfigParseWorkdir(c Config) error { dir := GetString(c.Get("workdir")) if dir != "" { configPrint(c, "changes working directory to: "+dir) return os.Chdir(dir) } return nil } // ConfigParseHelp 函数测试配置内容,如果存在help项会层叠获取到结构体的的description tag值作为帮助信息输出。 // // 注意配置结构体的属性需要是非空,否则不会进入遍历。 func ConfigParseHelp(c Config) error { if !GetBool(c.Get("help")) { return nil } conf := reflect.ValueOf(c.Get("")) flag := &eachTags{tag: "flag", Repeat: make(map[uintptr]string)} flag.Each("", conf) flagmap := make(map[string]string) for i, tag := range flag.Tags { flagmap[tag[1:]] = flag.Vals[i] } desc := &eachTags{tag: "description", Repeat: make(map[uintptr]string)} desc.Each("", conf) var length int for i, tag := range desc.Tags { desc.Tags[i] = tag[1:] if len(tag) > length { length = len(tag) } } for i, tag := range desc.Tags { f, ok := flagmap[tag] if ok && !strings.Contains(tag, "{") && len(f) < 5 { fmt.Printf(" -%s,", f) } fmt.Printf("\t --%s=%s\t%s\n", tag, strings.Repeat(" ", length-len(tag)), desc.Vals[i]) } return nil } type eachTags struct { tag string Tags []string Vals []string Repeat map[uintptr]string LastTag string } func (each *eachTags) Each(prefix string, iValue reflect.Value) { swit
se reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer: if !iValue.IsNil() { _, ok := each.Repeat[iValue.Pointer()] if ok { return } each.Repeat[iValue.Pointer()] = prefix } } switch iValue.Kind() { case reflect.Ptr, reflect.Interface: if !iValue.IsNil() { each.Each(prefix, iValue.Elem()) } case reflect.Map: if each.LastTag != "" { each.Tags = append(each.Tags, fmt.Sprintf("%s.{%s}", prefix, iValue.Type().Key().Name())) each.Vals = append(each.Vals, each.LastTag) } case reflect.Slice, reflect.Array: length := "n" if iValue.Kind() == reflect.Array { length = fmt.Sprint(iValue.Type().Len() - 1) } last := each.LastTag if last != "" { each.Tags = append(each.Tags, fmt.Sprintf("%s.{0-%s}", prefix, length)) each.Vals = append(each.Vals, last) } each.LastTag = last each.Each(fmt.Sprintf("%s.{0-%s}", prefix, length), reflect.New(iValue.Type().Elem())) case reflect.Struct: each.EachStruct(prefix, iValue) } } func (each *eachTags) EachStruct(prefix string, iValue reflect.Value) { iType := iValue.Type() for i := 0; i < iType.NumField(); i++ { if iValue.Field(i).CanSet() { val := iType.Field(i).Tag.Get(each.tag) name := iType.Field(i).Tag.Get("alias") if name == "" { name = iType.Field(i).Name } if val != "" && each.getValueKind(iType.Field(i).Type) != "" { each.Tags = append(each.Tags, prefix+"."+name) each.Vals = append(each.Vals, val) } each.LastTag = val each.Each(prefix+"."+name, iValue.Field(i)) } } } func (each *eachTags) getValueKind(iType reflect.Type) string { switch iType.Kind() { case reflect.Bool: return "bool" case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return "int" case reflect.Float32, reflect.Float64: return "float" case reflect.String: return "string" default: if iType.Kind() == reflect.Slice && iType.Elem().Kind() == reflect.Uint8 { return "string" } return "" } }
ch iValue.Kind() { ca
conditional_block
config.go
package eudore import ( "encoding/json" "fmt" "os" "reflect" "runtime" "strings" "sync"
type ConfigParseFunc func(Config) error /* Config defines configuration management and uses configuration read-write and analysis functions. Get/Set read and write data implementation: Use custom map or struct as data storage Support Lock concurrency safety Access attributes based on string path hierarchy The default analysis function implementation: Custom configuration analysis function Parse multiple json files Parse the length and short parameters of the command line Parse Env environment variables Configuration differentiation Generate help information based on the structure Switch working directory Config 定义配置管理,使用配置读写和解析功能。 Get/Set读写数据实现下列功能: 使用自定义map或struct作为数据存储 支持Lock并发安全 基于字符串路径层次访问属性 默认解析函数实现下列功能: 自定义配置解析函数 解析多json文件 解析命令行长短参数 解析Env环境变量 配置差异化 根据结构体生成帮助信息 切换工作目录 */ type Config interface { Get(string) interface{} Set(string, interface{}) error ParseOption([]ConfigParseFunc) []ConfigParseFunc Parse() error } // configMap 使用map保存配置。 type configMap struct { Keys map[string]interface{} `alias:"keys"` Print func(...interface{}) `alias:"print"` funcs []ConfigParseFunc `alias:"-"` Locker sync.RWMutex `alias:"-"` } // configEudore 使用结构体或map保存配置,通过属性或反射来读写属性。 type configEudore struct { Keys interface{} `alias:"keys"` Print func(...interface{}) `alias:"print"` funcs []ConfigParseFunc `alias:"-"` configRLocker `alias:"-"` } type configRLocker interface { sync.Locker RLock() RUnlock() } // NewConfigMap 创建一个ConfigMap,如果传入参数为map[string]interface{},则作为初始化数据。 // // ConfigMap将使用传入的map作为配置存储去Get/Set一个键值。 // // ConfigMap已实现json.Marshaler和json.Unmarshaler接口. func NewConfigMap(arg interface{}) Config { var keys map[string]interface{} if ks, ok := arg.(map[string]interface{}); ok { keys = ks } else { keys = make(map[string]interface{}) } return &configMap{ Keys: keys, Print: printEmpty, funcs: ConfigAllParseFunc, } } // Get 方法获取一个属性,如果键为空字符串,返回保存全部数据的map对象。 func (c *configMap) Get(key string) interface{} { c.Locker.RLock() defer c.Locker.RUnlock() if len(key) == 0 { return c.Keys } return c.Keys[key] } // Set 方法设置一个属性,如果键为空字符串且值类型是map[string]interface{},则替换保存全部数据的map对象。 func (c *configMap) Set(key string, val interface{}) error { c.Locker.Lock() if len(key) == 0 { keys, ok := val.(map[string]interface{}) if ok { c.Keys = keys } } else if key == "print" { fn, ok := val.(func(...interface{})) if ok { c.Print = fn } else { c.Print(val) } } else { c.Keys[key] = val } c.Locker.Unlock() return nil } // ParseOption 执行一个配置解析函数选项。 func (c *configMap) ParseOption(fn []ConfigParseFunc) []ConfigParseFunc { c.funcs, fn = fn, c.funcs return fn } // Parse 方法执行全部配置解析函数,如果其中解析函数返回err,则停止解析并返回err。 func (c *configMap) Parse() (err error) { for _, fn := range c.funcs { err = fn(c) if err != nil { c.Print(err) return } } return nil } // MarshalJSON 实现json.Marshaler接口,试json序列化直接操作保存的数据。 func (c *configMap) MarshalJSON() ([]byte, error) { c.Locker.RLock() defer c.Locker.RUnlock() return json.Marshal(c.Keys) } // UnmarshalJSON 实现json.Unmarshaler接口,试json反序列化直接操作保存的数据。 func (c *configMap) UnmarshalJSON(data []byte) error { c.Locker.Lock() defer c.Locker.Unlock() return json.Unmarshal(data, &c.Keys) } // NewConfigEudore 创建一个ConfigEudore,如果传入参数为空,使用空map[string]interface{}作为初始化数据。 // // ConfigEduoew允许传入一个map或struct作为配置存储,使用eudore.Set和eudore.Get方法去读写数据。 // // 如果传入的配置对象实现sync.RLock一样的读写锁,则使用配置的读写锁,否则会创建一个sync.RWMutex锁。 // // ConfigEduoe已实现json.Marshaler和json.Unmarshaler接口. func NewConfigEudore(i interface{}) Config { if i == nil { i = make(map[string]interface{}) } mu, ok := i.(configRLocker) if !ok { mu = new(sync.RWMutex) } return &configEudore{ Keys: i, Print: printEmpty, funcs: ConfigAllParseFunc, configRLocker: mu, } } // Get 方法实现读取数据属性的一个属性。 func (c *configEudore) Get(key string) (i interface{}) { if len(key) == 0 { return c.Keys } c.RLock() i = Get(c.Keys, key) c.RUnlock() return } // Set 方法实现设置数据的一个属性。 func (c *configEudore) Set(key string, val interface{}) (err error) { c.Lock() if len(key) == 0 { c.Keys = val } else if key == "print" { fn, ok := val.(func(...interface{})) if ok { c.Print = fn } else { c.Print(val) } } else { err = Set(c.Keys, key, val) } c.Unlock() return } // ParseOption 执行一个配置解析函数选项。 func (c *configEudore) ParseOption(fn []ConfigParseFunc) []ConfigParseFunc { c.funcs, fn = fn, c.funcs return fn } // Parse 方法执行全部配置解析函数,如果其中解析函数返回err,则停止解析并返回err。 func (c *configEudore) Parse() (err error) { for _, fn := range c.funcs { err = fn(c) if err != nil { c.Print(err) return } } return nil } // MarshalJSON 实现json.Marshaler接口,试json序列化直接操作保存的数据。 func (c *configEudore) MarshalJSON() ([]byte, error) { c.RLock() defer c.RUnlock() return json.Marshal(c.Keys) } // UnmarshalJSON 实现json.Unmarshaler接口,试json反序列化直接操作保存的数据。 func (c *configEudore) UnmarshalJSON(data []byte) error { c.Lock() defer c.Unlock() return json.Unmarshal(data, &c.Keys) } func configPrint(c Config, args ...interface{}) { c.Set("print", fmt.Sprint(args...)) } // ConfigParseJSON 方法解析json文件配置。 func ConfigParseJSON(c Config) error { configPrint(c, "config read paths: ", c.Get("config")) for _, path := range GetStrings(c.Get("config")) { file, err := os.Open(path) if err == nil { err = json.NewDecoder(file).Decode(c) file.Close() } if err == nil { configPrint(c, "config load path: ", path) return nil } if !os.IsNotExist(err) { return fmt.Errorf("config load %s error: %s", path, err.Error()) } } return nil } // ConfigParseArgs 函数使用参数设置配置,参数使用'--'为前缀。 // // 如果结构体存在flag tag将作为该路径的缩写,tag长度小于5使用'-'为前缀。 func ConfigParseArgs(c Config) (err error) { flag := &eachTags{tag: "flag", Repeat: make(map[uintptr]string)} flag.Each("", reflect.ValueOf(c.Get(""))) short := make(map[string][]string) for i, tag := range flag.Tags { short[flag.Vals[i]] = append(short[flag.Vals[i]], tag[1:]) } for _, str := range os.Args[1:] { key, val := split2byte(str, '=') if len(key) > 1 && key[0] == '-' && key[1] != '-' { for _, lkey := range short[key[1:]] { val := val if val == "" && reflect.ValueOf(c.Get(lkey)).Kind() == reflect.Bool { val = "true" } configPrint(c, fmt.Sprintf("config set short arg %s: --%s=%s", key[1:], lkey, val)) c.Set(lkey, val) } } else if strings.HasPrefix(key, "--") { if val == "" && reflect.ValueOf(c.Get(key[2:])).Kind() == reflect.Bool { val = "true" } configPrint(c, "config set arg: ", str) c.Set(key[2:], val) } } return } // ConfigParseEnvs 函数使用环境变量设置配置,环境变量使用'ENV_'为前缀,'_'下划线相当于'.'的作用。 func ConfigParseEnvs(c Config) error { for _, value := range os.Environ() { if strings.HasPrefix(value, "ENV_") { configPrint(c, "config set env: ", value) k, v := split2byte(value, '=') k = strings.ToLower(strings.Replace(k, "_", ".", -1))[4:] c.Set(k, v) } } return nil } // ConfigParseMods 函数从'enable'项获得使用的模式的数组字符串,从'mods.xxx'加载配置。 // // 默认会加载OS mod,如果是docker环境下使用docker模式。 func ConfigParseMods(c Config) error { mod := GetStrings(c.Get("enable")) mod = append([]string{getOS()}, mod...) for _, i := range mod { m := c.Get("mods." + i) if m != nil { configPrint(c, "config load mod "+i) ConvertTo(m, c.Get("")) } } return nil } func getOS() string { // check docker _, err := os.Stat("/.dockerenv") if err == nil || !os.IsNotExist(err) { return "docker" } // 返回默认OS return runtime.GOOS } // ConfigParseWorkdir 函数初始化工作空间,从config获取workdir的值为工作空间,然后切换目录。 func ConfigParseWorkdir(c Config) error { dir := GetString(c.Get("workdir")) if dir != "" { configPrint(c, "changes working directory to: "+dir) return os.Chdir(dir) } return nil } // ConfigParseHelp 函数测试配置内容,如果存在help项会层叠获取到结构体的的description tag值作为帮助信息输出。 // // 注意配置结构体的属性需要是非空,否则不会进入遍历。 func ConfigParseHelp(c Config) error { if !GetBool(c.Get("help")) { return nil } conf := reflect.ValueOf(c.Get("")) flag := &eachTags{tag: "flag", Repeat: make(map[uintptr]string)} flag.Each("", conf) flagmap := make(map[string]string) for i, tag := range flag.Tags { flagmap[tag[1:]] = flag.Vals[i] } desc := &eachTags{tag: "description", Repeat: make(map[uintptr]string)} desc.Each("", conf) var length int for i, tag := range desc.Tags { desc.Tags[i] = tag[1:] if len(tag) > length { length = len(tag) } } for i, tag := range desc.Tags { f, ok := flagmap[tag] if ok && !strings.Contains(tag, "{") && len(f) < 5 { fmt.Printf(" -%s,", f) } fmt.Printf("\t --%s=%s\t%s\n", tag, strings.Repeat(" ", length-len(tag)), desc.Vals[i]) } return nil } type eachTags struct { tag string Tags []string Vals []string Repeat map[uintptr]string LastTag string } func (each *eachTags) Each(prefix string, iValue reflect.Value) { switch iValue.Kind() { case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer: if !iValue.IsNil() { _, ok := each.Repeat[iValue.Pointer()] if ok { return } each.Repeat[iValue.Pointer()] = prefix } } switch iValue.Kind() { case reflect.Ptr, reflect.Interface: if !iValue.IsNil() { each.Each(prefix, iValue.Elem()) } case reflect.Map: if each.LastTag != "" { each.Tags = append(each.Tags, fmt.Sprintf("%s.{%s}", prefix, iValue.Type().Key().Name())) each.Vals = append(each.Vals, each.LastTag) } case reflect.Slice, reflect.Array: length := "n" if iValue.Kind() == reflect.Array { length = fmt.Sprint(iValue.Type().Len() - 1) } last := each.LastTag if last != "" { each.Tags = append(each.Tags, fmt.Sprintf("%s.{0-%s}", prefix, length)) each.Vals = append(each.Vals, last) } each.LastTag = last each.Each(fmt.Sprintf("%s.{0-%s}", prefix, length), reflect.New(iValue.Type().Elem())) case reflect.Struct: each.EachStruct(prefix, iValue) } } func (each *eachTags) EachStruct(prefix string, iValue reflect.Value) { iType := iValue.Type() for i := 0; i < iType.NumField(); i++ { if iValue.Field(i).CanSet() { val := iType.Field(i).Tag.Get(each.tag) name := iType.Field(i).Tag.Get("alias") if name == "" { name = iType.Field(i).Name } if val != "" && each.getValueKind(iType.Field(i).Type) != "" { each.Tags = append(each.Tags, prefix+"."+name) each.Vals = append(each.Vals, val) } each.LastTag = val each.Each(prefix+"."+name, iValue.Field(i)) } } } func (each *eachTags) getValueKind(iType reflect.Type) string { switch iType.Kind() { case reflect.Bool: return "bool" case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return "int" case reflect.Float32, reflect.Float64: return "float" case reflect.String: return "string" default: if iType.Kind() == reflect.Slice && iType.Elem().Kind() == reflect.Uint8 { return "string" } return "" } }
) // ConfigParseFunc 定义配置解析函数。 // // Config 默认解析函数为eudore.ConfigAllParseFunc
random_line_split
config.go
package eudore import ( "encoding/json" "fmt" "os" "reflect" "runtime" "strings" "sync" ) // ConfigParseFunc 定义配置解析函数。 // // Config 默认解析函数为eudore.ConfigAllParseFunc type ConfigParseFunc func(Config) error /* Config defines configuration management and uses configuration read-write and analysis functions. Get/Set read and write data implementation: Use custom map or struct as data storage Support Lock concurrency safety Access attributes based on string path hierarchy The default analysis function implementation: Custom configuration analysis function Parse multiple json files Parse the length and short parameters of the command line Parse Env environment variables Configuration differentiation Generate help information based on the structure Switch working directory Config 定义配置管理,使用配置读写和解析功能。 Get/Set读写数据实现下列功能: 使用自定义map或struct作为数据存储 支持Lock并发安全 基于字符串路径层次访问属性 默认解析函数实现下列功能: 自定义配置解析函数 解析多json文件 解析命令行长短参数 解析Env环境变量 配置差异化 根据结构体生成帮助信息 切换工作目录 */ type Config interface { Get(string) interface{} Set(string, interface{}) error ParseOption([]ConfigParseFunc) []ConfigParseFunc Parse() error } // configMap 使用map保存配置。 type configMap struct { Keys map[string]interface{} `alias:"keys"` Print func(...interface{}) `alias:"print"` funcs []ConfigParseFunc `alias:"-"` Locker sync.RWMutex `alias:"-"` } // configEudore 使用结构体或map保存配置,通过属性或反射来读写属性。 type configEudore struct { Keys interface{} `alias:"keys"` Print func(...interface{}) `alias:"print"` funcs []ConfigParseFunc `alias:"-"` configRLocker `alias:"-"` } type configRLocker interface { sync.Locker RLock() RUnlock() } // NewConfigMap 创建一个ConfigMap,如果传入参数为map[string]interface{},则作为初始化数据。 // // ConfigMap将使用传入的map作为配置存储去Get/Set一个键值。 // // ConfigMap已实现json.Marshaler和json.Unmarshaler接口. func NewConfigMap(arg interface{}) Config { var keys map[string]interface{} if ks, ok := arg.(map[string]interface{}); ok { keys = ks } else { keys = make(map[string]interface{}) } return &configMap{ Keys: keys, Print: printEmpty, funcs: ConfigAllParseFunc, } } // Get 方法获取一个属性,如果键为空字符串,返回保存全部数据的map对象。 func (c *configMap) Get(key string) interface{} { c.Locker.RLock() defer c.Locker.RUnlock() if len(key) == 0 { return c.Keys } return c.Keys[key] } // Set 方法设置一个属性,如果键为空字符串且值类型是map[string]interface{},则替换保存全部数据的map对象。 func (c *configMap) Set(key string, val interface{}) error { c.Locker.Lock() if len(key) == 0 { keys, ok := val.(map[string]interface{}) if ok { c.Keys = keys } } else if key == "print" { fn, ok := val.(func(...interface{})) if ok { c.Print = fn } else { c.Print(val) } } else { c.Keys[key] = val } c.Locker.Unlock() return nil } // ParseOption 执行一个配置解析函数选项。 func (c *configMap) ParseOption(fn []ConfigParseFunc) []ConfigParseFunc { c.funcs, fn = fn, c.funcs return fn } // Parse 方法执行全部配置解析函数,如果其中解析函数返回err,则停止解析并返回err。 func (c *configMap) Parse() (err error) { for _, fn := range c.funcs { err = fn(c) if err != nil { c.Print(err) return } } return nil } // MarshalJSON 实现json.Marshaler接口,试json序列化直接操作保存的数据。 func (c *configMap) MarshalJSON() ([]byte, error) { c.Locker.RLock() defer c.Locker.RUnlock() return json.Marshal(c.Keys) } // UnmarshalJSON 实现json.Unmarshaler接口,试json反序列化直接操作保存的数据。 func (c *configMap) UnmarshalJSON(data []byte) error { c.Locker.Lock() defer c.Locker.Unlock() return json.Unmarshal(data, &c.Keys) } // NewConfigEudore 创建一个ConfigEudore,如果传入参数为空,使用空map[string]interface{}作为初始化数据。 // // ConfigEduoew允许传入一个map或struct作为配置存储,使用eudore.Set和eudore.Get方法去读写数据。 // // 如果传入的配置对象实现sync.RLock一样的读写锁,则使用配置的读写锁,否则会创建一个sync.RWMutex锁。 // // ConfigEduoe已实现json.Marshaler和json.Unmarshaler接口. func NewConfigEudore(i interface{}) Config { if i == nil { i = make(map[string]interface{}) } mu, ok := i.(configRLocker) if !ok { mu = new(sync.RWMutex) } return &configEudore{ Keys: i, Print: printEmpty, funcs: ConfigAllParseFunc, configRLocker: mu, } } // Get 方法实现读取数据属性的一个属性。 func (c *configEudore) Get(key string) (i interface{}) { if len(key) == 0 { return c.Keys } c.RLock() i = Get(c.Keys, key) c.RUnlock() return } // Set 方法实现设置数据的一个属性。 func (c *configEudore) Set(key string, val interface{}) (err error) { c.Lock() if len(key) == 0 { c.Keys = val } else if key == "print" { fn, ok := val.(func(...interface{})) if ok { c.Print = fn } else { c.Print(val) } } else { err = Set(c.Keys, key, val) } c.Unlock() return } // ParseOption 执行一个配置解析函数选项。 func (c *configEudore) ParseOption(fn []ConfigParseFunc) []ConfigParseFunc { c.funcs, fn = fn, c.funcs return fn } // Parse 方法执行全部配置解析函数,如果其中解析函数返回err,则停止解析并返回err。 func (c *configEudore) Parse() (err error) { for _, fn := range c.funcs { err = fn(c) if err != nil { c.Print(err) return } } return nil } // MarshalJSON 实现json.Marshaler接口,试json序列化直接操作保存的数据。 func (c *configEudore) MarshalJSON() ([]byte, error) { c.RLock() defer c.RUnlock() return json.Marshal(c.Keys) } // UnmarshalJSON 实现json.Unmarshaler接口,试json反序列化直接操作保存的数据。 func (c *configEudore) UnmarshalJSON(data []byte) error { c.Lock() defer c.Unlock() return json.Unmarshal(data, &c.Keys) } func configPrint(c Config, args ...interface{}) { c.Set("print", fmt.Sprint(args...)) } // ConfigParseJSON 方法解析json文件配置。 func ConfigParseJSON(c Config) error { configPrint(c, "config read paths: ", c.Get("config")) for _, path := range GetStrings(c.Get("config")) { file, err := os.Open(path) if err == nil { err = json.NewDecoder(file).Decode(c) file.Close() } if err == nil { configPrint(c, "config load path: ", path) return nil } if !os.IsNotExist(err) { return fmt.Errorf("config load %s error: %s", path, err.Error()) } } return nil } // C
ParseArgs 函数使用参数设置配置,参数使用'--'为前缀。 // // 如果结构体存在flag tag将作为该路径的缩写,tag长度小于5使用'-'为前缀。 func ConfigParseArgs(c Config) (err error) { flag := &eachTags{tag: "flag", Repeat: make(map[uintptr]string)} flag.Each("", reflect.ValueOf(c.Get(""))) short := make(map[string][]string) for i, tag := range flag.Tags { short[flag.Vals[i]] = append(short[flag.Vals[i]], tag[1:]) } for _, str := range os.Args[1:] { key, val := split2byte(str, '=') if len(key) > 1 && key[0] == '-' && key[1] != '-' { for _, lkey := range short[key[1:]] { val := val if val == "" && reflect.ValueOf(c.Get(lkey)).Kind() == reflect.Bool { val = "true" } configPrint(c, fmt.Sprintf("config set short arg %s: --%s=%s", key[1:], lkey, val)) c.Set(lkey, val) } } else if strings.HasPrefix(key, "--") { if val == "" && reflect.ValueOf(c.Get(key[2:])).Kind() == reflect.Bool { val = "true" } configPrint(c, "config set arg: ", str) c.Set(key[2:], val) } } return } // ConfigParseEnvs 函数使用环境变量设置配置,环境变量使用'ENV_'为前缀,'_'下划线相当于'.'的作用。 func ConfigParseEnvs(c Config) error { for _, value := range os.Environ() { if strings.HasPrefix(value, "ENV_") { configPrint(c, "config set env: ", value) k, v := split2byte(value, '=') k = strings.ToLower(strings.Replace(k, "_", ".", -1))[4:] c.Set(k, v) } } return nil } // ConfigParseMods 函数从'enable'项获得使用的模式的数组字符串,从'mods.xxx'加载配置。 // // 默认会加载OS mod,如果是docker环境下使用docker模式。 func ConfigParseMods(c Config) error { mod := GetStrings(c.Get("enable")) mod = append([]string{getOS()}, mod...) for _, i := range mod { m := c.Get("mods." + i) if m != nil { configPrint(c, "config load mod "+i) ConvertTo(m, c.Get("")) } } return nil } func getOS() string { // check docker _, err := os.Stat("/.dockerenv") if err == nil || !os.IsNotExist(err) { return "docker" } // 返回默认OS return runtime.GOOS } // ConfigParseWorkdir 函数初始化工作空间,从config获取workdir的值为工作空间,然后切换目录。 func ConfigParseWorkdir(c Config) error { dir := GetString(c.Get("workdir")) if dir != "" { configPrint(c, "changes working directory to: "+dir) return os.Chdir(dir) } return nil } // ConfigParseHelp 函数测试配置内容,如果存在help项会层叠获取到结构体的的description tag值作为帮助信息输出。 // // 注意配置结构体的属性需要是非空,否则不会进入遍历。 func ConfigParseHelp(c Config) error { if !GetBool(c.Get("help")) { return nil } conf := reflect.ValueOf(c.Get("")) flag := &eachTags{tag: "flag", Repeat: make(map[uintptr]string)} flag.Each("", conf) flagmap := make(map[string]string) for i, tag := range flag.Tags { flagmap[tag[1:]] = flag.Vals[i] } desc := &eachTags{tag: "description", Repeat: make(map[uintptr]string)} desc.Each("", conf) var length int for i, tag := range desc.Tags { desc.Tags[i] = tag[1:] if len(tag) > length { length = len(tag) } } for i, tag := range desc.Tags { f, ok := flagmap[tag] if ok && !strings.Contains(tag, "{") && len(f) < 5 { fmt.Printf(" -%s,", f) } fmt.Printf("\t --%s=%s\t%s\n", tag, strings.Repeat(" ", length-len(tag)), desc.Vals[i]) } return nil } type eachTags struct { tag string Tags []string Vals []string Repeat map[uintptr]string LastTag string } func (each *eachTags) Each(prefix string, iValue reflect.Value) { switch iValue.Kind() { case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer: if !iValue.IsNil() { _, ok := each.Repeat[iValue.Pointer()] if ok { return } each.Repeat[iValue.Pointer()] = prefix } } switch iValue.Kind() { case reflect.Ptr, reflect.Interface: if !iValue.IsNil() { each.Each(prefix, iValue.Elem()) } case reflect.Map: if each.LastTag != "" { each.Tags = append(each.Tags, fmt.Sprintf("%s.{%s}", prefix, iValue.Type().Key().Name())) each.Vals = append(each.Vals, each.LastTag) } case reflect.Slice, reflect.Array: length := "n" if iValue.Kind() == reflect.Array { length = fmt.Sprint(iValue.Type().Len() - 1) } last := each.LastTag if last != "" { each.Tags = append(each.Tags, fmt.Sprintf("%s.{0-%s}", prefix, length)) each.Vals = append(each.Vals, last) } each.LastTag = last each.Each(fmt.Sprintf("%s.{0-%s}", prefix, length), reflect.New(iValue.Type().Elem())) case reflect.Struct: each.EachStruct(prefix, iValue) } } func (each *eachTags) EachStruct(prefix string, iValue reflect.Value) { iType := iValue.Type() for i := 0; i < iType.NumField(); i++ { if iValue.Field(i).CanSet() { val := iType.Field(i).Tag.Get(each.tag) name := iType.Field(i).Tag.Get("alias") if name == "" { name = iType.Field(i).Name } if val != "" && each.getValueKind(iType.Field(i).Type) != "" { each.Tags = append(each.Tags, prefix+"."+name) each.Vals = append(each.Vals, val) } each.LastTag = val each.Each(prefix+"."+name, iValue.Field(i)) } } } func (each *eachTags) getValueKind(iType reflect.Type) string { switch iType.Kind() { case reflect.Bool: return "bool" case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return "int" case reflect.Float32, reflect.Float64: return "float" case reflect.String: return "string" default: if iType.Kind() == reflect.Slice && iType.Elem().Kind() == reflect.Uint8 { return "string" } return "" } }
onfig
identifier_name
config.go
package eudore import ( "encoding/json" "fmt" "os" "reflect" "runtime" "strings" "sync" ) // ConfigParseFunc 定义配置解析函数。 // // Config 默认解析函数为eudore.ConfigAllParseFunc type ConfigParseFunc func(Config) error /* Config defines configuration management and uses configuration read-write and analysis functions. Get/Set read and write data implementation: Use custom map or struct as data storage Support Lock concurrency safety Access attributes based on string path hierarchy The default analysis function implementation: Custom configuration analysis function Parse multiple json files Parse the length and short parameters of the command line Parse Env environment variables Configuration differentiation Generate help information based on the structure Switch working directory Config 定义配置管理,使用配置读写和解析功能。 Get/Set读写数据实现下列功能: 使用自定义map或struct作为数据存储 支持Lock并发安全 基于字符串路径层次访问属性 默认解析函数实现下列功能: 自定义配置解析函数 解析多json文件 解析命令行长短参数 解析Env环境变量 配置差异化 根据结构体生成帮助信息 切换工作目录 */ type Config interface { Get(string) interface{} Set(string, interface{}) error ParseOption([]ConfigParseFunc) []ConfigParseFunc Parse() error } // configMap 使用map保存配置。 type configMap struct { Keys map[string]interface{} `alias:"keys"` Print func(...interface{}) `alias:"print"` funcs []ConfigParseFunc `alias:"-"` Locker sync.RWMutex `alias:"-"` } // configEudore 使用结构体或map保存配置,通过属性或反射来读写属性。 type configEudore struct { Keys interface{} `alias:"keys"` Print func(...interface{}) `alias:"print"` funcs []ConfigParseFunc `alias:"-"` configRLocker `alias:"-"` } type configRLocker interface { sync.Locker RLock() RUnlock() } // NewConfigMap 创建一个ConfigMap,如果传入参数为map[string]interface{},则作为初始化数据。 // // ConfigMap将使用传入的map作为配置存储去Get/Set一个键值。 // // ConfigMap已实现json.Marshaler和json.Unmarshaler接口. func NewConfigMap(arg interface{}) Config { var keys map[string]interface{} if ks, ok := arg.(map[string]interface{}); ok { keys = ks } else { keys = make(map[string]interface{}) } return &configMap{ Keys: keys, Print: printEmpty, funcs: ConfigAllParseFunc, } } // Get 方法获取一个属性,如果键为空字符串,返回保存全部数据的map对象。 func (c *configMap) Get(key string) interface{} { c.Locker.RLock() defer c.Locker.RUnlock() if len(key) == 0 { return c.Keys } return c.Keys[key] } // Set 方法设置一个属性,如果键为空字符串且值类型是map[string]interface{},则替换保存全部数据的map对象。 func (c *configMap) Set(key string, val interface{}) error { c.Locker.Lock() if len(key) == 0 { keys, ok := val.(map[string]interface{}) if ok { c.Keys = keys } } else if key == "print" { fn, ok := val.(func(...interface{})) if ok { c.Print = fn } else { c.Print(val) } } else { c.Keys[key] = val } c.Locker.Unlock() return nil } // ParseOption 执行一个配置解析函数选项。 func (c *configMap) ParseOption(fn []ConfigParseFunc) []ConfigParseFunc { c.funcs, fn = fn, c.funcs return fn } // Parse 方法执行全部配置解析函数,如果其中解析函数返回err,则停止解析并返回err。 func (c *configMap) Parse() (err error) { for _, fn := range c.funcs { err = fn(c) if err != nil { c.Print(err) return } } return nil } // MarshalJSON 实现json.Marshaler接口,试json序列化直接操作保存的数据。 func (c *configMap) MarshalJSON() ([]byte, error) { c.Locker.RLock() defer c.Locker.RUnlock() return json.Marshal(c.Keys) } // UnmarshalJSON 实现json.Unmarshaler接口,试json反序列化直接操作保存的数据。 func (c *configMap) UnmarshalJSON(data []byte) error { c.Locker.Lock() defer c.Locker.Unlock() return json.Unmarshal(data, &c.Keys) } // NewConfigEudore 创建一个ConfigEudore,如果传入参数为空,使用空map[string]interface{}作为初始化数据。 // // ConfigEduoew允许传入一个map或struct作为配置存储,使用eudore.Set和eudore.Get方法去读写数据。 // // 如果传入的配置对象实现sync.RLock一样的读写锁,则使用配置的读写锁,否则会创建一个sync.RWMutex锁。 // // ConfigEduoe已实现json.Marshaler和json.Unmarshaler接口. func NewConfigEudore(i interface{}) Config { if i == nil { i = make(map[string]interface{}) } mu, ok := i.(configRLocker) if !ok { mu = new(sync.RWMutex) } return &configEudore{ Keys: i, Print: printEmpty, funcs: ConfigAllParseFunc, configRLocker: mu, } } // Get 方法实现读取数据属性的一个属性。 func (c *configEudore) Get(key string) (i interface{}) { if len(key) == 0 { return c.Keys } c.RLock() i = Get(c.Keys, key) c.RUnlock() return } // Set 方法实现设置数据的一个属性。 func (c *configEudore) Set(key string, val interface{}) (err error) { c.Lock() if len(key) == 0 { c.Keys = val } else if key == "print" { fn, ok := val.(func(...interface{})) if ok { c.Print = fn } else { c.Print(val) } } else { err = Set(c.Keys, key, val) } c.Unlock() return } // ParseOption 执行一个配置解析函数选项。 func (c *configEudore) ParseOption(fn []ConfigParseFunc) []ConfigParseFunc { c.funcs, fn = fn, c.funcs return fn } // Parse 方法执行全部配置解析函数,如果其中解析函数返回err,则停止解析并返回err。 func (c *configEudore) Parse() (err error) { for _, fn := range c.funcs { err = fn(c) if err != nil { c.Print(err) return } } return nil } // MarshalJSON 实现json.Marshaler接口,试json序列化直接操作保存的数据。 func (c *configEudore) MarshalJSON() ([]byte, error) { c.RLock() defer c.RUnlock() return json.Marshal(c.Keys) } //
a []byte) error { c.Lock() defer c.Unlock() return json.Unmarshal(data, &c.Keys) } func configPrint(c Config, args ...interface{}) { c.Set("print", fmt.Sprint(args...)) } // ConfigParseJSON 方法解析json文件配置。 func ConfigParseJSON(c Config) error { configPrint(c, "config read paths: ", c.Get("config")) for _, path := range GetStrings(c.Get("config")) { file, err := os.Open(path) if err == nil { err = json.NewDecoder(file).Decode(c) file.Close() } if err == nil { configPrint(c, "config load path: ", path) return nil } if !os.IsNotExist(err) { return fmt.Errorf("config load %s error: %s", path, err.Error()) } } return nil } // ConfigParseArgs 函数使用参数设置配置,参数使用'--'为前缀。 // // 如果结构体存在flag tag将作为该路径的缩写,tag长度小于5使用'-'为前缀。 func ConfigParseArgs(c Config) (err error) { flag := &eachTags{tag: "flag", Repeat: make(map[uintptr]string)} flag.Each("", reflect.ValueOf(c.Get(""))) short := make(map[string][]string) for i, tag := range flag.Tags { short[flag.Vals[i]] = append(short[flag.Vals[i]], tag[1:]) } for _, str := range os.Args[1:] { key, val := split2byte(str, '=') if len(key) > 1 && key[0] == '-' && key[1] != '-' { for _, lkey := range short[key[1:]] { val := val if val == "" && reflect.ValueOf(c.Get(lkey)).Kind() == reflect.Bool { val = "true" } configPrint(c, fmt.Sprintf("config set short arg %s: --%s=%s", key[1:], lkey, val)) c.Set(lkey, val) } } else if strings.HasPrefix(key, "--") { if val == "" && reflect.ValueOf(c.Get(key[2:])).Kind() == reflect.Bool { val = "true" } configPrint(c, "config set arg: ", str) c.Set(key[2:], val) } } return } // ConfigParseEnvs 函数使用环境变量设置配置,环境变量使用'ENV_'为前缀,'_'下划线相当于'.'的作用。 func ConfigParseEnvs(c Config) error { for _, value := range os.Environ() { if strings.HasPrefix(value, "ENV_") { configPrint(c, "config set env: ", value) k, v := split2byte(value, '=') k = strings.ToLower(strings.Replace(k, "_", ".", -1))[4:] c.Set(k, v) } } return nil } // ConfigParseMods 函数从'enable'项获得使用的模式的数组字符串,从'mods.xxx'加载配置。 // // 默认会加载OS mod,如果是docker环境下使用docker模式。 func ConfigParseMods(c Config) error { mod := GetStrings(c.Get("enable")) mod = append([]string{getOS()}, mod...) for _, i := range mod { m := c.Get("mods." + i) if m != nil { configPrint(c, "config load mod "+i) ConvertTo(m, c.Get("")) } } return nil } func getOS() string { // check docker _, err := os.Stat("/.dockerenv") if err == nil || !os.IsNotExist(err) { return "docker" } // 返回默认OS return runtime.GOOS } // ConfigParseWorkdir 函数初始化工作空间,从config获取workdir的值为工作空间,然后切换目录。 func ConfigParseWorkdir(c Config) error { dir := GetString(c.Get("workdir")) if dir != "" { configPrint(c, "changes working directory to: "+dir) return os.Chdir(dir) } return nil } // ConfigParseHelp 函数测试配置内容,如果存在help项会层叠获取到结构体的的description tag值作为帮助信息输出。 // // 注意配置结构体的属性需要是非空,否则不会进入遍历。 func ConfigParseHelp(c Config) error { if !GetBool(c.Get("help")) { return nil } conf := reflect.ValueOf(c.Get("")) flag := &eachTags{tag: "flag", Repeat: make(map[uintptr]string)} flag.Each("", conf) flagmap := make(map[string]string) for i, tag := range flag.Tags { flagmap[tag[1:]] = flag.Vals[i] } desc := &eachTags{tag: "description", Repeat: make(map[uintptr]string)} desc.Each("", conf) var length int for i, tag := range desc.Tags { desc.Tags[i] = tag[1:] if len(tag) > length { length = len(tag) } } for i, tag := range desc.Tags { f, ok := flagmap[tag] if ok && !strings.Contains(tag, "{") && len(f) < 5 { fmt.Printf(" -%s,", f) } fmt.Printf("\t --%s=%s\t%s\n", tag, strings.Repeat(" ", length-len(tag)), desc.Vals[i]) } return nil } type eachTags struct { tag string Tags []string Vals []string Repeat map[uintptr]string LastTag string } func (each *eachTags) Each(prefix string, iValue reflect.Value) { switch iValue.Kind() { case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer: if !iValue.IsNil() { _, ok := each.Repeat[iValue.Pointer()] if ok { return } each.Repeat[iValue.Pointer()] = prefix } } switch iValue.Kind() { case reflect.Ptr, reflect.Interface: if !iValue.IsNil() { each.Each(prefix, iValue.Elem()) } case reflect.Map: if each.LastTag != "" { each.Tags = append(each.Tags, fmt.Sprintf("%s.{%s}", prefix, iValue.Type().Key().Name())) each.Vals = append(each.Vals, each.LastTag) } case reflect.Slice, reflect.Array: length := "n" if iValue.Kind() == reflect.Array { length = fmt.Sprint(iValue.Type().Len() - 1) } last := each.LastTag if last != "" { each.Tags = append(each.Tags, fmt.Sprintf("%s.{0-%s}", prefix, length)) each.Vals = append(each.Vals, last) } each.LastTag = last each.Each(fmt.Sprintf("%s.{0-%s}", prefix, length), reflect.New(iValue.Type().Elem())) case reflect.Struct: each.EachStruct(prefix, iValue) } } func (each *eachTags) EachStruct(prefix string, iValue reflect.Value) { iType := iValue.Type() for i := 0; i < iType.NumField(); i++ { if iValue.Field(i).CanSet() { val := iType.Field(i).Tag.Get(each.tag) name := iType.Field(i).Tag.Get("alias") if name == "" { name = iType.Field(i).Name } if val != "" && each.getValueKind(iType.Field(i).Type) != "" { each.Tags = append(each.Tags, prefix+"."+name) each.Vals = append(each.Vals, val) } each.LastTag = val each.Each(prefix+"."+name, iValue.Field(i)) } } } func (each *eachTags) getValueKind(iType reflect.Type) string { switch iType.Kind() { case reflect.Bool: return "bool" case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return "int" case reflect.Float32, reflect.Float64: return "float" case reflect.String: return "string" default: if iType.Kind() == reflect.Slice && iType.Elem().Kind() == reflect.Uint8 { return "string" } return "" } }
UnmarshalJSON 实现json.Unmarshaler接口,试json反序列化直接操作保存的数据。 func (c *configEudore) UnmarshalJSON(dat
identifier_body
f3_modeling_report2.py
"""------------------------------------------------------------------------ """ """Introduction To Data Science Coursework 2 Arshad Ahmed Flow 3: Modelling/ML""" """------------------------------------------------------------------------ """ """------------------------------------------------------------------------ """ """Import Libraries """ """------------------------------------------------------------------------ """ import numpy as np import pandas as pd import matplotlib as mpl import scipy import matplotlib.pyplot as plt import statsmodels as sm import sklearn import networkx as nx import seaborn as sns; sns.set() import re, os , sys from time import time from sklearn import decomposition, manifold, cluster, metrics from scipy.stats import kendalltau, pointbiserialr, pearsonr import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D """------------------------------------------------------------------------ """ """Step 11: Apply Dimensionality Reduction and ML: Testing """ """------------------------------------------------------------------------ """ datadir = 'C:/Users/arsha_000/Downloads/data ideas/' d6 = pd.read_excel(datadir + 'input_to_modeling.xlsx') d6 = d6.ix[34::,:] d6.head() printrowname(d6) target = d6['RowMedian_FertilityRate'];target.head() d7 = d6.drop(['RowMedian_FertilityRate', 'RowMean_FertilityRate', 'RowStd_FertilityRate','RowIQR_FertilityRate'], axis=1) printrowname(d7) """Step 11_0: Apply PCA """ """------------------------------------------------------------------------ """ pca = sklearn.decomposition.PCA() pca_data = pca.fit(d7) pca_data.explained_variance_ratio_ sum(pca_data.explained_variance_ratio_[0:2]) pca1 = pca_data.components_[:,0] pca2 = pca_data.components_[:,1] pca3 = pca_data.components_[:,2] """ Project Data""" pca1_data = matrix(pca1) * matrix(d7).transpose() pca2_data = matrix(pca2) * matrix(d7).transpose() pca3_data = matrix(pca3) * matrix(d7).transpose() pca_df1 = pd.DataFrame(pca1_data.transpose()) pca_df2 = pd.DataFrame(pca2_data.transpose()) pca_df3 = pd.DataFrame(pca3_data.transpose()) pca_df_all = pd.concat([pca_df1, pca_df2, pca_df3], axis=1) pcaname = ('PCA1','PCA2','PCA3') pca_df_all.columns= pcaname pca_df_all.head() sortid_pca1 = pca1.argsort() featname = np.asanyarray(list(d7)) featrank_pca = pd.DataFrame(featname[sortid_pca1].transpose()) """ PCA fitted data""" pca_data_fit = pca.fit_transform(d7) pca_3c = pca_data_fit[:,0:3] """Step 11_1: Apply Factor Analysis """ """------------------------------------------------------------------------ """ fa = decomposition.FactorAnalysis() data_fa = fa.fit_transform(pca_3c) fa.components_ fa.loglike_ data_fa = fa.fit(d7) data_fa.components_[:,0] fa1_sortidx = data_fa.components_[:,0].argsort() featrank_fa = pd.DataFrame(featname[fa1_sortidx].transpose()) data_pca_fa_mdx = fa.fit(pca_data_fit) pca_fa_sortidx = data_pca_fa_mdx.components_[:,0].argsort() featname[pca_fa_sortidx] featrank_pca_fa = pd.DataFrame(featname[pca_fa_sortidx]) """Step 11_2: Apply ICA """ """------------------------------------------------------------------------ """ ica = sklearn.decomposition.FastICA() data_ica = ica.fit(d7) data_ica.components_[:,0] ica1_sortidx = data_ica.components_[:,0].argsort() featrank_ica = pd.DataFrame(featname[ica1_sortidx].transpose()) data_pca_ica_mdx = ica.fit(pca_data_fit) pca_ica1= data_pca_ica_mdx.components_[:,0] pca_ica_sortidx = pca_ica1.argsort() featname[pca_ica_sortidx ] featrank_pca_ica = pd.DataFrame(featname[pca_ica_sortidx ]) """Feature Ranking By PCA ,ICA, FA """ featureRank = pd.concat([featrank_ica, featrank_pca, featrank_fa, featrank_pca_fa, featrank_pca_ica], axis=1) featureRank.columns = ('ICA Comp1', 'PCA Comp1', 'FA Comp1', 'PCA + FA Comp1', 'PCA + ICA Comp1') featureRank[1:11] featureRank.to_excel(datadir +'feature_ranking_DR.xlsx') data_pca_ica = ica.fit_transform(pca_3c) data_pca_fa_ica = ica.fit_transform(data_pca_fa) """Step 11_2: Apply FA to PCA + ICA data """ """------------------------------------------------------------------------ """ data_pca_ica_fa = fa.fit_transform(data_ica) #produces zeros dont use data_pca_fa = fa.fit_transform(pca_3c) """Step 11_3: Apply LLE to data """ """------------------------------------------------------------------------ """ data_lle = sklearn.manifold.locally_linear_embedding(d7,n_neighbors=12, n_components=3) data_pca_fa_ica_lle = sklearn.manifold.locally_linear_embedding(data_pca_fa_ica,n_neighbors=12, n_components=3) """Step 12: Machine Learning """ """------------------------------------------------------------------------ """ from sklearn.feature_selection import SelectFromModel from sklearn.linear_model import LassoCV from sklearn import ensemble from sklearn.utils import shuffle from sklearn.metrics import mean_squared_error from sklearn.ensemble import ExtraTreesRegressor, RandomForestRegressor, ExtraTreesClassifier, RandomForestClassifier """ Test and Training Set """ X = d7.copy(deep=True) y=target X = X.astype(np.float32) offset = int(X.shape[0] * 0.9) X_train, y_train = X[:offset], y[:offset] X_test, y_test = X[offset:], y[offset:] """ML 1: Gradient Boosting Regressor """ params = {'n_estimators': 10, 'max_depth': 10, 'min_samples_split': 10, 'learning_rate': 0.1, 'loss': 'ls'} clf = ensemble.GradientBoostingRegressor(**params) clf.fit(X_train, y_train) """ Feature Selection """ feature_importance = clf.feature_importances_ # make importances relative to max importance plt.figure(figsize=(7,18)) feature_importance = 100.0 * (feature_importance / feature_importance.max()) sorted_idx = np.argsort(feature_importance) feature_names = list(X) pos = np.arange(sorted_idx.shape[0]) + .5 plt.barh(pos, feature_importance[sorted_idx], align='center') plt.yticks(pos, feature_names) plt.xlabel('Relative Importance') plt.title('Variable Importance') plt.show() """Plot training deviance and compute test set deviance """ test_score = np.zeros((params['n_estimators'],), dtype=np.float64) for i, y_pred in enumerate(clf.staged_predict(X_test)):
plt.figure(figsize=(12, 6)) plt.subplot(1, 2, 1) plt.title('Deviance of Gradient Boosting Regression Model') plt.plot(np.arange(params['n_estimators']) + 1, clf.train_score_, 'b-', label='Training Set Deviance') plt.plot(np.arange(params['n_estimators']) + 1, test_score, 'r-', label='Test Set Deviance') plt.legend(loc='upper right') plt.xlabel('Boosting Iterations') plt.ylabel('Deviance') """ML 2: Extra Trees Regressor """ forest = ExtraTreesRegressor(n_estimators=250,random_state=0) forest.fit(X_train,y_train) """ML 3: Random Forest Regressor """ rforest = RandomForestRegressor() rforest.fit(X_train,y_train) mse = mean_squared_error(y_test, clf.predict(X_test)) print("Gradient Boosting MSE: " ,mse) mse1 = mean_squared_error(y_test, forest.predict(X_test)) print("Extra Trees MSE: " ,mse1) mse2 = mean_squared_error(y_test, rforest.predict(X_test)) print("Random Forest MSE: " ,mse2) """ ML with PCA """ X1 = pca_df_all.copy(deep=True) y1=target X1 = X1.astype(np.float32) offset = int(X1.shape[0] * 0.9) X1_train, y1_train = X1[:offset], y1[:offset] X1_test, y1_test = X1[offset:], y1[offset:] forest.fit(X1_train,y1_train) rforest.fit(X1_train,y1_train) clf.fit(X1_train, y1_train) mse = mean_squared_error(y1_test, clf.predict(X1_test)) print("Gradient Boosting w. PCA MSE: " ,mse) mse1 = mean_squared_error(y_test, forest.predict(X1_test)) print("Extra Trees w. PCA MSE: " ,mse1) mse2 = mean_squared_error(y_test, rforest.predict(X1_test)) print("Random Forest w. PCA MSE: " ,mse2) """ ML with PCA + FA """ X2 = data_fa.copy() y1=target X2 = X2.astype(np.float32) offset = int(X1.shape[0] * 0.9) X2_train, y1_train = X2[:offset], y1[:offset] X2_test, y1_test = X2[offset:], y1[offset:] forest.fit(X2_train,y1_train) rforest.fit(X2_train,y1_train) clf.fit(X2_train, y1_train) mse = mean_squared_error(y1_test, clf.predict(X2_test)) print("Gradient Boosting w. PCA + FA MSE: " ,mse) mse1 = mean_squared_error(y_test, forest.predict(X2_test)) print("Extra Trees w. PCA + FA MSE: " ,mse1) mse2 = mean_squared_error(y_test, rforest.predict(X2_test)) print("Random Forest w. PCA + FA MSE: " ,mse2) """ ML with PCA + ICA """ X2 = data_ica.copy() y1=target X2 = X2.astype(np.float32) offset = int(X1.shape[0] * 0.9) X2_train, y1_train = X2[:offset], y1[:offset] X2_test, y1_test = X2[offset:], y1[offset:] forest.fit(X2_train,y1_train) rforest.fit(X2_train,y1_train) clf.fit(X2_train, y1_train) mse = mean_squared_error(y1_test, clf.predict(X2_test)) print("Gradient Boosting w. PCA + ICA MSE: " ,mse) mse1 = mean_squared_error(y_test, forest.predict(X2_test)) print("Extra Trees w. PCA + ICA MSE: " ,mse1) mse2 = mean_squared_error(y_test, rforest.predict(X2_test)) print("Random Forest w. PCA + ICA MSE: " ,mse2) """ ML with PCA + ICA + FA """ X2 = data_pca_ica_fa.copy() y1=target X2 = X2.astype(np.float32) offset = int(X1.shape[0] * 0.9) X2_train, y1_train = X2[:offset], y1[:offset] X2_test, y1_test = X2[offset:], y1[offset:] forest.fit(X2_train,y1_train) rforest.fit(X2_train,y1_train) clf.fit(X2_train, y1_train) mse = mean_squared_error(y1_test, clf.predict(X2_test)) print("Gradient Boosting w. PCA + ICA + FA MSE: " ,mse) mse1 = mean_squared_error(y_test, forest.predict(X2_test)) print("Extra Trees w. PCA + ICA + FA MSE: " ,mse1) mse2 = mean_squared_error(y_test, rforest.predict(X2_test)) print("Random Forest w. PCA + ICA + FA MSE: " ,mse2) """Step 13: Merge Country Names back to data for visual analytics """ """------------------------------------------------------------------------ """ """Strip Country Names """ countryname = pd.read_excel(datadir + 'merged_data.xlsx') countryname = countryname['Country Name'].ix[34::];printrowname(countryname) countryname_df = pd.DataFrame(countryname) countryname_df.shape[0] d6.shape[0] countryname_df.tail(n=59) """Merge COuntry Names to Data """ d8 = pd.concat([countryname_df, d6],axis=1) d8.shape[0] """Write Out Data for Visual Analytics""" fdout = 'C:/Users/arsha_000/OneDrive/MSc Data Science Work/Introduction to Data Science/Coursework 2/' d8.to_excel(fdout + 'f3_final_merged.xlsx')
test_score[i] = clf.loss_(y_test, y_pred)
conditional_block
f3_modeling_report2.py
"""------------------------------------------------------------------------ """ """Introduction To Data Science Coursework 2 Arshad Ahmed Flow 3: Modelling/ML""" """------------------------------------------------------------------------ """ """------------------------------------------------------------------------ """ """Import Libraries """ """------------------------------------------------------------------------ """ import numpy as np import pandas as pd import matplotlib as mpl import scipy import matplotlib.pyplot as plt import statsmodels as sm import sklearn import networkx as nx import seaborn as sns; sns.set() import re, os , sys from time import time from sklearn import decomposition, manifold, cluster, metrics from scipy.stats import kendalltau, pointbiserialr, pearsonr import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D """------------------------------------------------------------------------ """ """Step 11: Apply Dimensionality Reduction and ML: Testing """ """------------------------------------------------------------------------ """ datadir = 'C:/Users/arsha_000/Downloads/data ideas/' d6 = pd.read_excel(datadir + 'input_to_modeling.xlsx') d6 = d6.ix[34::,:] d6.head() printrowname(d6) target = d6['RowMedian_FertilityRate'];target.head() d7 = d6.drop(['RowMedian_FertilityRate', 'RowMean_FertilityRate', 'RowStd_FertilityRate','RowIQR_FertilityRate'], axis=1) printrowname(d7) """Step 11_0: Apply PCA """ """------------------------------------------------------------------------ """ pca = sklearn.decomposition.PCA() pca_data = pca.fit(d7) pca_data.explained_variance_ratio_ sum(pca_data.explained_variance_ratio_[0:2]) pca1 = pca_data.components_[:,0] pca2 = pca_data.components_[:,1] pca3 = pca_data.components_[:,2] """ Project Data""" pca1_data = matrix(pca1) * matrix(d7).transpose() pca2_data = matrix(pca2) * matrix(d7).transpose() pca3_data = matrix(pca3) * matrix(d7).transpose() pca_df1 = pd.DataFrame(pca1_data.transpose()) pca_df2 = pd.DataFrame(pca2_data.transpose()) pca_df3 = pd.DataFrame(pca3_data.transpose()) pca_df_all = pd.concat([pca_df1, pca_df2, pca_df3], axis=1) pcaname = ('PCA1','PCA2','PCA3') pca_df_all.columns= pcaname pca_df_all.head() sortid_pca1 = pca1.argsort() featname = np.asanyarray(list(d7)) featrank_pca = pd.DataFrame(featname[sortid_pca1].transpose()) """ PCA fitted data""" pca_data_fit = pca.fit_transform(d7) pca_3c = pca_data_fit[:,0:3] """Step 11_1: Apply Factor Analysis """ """------------------------------------------------------------------------ """ fa = decomposition.FactorAnalysis() data_fa = fa.fit_transform(pca_3c) fa.components_ fa.loglike_ data_fa = fa.fit(d7) data_fa.components_[:,0] fa1_sortidx = data_fa.components_[:,0].argsort() featrank_fa = pd.DataFrame(featname[fa1_sortidx].transpose()) data_pca_fa_mdx = fa.fit(pca_data_fit) pca_fa_sortidx = data_pca_fa_mdx.components_[:,0].argsort() featname[pca_fa_sortidx] featrank_pca_fa = pd.DataFrame(featname[pca_fa_sortidx]) """Step 11_2: Apply ICA """ """------------------------------------------------------------------------ """ ica = sklearn.decomposition.FastICA() data_ica = ica.fit(d7) data_ica.components_[:,0] ica1_sortidx = data_ica.components_[:,0].argsort() featrank_ica = pd.DataFrame(featname[ica1_sortidx].transpose()) data_pca_ica_mdx = ica.fit(pca_data_fit) pca_ica1= data_pca_ica_mdx.components_[:,0] pca_ica_sortidx = pca_ica1.argsort() featname[pca_ica_sortidx ] featrank_pca_ica = pd.DataFrame(featname[pca_ica_sortidx ]) """Feature Ranking By PCA ,ICA, FA """ featureRank = pd.concat([featrank_ica, featrank_pca, featrank_fa, featrank_pca_fa, featrank_pca_ica], axis=1) featureRank.columns = ('ICA Comp1', 'PCA Comp1', 'FA Comp1', 'PCA + FA Comp1', 'PCA + ICA Comp1') featureRank[1:11] featureRank.to_excel(datadir +'feature_ranking_DR.xlsx') data_pca_ica = ica.fit_transform(pca_3c) data_pca_fa_ica = ica.fit_transform(data_pca_fa) """Step 11_2: Apply FA to PCA + ICA data """ """------------------------------------------------------------------------ """ data_pca_ica_fa = fa.fit_transform(data_ica) #produces zeros dont use data_pca_fa = fa.fit_transform(pca_3c) """Step 11_3: Apply LLE to data """ """------------------------------------------------------------------------ """ data_lle = sklearn.manifold.locally_linear_embedding(d7,n_neighbors=12, n_components=3) data_pca_fa_ica_lle = sklearn.manifold.locally_linear_embedding(data_pca_fa_ica,n_neighbors=12, n_components=3) """Step 12: Machine Learning """ """------------------------------------------------------------------------ """ from sklearn.feature_selection import SelectFromModel from sklearn.linear_model import LassoCV from sklearn import ensemble from sklearn.utils import shuffle from sklearn.metrics import mean_squared_error from sklearn.ensemble import ExtraTreesRegressor, RandomForestRegressor, ExtraTreesClassifier, RandomForestClassifier """ Test and Training Set """ X = d7.copy(deep=True) y=target X = X.astype(np.float32) offset = int(X.shape[0] * 0.9) X_train, y_train = X[:offset], y[:offset] X_test, y_test = X[offset:], y[offset:] """ML 1: Gradient Boosting Regressor """ params = {'n_estimators': 10, 'max_depth': 10, 'min_samples_split': 10, 'learning_rate': 0.1, 'loss': 'ls'} clf = ensemble.GradientBoostingRegressor(**params) clf.fit(X_train, y_train) """ Feature Selection """ feature_importance = clf.feature_importances_ # make importances relative to max importance plt.figure(figsize=(7,18)) feature_importance = 100.0 * (feature_importance / feature_importance.max()) sorted_idx = np.argsort(feature_importance) feature_names = list(X) pos = np.arange(sorted_idx.shape[0]) + .5 plt.barh(pos, feature_importance[sorted_idx], align='center') plt.yticks(pos, feature_names) plt.xlabel('Relative Importance') plt.title('Variable Importance') plt.show() """Plot training deviance and compute test set deviance """ test_score = np.zeros((params['n_estimators'],), dtype=np.float64) for i, y_pred in enumerate(clf.staged_predict(X_test)): test_score[i] = clf.loss_(y_test, y_pred) plt.figure(figsize=(12, 6)) plt.subplot(1, 2, 1) plt.title('Deviance of Gradient Boosting Regression Model')
label='Test Set Deviance') plt.legend(loc='upper right') plt.xlabel('Boosting Iterations') plt.ylabel('Deviance') """ML 2: Extra Trees Regressor """ forest = ExtraTreesRegressor(n_estimators=250,random_state=0) forest.fit(X_train,y_train) """ML 3: Random Forest Regressor """ rforest = RandomForestRegressor() rforest.fit(X_train,y_train) mse = mean_squared_error(y_test, clf.predict(X_test)) print("Gradient Boosting MSE: " ,mse) mse1 = mean_squared_error(y_test, forest.predict(X_test)) print("Extra Trees MSE: " ,mse1) mse2 = mean_squared_error(y_test, rforest.predict(X_test)) print("Random Forest MSE: " ,mse2) """ ML with PCA """ X1 = pca_df_all.copy(deep=True) y1=target X1 = X1.astype(np.float32) offset = int(X1.shape[0] * 0.9) X1_train, y1_train = X1[:offset], y1[:offset] X1_test, y1_test = X1[offset:], y1[offset:] forest.fit(X1_train,y1_train) rforest.fit(X1_train,y1_train) clf.fit(X1_train, y1_train) mse = mean_squared_error(y1_test, clf.predict(X1_test)) print("Gradient Boosting w. PCA MSE: " ,mse) mse1 = mean_squared_error(y_test, forest.predict(X1_test)) print("Extra Trees w. PCA MSE: " ,mse1) mse2 = mean_squared_error(y_test, rforest.predict(X1_test)) print("Random Forest w. PCA MSE: " ,mse2) """ ML with PCA + FA """ X2 = data_fa.copy() y1=target X2 = X2.astype(np.float32) offset = int(X1.shape[0] * 0.9) X2_train, y1_train = X2[:offset], y1[:offset] X2_test, y1_test = X2[offset:], y1[offset:] forest.fit(X2_train,y1_train) rforest.fit(X2_train,y1_train) clf.fit(X2_train, y1_train) mse = mean_squared_error(y1_test, clf.predict(X2_test)) print("Gradient Boosting w. PCA + FA MSE: " ,mse) mse1 = mean_squared_error(y_test, forest.predict(X2_test)) print("Extra Trees w. PCA + FA MSE: " ,mse1) mse2 = mean_squared_error(y_test, rforest.predict(X2_test)) print("Random Forest w. PCA + FA MSE: " ,mse2) """ ML with PCA + ICA """ X2 = data_ica.copy() y1=target X2 = X2.astype(np.float32) offset = int(X1.shape[0] * 0.9) X2_train, y1_train = X2[:offset], y1[:offset] X2_test, y1_test = X2[offset:], y1[offset:] forest.fit(X2_train,y1_train) rforest.fit(X2_train,y1_train) clf.fit(X2_train, y1_train) mse = mean_squared_error(y1_test, clf.predict(X2_test)) print("Gradient Boosting w. PCA + ICA MSE: " ,mse) mse1 = mean_squared_error(y_test, forest.predict(X2_test)) print("Extra Trees w. PCA + ICA MSE: " ,mse1) mse2 = mean_squared_error(y_test, rforest.predict(X2_test)) print("Random Forest w. PCA + ICA MSE: " ,mse2) """ ML with PCA + ICA + FA """ X2 = data_pca_ica_fa.copy() y1=target X2 = X2.astype(np.float32) offset = int(X1.shape[0] * 0.9) X2_train, y1_train = X2[:offset], y1[:offset] X2_test, y1_test = X2[offset:], y1[offset:] forest.fit(X2_train,y1_train) rforest.fit(X2_train,y1_train) clf.fit(X2_train, y1_train) mse = mean_squared_error(y1_test, clf.predict(X2_test)) print("Gradient Boosting w. PCA + ICA + FA MSE: " ,mse) mse1 = mean_squared_error(y_test, forest.predict(X2_test)) print("Extra Trees w. PCA + ICA + FA MSE: " ,mse1) mse2 = mean_squared_error(y_test, rforest.predict(X2_test)) print("Random Forest w. PCA + ICA + FA MSE: " ,mse2) """Step 13: Merge Country Names back to data for visual analytics """ """------------------------------------------------------------------------ """ """Strip Country Names """ countryname = pd.read_excel(datadir + 'merged_data.xlsx') countryname = countryname['Country Name'].ix[34::];printrowname(countryname) countryname_df = pd.DataFrame(countryname) countryname_df.shape[0] d6.shape[0] countryname_df.tail(n=59) """Merge COuntry Names to Data """ d8 = pd.concat([countryname_df, d6],axis=1) d8.shape[0] """Write Out Data for Visual Analytics""" fdout = 'C:/Users/arsha_000/OneDrive/MSc Data Science Work/Introduction to Data Science/Coursework 2/' d8.to_excel(fdout + 'f3_final_merged.xlsx')
plt.plot(np.arange(params['n_estimators']) + 1, clf.train_score_, 'b-', label='Training Set Deviance') plt.plot(np.arange(params['n_estimators']) + 1, test_score, 'r-',
random_line_split
lib.rs
#![deny( missing_docs, unused_import_braces, unused_qualifications, intra_doc_link_resolution_failure, clippy::all )] //! A Hedwig library for Rust. Hedwig is a message bus that works with arbitrary pubsub services //! such as AWS SNS/SQS or Google Cloud Pubsub. Messages are validated using a JSON schema. The //! publisher and consumer are de-coupled and fan-out is supported out of the box. //! //! # Example: publish a new message //! //! ```no_run //! use hedwig::{Hedwig, MajorVersion, MinorVersion, Version, Message, publishers::MockPublisher}; //! # use std::path::Path; //! # use serde::Serialize; //! # use strum_macros::IntoStaticStr; //! //! fn main() -> Result<(), Box<dyn std::error::Error>> { //! let schema = r#" //! { //! "$id": "https://hedwig.standard.ai/schema", //! "$schema": "https://json-schema.org/draft-04/schema#", //! "description": "Example Schema", //! "schemas": { //! "user-created": { //! "1.*": { //! "description": "A new user was created", //! "type": "object", //! "x-versions": [ //! "1.0" //! ], //! "required": [ //! "user_id" //! ], //! "properties": { //! "user_id": { //! "$ref": "https://hedwig.standard.ai/schema#/definitions/UserId/1.0" //! } //! } //! } //! } //! }, //! "definitions": { //! "UserId": { //! "1.0": { //! "type": "string" //! } //! } //! } //! }"#; //! //! # #[derive(Clone, Copy, IntoStaticStr, Hash, PartialEq, Eq)] //! # enum MessageType { //! # #[strum(serialize = "user.created")] //! # UserCreated, //! # } //! # //! # #[derive(Serialize)] //! # struct UserCreatedData { //! # user_id: String, //! # } //! # //! fn router(t: MessageType, v: MajorVersion) -> Option<&'static str> { //! match (t, v) { //! (MessageType::UserCreated, MajorVersion(1)) => Some("dev-user-created-v1"), //! _ => None, //! } //! } //! //! // create a publisher instance //! let publisher = MockPublisher::default(); //! let hedwig = Hedwig::new( //! schema, //! "myapp", //! publisher, //! router, //! )?; //! //! async { //! let published_ids = hedwig.publish(Message::new( //! MessageType::UserCreated, //! Version(MajorVersion(1), MinorVersion(0)), //! UserCreatedData { user_id: "U_123".into() } //! )).await; //! }; //! //! # Ok(()) //! # } //! ``` #![deny(missing_docs, unused_import_braces, unused_qualifications)] #![warn(trivial_casts, trivial_numeric_casts, unsafe_code, unstable_features)] use std::{ collections::HashMap, fmt, future::Future, mem, time::{SystemTime, UNIX_EPOCH}, }; use futures::stream::StreamExt; use uuid::Uuid; use valico::json_schema::{SchemaError, Scope, ValidationState}; #[cfg(feature = "google")] mod google_publisher; mod mock_publisher; mod null_publisher; /// Implementations of the Publisher trait pub mod publishers { #[cfg(feature = "google")] pub use super::google_publisher::GooglePubSubPublisher; pub use super::mock_publisher::MockPublisher; pub use super::null_publisher::NullPublisher; } const FORMAT_VERSION_V1: Version = Version(MajorVersion(1), MinorVersion(0)); /// All errors that may be returned when instantiating a new Hedwig instance. #[derive(Debug, thiserror::Error)] #[non_exhaustive] pub enum Error { /// Unable to deserialize schema #[error("Unable to deserialize schema")] SchemaDeserialize(#[source] serde_json::Error), /// Schema failed to compile #[error("Schema failed to compile")] SchemaCompile(#[from] SchemaError), /// Unable to serialize message #[error("Unable to serialize message")] MessageSerialize(#[source] serde_json::Error), /// Message is not routable #[error("Message {0} is not routable")] MessageRoute(Uuid), /// Could not parse a schema URL #[error("Could not parse `{1}` as a schema URL")] SchemaUrlParse(#[source] url::ParseError, String), /// Could not resolve the schema URL #[error("Could not resolve `{0}` to a schema")] SchemaUrlResolve(url::Url), /// Could not validate message data #[error("Message data does not validate per the schema: {0}")] DataValidation(String), /// Publisher failed to publish a message #[error("Publisher failed to publish a message batch")] Publisher(#[source] Box<dyn std::error::Error + Send + Sync>), /// Publisher failed to publish multiple batches of messages #[error("Publisher failed to publish multiple batches (total of {} errors)", _1.len() + 1)] PublisherMultiple( #[source] Box<dyn std::error::Error + Send + Sync>, Vec<Box<dyn std::error::Error + Send + Sync>>, ), } type AnyError = Box<dyn std::error::Error + Send + Sync>; /// The special result type for [`Publisher::publish`](trait.Publisher.html) #[derive(Debug)] pub enum PublisherResult<Id> { /// Publisher succeeded. /// /// Contains a vector of published message IDs. Success(Vec<Id>), /// Publisher failed to publish any of the messages. OneError(AnyError, Vec<ValidatedMessage>), /// Publisher failed to publish some of the messages. /// /// The error type has a per-message granularity. PerMessage(Vec<Result<Id, (AnyError, ValidatedMessage)>>), } /// Interface for message publishers pub trait Publisher { /// The list of identifiers for successfully published messages type MessageId: 'static; /// The future that the `publish` method returns type PublishFuture: Future<Output = PublisherResult<Self::MessageId>> + Send; /// Publish a batch of messages /// /// # Return value /// /// Shall return [`PublisherResult::Success`](PublisherResult::Success) only if all of the /// messages are successfully published. Otherwise `PublisherResult::OneError` or /// `PublisherResult::PerMessage` shall be returned to indicate an error. fn publish(&self, topic: &'static str, messages: Vec<ValidatedMessage>) -> Self::PublishFuture; } /// Type alias for custom headers associated with a message type Headers = HashMap<String, String>; struct Validator { scope: Scope, schema_id: url::Url, } impl Validator { fn new(schema: &str) -> Result<Validator, Error> { let master_schema: serde_json::Value = serde_json::from_str(schema).map_err(Error::SchemaDeserialize)?; let mut scope = Scope::new(); let schema_id = scope.compile(master_schema, false)?; Ok(Validator { scope, schema_id }) } fn validate<D, T>( &self, message: &Message<D, T>, schema: &str, ) -> Result<ValidationState, Error> where D: serde::Serialize, { // convert user.created/1.0 -> user.created/1.* let msg_schema_ptr = schema.trim_end_matches(char::is_numeric).to_owned() + "*"; let msg_schema_url = url::Url::parse(&msg_schema_ptr) .map_err(|e| Error::SchemaUrlParse(e, msg_schema_ptr))?; let msg_schema = self .scope .resolve(&msg_schema_url) .ok_or_else(|| Error::SchemaUrlResolve(msg_schema_url))?; let msg_data = serde_json::to_value(&message.data).map_err(Error::MessageSerialize)?; let validation_state = msg_schema.validate(&msg_data); if !validation_state.is_strictly_valid() { return Err(Error::DataValidation(format!("{:?}", validation_state))); } Ok(validation_state) } } /// Major part component in semver #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize)] pub struct MajorVersion(pub u8); impl fmt::Display for MajorVersion { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.0) } } /// Minor part component in semver #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize)] pub struct MinorVersion(pub u8); impl fmt::Display for MinorVersion { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.0) } } /// A semver version without patch part #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct Version(pub MajorVersion, pub MinorVersion); impl serde::Serialize for Version { fn serialize<S>( &self, serializer: S, ) -> Result<<S as serde::Serializer>::Ok, <S as serde::Serializer>::Error> where S: serde::Serializer, { serializer.serialize_str(format!("{}.{}", self.0, self.1).as_ref()) } } /// Mapping of message types to Hedwig topics /// /// # Examples /// ``` /// # use serde::Serialize; /// # use strum_macros::IntoStaticStr; /// use hedwig::{MajorVersion, MessageRouter}; /// /// # #[derive(Clone, Copy, IntoStaticStr, Hash, PartialEq, Eq)] /// # enum MessageType { /// # #[strum(serialize = "user.created")] /// # UserCreated, /// # } /// # /// let r: MessageRouter<MessageType> = |t, v| match (t, v) { /// (MessageType::UserCreated, MajorVersion(1)) => Some("user-created-v1"), /// _ => None, /// }; /// ``` pub type MessageRouter<T> = fn(T, MajorVersion) -> Option<&'static str>; /// The core type in this library #[allow(missing_debug_implementations)] pub struct Hedwig<T, P> { validator: Validator, publisher_name: String, message_router: MessageRouter<T>, publisher: P, } impl<T, P> Hedwig<T, P> where P: Publisher, { /// Creates a new Hedwig instance /// /// # Arguments /// /// * `schema`: The JSON schema content. It's up to the caller to read the schema; /// * `publisher_name`: Name of the publisher service which will be included in the message /// metadata; /// * `publisher`: An implementation of Publisher; pub fn new( schema: &str, publisher_name: &str, publisher: P, message_router: MessageRouter<T>, ) -> Result<Hedwig<T, P>, Error> { Ok(Hedwig { validator: Validator::new(schema)?, publisher_name: String::from(publisher_name), message_router, publisher, }) } /// Create a batch of messages to publish /// /// This allows to transparently retry failed messages and send them in batches larger than /// one, leading to potential throughput gains. pub fn build_batch(&self) -> PublishBatch<T, P> { PublishBatch { hedwig: self, messages: Vec::new(), } } /// Publish a single message /// /// Note, that unlike the batch builder, this does not allow recovering failed-to-publish /// messages. pub async fn publish<D>(&self, msg: Message<D, T>) -> Result<P::MessageId, Error> where D: serde::Serialize, T: Copy + Into<&'static str>, { let mut builder = self.build_batch(); builder.message(msg)?; builder.publish_one().await } } /// A builder for publishing in batches /// /// Among other things this structure also enables transparent retrying of failed-to-publish /// messages. #[allow(missing_debug_implementations)] pub struct PublishBatch<'hedwig, T, P> { hedwig: &'hedwig Hedwig<T, P>, messages: Vec<(&'static str, ValidatedMessage)>, } impl<'hedwig, T, P> PublishBatch<'hedwig, T, P> { /// Add a message to be published in a batch pub fn message<D>(&mut self, msg: Message<D, T>) -> Result<&mut Self, Error> where D: serde::Serialize, T: Copy + Into<&'static str>, { let data_type = msg.data_type; let schema_version = msg.data_schema_version; let data_type_str = msg.data_type.into(); let schema_url = format!( "{}#/schemas/{}/{}.{}", self.hedwig.validator.schema_id, data_type_str, schema_version.0, schema_version.1, ); self.hedwig.validator.validate(&msg, &schema_url)?; let converted = msg .into_schema( self.hedwig.publisher_name.clone(), schema_url, FORMAT_VERSION_V1, ) .map_err(Error::MessageSerialize)?; let route = (self.hedwig.message_router)(data_type, converted.format_version.0) .ok_or_else(|| Error::MessageRoute(converted.id))?; self.messages.push((route, converted)); Ok(self) } /// Publish all the messages /// /// Does not consume the builder. Will return `Ok` only if and when all of the messages from /// the builder have been published successfully. In case of failure, unpublished messages will /// remain enqueued in this builder for a subsequent publish call. pub async fn publish(&mut self) -> Result<Vec<P::MessageId>, Error> where P: Publisher, { let mut message_ids = Vec::with_capacity(self.messages.len()); // Sort the messages by the topic and group them into batches self.messages.sort_by_key(|&(k, _)| k); let mut current_topic = ""; let mut current_batch = Vec::new(); let mut futures_unordered = futures::stream::FuturesUnordered::new(); let publisher = &self.hedwig.publisher; let make_job = |topic: &'static str, batch: Vec<ValidatedMessage>| async move { (topic, publisher.publish(topic, batch).await) }; for (topic, message) in mem::replace(&mut self.messages, Vec::new()) { if current_topic != topic && !current_batch.is_empty() { let batch = mem::replace(&mut current_batch, Vec::new()); futures_unordered.push(make_job(current_topic, batch)); } current_topic = topic; current_batch.push(message) } if !current_batch.is_empty() { futures_unordered.push(make_job(current_topic, current_batch)); } let mut errors = Vec::new(); // Extract the results from all the futures while let (Some(result), stream) = futures_unordered.into_future().await { match result { (_, PublisherResult::Success(ids)) => message_ids.extend(ids), (topic, PublisherResult::OneError(err, failed_msgs)) => { self.messages .extend(failed_msgs.into_iter().map(|m| (topic, m))); errors.push(err); } (topic, PublisherResult::PerMessage(vec)) => { for message in vec { match message { Ok(id) => message_ids.push(id), Err((err, failed_msg)) => { self.messages.push((topic, failed_msg)); errors.push(err); } } } } } futures_unordered = stream; } if let Some(first_error) = errors.pop() { Err(if errors.is_empty() { Error::Publisher(first_error) } else { Error::PublisherMultiple(first_error, errors) }) } else { Ok(message_ids) } } /// Publishes just one message /// /// Panics if the builder contains anything but 1 message. async fn publish_one(mut self) -> Result<P::MessageId, Error> where P: Publisher, { let (topic, message) = if let Some(v) = self.messages.pop() { assert!( self.messages.is_empty(), "messages buffer must contain exactly 1 entry!" ); v } else { panic!("messages buffer must contain exactly 1 entry!") }; match self.hedwig.publisher.publish(topic, vec![message]).await { PublisherResult::Success(mut ids) if ids.len() == 1 => Ok(ids.pop().unwrap()), PublisherResult::OneError(err, _) => Err(Error::Publisher(err)), PublisherResult::PerMessage(mut results) if results.len() == 1 => { results.pop().unwrap().map_err(|(e, _)| Error::Publisher(e)) } _ => { panic!("Publisher should have returned 1 result only!"); } } } } /// A message builder #[derive(Clone, Debug, PartialEq)] pub struct Message<D, T> { /// Message identifier id: Option<Uuid>, /// Creation timestamp timestamp: std::time::Duration, /// Message headers headers: Option<Headers>, /// Message data data: D, /// Message type data_type: T, data_schema_version: Version, } impl<D, T> Message<D, T> { /// Construct a new message pub fn new(data_type: T, data_schema_version: Version, data: D) -> Self { Message { id: None, timestamp: SystemTime::now() .duration_since(UNIX_EPOCH) .expect("time is before the unix epoch"), headers: None, data, data_type, data_schema_version, } } /// Overwrite the header map associated with the message /// /// This may be used to track the `request_id`, for example. pub fn headers(mut self, headers: Headers) -> Self { self.headers = Some(headers); self } /// Add a custom header to the message /// /// This may be used to track the `request_id`, for example. pub fn header<H, V>(mut self, header: H, value: V) -> Self where H: Into<String>, V: Into<String>, { if let Some(ref mut hdrs) = self.headers { hdrs.insert(header.into(), value.into()); } else { let mut map = HashMap::new(); map.insert(header.into(), value.into()); self.headers = Some(map); } self } /// Add custom id to the message /// /// If not called, a random UUID is generated for this message. pub fn id(mut self, id: Uuid) -> Self { self.id = Some(id); self } fn into_schema( self, publisher_name: String, schema: String, format_version: Version, ) -> Result<ValidatedMessage, serde_json::Error> where D: serde::Serialize,
} /// Additional metadata associated with a message #[derive(Clone, Debug, PartialEq, serde::Serialize)] struct Metadata { /// The timestamp when message was created in the publishing service timestamp: u128, /// Name of the publishing service publisher: String, /// Custom headers /// /// This may be used to track request_id, for example. headers: Headers, } /// A validated message /// /// This data type is the schema or the json messages being sent over the wire. #[derive(Debug, serde::Serialize)] pub struct ValidatedMessage { /// Unique message identifier id: Uuid, /// The metadata associated with the message metadata: Metadata, /// URI of the schema validating this message /// /// E.g. `https://hedwig.domain.xyz/schemas#/schemas/user.created/1.0` schema: String, /// Format of the message schema used format_version: Version, /// The message data data: serde_json::Value, } #[cfg(test)] mod tests { use super::*; use strum_macros::IntoStaticStr; #[derive(Clone, Copy, Debug, IntoStaticStr, Hash, PartialEq, Eq)] enum MessageType { #[strum(serialize = "user.created")] UserCreated, #[strum(serialize = "invalid.schema")] InvalidSchema, #[strum(serialize = "invalid.route")] InvalidRoute, } #[derive(Clone, Debug, serde::Serialize, PartialEq)] struct UserCreatedData { user_id: String, } const VERSION_1_0: Version = Version(MajorVersion(1), MinorVersion(0)); const SCHEMA: &str = r#" { "$id": "https://hedwig.standard.ai/schema", "$schema": "https://json-schema.org/draft-04/schema#", "description": "Example Schema", "schemas": { "user.created": { "1.*": { "description": "A new user was created", "type": "object", "x-versions": [ "1.0" ], "required": [ "user_id" ], "properties": { "user_id": { "$ref": "https://hedwig.standard.ai/schema#/definitions/UserId/1.0" } } } }, "invalid.route": { "1.*": {} } }, "definitions": { "UserId": { "1.0": { "type": "string" } } } }"#; fn router(t: MessageType, v: MajorVersion) -> Option<&'static str> { match (t, v) { (MessageType::UserCreated, MajorVersion(1)) => Some("dev-user-created-v1"), (MessageType::InvalidSchema, MajorVersion(1)) => Some("invalid-schema"), _ => None, } } fn mock_hedwig() -> Hedwig<MessageType, publishers::MockPublisher> { Hedwig::new( SCHEMA, "myapp", publishers::MockPublisher::default(), router, ) .unwrap() } #[test] fn message_constructor() { let data = UserCreatedData { user_id: "U_123".into(), }; let message = Message::new(MessageType::UserCreated, VERSION_1_0, data.clone()); assert_eq!(None, message.headers); assert_eq!(data, message.data); assert_eq!(MessageType::UserCreated, message.data_type); assert_eq!(VERSION_1_0, message.data_schema_version); } #[test] fn message_set_headers() { let request_id = Uuid::new_v4().to_string(); let message = Message::new( MessageType::UserCreated, VERSION_1_0, UserCreatedData { user_id: "U_123".into(), }, ) .header("request_id", request_id.clone()); assert_eq!( request_id, message .headers .unwrap() .get(&"request_id".to_owned()) .unwrap() .as_str() ); } #[test] fn message_with_id() { let id = uuid::Uuid::new_v4(); let message = Message::new( MessageType::UserCreated, VERSION_1_0, UserCreatedData { user_id: "U_123".into(), }, ) .id(id); assert_eq!(id, message.id.unwrap()); } #[tokio::test] async fn publish() { let hedwig = mock_hedwig(); let mut custom_headers = Headers::new(); let request_id = Uuid::new_v4().to_string(); let msg_id = Uuid::new_v4(); let message = Message::new( MessageType::UserCreated, VERSION_1_0, UserCreatedData { user_id: "U_123".into(), }, ) .header("request_id", request_id.clone()) .id(msg_id); custom_headers.insert("request_id".to_owned(), request_id); let mut builder = hedwig.build_batch(); builder.message(message.clone()).unwrap(); builder.publish().await.unwrap(); hedwig .publisher .assert_message_published("dev-user-created-v1", msg_id); } #[tokio::test] async fn publish_empty() { let hedwig = mock_hedwig(); let mut builder = hedwig.build_batch(); builder.publish().await.unwrap(); } #[test] fn validator_deserialization_error() { let r = Validator::new("bad json"); assert!(matches!(r.err(), Some(Error::SchemaDeserialize(_)))); } #[test] fn validator_schema_compile_error() { const BAD_SCHEMA: &str = r#" { "$schema": "https://json-schema.org/draft-04/schema#", "definitions": { "UserId": { "1.0": { "type": "bad value" } } } }"#; let r = Validator::new(BAD_SCHEMA); assert!(matches!(r.err(), Some(Error::SchemaCompile(_)))); } #[test] fn message_serialization_error() { let hedwig = mock_hedwig(); #[derive(serde::Serialize)] struct BadUserCreatedData { user_ids: HashMap<Vec<i32>, String>, }; let mut user_ids = HashMap::new(); user_ids.insert(vec![32, 64], "U_123".to_owned()); let data = BadUserCreatedData { user_ids }; let m = Message::new(MessageType::UserCreated, VERSION_1_0, data); let mut builder = hedwig.build_batch(); assert!(matches!(builder.message(m).err(), Some(Error::MessageSerialize(_)))); } #[test] fn message_router_error() { let hedwig = mock_hedwig(); let m = Message::new(MessageType::InvalidRoute, VERSION_1_0, ()); let mut builder = hedwig.build_batch(); assert!(matches!(builder.message(m).err(), Some(Error::MessageRoute(_)))); } #[test] fn message_invalid_schema_error() { let hedwig = mock_hedwig(); let m = Message::new(MessageType::InvalidSchema, VERSION_1_0, ()); let mut builder = hedwig.build_batch(); assert!(matches!(builder.message(m).err(), Some(Error::SchemaUrlResolve(_)))); } #[test] fn message_data_validation_eror() { let hedwig = mock_hedwig(); #[derive(serde::Serialize)] struct BadUserCreatedData { user_ids: Vec<i32>, }; let data = BadUserCreatedData { user_ids: vec![1] }; let m = Message::new(MessageType::UserCreated, VERSION_1_0, data); let mut builder = hedwig.build_batch(); assert!(matches!(builder.message(m).err(), Some(Error::DataValidation(_)))); } #[test] fn errors_send_sync() { fn assert_error<T: std::error::Error + Send + Sync + 'static>() {} assert_error::<Error>(); assert_error::<Error>(); } }
{ Ok(ValidatedMessage { id: self.id.unwrap_or_else(Uuid::new_v4), metadata: Metadata { timestamp: self.timestamp.as_millis(), publisher: publisher_name, headers: self.headers.unwrap_or_else(HashMap::new), }, schema, format_version, data: serde_json::to_value(self.data)?, }) }
identifier_body
lib.rs
#![deny( missing_docs, unused_import_braces, unused_qualifications, intra_doc_link_resolution_failure, clippy::all )] //! A Hedwig library for Rust. Hedwig is a message bus that works with arbitrary pubsub services //! such as AWS SNS/SQS or Google Cloud Pubsub. Messages are validated using a JSON schema. The //! publisher and consumer are de-coupled and fan-out is supported out of the box. //! //! # Example: publish a new message //! //! ```no_run //! use hedwig::{Hedwig, MajorVersion, MinorVersion, Version, Message, publishers::MockPublisher}; //! # use std::path::Path; //! # use serde::Serialize; //! # use strum_macros::IntoStaticStr; //! //! fn main() -> Result<(), Box<dyn std::error::Error>> { //! let schema = r#" //! { //! "$id": "https://hedwig.standard.ai/schema", //! "$schema": "https://json-schema.org/draft-04/schema#", //! "description": "Example Schema", //! "schemas": { //! "user-created": { //! "1.*": { //! "description": "A new user was created", //! "type": "object", //! "x-versions": [ //! "1.0" //! ], //! "required": [ //! "user_id" //! ], //! "properties": { //! "user_id": { //! "$ref": "https://hedwig.standard.ai/schema#/definitions/UserId/1.0" //! } //! } //! } //! } //! }, //! "definitions": { //! "UserId": { //! "1.0": { //! "type": "string" //! } //! } //! } //! }"#; //! //! # #[derive(Clone, Copy, IntoStaticStr, Hash, PartialEq, Eq)] //! # enum MessageType { //! # #[strum(serialize = "user.created")] //! # UserCreated, //! # } //! # //! # #[derive(Serialize)] //! # struct UserCreatedData { //! # user_id: String, //! # } //! # //! fn router(t: MessageType, v: MajorVersion) -> Option<&'static str> { //! match (t, v) { //! (MessageType::UserCreated, MajorVersion(1)) => Some("dev-user-created-v1"), //! _ => None, //! } //! } //! //! // create a publisher instance //! let publisher = MockPublisher::default(); //! let hedwig = Hedwig::new( //! schema, //! "myapp", //! publisher, //! router, //! )?; //! //! async { //! let published_ids = hedwig.publish(Message::new( //! MessageType::UserCreated, //! Version(MajorVersion(1), MinorVersion(0)), //! UserCreatedData { user_id: "U_123".into() } //! )).await; //! }; //! //! # Ok(()) //! # } //! ``` #![deny(missing_docs, unused_import_braces, unused_qualifications)] #![warn(trivial_casts, trivial_numeric_casts, unsafe_code, unstable_features)] use std::{ collections::HashMap, fmt, future::Future, mem, time::{SystemTime, UNIX_EPOCH}, }; use futures::stream::StreamExt; use uuid::Uuid; use valico::json_schema::{SchemaError, Scope, ValidationState}; #[cfg(feature = "google")] mod google_publisher; mod mock_publisher; mod null_publisher; /// Implementations of the Publisher trait pub mod publishers { #[cfg(feature = "google")] pub use super::google_publisher::GooglePubSubPublisher; pub use super::mock_publisher::MockPublisher; pub use super::null_publisher::NullPublisher; } const FORMAT_VERSION_V1: Version = Version(MajorVersion(1), MinorVersion(0)); /// All errors that may be returned when instantiating a new Hedwig instance. #[derive(Debug, thiserror::Error)] #[non_exhaustive] pub enum Error { /// Unable to deserialize schema #[error("Unable to deserialize schema")] SchemaDeserialize(#[source] serde_json::Error), /// Schema failed to compile #[error("Schema failed to compile")] SchemaCompile(#[from] SchemaError), /// Unable to serialize message #[error("Unable to serialize message")] MessageSerialize(#[source] serde_json::Error), /// Message is not routable #[error("Message {0} is not routable")] MessageRoute(Uuid), /// Could not parse a schema URL #[error("Could not parse `{1}` as a schema URL")] SchemaUrlParse(#[source] url::ParseError, String), /// Could not resolve the schema URL #[error("Could not resolve `{0}` to a schema")] SchemaUrlResolve(url::Url), /// Could not validate message data #[error("Message data does not validate per the schema: {0}")] DataValidation(String), /// Publisher failed to publish a message #[error("Publisher failed to publish a message batch")] Publisher(#[source] Box<dyn std::error::Error + Send + Sync>), /// Publisher failed to publish multiple batches of messages #[error("Publisher failed to publish multiple batches (total of {} errors)", _1.len() + 1)] PublisherMultiple( #[source] Box<dyn std::error::Error + Send + Sync>, Vec<Box<dyn std::error::Error + Send + Sync>>, ), } type AnyError = Box<dyn std::error::Error + Send + Sync>; /// The special result type for [`Publisher::publish`](trait.Publisher.html) #[derive(Debug)] pub enum PublisherResult<Id> { /// Publisher succeeded. /// /// Contains a vector of published message IDs. Success(Vec<Id>), /// Publisher failed to publish any of the messages. OneError(AnyError, Vec<ValidatedMessage>), /// Publisher failed to publish some of the messages. /// /// The error type has a per-message granularity. PerMessage(Vec<Result<Id, (AnyError, ValidatedMessage)>>), } /// Interface for message publishers pub trait Publisher { /// The list of identifiers for successfully published messages type MessageId: 'static; /// The future that the `publish` method returns type PublishFuture: Future<Output = PublisherResult<Self::MessageId>> + Send; /// Publish a batch of messages /// /// # Return value /// /// Shall return [`PublisherResult::Success`](PublisherResult::Success) only if all of the /// messages are successfully published. Otherwise `PublisherResult::OneError` or /// `PublisherResult::PerMessage` shall be returned to indicate an error. fn publish(&self, topic: &'static str, messages: Vec<ValidatedMessage>) -> Self::PublishFuture; } /// Type alias for custom headers associated with a message type Headers = HashMap<String, String>; struct Validator { scope: Scope, schema_id: url::Url, } impl Validator { fn new(schema: &str) -> Result<Validator, Error> { let master_schema: serde_json::Value = serde_json::from_str(schema).map_err(Error::SchemaDeserialize)?; let mut scope = Scope::new(); let schema_id = scope.compile(master_schema, false)?; Ok(Validator { scope, schema_id }) } fn validate<D, T>( &self, message: &Message<D, T>, schema: &str, ) -> Result<ValidationState, Error> where D: serde::Serialize, { // convert user.created/1.0 -> user.created/1.* let msg_schema_ptr = schema.trim_end_matches(char::is_numeric).to_owned() + "*"; let msg_schema_url = url::Url::parse(&msg_schema_ptr) .map_err(|e| Error::SchemaUrlParse(e, msg_schema_ptr))?; let msg_schema = self .scope .resolve(&msg_schema_url) .ok_or_else(|| Error::SchemaUrlResolve(msg_schema_url))?; let msg_data = serde_json::to_value(&message.data).map_err(Error::MessageSerialize)?; let validation_state = msg_schema.validate(&msg_data); if !validation_state.is_strictly_valid() { return Err(Error::DataValidation(format!("{:?}", validation_state))); } Ok(validation_state) } } /// Major part component in semver #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize)] pub struct MajorVersion(pub u8); impl fmt::Display for MajorVersion { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.0) } } /// Minor part component in semver #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize)] pub struct MinorVersion(pub u8); impl fmt::Display for MinorVersion { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.0) } } /// A semver version without patch part #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct Version(pub MajorVersion, pub MinorVersion); impl serde::Serialize for Version { fn serialize<S>( &self, serializer: S, ) -> Result<<S as serde::Serializer>::Ok, <S as serde::Serializer>::Error> where S: serde::Serializer, { serializer.serialize_str(format!("{}.{}", self.0, self.1).as_ref()) } } /// Mapping of message types to Hedwig topics /// /// # Examples /// ``` /// # use serde::Serialize; /// # use strum_macros::IntoStaticStr; /// use hedwig::{MajorVersion, MessageRouter}; /// /// # #[derive(Clone, Copy, IntoStaticStr, Hash, PartialEq, Eq)] /// # enum MessageType { /// # #[strum(serialize = "user.created")] /// # UserCreated, /// # } /// # /// let r: MessageRouter<MessageType> = |t, v| match (t, v) { /// (MessageType::UserCreated, MajorVersion(1)) => Some("user-created-v1"), /// _ => None, /// }; /// ``` pub type MessageRouter<T> = fn(T, MajorVersion) -> Option<&'static str>; /// The core type in this library #[allow(missing_debug_implementations)] pub struct Hedwig<T, P> { validator: Validator, publisher_name: String, message_router: MessageRouter<T>, publisher: P, } impl<T, P> Hedwig<T, P> where P: Publisher, { /// Creates a new Hedwig instance /// /// # Arguments /// /// * `schema`: The JSON schema content. It's up to the caller to read the schema; /// * `publisher_name`: Name of the publisher service which will be included in the message /// metadata; /// * `publisher`: An implementation of Publisher; pub fn new( schema: &str, publisher_name: &str, publisher: P, message_router: MessageRouter<T>, ) -> Result<Hedwig<T, P>, Error> { Ok(Hedwig { validator: Validator::new(schema)?, publisher_name: String::from(publisher_name), message_router, publisher, }) } /// Create a batch of messages to publish /// /// This allows to transparently retry failed messages and send them in batches larger than /// one, leading to potential throughput gains. pub fn build_batch(&self) -> PublishBatch<T, P> { PublishBatch { hedwig: self, messages: Vec::new(), } } /// Publish a single message /// /// Note, that unlike the batch builder, this does not allow recovering failed-to-publish /// messages. pub async fn publish<D>(&self, msg: Message<D, T>) -> Result<P::MessageId, Error> where D: serde::Serialize, T: Copy + Into<&'static str>, { let mut builder = self.build_batch(); builder.message(msg)?; builder.publish_one().await } } /// A builder for publishing in batches /// /// Among other things this structure also enables transparent retrying of failed-to-publish /// messages. #[allow(missing_debug_implementations)] pub struct PublishBatch<'hedwig, T, P> { hedwig: &'hedwig Hedwig<T, P>, messages: Vec<(&'static str, ValidatedMessage)>, } impl<'hedwig, T, P> PublishBatch<'hedwig, T, P> { /// Add a message to be published in a batch pub fn message<D>(&mut self, msg: Message<D, T>) -> Result<&mut Self, Error> where D: serde::Serialize, T: Copy + Into<&'static str>, { let data_type = msg.data_type; let schema_version = msg.data_schema_version; let data_type_str = msg.data_type.into(); let schema_url = format!( "{}#/schemas/{}/{}.{}", self.hedwig.validator.schema_id, data_type_str, schema_version.0, schema_version.1, ); self.hedwig.validator.validate(&msg, &schema_url)?; let converted = msg .into_schema( self.hedwig.publisher_name.clone(), schema_url, FORMAT_VERSION_V1, ) .map_err(Error::MessageSerialize)?; let route = (self.hedwig.message_router)(data_type, converted.format_version.0) .ok_or_else(|| Error::MessageRoute(converted.id))?; self.messages.push((route, converted)); Ok(self) } /// Publish all the messages /// /// Does not consume the builder. Will return `Ok` only if and when all of the messages from /// the builder have been published successfully. In case of failure, unpublished messages will /// remain enqueued in this builder for a subsequent publish call. pub async fn publish(&mut self) -> Result<Vec<P::MessageId>, Error> where P: Publisher, { let mut message_ids = Vec::with_capacity(self.messages.len()); // Sort the messages by the topic and group them into batches self.messages.sort_by_key(|&(k, _)| k); let mut current_topic = ""; let mut current_batch = Vec::new(); let mut futures_unordered = futures::stream::FuturesUnordered::new(); let publisher = &self.hedwig.publisher; let make_job = |topic: &'static str, batch: Vec<ValidatedMessage>| async move { (topic, publisher.publish(topic, batch).await) }; for (topic, message) in mem::replace(&mut self.messages, Vec::new()) { if current_topic != topic && !current_batch.is_empty() { let batch = mem::replace(&mut current_batch, Vec::new()); futures_unordered.push(make_job(current_topic, batch)); } current_topic = topic; current_batch.push(message) } if !current_batch.is_empty() { futures_unordered.push(make_job(current_topic, current_batch)); } let mut errors = Vec::new(); // Extract the results from all the futures while let (Some(result), stream) = futures_unordered.into_future().await { match result { (_, PublisherResult::Success(ids)) => message_ids.extend(ids), (topic, PublisherResult::OneError(err, failed_msgs)) => { self.messages .extend(failed_msgs.into_iter().map(|m| (topic, m))); errors.push(err); } (topic, PublisherResult::PerMessage(vec)) => { for message in vec { match message { Ok(id) => message_ids.push(id), Err((err, failed_msg)) => { self.messages.push((topic, failed_msg)); errors.push(err); } } } } } futures_unordered = stream; } if let Some(first_error) = errors.pop() { Err(if errors.is_empty() { Error::Publisher(first_error) } else { Error::PublisherMultiple(first_error, errors) }) } else { Ok(message_ids) } } /// Publishes just one message /// /// Panics if the builder contains anything but 1 message. async fn publish_one(mut self) -> Result<P::MessageId, Error> where P: Publisher, { let (topic, message) = if let Some(v) = self.messages.pop() { assert!( self.messages.is_empty(), "messages buffer must contain exactly 1 entry!" ); v } else { panic!("messages buffer must contain exactly 1 entry!") }; match self.hedwig.publisher.publish(topic, vec![message]).await { PublisherResult::Success(mut ids) if ids.len() == 1 => Ok(ids.pop().unwrap()), PublisherResult::OneError(err, _) => Err(Error::Publisher(err)), PublisherResult::PerMessage(mut results) if results.len() == 1 => { results.pop().unwrap().map_err(|(e, _)| Error::Publisher(e)) } _ => { panic!("Publisher should have returned 1 result only!"); } } } } /// A message builder #[derive(Clone, Debug, PartialEq)] pub struct Message<D, T> { /// Message identifier id: Option<Uuid>, /// Creation timestamp timestamp: std::time::Duration, /// Message headers headers: Option<Headers>, /// Message data data: D, /// Message type data_type: T, data_schema_version: Version, } impl<D, T> Message<D, T> { /// Construct a new message pub fn new(data_type: T, data_schema_version: Version, data: D) -> Self { Message { id: None, timestamp: SystemTime::now() .duration_since(UNIX_EPOCH) .expect("time is before the unix epoch"), headers: None, data, data_type, data_schema_version, } } /// Overwrite the header map associated with the message /// /// This may be used to track the `request_id`, for example. pub fn headers(mut self, headers: Headers) -> Self { self.headers = Some(headers); self } /// Add a custom header to the message /// /// This may be used to track the `request_id`, for example. pub fn header<H, V>(mut self, header: H, value: V) -> Self where H: Into<String>, V: Into<String>, { if let Some(ref mut hdrs) = self.headers
else { let mut map = HashMap::new(); map.insert(header.into(), value.into()); self.headers = Some(map); } self } /// Add custom id to the message /// /// If not called, a random UUID is generated for this message. pub fn id(mut self, id: Uuid) -> Self { self.id = Some(id); self } fn into_schema( self, publisher_name: String, schema: String, format_version: Version, ) -> Result<ValidatedMessage, serde_json::Error> where D: serde::Serialize, { Ok(ValidatedMessage { id: self.id.unwrap_or_else(Uuid::new_v4), metadata: Metadata { timestamp: self.timestamp.as_millis(), publisher: publisher_name, headers: self.headers.unwrap_or_else(HashMap::new), }, schema, format_version, data: serde_json::to_value(self.data)?, }) } } /// Additional metadata associated with a message #[derive(Clone, Debug, PartialEq, serde::Serialize)] struct Metadata { /// The timestamp when message was created in the publishing service timestamp: u128, /// Name of the publishing service publisher: String, /// Custom headers /// /// This may be used to track request_id, for example. headers: Headers, } /// A validated message /// /// This data type is the schema or the json messages being sent over the wire. #[derive(Debug, serde::Serialize)] pub struct ValidatedMessage { /// Unique message identifier id: Uuid, /// The metadata associated with the message metadata: Metadata, /// URI of the schema validating this message /// /// E.g. `https://hedwig.domain.xyz/schemas#/schemas/user.created/1.0` schema: String, /// Format of the message schema used format_version: Version, /// The message data data: serde_json::Value, } #[cfg(test)] mod tests { use super::*; use strum_macros::IntoStaticStr; #[derive(Clone, Copy, Debug, IntoStaticStr, Hash, PartialEq, Eq)] enum MessageType { #[strum(serialize = "user.created")] UserCreated, #[strum(serialize = "invalid.schema")] InvalidSchema, #[strum(serialize = "invalid.route")] InvalidRoute, } #[derive(Clone, Debug, serde::Serialize, PartialEq)] struct UserCreatedData { user_id: String, } const VERSION_1_0: Version = Version(MajorVersion(1), MinorVersion(0)); const SCHEMA: &str = r#" { "$id": "https://hedwig.standard.ai/schema", "$schema": "https://json-schema.org/draft-04/schema#", "description": "Example Schema", "schemas": { "user.created": { "1.*": { "description": "A new user was created", "type": "object", "x-versions": [ "1.0" ], "required": [ "user_id" ], "properties": { "user_id": { "$ref": "https://hedwig.standard.ai/schema#/definitions/UserId/1.0" } } } }, "invalid.route": { "1.*": {} } }, "definitions": { "UserId": { "1.0": { "type": "string" } } } }"#; fn router(t: MessageType, v: MajorVersion) -> Option<&'static str> { match (t, v) { (MessageType::UserCreated, MajorVersion(1)) => Some("dev-user-created-v1"), (MessageType::InvalidSchema, MajorVersion(1)) => Some("invalid-schema"), _ => None, } } fn mock_hedwig() -> Hedwig<MessageType, publishers::MockPublisher> { Hedwig::new( SCHEMA, "myapp", publishers::MockPublisher::default(), router, ) .unwrap() } #[test] fn message_constructor() { let data = UserCreatedData { user_id: "U_123".into(), }; let message = Message::new(MessageType::UserCreated, VERSION_1_0, data.clone()); assert_eq!(None, message.headers); assert_eq!(data, message.data); assert_eq!(MessageType::UserCreated, message.data_type); assert_eq!(VERSION_1_0, message.data_schema_version); } #[test] fn message_set_headers() { let request_id = Uuid::new_v4().to_string(); let message = Message::new( MessageType::UserCreated, VERSION_1_0, UserCreatedData { user_id: "U_123".into(), }, ) .header("request_id", request_id.clone()); assert_eq!( request_id, message .headers .unwrap() .get(&"request_id".to_owned()) .unwrap() .as_str() ); } #[test] fn message_with_id() { let id = uuid::Uuid::new_v4(); let message = Message::new( MessageType::UserCreated, VERSION_1_0, UserCreatedData { user_id: "U_123".into(), }, ) .id(id); assert_eq!(id, message.id.unwrap()); } #[tokio::test] async fn publish() { let hedwig = mock_hedwig(); let mut custom_headers = Headers::new(); let request_id = Uuid::new_v4().to_string(); let msg_id = Uuid::new_v4(); let message = Message::new( MessageType::UserCreated, VERSION_1_0, UserCreatedData { user_id: "U_123".into(), }, ) .header("request_id", request_id.clone()) .id(msg_id); custom_headers.insert("request_id".to_owned(), request_id); let mut builder = hedwig.build_batch(); builder.message(message.clone()).unwrap(); builder.publish().await.unwrap(); hedwig .publisher .assert_message_published("dev-user-created-v1", msg_id); } #[tokio::test] async fn publish_empty() { let hedwig = mock_hedwig(); let mut builder = hedwig.build_batch(); builder.publish().await.unwrap(); } #[test] fn validator_deserialization_error() { let r = Validator::new("bad json"); assert!(matches!(r.err(), Some(Error::SchemaDeserialize(_)))); } #[test] fn validator_schema_compile_error() { const BAD_SCHEMA: &str = r#" { "$schema": "https://json-schema.org/draft-04/schema#", "definitions": { "UserId": { "1.0": { "type": "bad value" } } } }"#; let r = Validator::new(BAD_SCHEMA); assert!(matches!(r.err(), Some(Error::SchemaCompile(_)))); } #[test] fn message_serialization_error() { let hedwig = mock_hedwig(); #[derive(serde::Serialize)] struct BadUserCreatedData { user_ids: HashMap<Vec<i32>, String>, }; let mut user_ids = HashMap::new(); user_ids.insert(vec![32, 64], "U_123".to_owned()); let data = BadUserCreatedData { user_ids }; let m = Message::new(MessageType::UserCreated, VERSION_1_0, data); let mut builder = hedwig.build_batch(); assert!(matches!(builder.message(m).err(), Some(Error::MessageSerialize(_)))); } #[test] fn message_router_error() { let hedwig = mock_hedwig(); let m = Message::new(MessageType::InvalidRoute, VERSION_1_0, ()); let mut builder = hedwig.build_batch(); assert!(matches!(builder.message(m).err(), Some(Error::MessageRoute(_)))); } #[test] fn message_invalid_schema_error() { let hedwig = mock_hedwig(); let m = Message::new(MessageType::InvalidSchema, VERSION_1_0, ()); let mut builder = hedwig.build_batch(); assert!(matches!(builder.message(m).err(), Some(Error::SchemaUrlResolve(_)))); } #[test] fn message_data_validation_eror() { let hedwig = mock_hedwig(); #[derive(serde::Serialize)] struct BadUserCreatedData { user_ids: Vec<i32>, }; let data = BadUserCreatedData { user_ids: vec![1] }; let m = Message::new(MessageType::UserCreated, VERSION_1_0, data); let mut builder = hedwig.build_batch(); assert!(matches!(builder.message(m).err(), Some(Error::DataValidation(_)))); } #[test] fn errors_send_sync() { fn assert_error<T: std::error::Error + Send + Sync + 'static>() {} assert_error::<Error>(); assert_error::<Error>(); } }
{ hdrs.insert(header.into(), value.into()); }
conditional_block
lib.rs
#![deny( missing_docs, unused_import_braces, unused_qualifications, intra_doc_link_resolution_failure, clippy::all )] //! A Hedwig library for Rust. Hedwig is a message bus that works with arbitrary pubsub services //! such as AWS SNS/SQS or Google Cloud Pubsub. Messages are validated using a JSON schema. The //! publisher and consumer are de-coupled and fan-out is supported out of the box. //! //! # Example: publish a new message //! //! ```no_run //! use hedwig::{Hedwig, MajorVersion, MinorVersion, Version, Message, publishers::MockPublisher}; //! # use std::path::Path; //! # use serde::Serialize; //! # use strum_macros::IntoStaticStr; //! //! fn main() -> Result<(), Box<dyn std::error::Error>> { //! let schema = r#" //! { //! "$id": "https://hedwig.standard.ai/schema", //! "$schema": "https://json-schema.org/draft-04/schema#", //! "description": "Example Schema", //! "schemas": { //! "user-created": { //! "1.*": { //! "description": "A new user was created", //! "type": "object", //! "x-versions": [ //! "1.0" //! ], //! "required": [ //! "user_id" //! ], //! "properties": { //! "user_id": { //! "$ref": "https://hedwig.standard.ai/schema#/definitions/UserId/1.0" //! } //! } //! } //! } //! }, //! "definitions": { //! "UserId": { //! "1.0": { //! "type": "string" //! } //! } //! } //! }"#; //! //! # #[derive(Clone, Copy, IntoStaticStr, Hash, PartialEq, Eq)] //! # enum MessageType { //! # #[strum(serialize = "user.created")] //! # UserCreated, //! # } //! # //! # #[derive(Serialize)] //! # struct UserCreatedData { //! # user_id: String, //! # } //! # //! fn router(t: MessageType, v: MajorVersion) -> Option<&'static str> { //! match (t, v) { //! (MessageType::UserCreated, MajorVersion(1)) => Some("dev-user-created-v1"), //! _ => None, //! } //! } //! //! // create a publisher instance //! let publisher = MockPublisher::default(); //! let hedwig = Hedwig::new( //! schema, //! "myapp", //! publisher, //! router, //! )?; //! //! async { //! let published_ids = hedwig.publish(Message::new( //! MessageType::UserCreated, //! Version(MajorVersion(1), MinorVersion(0)), //! UserCreatedData { user_id: "U_123".into() } //! )).await; //! }; //! //! # Ok(()) //! # } //! ``` #![deny(missing_docs, unused_import_braces, unused_qualifications)] #![warn(trivial_casts, trivial_numeric_casts, unsafe_code, unstable_features)] use std::{ collections::HashMap, fmt, future::Future, mem, time::{SystemTime, UNIX_EPOCH}, }; use futures::stream::StreamExt; use uuid::Uuid; use valico::json_schema::{SchemaError, Scope, ValidationState}; #[cfg(feature = "google")] mod google_publisher; mod mock_publisher; mod null_publisher; /// Implementations of the Publisher trait pub mod publishers { #[cfg(feature = "google")] pub use super::google_publisher::GooglePubSubPublisher; pub use super::mock_publisher::MockPublisher; pub use super::null_publisher::NullPublisher; } const FORMAT_VERSION_V1: Version = Version(MajorVersion(1), MinorVersion(0)); /// All errors that may be returned when instantiating a new Hedwig instance. #[derive(Debug, thiserror::Error)] #[non_exhaustive] pub enum Error { /// Unable to deserialize schema #[error("Unable to deserialize schema")] SchemaDeserialize(#[source] serde_json::Error), /// Schema failed to compile #[error("Schema failed to compile")] SchemaCompile(#[from] SchemaError), /// Unable to serialize message #[error("Unable to serialize message")] MessageSerialize(#[source] serde_json::Error), /// Message is not routable #[error("Message {0} is not routable")] MessageRoute(Uuid), /// Could not parse a schema URL #[error("Could not parse `{1}` as a schema URL")] SchemaUrlParse(#[source] url::ParseError, String), /// Could not resolve the schema URL #[error("Could not resolve `{0}` to a schema")] SchemaUrlResolve(url::Url), /// Could not validate message data #[error("Message data does not validate per the schema: {0}")] DataValidation(String), /// Publisher failed to publish a message #[error("Publisher failed to publish a message batch")] Publisher(#[source] Box<dyn std::error::Error + Send + Sync>), /// Publisher failed to publish multiple batches of messages #[error("Publisher failed to publish multiple batches (total of {} errors)", _1.len() + 1)] PublisherMultiple( #[source] Box<dyn std::error::Error + Send + Sync>, Vec<Box<dyn std::error::Error + Send + Sync>>, ), } type AnyError = Box<dyn std::error::Error + Send + Sync>; /// The special result type for [`Publisher::publish`](trait.Publisher.html) #[derive(Debug)] pub enum PublisherResult<Id> { /// Publisher succeeded. /// /// Contains a vector of published message IDs. Success(Vec<Id>), /// Publisher failed to publish any of the messages. OneError(AnyError, Vec<ValidatedMessage>), /// Publisher failed to publish some of the messages. /// /// The error type has a per-message granularity. PerMessage(Vec<Result<Id, (AnyError, ValidatedMessage)>>), } /// Interface for message publishers pub trait Publisher { /// The list of identifiers for successfully published messages type MessageId: 'static; /// The future that the `publish` method returns type PublishFuture: Future<Output = PublisherResult<Self::MessageId>> + Send; /// Publish a batch of messages /// /// # Return value /// /// Shall return [`PublisherResult::Success`](PublisherResult::Success) only if all of the /// messages are successfully published. Otherwise `PublisherResult::OneError` or /// `PublisherResult::PerMessage` shall be returned to indicate an error. fn publish(&self, topic: &'static str, messages: Vec<ValidatedMessage>) -> Self::PublishFuture; } /// Type alias for custom headers associated with a message type Headers = HashMap<String, String>; struct Validator { scope: Scope, schema_id: url::Url, } impl Validator { fn new(schema: &str) -> Result<Validator, Error> { let master_schema: serde_json::Value = serde_json::from_str(schema).map_err(Error::SchemaDeserialize)?; let mut scope = Scope::new(); let schema_id = scope.compile(master_schema, false)?; Ok(Validator { scope, schema_id }) } fn validate<D, T>( &self, message: &Message<D, T>, schema: &str, ) -> Result<ValidationState, Error> where D: serde::Serialize, { // convert user.created/1.0 -> user.created/1.* let msg_schema_ptr = schema.trim_end_matches(char::is_numeric).to_owned() + "*"; let msg_schema_url = url::Url::parse(&msg_schema_ptr) .map_err(|e| Error::SchemaUrlParse(e, msg_schema_ptr))?; let msg_schema = self .scope .resolve(&msg_schema_url) .ok_or_else(|| Error::SchemaUrlResolve(msg_schema_url))?; let msg_data = serde_json::to_value(&message.data).map_err(Error::MessageSerialize)?; let validation_state = msg_schema.validate(&msg_data); if !validation_state.is_strictly_valid() { return Err(Error::DataValidation(format!("{:?}", validation_state))); } Ok(validation_state) } } /// Major part component in semver #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize)] pub struct MajorVersion(pub u8); impl fmt::Display for MajorVersion { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.0) } } /// Minor part component in semver #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize)] pub struct MinorVersion(pub u8); impl fmt::Display for MinorVersion { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.0) } } /// A semver version without patch part #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct Version(pub MajorVersion, pub MinorVersion); impl serde::Serialize for Version { fn serialize<S>( &self, serializer: S, ) -> Result<<S as serde::Serializer>::Ok, <S as serde::Serializer>::Error> where S: serde::Serializer, { serializer.serialize_str(format!("{}.{}", self.0, self.1).as_ref()) } } /// Mapping of message types to Hedwig topics /// /// # Examples /// ``` /// # use serde::Serialize; /// # use strum_macros::IntoStaticStr; /// use hedwig::{MajorVersion, MessageRouter}; /// /// # #[derive(Clone, Copy, IntoStaticStr, Hash, PartialEq, Eq)] /// # enum MessageType { /// # #[strum(serialize = "user.created")] /// # UserCreated, /// # } /// # /// let r: MessageRouter<MessageType> = |t, v| match (t, v) { /// (MessageType::UserCreated, MajorVersion(1)) => Some("user-created-v1"), /// _ => None, /// }; /// ``` pub type MessageRouter<T> = fn(T, MajorVersion) -> Option<&'static str>; /// The core type in this library #[allow(missing_debug_implementations)] pub struct Hedwig<T, P> { validator: Validator, publisher_name: String, message_router: MessageRouter<T>, publisher: P, } impl<T, P> Hedwig<T, P> where P: Publisher, { /// Creates a new Hedwig instance /// /// # Arguments /// /// * `schema`: The JSON schema content. It's up to the caller to read the schema; /// * `publisher_name`: Name of the publisher service which will be included in the message /// metadata; /// * `publisher`: An implementation of Publisher; pub fn new( schema: &str, publisher_name: &str, publisher: P, message_router: MessageRouter<T>, ) -> Result<Hedwig<T, P>, Error> { Ok(Hedwig { validator: Validator::new(schema)?, publisher_name: String::from(publisher_name), message_router, publisher, }) } /// Create a batch of messages to publish /// /// This allows to transparently retry failed messages and send them in batches larger than /// one, leading to potential throughput gains. pub fn build_batch(&self) -> PublishBatch<T, P> { PublishBatch { hedwig: self, messages: Vec::new(), } } /// Publish a single message /// /// Note, that unlike the batch builder, this does not allow recovering failed-to-publish /// messages. pub async fn publish<D>(&self, msg: Message<D, T>) -> Result<P::MessageId, Error> where D: serde::Serialize, T: Copy + Into<&'static str>, { let mut builder = self.build_batch(); builder.message(msg)?; builder.publish_one().await } } /// A builder for publishing in batches /// /// Among other things this structure also enables transparent retrying of failed-to-publish /// messages. #[allow(missing_debug_implementations)] pub struct PublishBatch<'hedwig, T, P> { hedwig: &'hedwig Hedwig<T, P>, messages: Vec<(&'static str, ValidatedMessage)>, } impl<'hedwig, T, P> PublishBatch<'hedwig, T, P> { /// Add a message to be published in a batch pub fn message<D>(&mut self, msg: Message<D, T>) -> Result<&mut Self, Error> where D: serde::Serialize, T: Copy + Into<&'static str>, { let data_type = msg.data_type; let schema_version = msg.data_schema_version; let data_type_str = msg.data_type.into(); let schema_url = format!( "{}#/schemas/{}/{}.{}", self.hedwig.validator.schema_id, data_type_str, schema_version.0, schema_version.1, ); self.hedwig.validator.validate(&msg, &schema_url)?; let converted = msg .into_schema( self.hedwig.publisher_name.clone(), schema_url, FORMAT_VERSION_V1, ) .map_err(Error::MessageSerialize)?; let route = (self.hedwig.message_router)(data_type, converted.format_version.0) .ok_or_else(|| Error::MessageRoute(converted.id))?; self.messages.push((route, converted)); Ok(self) } /// Publish all the messages /// /// Does not consume the builder. Will return `Ok` only if and when all of the messages from /// the builder have been published successfully. In case of failure, unpublished messages will /// remain enqueued in this builder for a subsequent publish call. pub async fn publish(&mut self) -> Result<Vec<P::MessageId>, Error> where P: Publisher, { let mut message_ids = Vec::with_capacity(self.messages.len()); // Sort the messages by the topic and group them into batches self.messages.sort_by_key(|&(k, _)| k); let mut current_topic = ""; let mut current_batch = Vec::new(); let mut futures_unordered = futures::stream::FuturesUnordered::new(); let publisher = &self.hedwig.publisher; let make_job = |topic: &'static str, batch: Vec<ValidatedMessage>| async move { (topic, publisher.publish(topic, batch).await) }; for (topic, message) in mem::replace(&mut self.messages, Vec::new()) { if current_topic != topic && !current_batch.is_empty() { let batch = mem::replace(&mut current_batch, Vec::new()); futures_unordered.push(make_job(current_topic, batch)); } current_topic = topic; current_batch.push(message) } if !current_batch.is_empty() { futures_unordered.push(make_job(current_topic, current_batch)); } let mut errors = Vec::new(); // Extract the results from all the futures while let (Some(result), stream) = futures_unordered.into_future().await { match result { (_, PublisherResult::Success(ids)) => message_ids.extend(ids), (topic, PublisherResult::OneError(err, failed_msgs)) => { self.messages .extend(failed_msgs.into_iter().map(|m| (topic, m))); errors.push(err); } (topic, PublisherResult::PerMessage(vec)) => { for message in vec { match message { Ok(id) => message_ids.push(id), Err((err, failed_msg)) => { self.messages.push((topic, failed_msg)); errors.push(err); } } } } } futures_unordered = stream; } if let Some(first_error) = errors.pop() { Err(if errors.is_empty() { Error::Publisher(first_error) } else { Error::PublisherMultiple(first_error, errors) }) } else { Ok(message_ids) } } /// Publishes just one message /// /// Panics if the builder contains anything but 1 message. async fn publish_one(mut self) -> Result<P::MessageId, Error> where P: Publisher, { let (topic, message) = if let Some(v) = self.messages.pop() { assert!( self.messages.is_empty(), "messages buffer must contain exactly 1 entry!" ); v } else { panic!("messages buffer must contain exactly 1 entry!") }; match self.hedwig.publisher.publish(topic, vec![message]).await { PublisherResult::Success(mut ids) if ids.len() == 1 => Ok(ids.pop().unwrap()), PublisherResult::OneError(err, _) => Err(Error::Publisher(err)), PublisherResult::PerMessage(mut results) if results.len() == 1 => { results.pop().unwrap().map_err(|(e, _)| Error::Publisher(e)) } _ => { panic!("Publisher should have returned 1 result only!"); }
/// A message builder #[derive(Clone, Debug, PartialEq)] pub struct Message<D, T> { /// Message identifier id: Option<Uuid>, /// Creation timestamp timestamp: std::time::Duration, /// Message headers headers: Option<Headers>, /// Message data data: D, /// Message type data_type: T, data_schema_version: Version, } impl<D, T> Message<D, T> { /// Construct a new message pub fn new(data_type: T, data_schema_version: Version, data: D) -> Self { Message { id: None, timestamp: SystemTime::now() .duration_since(UNIX_EPOCH) .expect("time is before the unix epoch"), headers: None, data, data_type, data_schema_version, } } /// Overwrite the header map associated with the message /// /// This may be used to track the `request_id`, for example. pub fn headers(mut self, headers: Headers) -> Self { self.headers = Some(headers); self } /// Add a custom header to the message /// /// This may be used to track the `request_id`, for example. pub fn header<H, V>(mut self, header: H, value: V) -> Self where H: Into<String>, V: Into<String>, { if let Some(ref mut hdrs) = self.headers { hdrs.insert(header.into(), value.into()); } else { let mut map = HashMap::new(); map.insert(header.into(), value.into()); self.headers = Some(map); } self } /// Add custom id to the message /// /// If not called, a random UUID is generated for this message. pub fn id(mut self, id: Uuid) -> Self { self.id = Some(id); self } fn into_schema( self, publisher_name: String, schema: String, format_version: Version, ) -> Result<ValidatedMessage, serde_json::Error> where D: serde::Serialize, { Ok(ValidatedMessage { id: self.id.unwrap_or_else(Uuid::new_v4), metadata: Metadata { timestamp: self.timestamp.as_millis(), publisher: publisher_name, headers: self.headers.unwrap_or_else(HashMap::new), }, schema, format_version, data: serde_json::to_value(self.data)?, }) } } /// Additional metadata associated with a message #[derive(Clone, Debug, PartialEq, serde::Serialize)] struct Metadata { /// The timestamp when message was created in the publishing service timestamp: u128, /// Name of the publishing service publisher: String, /// Custom headers /// /// This may be used to track request_id, for example. headers: Headers, } /// A validated message /// /// This data type is the schema or the json messages being sent over the wire. #[derive(Debug, serde::Serialize)] pub struct ValidatedMessage { /// Unique message identifier id: Uuid, /// The metadata associated with the message metadata: Metadata, /// URI of the schema validating this message /// /// E.g. `https://hedwig.domain.xyz/schemas#/schemas/user.created/1.0` schema: String, /// Format of the message schema used format_version: Version, /// The message data data: serde_json::Value, } #[cfg(test)] mod tests { use super::*; use strum_macros::IntoStaticStr; #[derive(Clone, Copy, Debug, IntoStaticStr, Hash, PartialEq, Eq)] enum MessageType { #[strum(serialize = "user.created")] UserCreated, #[strum(serialize = "invalid.schema")] InvalidSchema, #[strum(serialize = "invalid.route")] InvalidRoute, } #[derive(Clone, Debug, serde::Serialize, PartialEq)] struct UserCreatedData { user_id: String, } const VERSION_1_0: Version = Version(MajorVersion(1), MinorVersion(0)); const SCHEMA: &str = r#" { "$id": "https://hedwig.standard.ai/schema", "$schema": "https://json-schema.org/draft-04/schema#", "description": "Example Schema", "schemas": { "user.created": { "1.*": { "description": "A new user was created", "type": "object", "x-versions": [ "1.0" ], "required": [ "user_id" ], "properties": { "user_id": { "$ref": "https://hedwig.standard.ai/schema#/definitions/UserId/1.0" } } } }, "invalid.route": { "1.*": {} } }, "definitions": { "UserId": { "1.0": { "type": "string" } } } }"#; fn router(t: MessageType, v: MajorVersion) -> Option<&'static str> { match (t, v) { (MessageType::UserCreated, MajorVersion(1)) => Some("dev-user-created-v1"), (MessageType::InvalidSchema, MajorVersion(1)) => Some("invalid-schema"), _ => None, } } fn mock_hedwig() -> Hedwig<MessageType, publishers::MockPublisher> { Hedwig::new( SCHEMA, "myapp", publishers::MockPublisher::default(), router, ) .unwrap() } #[test] fn message_constructor() { let data = UserCreatedData { user_id: "U_123".into(), }; let message = Message::new(MessageType::UserCreated, VERSION_1_0, data.clone()); assert_eq!(None, message.headers); assert_eq!(data, message.data); assert_eq!(MessageType::UserCreated, message.data_type); assert_eq!(VERSION_1_0, message.data_schema_version); } #[test] fn message_set_headers() { let request_id = Uuid::new_v4().to_string(); let message = Message::new( MessageType::UserCreated, VERSION_1_0, UserCreatedData { user_id: "U_123".into(), }, ) .header("request_id", request_id.clone()); assert_eq!( request_id, message .headers .unwrap() .get(&"request_id".to_owned()) .unwrap() .as_str() ); } #[test] fn message_with_id() { let id = uuid::Uuid::new_v4(); let message = Message::new( MessageType::UserCreated, VERSION_1_0, UserCreatedData { user_id: "U_123".into(), }, ) .id(id); assert_eq!(id, message.id.unwrap()); } #[tokio::test] async fn publish() { let hedwig = mock_hedwig(); let mut custom_headers = Headers::new(); let request_id = Uuid::new_v4().to_string(); let msg_id = Uuid::new_v4(); let message = Message::new( MessageType::UserCreated, VERSION_1_0, UserCreatedData { user_id: "U_123".into(), }, ) .header("request_id", request_id.clone()) .id(msg_id); custom_headers.insert("request_id".to_owned(), request_id); let mut builder = hedwig.build_batch(); builder.message(message.clone()).unwrap(); builder.publish().await.unwrap(); hedwig .publisher .assert_message_published("dev-user-created-v1", msg_id); } #[tokio::test] async fn publish_empty() { let hedwig = mock_hedwig(); let mut builder = hedwig.build_batch(); builder.publish().await.unwrap(); } #[test] fn validator_deserialization_error() { let r = Validator::new("bad json"); assert!(matches!(r.err(), Some(Error::SchemaDeserialize(_)))); } #[test] fn validator_schema_compile_error() { const BAD_SCHEMA: &str = r#" { "$schema": "https://json-schema.org/draft-04/schema#", "definitions": { "UserId": { "1.0": { "type": "bad value" } } } }"#; let r = Validator::new(BAD_SCHEMA); assert!(matches!(r.err(), Some(Error::SchemaCompile(_)))); } #[test] fn message_serialization_error() { let hedwig = mock_hedwig(); #[derive(serde::Serialize)] struct BadUserCreatedData { user_ids: HashMap<Vec<i32>, String>, }; let mut user_ids = HashMap::new(); user_ids.insert(vec![32, 64], "U_123".to_owned()); let data = BadUserCreatedData { user_ids }; let m = Message::new(MessageType::UserCreated, VERSION_1_0, data); let mut builder = hedwig.build_batch(); assert!(matches!(builder.message(m).err(), Some(Error::MessageSerialize(_)))); } #[test] fn message_router_error() { let hedwig = mock_hedwig(); let m = Message::new(MessageType::InvalidRoute, VERSION_1_0, ()); let mut builder = hedwig.build_batch(); assert!(matches!(builder.message(m).err(), Some(Error::MessageRoute(_)))); } #[test] fn message_invalid_schema_error() { let hedwig = mock_hedwig(); let m = Message::new(MessageType::InvalidSchema, VERSION_1_0, ()); let mut builder = hedwig.build_batch(); assert!(matches!(builder.message(m).err(), Some(Error::SchemaUrlResolve(_)))); } #[test] fn message_data_validation_eror() { let hedwig = mock_hedwig(); #[derive(serde::Serialize)] struct BadUserCreatedData { user_ids: Vec<i32>, }; let data = BadUserCreatedData { user_ids: vec![1] }; let m = Message::new(MessageType::UserCreated, VERSION_1_0, data); let mut builder = hedwig.build_batch(); assert!(matches!(builder.message(m).err(), Some(Error::DataValidation(_)))); } #[test] fn errors_send_sync() { fn assert_error<T: std::error::Error + Send + Sync + 'static>() {} assert_error::<Error>(); assert_error::<Error>(); } }
} } }
random_line_split
lib.rs
#![deny( missing_docs, unused_import_braces, unused_qualifications, intra_doc_link_resolution_failure, clippy::all )] //! A Hedwig library for Rust. Hedwig is a message bus that works with arbitrary pubsub services //! such as AWS SNS/SQS or Google Cloud Pubsub. Messages are validated using a JSON schema. The //! publisher and consumer are de-coupled and fan-out is supported out of the box. //! //! # Example: publish a new message //! //! ```no_run //! use hedwig::{Hedwig, MajorVersion, MinorVersion, Version, Message, publishers::MockPublisher}; //! # use std::path::Path; //! # use serde::Serialize; //! # use strum_macros::IntoStaticStr; //! //! fn main() -> Result<(), Box<dyn std::error::Error>> { //! let schema = r#" //! { //! "$id": "https://hedwig.standard.ai/schema", //! "$schema": "https://json-schema.org/draft-04/schema#", //! "description": "Example Schema", //! "schemas": { //! "user-created": { //! "1.*": { //! "description": "A new user was created", //! "type": "object", //! "x-versions": [ //! "1.0" //! ], //! "required": [ //! "user_id" //! ], //! "properties": { //! "user_id": { //! "$ref": "https://hedwig.standard.ai/schema#/definitions/UserId/1.0" //! } //! } //! } //! } //! }, //! "definitions": { //! "UserId": { //! "1.0": { //! "type": "string" //! } //! } //! } //! }"#; //! //! # #[derive(Clone, Copy, IntoStaticStr, Hash, PartialEq, Eq)] //! # enum MessageType { //! # #[strum(serialize = "user.created")] //! # UserCreated, //! # } //! # //! # #[derive(Serialize)] //! # struct UserCreatedData { //! # user_id: String, //! # } //! # //! fn router(t: MessageType, v: MajorVersion) -> Option<&'static str> { //! match (t, v) { //! (MessageType::UserCreated, MajorVersion(1)) => Some("dev-user-created-v1"), //! _ => None, //! } //! } //! //! // create a publisher instance //! let publisher = MockPublisher::default(); //! let hedwig = Hedwig::new( //! schema, //! "myapp", //! publisher, //! router, //! )?; //! //! async { //! let published_ids = hedwig.publish(Message::new( //! MessageType::UserCreated, //! Version(MajorVersion(1), MinorVersion(0)), //! UserCreatedData { user_id: "U_123".into() } //! )).await; //! }; //! //! # Ok(()) //! # } //! ``` #![deny(missing_docs, unused_import_braces, unused_qualifications)] #![warn(trivial_casts, trivial_numeric_casts, unsafe_code, unstable_features)] use std::{ collections::HashMap, fmt, future::Future, mem, time::{SystemTime, UNIX_EPOCH}, }; use futures::stream::StreamExt; use uuid::Uuid; use valico::json_schema::{SchemaError, Scope, ValidationState}; #[cfg(feature = "google")] mod google_publisher; mod mock_publisher; mod null_publisher; /// Implementations of the Publisher trait pub mod publishers { #[cfg(feature = "google")] pub use super::google_publisher::GooglePubSubPublisher; pub use super::mock_publisher::MockPublisher; pub use super::null_publisher::NullPublisher; } const FORMAT_VERSION_V1: Version = Version(MajorVersion(1), MinorVersion(0)); /// All errors that may be returned when instantiating a new Hedwig instance. #[derive(Debug, thiserror::Error)] #[non_exhaustive] pub enum Error { /// Unable to deserialize schema #[error("Unable to deserialize schema")] SchemaDeserialize(#[source] serde_json::Error), /// Schema failed to compile #[error("Schema failed to compile")] SchemaCompile(#[from] SchemaError), /// Unable to serialize message #[error("Unable to serialize message")] MessageSerialize(#[source] serde_json::Error), /// Message is not routable #[error("Message {0} is not routable")] MessageRoute(Uuid), /// Could not parse a schema URL #[error("Could not parse `{1}` as a schema URL")] SchemaUrlParse(#[source] url::ParseError, String), /// Could not resolve the schema URL #[error("Could not resolve `{0}` to a schema")] SchemaUrlResolve(url::Url), /// Could not validate message data #[error("Message data does not validate per the schema: {0}")] DataValidation(String), /// Publisher failed to publish a message #[error("Publisher failed to publish a message batch")] Publisher(#[source] Box<dyn std::error::Error + Send + Sync>), /// Publisher failed to publish multiple batches of messages #[error("Publisher failed to publish multiple batches (total of {} errors)", _1.len() + 1)] PublisherMultiple( #[source] Box<dyn std::error::Error + Send + Sync>, Vec<Box<dyn std::error::Error + Send + Sync>>, ), } type AnyError = Box<dyn std::error::Error + Send + Sync>; /// The special result type for [`Publisher::publish`](trait.Publisher.html) #[derive(Debug)] pub enum PublisherResult<Id> { /// Publisher succeeded. /// /// Contains a vector of published message IDs. Success(Vec<Id>), /// Publisher failed to publish any of the messages. OneError(AnyError, Vec<ValidatedMessage>), /// Publisher failed to publish some of the messages. /// /// The error type has a per-message granularity. PerMessage(Vec<Result<Id, (AnyError, ValidatedMessage)>>), } /// Interface for message publishers pub trait Publisher { /// The list of identifiers for successfully published messages type MessageId: 'static; /// The future that the `publish` method returns type PublishFuture: Future<Output = PublisherResult<Self::MessageId>> + Send; /// Publish a batch of messages /// /// # Return value /// /// Shall return [`PublisherResult::Success`](PublisherResult::Success) only if all of the /// messages are successfully published. Otherwise `PublisherResult::OneError` or /// `PublisherResult::PerMessage` shall be returned to indicate an error. fn publish(&self, topic: &'static str, messages: Vec<ValidatedMessage>) -> Self::PublishFuture; } /// Type alias for custom headers associated with a message type Headers = HashMap<String, String>; struct Validator { scope: Scope, schema_id: url::Url, } impl Validator { fn new(schema: &str) -> Result<Validator, Error> { let master_schema: serde_json::Value = serde_json::from_str(schema).map_err(Error::SchemaDeserialize)?; let mut scope = Scope::new(); let schema_id = scope.compile(master_schema, false)?; Ok(Validator { scope, schema_id }) } fn validate<D, T>( &self, message: &Message<D, T>, schema: &str, ) -> Result<ValidationState, Error> where D: serde::Serialize, { // convert user.created/1.0 -> user.created/1.* let msg_schema_ptr = schema.trim_end_matches(char::is_numeric).to_owned() + "*"; let msg_schema_url = url::Url::parse(&msg_schema_ptr) .map_err(|e| Error::SchemaUrlParse(e, msg_schema_ptr))?; let msg_schema = self .scope .resolve(&msg_schema_url) .ok_or_else(|| Error::SchemaUrlResolve(msg_schema_url))?; let msg_data = serde_json::to_value(&message.data).map_err(Error::MessageSerialize)?; let validation_state = msg_schema.validate(&msg_data); if !validation_state.is_strictly_valid() { return Err(Error::DataValidation(format!("{:?}", validation_state))); } Ok(validation_state) } } /// Major part component in semver #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize)] pub struct MajorVersion(pub u8); impl fmt::Display for MajorVersion { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.0) } } /// Minor part component in semver #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize)] pub struct MinorVersion(pub u8); impl fmt::Display for MinorVersion { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.0) } } /// A semver version without patch part #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct Version(pub MajorVersion, pub MinorVersion); impl serde::Serialize for Version { fn serialize<S>( &self, serializer: S, ) -> Result<<S as serde::Serializer>::Ok, <S as serde::Serializer>::Error> where S: serde::Serializer, { serializer.serialize_str(format!("{}.{}", self.0, self.1).as_ref()) } } /// Mapping of message types to Hedwig topics /// /// # Examples /// ``` /// # use serde::Serialize; /// # use strum_macros::IntoStaticStr; /// use hedwig::{MajorVersion, MessageRouter}; /// /// # #[derive(Clone, Copy, IntoStaticStr, Hash, PartialEq, Eq)] /// # enum MessageType { /// # #[strum(serialize = "user.created")] /// # UserCreated, /// # } /// # /// let r: MessageRouter<MessageType> = |t, v| match (t, v) { /// (MessageType::UserCreated, MajorVersion(1)) => Some("user-created-v1"), /// _ => None, /// }; /// ``` pub type MessageRouter<T> = fn(T, MajorVersion) -> Option<&'static str>; /// The core type in this library #[allow(missing_debug_implementations)] pub struct Hedwig<T, P> { validator: Validator, publisher_name: String, message_router: MessageRouter<T>, publisher: P, } impl<T, P> Hedwig<T, P> where P: Publisher, { /// Creates a new Hedwig instance /// /// # Arguments /// /// * `schema`: The JSON schema content. It's up to the caller to read the schema; /// * `publisher_name`: Name of the publisher service which will be included in the message /// metadata; /// * `publisher`: An implementation of Publisher; pub fn new( schema: &str, publisher_name: &str, publisher: P, message_router: MessageRouter<T>, ) -> Result<Hedwig<T, P>, Error> { Ok(Hedwig { validator: Validator::new(schema)?, publisher_name: String::from(publisher_name), message_router, publisher, }) } /// Create a batch of messages to publish /// /// This allows to transparently retry failed messages and send them in batches larger than /// one, leading to potential throughput gains. pub fn build_batch(&self) -> PublishBatch<T, P> { PublishBatch { hedwig: self, messages: Vec::new(), } } /// Publish a single message /// /// Note, that unlike the batch builder, this does not allow recovering failed-to-publish /// messages. pub async fn publish<D>(&self, msg: Message<D, T>) -> Result<P::MessageId, Error> where D: serde::Serialize, T: Copy + Into<&'static str>, { let mut builder = self.build_batch(); builder.message(msg)?; builder.publish_one().await } } /// A builder for publishing in batches /// /// Among other things this structure also enables transparent retrying of failed-to-publish /// messages. #[allow(missing_debug_implementations)] pub struct PublishBatch<'hedwig, T, P> { hedwig: &'hedwig Hedwig<T, P>, messages: Vec<(&'static str, ValidatedMessage)>, } impl<'hedwig, T, P> PublishBatch<'hedwig, T, P> { /// Add a message to be published in a batch pub fn message<D>(&mut self, msg: Message<D, T>) -> Result<&mut Self, Error> where D: serde::Serialize, T: Copy + Into<&'static str>, { let data_type = msg.data_type; let schema_version = msg.data_schema_version; let data_type_str = msg.data_type.into(); let schema_url = format!( "{}#/schemas/{}/{}.{}", self.hedwig.validator.schema_id, data_type_str, schema_version.0, schema_version.1, ); self.hedwig.validator.validate(&msg, &schema_url)?; let converted = msg .into_schema( self.hedwig.publisher_name.clone(), schema_url, FORMAT_VERSION_V1, ) .map_err(Error::MessageSerialize)?; let route = (self.hedwig.message_router)(data_type, converted.format_version.0) .ok_or_else(|| Error::MessageRoute(converted.id))?; self.messages.push((route, converted)); Ok(self) } /// Publish all the messages /// /// Does not consume the builder. Will return `Ok` only if and when all of the messages from /// the builder have been published successfully. In case of failure, unpublished messages will /// remain enqueued in this builder for a subsequent publish call. pub async fn publish(&mut self) -> Result<Vec<P::MessageId>, Error> where P: Publisher, { let mut message_ids = Vec::with_capacity(self.messages.len()); // Sort the messages by the topic and group them into batches self.messages.sort_by_key(|&(k, _)| k); let mut current_topic = ""; let mut current_batch = Vec::new(); let mut futures_unordered = futures::stream::FuturesUnordered::new(); let publisher = &self.hedwig.publisher; let make_job = |topic: &'static str, batch: Vec<ValidatedMessage>| async move { (topic, publisher.publish(topic, batch).await) }; for (topic, message) in mem::replace(&mut self.messages, Vec::new()) { if current_topic != topic && !current_batch.is_empty() { let batch = mem::replace(&mut current_batch, Vec::new()); futures_unordered.push(make_job(current_topic, batch)); } current_topic = topic; current_batch.push(message) } if !current_batch.is_empty() { futures_unordered.push(make_job(current_topic, current_batch)); } let mut errors = Vec::new(); // Extract the results from all the futures while let (Some(result), stream) = futures_unordered.into_future().await { match result { (_, PublisherResult::Success(ids)) => message_ids.extend(ids), (topic, PublisherResult::OneError(err, failed_msgs)) => { self.messages .extend(failed_msgs.into_iter().map(|m| (topic, m))); errors.push(err); } (topic, PublisherResult::PerMessage(vec)) => { for message in vec { match message { Ok(id) => message_ids.push(id), Err((err, failed_msg)) => { self.messages.push((topic, failed_msg)); errors.push(err); } } } } } futures_unordered = stream; } if let Some(first_error) = errors.pop() { Err(if errors.is_empty() { Error::Publisher(first_error) } else { Error::PublisherMultiple(first_error, errors) }) } else { Ok(message_ids) } } /// Publishes just one message /// /// Panics if the builder contains anything but 1 message. async fn publish_one(mut self) -> Result<P::MessageId, Error> where P: Publisher, { let (topic, message) = if let Some(v) = self.messages.pop() { assert!( self.messages.is_empty(), "messages buffer must contain exactly 1 entry!" ); v } else { panic!("messages buffer must contain exactly 1 entry!") }; match self.hedwig.publisher.publish(topic, vec![message]).await { PublisherResult::Success(mut ids) if ids.len() == 1 => Ok(ids.pop().unwrap()), PublisherResult::OneError(err, _) => Err(Error::Publisher(err)), PublisherResult::PerMessage(mut results) if results.len() == 1 => { results.pop().unwrap().map_err(|(e, _)| Error::Publisher(e)) } _ => { panic!("Publisher should have returned 1 result only!"); } } } } /// A message builder #[derive(Clone, Debug, PartialEq)] pub struct Message<D, T> { /// Message identifier id: Option<Uuid>, /// Creation timestamp timestamp: std::time::Duration, /// Message headers headers: Option<Headers>, /// Message data data: D, /// Message type data_type: T, data_schema_version: Version, } impl<D, T> Message<D, T> { /// Construct a new message pub fn
(data_type: T, data_schema_version: Version, data: D) -> Self { Message { id: None, timestamp: SystemTime::now() .duration_since(UNIX_EPOCH) .expect("time is before the unix epoch"), headers: None, data, data_type, data_schema_version, } } /// Overwrite the header map associated with the message /// /// This may be used to track the `request_id`, for example. pub fn headers(mut self, headers: Headers) -> Self { self.headers = Some(headers); self } /// Add a custom header to the message /// /// This may be used to track the `request_id`, for example. pub fn header<H, V>(mut self, header: H, value: V) -> Self where H: Into<String>, V: Into<String>, { if let Some(ref mut hdrs) = self.headers { hdrs.insert(header.into(), value.into()); } else { let mut map = HashMap::new(); map.insert(header.into(), value.into()); self.headers = Some(map); } self } /// Add custom id to the message /// /// If not called, a random UUID is generated for this message. pub fn id(mut self, id: Uuid) -> Self { self.id = Some(id); self } fn into_schema( self, publisher_name: String, schema: String, format_version: Version, ) -> Result<ValidatedMessage, serde_json::Error> where D: serde::Serialize, { Ok(ValidatedMessage { id: self.id.unwrap_or_else(Uuid::new_v4), metadata: Metadata { timestamp: self.timestamp.as_millis(), publisher: publisher_name, headers: self.headers.unwrap_or_else(HashMap::new), }, schema, format_version, data: serde_json::to_value(self.data)?, }) } } /// Additional metadata associated with a message #[derive(Clone, Debug, PartialEq, serde::Serialize)] struct Metadata { /// The timestamp when message was created in the publishing service timestamp: u128, /// Name of the publishing service publisher: String, /// Custom headers /// /// This may be used to track request_id, for example. headers: Headers, } /// A validated message /// /// This data type is the schema or the json messages being sent over the wire. #[derive(Debug, serde::Serialize)] pub struct ValidatedMessage { /// Unique message identifier id: Uuid, /// The metadata associated with the message metadata: Metadata, /// URI of the schema validating this message /// /// E.g. `https://hedwig.domain.xyz/schemas#/schemas/user.created/1.0` schema: String, /// Format of the message schema used format_version: Version, /// The message data data: serde_json::Value, } #[cfg(test)] mod tests { use super::*; use strum_macros::IntoStaticStr; #[derive(Clone, Copy, Debug, IntoStaticStr, Hash, PartialEq, Eq)] enum MessageType { #[strum(serialize = "user.created")] UserCreated, #[strum(serialize = "invalid.schema")] InvalidSchema, #[strum(serialize = "invalid.route")] InvalidRoute, } #[derive(Clone, Debug, serde::Serialize, PartialEq)] struct UserCreatedData { user_id: String, } const VERSION_1_0: Version = Version(MajorVersion(1), MinorVersion(0)); const SCHEMA: &str = r#" { "$id": "https://hedwig.standard.ai/schema", "$schema": "https://json-schema.org/draft-04/schema#", "description": "Example Schema", "schemas": { "user.created": { "1.*": { "description": "A new user was created", "type": "object", "x-versions": [ "1.0" ], "required": [ "user_id" ], "properties": { "user_id": { "$ref": "https://hedwig.standard.ai/schema#/definitions/UserId/1.0" } } } }, "invalid.route": { "1.*": {} } }, "definitions": { "UserId": { "1.0": { "type": "string" } } } }"#; fn router(t: MessageType, v: MajorVersion) -> Option<&'static str> { match (t, v) { (MessageType::UserCreated, MajorVersion(1)) => Some("dev-user-created-v1"), (MessageType::InvalidSchema, MajorVersion(1)) => Some("invalid-schema"), _ => None, } } fn mock_hedwig() -> Hedwig<MessageType, publishers::MockPublisher> { Hedwig::new( SCHEMA, "myapp", publishers::MockPublisher::default(), router, ) .unwrap() } #[test] fn message_constructor() { let data = UserCreatedData { user_id: "U_123".into(), }; let message = Message::new(MessageType::UserCreated, VERSION_1_0, data.clone()); assert_eq!(None, message.headers); assert_eq!(data, message.data); assert_eq!(MessageType::UserCreated, message.data_type); assert_eq!(VERSION_1_0, message.data_schema_version); } #[test] fn message_set_headers() { let request_id = Uuid::new_v4().to_string(); let message = Message::new( MessageType::UserCreated, VERSION_1_0, UserCreatedData { user_id: "U_123".into(), }, ) .header("request_id", request_id.clone()); assert_eq!( request_id, message .headers .unwrap() .get(&"request_id".to_owned()) .unwrap() .as_str() ); } #[test] fn message_with_id() { let id = uuid::Uuid::new_v4(); let message = Message::new( MessageType::UserCreated, VERSION_1_0, UserCreatedData { user_id: "U_123".into(), }, ) .id(id); assert_eq!(id, message.id.unwrap()); } #[tokio::test] async fn publish() { let hedwig = mock_hedwig(); let mut custom_headers = Headers::new(); let request_id = Uuid::new_v4().to_string(); let msg_id = Uuid::new_v4(); let message = Message::new( MessageType::UserCreated, VERSION_1_0, UserCreatedData { user_id: "U_123".into(), }, ) .header("request_id", request_id.clone()) .id(msg_id); custom_headers.insert("request_id".to_owned(), request_id); let mut builder = hedwig.build_batch(); builder.message(message.clone()).unwrap(); builder.publish().await.unwrap(); hedwig .publisher .assert_message_published("dev-user-created-v1", msg_id); } #[tokio::test] async fn publish_empty() { let hedwig = mock_hedwig(); let mut builder = hedwig.build_batch(); builder.publish().await.unwrap(); } #[test] fn validator_deserialization_error() { let r = Validator::new("bad json"); assert!(matches!(r.err(), Some(Error::SchemaDeserialize(_)))); } #[test] fn validator_schema_compile_error() { const BAD_SCHEMA: &str = r#" { "$schema": "https://json-schema.org/draft-04/schema#", "definitions": { "UserId": { "1.0": { "type": "bad value" } } } }"#; let r = Validator::new(BAD_SCHEMA); assert!(matches!(r.err(), Some(Error::SchemaCompile(_)))); } #[test] fn message_serialization_error() { let hedwig = mock_hedwig(); #[derive(serde::Serialize)] struct BadUserCreatedData { user_ids: HashMap<Vec<i32>, String>, }; let mut user_ids = HashMap::new(); user_ids.insert(vec![32, 64], "U_123".to_owned()); let data = BadUserCreatedData { user_ids }; let m = Message::new(MessageType::UserCreated, VERSION_1_0, data); let mut builder = hedwig.build_batch(); assert!(matches!(builder.message(m).err(), Some(Error::MessageSerialize(_)))); } #[test] fn message_router_error() { let hedwig = mock_hedwig(); let m = Message::new(MessageType::InvalidRoute, VERSION_1_0, ()); let mut builder = hedwig.build_batch(); assert!(matches!(builder.message(m).err(), Some(Error::MessageRoute(_)))); } #[test] fn message_invalid_schema_error() { let hedwig = mock_hedwig(); let m = Message::new(MessageType::InvalidSchema, VERSION_1_0, ()); let mut builder = hedwig.build_batch(); assert!(matches!(builder.message(m).err(), Some(Error::SchemaUrlResolve(_)))); } #[test] fn message_data_validation_eror() { let hedwig = mock_hedwig(); #[derive(serde::Serialize)] struct BadUserCreatedData { user_ids: Vec<i32>, }; let data = BadUserCreatedData { user_ids: vec![1] }; let m = Message::new(MessageType::UserCreated, VERSION_1_0, data); let mut builder = hedwig.build_batch(); assert!(matches!(builder.message(m).err(), Some(Error::DataValidation(_)))); } #[test] fn errors_send_sync() { fn assert_error<T: std::error::Error + Send + Sync + 'static>() {} assert_error::<Error>(); assert_error::<Error>(); } }
new
identifier_name
bundler.py
# bundler.py """Module to implement the Bundler component of the Long Term Archive.""" import asyncio import json import logging import os from pathlib import Path import shutil import sys from typing import Any, Dict, Optional from zipfile import ZIP_STORED, ZipFile from rest_tools.client import ClientCredentialsAuth, RestClient from wipac_dev_tools import from_environment import wipac_telemetry.tracing_tools as wtt from .component import COMMON_CONFIG, Component, now, work_loop from .crypto import lta_checksums from .lta_types import BundleType Logger = logging.Logger LOG = logging.getLogger(__name__) # maximum number of Metadata UUIDs to work with at a time CREATE_CHUNK_SIZE = 1000 EXPECTED_CONFIG = COMMON_CONFIG.copy() EXPECTED_CONFIG.update({ "BUNDLER_OUTBOX_PATH": None, "BUNDLER_WORKBOX_PATH": None, "FILE_CATALOG_CLIENT_ID": None, "FILE_CATALOG_CLIENT_SECRET": None, "FILE_CATALOG_REST_URL": None, "WORK_RETRIES": "3", "WORK_TIMEOUT_SECONDS": "30", }) class Bundler(Component): """ Bundler is a Long Term Archive component. A Bundler is responsible for creating large ZIP64 archives of files that should be moved to long term archive. It requests work from the LTA REST API in the form of files to put into a large archive. It creates the ZIP64 archive and moves the file to staging disk. It then updates the LTA REST API to indicate that the provided files were so bundled. """ def __init__(self, config: Dict[str, str], logger: Logger) -> None: """ Create a Bundler component. config - A dictionary of required configuration values. logger - The object the bundler should use for logging. """ super(Bundler, self).__init__("bundler", config, logger) self.file_catalog_client_id = config["FILE_CATALOG_CLIENT_ID"] self.file_catalog_client_secret = config["FILE_CATALOG_CLIENT_SECRET"] self.file_catalog_rest_url = config["FILE_CATALOG_REST_URL"] self.outbox_path = config["BUNDLER_OUTBOX_PATH"] self.work_retries = int(config["WORK_RETRIES"]) self.work_timeout_seconds = float(config["WORK_TIMEOUT_SECONDS"]) self.workbox_path = config["BUNDLER_WORKBOX_PATH"] def _do_status(self) -> Dict[str, Any]: """Bundler has no additional status to contribute.""" return {} def _expected_config(self) -> Dict[str, Optional[str]]: """Bundler provides our expected configuration dictionary.""" return EXPECTED_CONFIG @wtt.spanned() async def _do_work(self) -> None: """Perform a work cycle for this component.""" self.logger.info("Starting work on Bundles.") work_claimed = True while work_claimed: work_claimed = await self._do_work_claim() # if we are configured to run once and die, then die if self.run_once_and_die: sys.exit() self.logger.info("Ending work on Bundles.") @wtt.spanned() async def _do_work_claim(self) -> bool: """Claim a bundle and perform work on it.""" # 1. Ask the LTA DB for the next Bundle to be built # configure a RestClient to talk to the File Catalog fc_rc = ClientCredentialsAuth(address=self.file_catalog_rest_url, token_url=self.lta_auth_openid_url, client_id=self.file_catalog_client_id, client_secret=self.file_catalog_client_secret) # configure a RestClient to talk to the LTA DB lta_rc = ClientCredentialsAuth(address=self.lta_rest_url, token_url=self.lta_auth_openid_url, client_id=self.client_id, client_secret=self.client_secret, timeout=self.work_timeout_seconds, retries=self.work_retries) self.logger.info("Asking the LTA DB for a Bundle to build.") pop_body = { "claimant": f"{self.name}-{self.instance_uuid}" } response = await lta_rc.request('POST', f'/Bundles/actions/pop?source={self.source_site}&dest={self.dest_site}&status={self.input_status}', pop_body) self.logger.info(f"LTA DB responded with: {response}") bundle = response["bundle"] if not bundle: self.logger.info("LTA DB did not provide a Bundle to build. Going on vacation.") return False # process the Bundle that we were given try: await self._do_work_bundle(fc_rc, lta_rc, bundle) except Exception as e: await self._quarantine_bundle(lta_rc, bundle, f"{e}") raise e # signal the work was processed successfully return True @wtt.spanned() async def _do_work_bundle(self, fc_rc: RestClient, lta_rc: RestClient, bundle: BundleType) -> None: # 0. Get our ducks in a row about what we're doing here bundle_uuid = bundle["uuid"] dest = bundle["dest"] file_count = bundle["file_count"] source = bundle["source"] self.logger.info(f"There are {file_count} Files to bundle from '{source}' to '{dest}'.") self.logger.info(f"Bundle archive file will be '{bundle_uuid}.zip'") # 1. Create a manifest of the bundle, including all metadata metadata_file_path = os.path.join(self.workbox_path, f"{bundle_uuid}.metadata.ndjson") await self._create_metadata_file(fc_rc, lta_rc, bundle, metadata_file_path, file_count) # 2. Create a ZIP bundle by writing constituent files to it bundle_file_path = os.path.join(self.workbox_path, f"{bundle_uuid}.zip") await self._create_bundle_archive(fc_rc, lta_rc, bundle, bundle_file_path, metadata_file_path, file_count) # 3. Clean up generated JSON metadata file self.logger.info(f"Deleting bundle metadata file: '{metadata_file_path}'") os.remove(metadata_file_path) self.logger.info(f"Bundle metadata '{metadata_file_path}' was deleted.") # 4. Compute the size of the bundle bundle_size = os.path.getsize(bundle_file_path) self.logger.info(f"Archive bundle has size {bundle_size} bytes") # 5. Compute the LTA checksums for the bundle self.logger.info(f"Computing LTA checksums for bundle: '{bundle_file_path}'") checksum = lta_checksums(bundle_file_path) self.logger.info(f"Bundle '{bundle_file_path}' has adler32 checksum '{checksum['adler32']}'") self.logger.info(f"Bundle '{bundle_file_path}' has SHA512 checksum '{checksum['sha512']}'") # 6. Determine the final destination path of the bundle final_bundle_path = bundle_file_path if self.outbox_path != self.workbox_path: final_bundle_path = os.path.join(self.outbox_path, f"{bundle_uuid}.zip") self.logger.info(f"Finished archive bundle will be located at: '{final_bundle_path}'") # 7. Update the bundle record we have with all the information we collected bundle["status"] = self.output_status bundle["reason"] = "" bundle["update_timestamp"] = now() bundle["bundle_path"] = final_bundle_path bundle["size"] = bundle_size bundle["checksum"] = checksum bundle["verified"] = False bundle["claimed"] = False # 8. Move the bundle from the work box to the outbox if final_bundle_path != bundle_file_path: self.logger.info(f"Moving bundle from '{bundle_file_path}' to '{final_bundle_path}'") shutil.move(bundle_file_path, final_bundle_path) self.logger.info(f"Finished archive bundle now located at: '{final_bundle_path}'") # 9. Update the Bundle record in the LTA DB self.logger.info(f"PATCH /Bundles/{bundle_uuid} - '{bundle}'") await lta_rc.request('PATCH', f'/Bundles/{bundle_uuid}', bundle) @wtt.spanned() async def _create_bundle_archive(self, fc_rc: RestClient, lta_rc: RestClient, bundle: BundleType, bundle_file_path: str, metadata_file_path: str, file_count: int) -> None: # 0. Remove an existing bundle, if we are re-trying Path(bundle_file_path).unlink(missing_ok=True) # 2. Create a ZIP bundle by writing constituent files to it bundle_uuid = bundle["uuid"] request_path = bundle["path"] count = 0 done = False limit = CREATE_CHUNK_SIZE skip = 0 self.logger.info(f"Creating bundle as ZIP archive at: {bundle_file_path}") with ZipFile(bundle_file_path, mode="x", compression=ZIP_STORED, allowZip64=True) as bundle_zip: # write the metadata file to the bundle archive self.logger.info(f"Adding bundle metadata '{metadata_file_path}' to bundle '{bundle_file_path}'") bundle_zip.write(metadata_file_path, os.path.basename(metadata_file_path)) # until we've finished processing all the Metadata records while not done: # ask the LTA DB for the next chunk of Metadata records self.logger.info(f"GET /Metadata?bundle_uuid={bundle_uuid}&limit={limit}&skip={skip}") lta_response = await lta_rc.request('GET', f'/Metadata?bundle_uuid={bundle_uuid}&limit={limit}&skip={skip}') num_files = len(lta_response["results"]) done = (num_files == 0) skip = skip + num_files self.logger.info(f'LTA returned {num_files} Metadata documents to process.') # for each Metadata record returned by the LTA DB for metadata_record in lta_response["results"]: # load the record from the File Catalog and add the warehouse file to the ZIP archive count = count + 1 file_catalog_uuid = metadata_record["file_catalog_uuid"] fc_response = await fc_rc.request('GET', f'/api/files/{file_catalog_uuid}') bundle_me_path = fc_response["logical_name"] self.logger.info(f"Writing file {count}/{num_files}: '{bundle_me_path}' to bundle '{bundle_file_path}'") zip_path = os.path.relpath(bundle_me_path, request_path) bundle_zip.write(bundle_me_path, zip_path) # do a last minute sanity check on our data if count != file_count: error_message = f'Bad mojo creating bundle archive file. Expected {file_count} Metadata records, but only processed {count} records.' self.logger.error(error_message) raise Exception(error_message) @wtt.spanned() async def _create_metadata_file(self, fc_rc: RestClient, lta_rc: RestClient, bundle: BundleType, metadata_file_path: str, file_count: int) -> None: # 0. Remove an existing manifest, if we are re-trying Path(metadata_file_path).unlink(missing_ok=True) # 1. Create a manifest of the bundle, including all metadata bundle_uuid = bundle["uuid"] self.logger.info(f"Bundle metadata file will be created at: {metadata_file_path}") metadata_dict = { "uuid": bundle_uuid, "component": "bundler", "version": 3, "create_timestamp": now(), "file_count": file_count, } # open the metadata file and write our data count = 0 done = False limit = CREATE_CHUNK_SIZE skip = 0 with open(metadata_file_path, mode="w") as metadata_file: self.logger.info(f"Writing metadata_dict to '{metadata_file_path}'") metadata_file.write(json.dumps(metadata_dict)) metadata_file.write("\n") # until we've finished processing all the Metadata records while not done: # ask the LTA DB for the next chunk of Metadata records lta_response = await lta_rc.request('GET', f'/Metadata?bundle_uuid={bundle_uuid}&limit={limit}&skip={skip}') num_files = len(lta_response["results"]) done = (num_files == 0) skip = skip + num_files self.logger.info(f'LTA returned {num_files} Metadata documents to process.') # for each Metadata record returned by the LTA DB for metadata_record in lta_response["results"]: # load the record from the File Catalog and preserve it in carbonite
# do a last minute sanity check on our data if count != file_count: error_message = f'Bad mojo creating metadata file. Expected {file_count} Metadata records, but only processed {count} records.' self.logger.error(error_message) raise Exception(error_message) @wtt.spanned() async def _quarantine_bundle(self, lta_rc: RestClient, bundle: BundleType, reason: str) -> None: """Quarantine the supplied bundle using the supplied reason.""" self.logger.error(f'Sending Bundle {bundle["uuid"]} to quarantine: {reason}.') right_now = now() patch_body = { "status": "quarantined", "reason": f"BY:{self.name}-{self.instance_uuid} REASON:{reason}", "work_priority_timestamp": right_now, } try: await lta_rc.request('PATCH', f'/Bundles/{bundle["uuid"]}', patch_body) except Exception as e: self.logger.error(f'Unable to quarantine Bundle {bundle["uuid"]}: {e}.') def runner() -> None: """Configure a Bundler component from the environment and set it running.""" # obtain our configuration from the environment config = from_environment(EXPECTED_CONFIG) # configure logging for the application log_level = getattr(logging, str(config["LOG_LEVEL"]).upper()) logging.basicConfig( format="{asctime} [{threadName}] {levelname:5} ({filename}:{lineno}) - {message}", level=log_level, stream=sys.stdout, style="{", ) # create our Bundler service bundler = Bundler(config, LOG) # type: ignore[arg-type] # let's get to work bundler.logger.info("Adding tasks to asyncio loop") loop = asyncio.get_event_loop() loop.create_task(work_loop(bundler)) def main() -> None: """Configure a Bundler component from the environment and set it running.""" runner() asyncio.get_event_loop().run_forever() if __name__ == "__main__": main()
count = count + 1 file_catalog_uuid = metadata_record["file_catalog_uuid"] fc_response = await fc_rc.request('GET', f'/api/files/{file_catalog_uuid}') self.logger.info(f"Writing File Catalog record {file_catalog_uuid} to '{metadata_file_path}'") metadata_file.write(json.dumps(fc_response)) metadata_file.write("\n")
conditional_block
bundler.py
# bundler.py """Module to implement the Bundler component of the Long Term Archive.""" import asyncio import json import logging import os from pathlib import Path import shutil import sys from typing import Any, Dict, Optional from zipfile import ZIP_STORED, ZipFile from rest_tools.client import ClientCredentialsAuth, RestClient from wipac_dev_tools import from_environment import wipac_telemetry.tracing_tools as wtt from .component import COMMON_CONFIG, Component, now, work_loop from .crypto import lta_checksums from .lta_types import BundleType Logger = logging.Logger LOG = logging.getLogger(__name__) # maximum number of Metadata UUIDs to work with at a time CREATE_CHUNK_SIZE = 1000 EXPECTED_CONFIG = COMMON_CONFIG.copy() EXPECTED_CONFIG.update({ "BUNDLER_OUTBOX_PATH": None, "BUNDLER_WORKBOX_PATH": None, "FILE_CATALOG_CLIENT_ID": None, "FILE_CATALOG_CLIENT_SECRET": None, "FILE_CATALOG_REST_URL": None, "WORK_RETRIES": "3", "WORK_TIMEOUT_SECONDS": "30", }) class Bundler(Component): """ Bundler is a Long Term Archive component. A Bundler is responsible for creating large ZIP64 archives of files that should be moved to long term archive. It requests work from the LTA REST API in the form of files to put into a large archive. It creates the ZIP64 archive and moves the file to staging disk. It then updates the LTA REST API to indicate that the provided files were so bundled. """ def __init__(self, config: Dict[str, str], logger: Logger) -> None: """ Create a Bundler component. config - A dictionary of required configuration values. logger - The object the bundler should use for logging. """ super(Bundler, self).__init__("bundler", config, logger) self.file_catalog_client_id = config["FILE_CATALOG_CLIENT_ID"] self.file_catalog_client_secret = config["FILE_CATALOG_CLIENT_SECRET"] self.file_catalog_rest_url = config["FILE_CATALOG_REST_URL"] self.outbox_path = config["BUNDLER_OUTBOX_PATH"] self.work_retries = int(config["WORK_RETRIES"]) self.work_timeout_seconds = float(config["WORK_TIMEOUT_SECONDS"]) self.workbox_path = config["BUNDLER_WORKBOX_PATH"] def _do_status(self) -> Dict[str, Any]: """Bundler has no additional status to contribute.""" return {} def _expected_config(self) -> Dict[str, Optional[str]]: """Bundler provides our expected configuration dictionary.""" return EXPECTED_CONFIG @wtt.spanned() async def _do_work(self) -> None: """Perform a work cycle for this component.""" self.logger.info("Starting work on Bundles.") work_claimed = True while work_claimed: work_claimed = await self._do_work_claim() # if we are configured to run once and die, then die if self.run_once_and_die: sys.exit() self.logger.info("Ending work on Bundles.") @wtt.spanned() async def _do_work_claim(self) -> bool: """Claim a bundle and perform work on it.""" # 1. Ask the LTA DB for the next Bundle to be built # configure a RestClient to talk to the File Catalog fc_rc = ClientCredentialsAuth(address=self.file_catalog_rest_url, token_url=self.lta_auth_openid_url, client_id=self.file_catalog_client_id, client_secret=self.file_catalog_client_secret) # configure a RestClient to talk to the LTA DB lta_rc = ClientCredentialsAuth(address=self.lta_rest_url, token_url=self.lta_auth_openid_url, client_id=self.client_id, client_secret=self.client_secret, timeout=self.work_timeout_seconds, retries=self.work_retries) self.logger.info("Asking the LTA DB for a Bundle to build.") pop_body = { "claimant": f"{self.name}-{self.instance_uuid}" } response = await lta_rc.request('POST', f'/Bundles/actions/pop?source={self.source_site}&dest={self.dest_site}&status={self.input_status}', pop_body) self.logger.info(f"LTA DB responded with: {response}") bundle = response["bundle"] if not bundle: self.logger.info("LTA DB did not provide a Bundle to build. Going on vacation.") return False # process the Bundle that we were given try: await self._do_work_bundle(fc_rc, lta_rc, bundle) except Exception as e: await self._quarantine_bundle(lta_rc, bundle, f"{e}") raise e # signal the work was processed successfully return True @wtt.spanned() async def _do_work_bundle(self, fc_rc: RestClient, lta_rc: RestClient, bundle: BundleType) -> None: # 0. Get our ducks in a row about what we're doing here bundle_uuid = bundle["uuid"] dest = bundle["dest"] file_count = bundle["file_count"] source = bundle["source"] self.logger.info(f"There are {file_count} Files to bundle from '{source}' to '{dest}'.") self.logger.info(f"Bundle archive file will be '{bundle_uuid}.zip'") # 1. Create a manifest of the bundle, including all metadata metadata_file_path = os.path.join(self.workbox_path, f"{bundle_uuid}.metadata.ndjson") await self._create_metadata_file(fc_rc, lta_rc, bundle, metadata_file_path, file_count) # 2. Create a ZIP bundle by writing constituent files to it bundle_file_path = os.path.join(self.workbox_path, f"{bundle_uuid}.zip") await self._create_bundle_archive(fc_rc, lta_rc, bundle, bundle_file_path, metadata_file_path, file_count) # 3. Clean up generated JSON metadata file self.logger.info(f"Deleting bundle metadata file: '{metadata_file_path}'") os.remove(metadata_file_path) self.logger.info(f"Bundle metadata '{metadata_file_path}' was deleted.") # 4. Compute the size of the bundle bundle_size = os.path.getsize(bundle_file_path) self.logger.info(f"Archive bundle has size {bundle_size} bytes") # 5. Compute the LTA checksums for the bundle self.logger.info(f"Computing LTA checksums for bundle: '{bundle_file_path}'") checksum = lta_checksums(bundle_file_path) self.logger.info(f"Bundle '{bundle_file_path}' has adler32 checksum '{checksum['adler32']}'") self.logger.info(f"Bundle '{bundle_file_path}' has SHA512 checksum '{checksum['sha512']}'") # 6. Determine the final destination path of the bundle final_bundle_path = bundle_file_path if self.outbox_path != self.workbox_path: final_bundle_path = os.path.join(self.outbox_path, f"{bundle_uuid}.zip") self.logger.info(f"Finished archive bundle will be located at: '{final_bundle_path}'") # 7. Update the bundle record we have with all the information we collected bundle["status"] = self.output_status bundle["reason"] = "" bundle["update_timestamp"] = now() bundle["bundle_path"] = final_bundle_path bundle["size"] = bundle_size bundle["checksum"] = checksum bundle["verified"] = False bundle["claimed"] = False # 8. Move the bundle from the work box to the outbox if final_bundle_path != bundle_file_path: self.logger.info(f"Moving bundle from '{bundle_file_path}' to '{final_bundle_path}'") shutil.move(bundle_file_path, final_bundle_path) self.logger.info(f"Finished archive bundle now located at: '{final_bundle_path}'") # 9. Update the Bundle record in the LTA DB self.logger.info(f"PATCH /Bundles/{bundle_uuid} - '{bundle}'") await lta_rc.request('PATCH', f'/Bundles/{bundle_uuid}', bundle) @wtt.spanned() async def _create_bundle_archive(self, fc_rc: RestClient, lta_rc: RestClient, bundle: BundleType, bundle_file_path: str, metadata_file_path: str, file_count: int) -> None: # 0. Remove an existing bundle, if we are re-trying
@wtt.spanned() async def _create_metadata_file(self, fc_rc: RestClient, lta_rc: RestClient, bundle: BundleType, metadata_file_path: str, file_count: int) -> None: # 0. Remove an existing manifest, if we are re-trying Path(metadata_file_path).unlink(missing_ok=True) # 1. Create a manifest of the bundle, including all metadata bundle_uuid = bundle["uuid"] self.logger.info(f"Bundle metadata file will be created at: {metadata_file_path}") metadata_dict = { "uuid": bundle_uuid, "component": "bundler", "version": 3, "create_timestamp": now(), "file_count": file_count, } # open the metadata file and write our data count = 0 done = False limit = CREATE_CHUNK_SIZE skip = 0 with open(metadata_file_path, mode="w") as metadata_file: self.logger.info(f"Writing metadata_dict to '{metadata_file_path}'") metadata_file.write(json.dumps(metadata_dict)) metadata_file.write("\n") # until we've finished processing all the Metadata records while not done: # ask the LTA DB for the next chunk of Metadata records lta_response = await lta_rc.request('GET', f'/Metadata?bundle_uuid={bundle_uuid}&limit={limit}&skip={skip}') num_files = len(lta_response["results"]) done = (num_files == 0) skip = skip + num_files self.logger.info(f'LTA returned {num_files} Metadata documents to process.') # for each Metadata record returned by the LTA DB for metadata_record in lta_response["results"]: # load the record from the File Catalog and preserve it in carbonite count = count + 1 file_catalog_uuid = metadata_record["file_catalog_uuid"] fc_response = await fc_rc.request('GET', f'/api/files/{file_catalog_uuid}') self.logger.info(f"Writing File Catalog record {file_catalog_uuid} to '{metadata_file_path}'") metadata_file.write(json.dumps(fc_response)) metadata_file.write("\n") # do a last minute sanity check on our data if count != file_count: error_message = f'Bad mojo creating metadata file. Expected {file_count} Metadata records, but only processed {count} records.' self.logger.error(error_message) raise Exception(error_message) @wtt.spanned() async def _quarantine_bundle(self, lta_rc: RestClient, bundle: BundleType, reason: str) -> None: """Quarantine the supplied bundle using the supplied reason.""" self.logger.error(f'Sending Bundle {bundle["uuid"]} to quarantine: {reason}.') right_now = now() patch_body = { "status": "quarantined", "reason": f"BY:{self.name}-{self.instance_uuid} REASON:{reason}", "work_priority_timestamp": right_now, } try: await lta_rc.request('PATCH', f'/Bundles/{bundle["uuid"]}', patch_body) except Exception as e: self.logger.error(f'Unable to quarantine Bundle {bundle["uuid"]}: {e}.') def runner() -> None: """Configure a Bundler component from the environment and set it running.""" # obtain our configuration from the environment config = from_environment(EXPECTED_CONFIG) # configure logging for the application log_level = getattr(logging, str(config["LOG_LEVEL"]).upper()) logging.basicConfig( format="{asctime} [{threadName}] {levelname:5} ({filename}:{lineno}) - {message}", level=log_level, stream=sys.stdout, style="{", ) # create our Bundler service bundler = Bundler(config, LOG) # type: ignore[arg-type] # let's get to work bundler.logger.info("Adding tasks to asyncio loop") loop = asyncio.get_event_loop() loop.create_task(work_loop(bundler)) def main() -> None: """Configure a Bundler component from the environment and set it running.""" runner() asyncio.get_event_loop().run_forever() if __name__ == "__main__": main()
Path(bundle_file_path).unlink(missing_ok=True) # 2. Create a ZIP bundle by writing constituent files to it bundle_uuid = bundle["uuid"] request_path = bundle["path"] count = 0 done = False limit = CREATE_CHUNK_SIZE skip = 0 self.logger.info(f"Creating bundle as ZIP archive at: {bundle_file_path}") with ZipFile(bundle_file_path, mode="x", compression=ZIP_STORED, allowZip64=True) as bundle_zip: # write the metadata file to the bundle archive self.logger.info(f"Adding bundle metadata '{metadata_file_path}' to bundle '{bundle_file_path}'") bundle_zip.write(metadata_file_path, os.path.basename(metadata_file_path)) # until we've finished processing all the Metadata records while not done: # ask the LTA DB for the next chunk of Metadata records self.logger.info(f"GET /Metadata?bundle_uuid={bundle_uuid}&limit={limit}&skip={skip}") lta_response = await lta_rc.request('GET', f'/Metadata?bundle_uuid={bundle_uuid}&limit={limit}&skip={skip}') num_files = len(lta_response["results"]) done = (num_files == 0) skip = skip + num_files self.logger.info(f'LTA returned {num_files} Metadata documents to process.') # for each Metadata record returned by the LTA DB for metadata_record in lta_response["results"]: # load the record from the File Catalog and add the warehouse file to the ZIP archive count = count + 1 file_catalog_uuid = metadata_record["file_catalog_uuid"] fc_response = await fc_rc.request('GET', f'/api/files/{file_catalog_uuid}') bundle_me_path = fc_response["logical_name"] self.logger.info(f"Writing file {count}/{num_files}: '{bundle_me_path}' to bundle '{bundle_file_path}'") zip_path = os.path.relpath(bundle_me_path, request_path) bundle_zip.write(bundle_me_path, zip_path) # do a last minute sanity check on our data if count != file_count: error_message = f'Bad mojo creating bundle archive file. Expected {file_count} Metadata records, but only processed {count} records.' self.logger.error(error_message) raise Exception(error_message)
identifier_body
bundler.py
# bundler.py """Module to implement the Bundler component of the Long Term Archive.""" import asyncio import json import logging import os from pathlib import Path import shutil import sys from typing import Any, Dict, Optional from zipfile import ZIP_STORED, ZipFile from rest_tools.client import ClientCredentialsAuth, RestClient from wipac_dev_tools import from_environment import wipac_telemetry.tracing_tools as wtt from .component import COMMON_CONFIG, Component, now, work_loop from .crypto import lta_checksums from .lta_types import BundleType Logger = logging.Logger LOG = logging.getLogger(__name__) # maximum number of Metadata UUIDs to work with at a time CREATE_CHUNK_SIZE = 1000 EXPECTED_CONFIG = COMMON_CONFIG.copy() EXPECTED_CONFIG.update({ "BUNDLER_OUTBOX_PATH": None, "BUNDLER_WORKBOX_PATH": None, "FILE_CATALOG_CLIENT_ID": None, "FILE_CATALOG_CLIENT_SECRET": None, "FILE_CATALOG_REST_URL": None, "WORK_RETRIES": "3", "WORK_TIMEOUT_SECONDS": "30", }) class Bundler(Component): """ Bundler is a Long Term Archive component. A Bundler is responsible for creating large ZIP64 archives of files that should be moved to long term archive. It requests work from the LTA REST API in the form of files to put into a large archive. It creates the ZIP64 archive and moves the file to staging disk. It then updates the LTA REST API to indicate that the provided files were so bundled. """ def __init__(self, config: Dict[str, str], logger: Logger) -> None: """ Create a Bundler component. config - A dictionary of required configuration values. logger - The object the bundler should use for logging. """ super(Bundler, self).__init__("bundler", config, logger) self.file_catalog_client_id = config["FILE_CATALOG_CLIENT_ID"] self.file_catalog_client_secret = config["FILE_CATALOG_CLIENT_SECRET"] self.file_catalog_rest_url = config["FILE_CATALOG_REST_URL"] self.outbox_path = config["BUNDLER_OUTBOX_PATH"] self.work_retries = int(config["WORK_RETRIES"]) self.work_timeout_seconds = float(config["WORK_TIMEOUT_SECONDS"]) self.workbox_path = config["BUNDLER_WORKBOX_PATH"] def _do_status(self) -> Dict[str, Any]: """Bundler has no additional status to contribute.""" return {} def
(self) -> Dict[str, Optional[str]]: """Bundler provides our expected configuration dictionary.""" return EXPECTED_CONFIG @wtt.spanned() async def _do_work(self) -> None: """Perform a work cycle for this component.""" self.logger.info("Starting work on Bundles.") work_claimed = True while work_claimed: work_claimed = await self._do_work_claim() # if we are configured to run once and die, then die if self.run_once_and_die: sys.exit() self.logger.info("Ending work on Bundles.") @wtt.spanned() async def _do_work_claim(self) -> bool: """Claim a bundle and perform work on it.""" # 1. Ask the LTA DB for the next Bundle to be built # configure a RestClient to talk to the File Catalog fc_rc = ClientCredentialsAuth(address=self.file_catalog_rest_url, token_url=self.lta_auth_openid_url, client_id=self.file_catalog_client_id, client_secret=self.file_catalog_client_secret) # configure a RestClient to talk to the LTA DB lta_rc = ClientCredentialsAuth(address=self.lta_rest_url, token_url=self.lta_auth_openid_url, client_id=self.client_id, client_secret=self.client_secret, timeout=self.work_timeout_seconds, retries=self.work_retries) self.logger.info("Asking the LTA DB for a Bundle to build.") pop_body = { "claimant": f"{self.name}-{self.instance_uuid}" } response = await lta_rc.request('POST', f'/Bundles/actions/pop?source={self.source_site}&dest={self.dest_site}&status={self.input_status}', pop_body) self.logger.info(f"LTA DB responded with: {response}") bundle = response["bundle"] if not bundle: self.logger.info("LTA DB did not provide a Bundle to build. Going on vacation.") return False # process the Bundle that we were given try: await self._do_work_bundle(fc_rc, lta_rc, bundle) except Exception as e: await self._quarantine_bundle(lta_rc, bundle, f"{e}") raise e # signal the work was processed successfully return True @wtt.spanned() async def _do_work_bundle(self, fc_rc: RestClient, lta_rc: RestClient, bundle: BundleType) -> None: # 0. Get our ducks in a row about what we're doing here bundle_uuid = bundle["uuid"] dest = bundle["dest"] file_count = bundle["file_count"] source = bundle["source"] self.logger.info(f"There are {file_count} Files to bundle from '{source}' to '{dest}'.") self.logger.info(f"Bundle archive file will be '{bundle_uuid}.zip'") # 1. Create a manifest of the bundle, including all metadata metadata_file_path = os.path.join(self.workbox_path, f"{bundle_uuid}.metadata.ndjson") await self._create_metadata_file(fc_rc, lta_rc, bundle, metadata_file_path, file_count) # 2. Create a ZIP bundle by writing constituent files to it bundle_file_path = os.path.join(self.workbox_path, f"{bundle_uuid}.zip") await self._create_bundle_archive(fc_rc, lta_rc, bundle, bundle_file_path, metadata_file_path, file_count) # 3. Clean up generated JSON metadata file self.logger.info(f"Deleting bundle metadata file: '{metadata_file_path}'") os.remove(metadata_file_path) self.logger.info(f"Bundle metadata '{metadata_file_path}' was deleted.") # 4. Compute the size of the bundle bundle_size = os.path.getsize(bundle_file_path) self.logger.info(f"Archive bundle has size {bundle_size} bytes") # 5. Compute the LTA checksums for the bundle self.logger.info(f"Computing LTA checksums for bundle: '{bundle_file_path}'") checksum = lta_checksums(bundle_file_path) self.logger.info(f"Bundle '{bundle_file_path}' has adler32 checksum '{checksum['adler32']}'") self.logger.info(f"Bundle '{bundle_file_path}' has SHA512 checksum '{checksum['sha512']}'") # 6. Determine the final destination path of the bundle final_bundle_path = bundle_file_path if self.outbox_path != self.workbox_path: final_bundle_path = os.path.join(self.outbox_path, f"{bundle_uuid}.zip") self.logger.info(f"Finished archive bundle will be located at: '{final_bundle_path}'") # 7. Update the bundle record we have with all the information we collected bundle["status"] = self.output_status bundle["reason"] = "" bundle["update_timestamp"] = now() bundle["bundle_path"] = final_bundle_path bundle["size"] = bundle_size bundle["checksum"] = checksum bundle["verified"] = False bundle["claimed"] = False # 8. Move the bundle from the work box to the outbox if final_bundle_path != bundle_file_path: self.logger.info(f"Moving bundle from '{bundle_file_path}' to '{final_bundle_path}'") shutil.move(bundle_file_path, final_bundle_path) self.logger.info(f"Finished archive bundle now located at: '{final_bundle_path}'") # 9. Update the Bundle record in the LTA DB self.logger.info(f"PATCH /Bundles/{bundle_uuid} - '{bundle}'") await lta_rc.request('PATCH', f'/Bundles/{bundle_uuid}', bundle) @wtt.spanned() async def _create_bundle_archive(self, fc_rc: RestClient, lta_rc: RestClient, bundle: BundleType, bundle_file_path: str, metadata_file_path: str, file_count: int) -> None: # 0. Remove an existing bundle, if we are re-trying Path(bundle_file_path).unlink(missing_ok=True) # 2. Create a ZIP bundle by writing constituent files to it bundle_uuid = bundle["uuid"] request_path = bundle["path"] count = 0 done = False limit = CREATE_CHUNK_SIZE skip = 0 self.logger.info(f"Creating bundle as ZIP archive at: {bundle_file_path}") with ZipFile(bundle_file_path, mode="x", compression=ZIP_STORED, allowZip64=True) as bundle_zip: # write the metadata file to the bundle archive self.logger.info(f"Adding bundle metadata '{metadata_file_path}' to bundle '{bundle_file_path}'") bundle_zip.write(metadata_file_path, os.path.basename(metadata_file_path)) # until we've finished processing all the Metadata records while not done: # ask the LTA DB for the next chunk of Metadata records self.logger.info(f"GET /Metadata?bundle_uuid={bundle_uuid}&limit={limit}&skip={skip}") lta_response = await lta_rc.request('GET', f'/Metadata?bundle_uuid={bundle_uuid}&limit={limit}&skip={skip}') num_files = len(lta_response["results"]) done = (num_files == 0) skip = skip + num_files self.logger.info(f'LTA returned {num_files} Metadata documents to process.') # for each Metadata record returned by the LTA DB for metadata_record in lta_response["results"]: # load the record from the File Catalog and add the warehouse file to the ZIP archive count = count + 1 file_catalog_uuid = metadata_record["file_catalog_uuid"] fc_response = await fc_rc.request('GET', f'/api/files/{file_catalog_uuid}') bundle_me_path = fc_response["logical_name"] self.logger.info(f"Writing file {count}/{num_files}: '{bundle_me_path}' to bundle '{bundle_file_path}'") zip_path = os.path.relpath(bundle_me_path, request_path) bundle_zip.write(bundle_me_path, zip_path) # do a last minute sanity check on our data if count != file_count: error_message = f'Bad mojo creating bundle archive file. Expected {file_count} Metadata records, but only processed {count} records.' self.logger.error(error_message) raise Exception(error_message) @wtt.spanned() async def _create_metadata_file(self, fc_rc: RestClient, lta_rc: RestClient, bundle: BundleType, metadata_file_path: str, file_count: int) -> None: # 0. Remove an existing manifest, if we are re-trying Path(metadata_file_path).unlink(missing_ok=True) # 1. Create a manifest of the bundle, including all metadata bundle_uuid = bundle["uuid"] self.logger.info(f"Bundle metadata file will be created at: {metadata_file_path}") metadata_dict = { "uuid": bundle_uuid, "component": "bundler", "version": 3, "create_timestamp": now(), "file_count": file_count, } # open the metadata file and write our data count = 0 done = False limit = CREATE_CHUNK_SIZE skip = 0 with open(metadata_file_path, mode="w") as metadata_file: self.logger.info(f"Writing metadata_dict to '{metadata_file_path}'") metadata_file.write(json.dumps(metadata_dict)) metadata_file.write("\n") # until we've finished processing all the Metadata records while not done: # ask the LTA DB for the next chunk of Metadata records lta_response = await lta_rc.request('GET', f'/Metadata?bundle_uuid={bundle_uuid}&limit={limit}&skip={skip}') num_files = len(lta_response["results"]) done = (num_files == 0) skip = skip + num_files self.logger.info(f'LTA returned {num_files} Metadata documents to process.') # for each Metadata record returned by the LTA DB for metadata_record in lta_response["results"]: # load the record from the File Catalog and preserve it in carbonite count = count + 1 file_catalog_uuid = metadata_record["file_catalog_uuid"] fc_response = await fc_rc.request('GET', f'/api/files/{file_catalog_uuid}') self.logger.info(f"Writing File Catalog record {file_catalog_uuid} to '{metadata_file_path}'") metadata_file.write(json.dumps(fc_response)) metadata_file.write("\n") # do a last minute sanity check on our data if count != file_count: error_message = f'Bad mojo creating metadata file. Expected {file_count} Metadata records, but only processed {count} records.' self.logger.error(error_message) raise Exception(error_message) @wtt.spanned() async def _quarantine_bundle(self, lta_rc: RestClient, bundle: BundleType, reason: str) -> None: """Quarantine the supplied bundle using the supplied reason.""" self.logger.error(f'Sending Bundle {bundle["uuid"]} to quarantine: {reason}.') right_now = now() patch_body = { "status": "quarantined", "reason": f"BY:{self.name}-{self.instance_uuid} REASON:{reason}", "work_priority_timestamp": right_now, } try: await lta_rc.request('PATCH', f'/Bundles/{bundle["uuid"]}', patch_body) except Exception as e: self.logger.error(f'Unable to quarantine Bundle {bundle["uuid"]}: {e}.') def runner() -> None: """Configure a Bundler component from the environment and set it running.""" # obtain our configuration from the environment config = from_environment(EXPECTED_CONFIG) # configure logging for the application log_level = getattr(logging, str(config["LOG_LEVEL"]).upper()) logging.basicConfig( format="{asctime} [{threadName}] {levelname:5} ({filename}:{lineno}) - {message}", level=log_level, stream=sys.stdout, style="{", ) # create our Bundler service bundler = Bundler(config, LOG) # type: ignore[arg-type] # let's get to work bundler.logger.info("Adding tasks to asyncio loop") loop = asyncio.get_event_loop() loop.create_task(work_loop(bundler)) def main() -> None: """Configure a Bundler component from the environment and set it running.""" runner() asyncio.get_event_loop().run_forever() if __name__ == "__main__": main()
_expected_config
identifier_name
bundler.py
# bundler.py """Module to implement the Bundler component of the Long Term Archive.""" import asyncio import json import logging import os from pathlib import Path import shutil import sys from typing import Any, Dict, Optional from zipfile import ZIP_STORED, ZipFile from rest_tools.client import ClientCredentialsAuth, RestClient from wipac_dev_tools import from_environment import wipac_telemetry.tracing_tools as wtt from .component import COMMON_CONFIG, Component, now, work_loop from .crypto import lta_checksums from .lta_types import BundleType Logger = logging.Logger LOG = logging.getLogger(__name__) # maximum number of Metadata UUIDs to work with at a time CREATE_CHUNK_SIZE = 1000 EXPECTED_CONFIG = COMMON_CONFIG.copy() EXPECTED_CONFIG.update({ "BUNDLER_OUTBOX_PATH": None, "BUNDLER_WORKBOX_PATH": None, "FILE_CATALOG_CLIENT_ID": None, "FILE_CATALOG_CLIENT_SECRET": None, "FILE_CATALOG_REST_URL": None, "WORK_RETRIES": "3", "WORK_TIMEOUT_SECONDS": "30", }) class Bundler(Component): """ Bundler is a Long Term Archive component. A Bundler is responsible for creating large ZIP64 archives of files that should be moved to long term archive. It requests work from the LTA REST API in the form of files to put into a large archive. It creates the ZIP64 archive and moves the file to staging disk. It then updates the LTA REST API to indicate that the provided files were so bundled. """ def __init__(self, config: Dict[str, str], logger: Logger) -> None: """ Create a Bundler component. config - A dictionary of required configuration values. logger - The object the bundler should use for logging. """ super(Bundler, self).__init__("bundler", config, logger) self.file_catalog_client_id = config["FILE_CATALOG_CLIENT_ID"] self.file_catalog_client_secret = config["FILE_CATALOG_CLIENT_SECRET"] self.file_catalog_rest_url = config["FILE_CATALOG_REST_URL"] self.outbox_path = config["BUNDLER_OUTBOX_PATH"] self.work_retries = int(config["WORK_RETRIES"]) self.work_timeout_seconds = float(config["WORK_TIMEOUT_SECONDS"]) self.workbox_path = config["BUNDLER_WORKBOX_PATH"] def _do_status(self) -> Dict[str, Any]: """Bundler has no additional status to contribute.""" return {}
@wtt.spanned() async def _do_work(self) -> None: """Perform a work cycle for this component.""" self.logger.info("Starting work on Bundles.") work_claimed = True while work_claimed: work_claimed = await self._do_work_claim() # if we are configured to run once and die, then die if self.run_once_and_die: sys.exit() self.logger.info("Ending work on Bundles.") @wtt.spanned() async def _do_work_claim(self) -> bool: """Claim a bundle and perform work on it.""" # 1. Ask the LTA DB for the next Bundle to be built # configure a RestClient to talk to the File Catalog fc_rc = ClientCredentialsAuth(address=self.file_catalog_rest_url, token_url=self.lta_auth_openid_url, client_id=self.file_catalog_client_id, client_secret=self.file_catalog_client_secret) # configure a RestClient to talk to the LTA DB lta_rc = ClientCredentialsAuth(address=self.lta_rest_url, token_url=self.lta_auth_openid_url, client_id=self.client_id, client_secret=self.client_secret, timeout=self.work_timeout_seconds, retries=self.work_retries) self.logger.info("Asking the LTA DB for a Bundle to build.") pop_body = { "claimant": f"{self.name}-{self.instance_uuid}" } response = await lta_rc.request('POST', f'/Bundles/actions/pop?source={self.source_site}&dest={self.dest_site}&status={self.input_status}', pop_body) self.logger.info(f"LTA DB responded with: {response}") bundle = response["bundle"] if not bundle: self.logger.info("LTA DB did not provide a Bundle to build. Going on vacation.") return False # process the Bundle that we were given try: await self._do_work_bundle(fc_rc, lta_rc, bundle) except Exception as e: await self._quarantine_bundle(lta_rc, bundle, f"{e}") raise e # signal the work was processed successfully return True @wtt.spanned() async def _do_work_bundle(self, fc_rc: RestClient, lta_rc: RestClient, bundle: BundleType) -> None: # 0. Get our ducks in a row about what we're doing here bundle_uuid = bundle["uuid"] dest = bundle["dest"] file_count = bundle["file_count"] source = bundle["source"] self.logger.info(f"There are {file_count} Files to bundle from '{source}' to '{dest}'.") self.logger.info(f"Bundle archive file will be '{bundle_uuid}.zip'") # 1. Create a manifest of the bundle, including all metadata metadata_file_path = os.path.join(self.workbox_path, f"{bundle_uuid}.metadata.ndjson") await self._create_metadata_file(fc_rc, lta_rc, bundle, metadata_file_path, file_count) # 2. Create a ZIP bundle by writing constituent files to it bundle_file_path = os.path.join(self.workbox_path, f"{bundle_uuid}.zip") await self._create_bundle_archive(fc_rc, lta_rc, bundle, bundle_file_path, metadata_file_path, file_count) # 3. Clean up generated JSON metadata file self.logger.info(f"Deleting bundle metadata file: '{metadata_file_path}'") os.remove(metadata_file_path) self.logger.info(f"Bundle metadata '{metadata_file_path}' was deleted.") # 4. Compute the size of the bundle bundle_size = os.path.getsize(bundle_file_path) self.logger.info(f"Archive bundle has size {bundle_size} bytes") # 5. Compute the LTA checksums for the bundle self.logger.info(f"Computing LTA checksums for bundle: '{bundle_file_path}'") checksum = lta_checksums(bundle_file_path) self.logger.info(f"Bundle '{bundle_file_path}' has adler32 checksum '{checksum['adler32']}'") self.logger.info(f"Bundle '{bundle_file_path}' has SHA512 checksum '{checksum['sha512']}'") # 6. Determine the final destination path of the bundle final_bundle_path = bundle_file_path if self.outbox_path != self.workbox_path: final_bundle_path = os.path.join(self.outbox_path, f"{bundle_uuid}.zip") self.logger.info(f"Finished archive bundle will be located at: '{final_bundle_path}'") # 7. Update the bundle record we have with all the information we collected bundle["status"] = self.output_status bundle["reason"] = "" bundle["update_timestamp"] = now() bundle["bundle_path"] = final_bundle_path bundle["size"] = bundle_size bundle["checksum"] = checksum bundle["verified"] = False bundle["claimed"] = False # 8. Move the bundle from the work box to the outbox if final_bundle_path != bundle_file_path: self.logger.info(f"Moving bundle from '{bundle_file_path}' to '{final_bundle_path}'") shutil.move(bundle_file_path, final_bundle_path) self.logger.info(f"Finished archive bundle now located at: '{final_bundle_path}'") # 9. Update the Bundle record in the LTA DB self.logger.info(f"PATCH /Bundles/{bundle_uuid} - '{bundle}'") await lta_rc.request('PATCH', f'/Bundles/{bundle_uuid}', bundle) @wtt.spanned() async def _create_bundle_archive(self, fc_rc: RestClient, lta_rc: RestClient, bundle: BundleType, bundle_file_path: str, metadata_file_path: str, file_count: int) -> None: # 0. Remove an existing bundle, if we are re-trying Path(bundle_file_path).unlink(missing_ok=True) # 2. Create a ZIP bundle by writing constituent files to it bundle_uuid = bundle["uuid"] request_path = bundle["path"] count = 0 done = False limit = CREATE_CHUNK_SIZE skip = 0 self.logger.info(f"Creating bundle as ZIP archive at: {bundle_file_path}") with ZipFile(bundle_file_path, mode="x", compression=ZIP_STORED, allowZip64=True) as bundle_zip: # write the metadata file to the bundle archive self.logger.info(f"Adding bundle metadata '{metadata_file_path}' to bundle '{bundle_file_path}'") bundle_zip.write(metadata_file_path, os.path.basename(metadata_file_path)) # until we've finished processing all the Metadata records while not done: # ask the LTA DB for the next chunk of Metadata records self.logger.info(f"GET /Metadata?bundle_uuid={bundle_uuid}&limit={limit}&skip={skip}") lta_response = await lta_rc.request('GET', f'/Metadata?bundle_uuid={bundle_uuid}&limit={limit}&skip={skip}') num_files = len(lta_response["results"]) done = (num_files == 0) skip = skip + num_files self.logger.info(f'LTA returned {num_files} Metadata documents to process.') # for each Metadata record returned by the LTA DB for metadata_record in lta_response["results"]: # load the record from the File Catalog and add the warehouse file to the ZIP archive count = count + 1 file_catalog_uuid = metadata_record["file_catalog_uuid"] fc_response = await fc_rc.request('GET', f'/api/files/{file_catalog_uuid}') bundle_me_path = fc_response["logical_name"] self.logger.info(f"Writing file {count}/{num_files}: '{bundle_me_path}' to bundle '{bundle_file_path}'") zip_path = os.path.relpath(bundle_me_path, request_path) bundle_zip.write(bundle_me_path, zip_path) # do a last minute sanity check on our data if count != file_count: error_message = f'Bad mojo creating bundle archive file. Expected {file_count} Metadata records, but only processed {count} records.' self.logger.error(error_message) raise Exception(error_message) @wtt.spanned() async def _create_metadata_file(self, fc_rc: RestClient, lta_rc: RestClient, bundle: BundleType, metadata_file_path: str, file_count: int) -> None: # 0. Remove an existing manifest, if we are re-trying Path(metadata_file_path).unlink(missing_ok=True) # 1. Create a manifest of the bundle, including all metadata bundle_uuid = bundle["uuid"] self.logger.info(f"Bundle metadata file will be created at: {metadata_file_path}") metadata_dict = { "uuid": bundle_uuid, "component": "bundler", "version": 3, "create_timestamp": now(), "file_count": file_count, } # open the metadata file and write our data count = 0 done = False limit = CREATE_CHUNK_SIZE skip = 0 with open(metadata_file_path, mode="w") as metadata_file: self.logger.info(f"Writing metadata_dict to '{metadata_file_path}'") metadata_file.write(json.dumps(metadata_dict)) metadata_file.write("\n") # until we've finished processing all the Metadata records while not done: # ask the LTA DB for the next chunk of Metadata records lta_response = await lta_rc.request('GET', f'/Metadata?bundle_uuid={bundle_uuid}&limit={limit}&skip={skip}') num_files = len(lta_response["results"]) done = (num_files == 0) skip = skip + num_files self.logger.info(f'LTA returned {num_files} Metadata documents to process.') # for each Metadata record returned by the LTA DB for metadata_record in lta_response["results"]: # load the record from the File Catalog and preserve it in carbonite count = count + 1 file_catalog_uuid = metadata_record["file_catalog_uuid"] fc_response = await fc_rc.request('GET', f'/api/files/{file_catalog_uuid}') self.logger.info(f"Writing File Catalog record {file_catalog_uuid} to '{metadata_file_path}'") metadata_file.write(json.dumps(fc_response)) metadata_file.write("\n") # do a last minute sanity check on our data if count != file_count: error_message = f'Bad mojo creating metadata file. Expected {file_count} Metadata records, but only processed {count} records.' self.logger.error(error_message) raise Exception(error_message) @wtt.spanned() async def _quarantine_bundle(self, lta_rc: RestClient, bundle: BundleType, reason: str) -> None: """Quarantine the supplied bundle using the supplied reason.""" self.logger.error(f'Sending Bundle {bundle["uuid"]} to quarantine: {reason}.') right_now = now() patch_body = { "status": "quarantined", "reason": f"BY:{self.name}-{self.instance_uuid} REASON:{reason}", "work_priority_timestamp": right_now, } try: await lta_rc.request('PATCH', f'/Bundles/{bundle["uuid"]}', patch_body) except Exception as e: self.logger.error(f'Unable to quarantine Bundle {bundle["uuid"]}: {e}.') def runner() -> None: """Configure a Bundler component from the environment and set it running.""" # obtain our configuration from the environment config = from_environment(EXPECTED_CONFIG) # configure logging for the application log_level = getattr(logging, str(config["LOG_LEVEL"]).upper()) logging.basicConfig( format="{asctime} [{threadName}] {levelname:5} ({filename}:{lineno}) - {message}", level=log_level, stream=sys.stdout, style="{", ) # create our Bundler service bundler = Bundler(config, LOG) # type: ignore[arg-type] # let's get to work bundler.logger.info("Adding tasks to asyncio loop") loop = asyncio.get_event_loop() loop.create_task(work_loop(bundler)) def main() -> None: """Configure a Bundler component from the environment and set it running.""" runner() asyncio.get_event_loop().run_forever() if __name__ == "__main__": main()
def _expected_config(self) -> Dict[str, Optional[str]]: """Bundler provides our expected configuration dictionary.""" return EXPECTED_CONFIG
random_line_split
lib.rs
//! A Rust wrapper around [Zathura's] plugin API, allowing plugin development in //! Rust. //! //! This library wraps the plugin interface and exposes the [`ZathuraPlugin`] //! trait and the [`plugin_entry!`] macro as the primary way to implement a Rust //! plugin for Zathura. //! //! # Examples //! //! ``` //! # use zathura_plugin::*; //! struct PluginType {} //! //! impl ZathuraPlugin for PluginType { //! type DocumentData = (); //! type PageData = (); //! //! fn document_open(doc: DocumentRef<'_>) -> Result<DocumentInfo<Self>, PluginError> { //! unimplemented!() //! } //! //! fn page_init(page: PageRef<'_>, doc_data: &mut ()) -> Result<PageInfo<Self>, PluginError> { //! unimplemented!() //! } //! //! fn page_render( //! page: PageRef<'_>, //! doc_data: &mut Self::DocumentData, //! page_data: &mut Self::PageData, //! cairo: &mut cairo::Context, //! printing: bool, //! ) -> Result<(), PluginError> { //! unimplemented!() //! } //! } //! //! plugin_entry!("MyPlugin", PluginType, ["text/plain", "application/pdf"]); //! ``` //! //! [Zathura's]: https://pwmt.org/projects/zathura/ //! [`ZathuraPlugin`]: trait.ZathuraPlugin.html //! [`plugin_entry!`]: macro.plugin_entry.html #![doc(html_root_url = "https://docs.rs/zathura-plugin/0.4.0")] #![warn(missing_debug_implementations, rust_2018_idioms)] mod document; mod error; mod page; pub use { self::{document::*, error::*, page::*}, zathura_plugin_sys as sys, }; // Used by the macro #[doc(hidden)] pub use pkg_version::{pkg_version_major, pkg_version_minor, pkg_version_patch}; /// Information needed to configure a Zathura document. #[derive(Debug)] pub struct DocumentInfo<P: ZathuraPlugin + ?Sized> { /// Number of pages to create in the document. pub page_count: u32, /// Plugin-specific data to attach to the document. pub plugin_data: P::DocumentData, } /// Information needed to configure a document page. #[derive(Debug)] pub struct PageInfo<P: ZathuraPlugin + ?Sized> { pub width: f64, pub height: f64, pub plugin_data: P::PageData, } /// Trait to be implemented by Zathura plugins. pub trait ZathuraPlugin { /// Plugin-specific data attached to Zathura documents. /// /// If the plugin doesn't need to associate custom data with the document, /// this can be set to `()`. type DocumentData; /// Plugin-specific data attached to every document page. /// /// If the plugin doesn't need to associate custom data with every page, /// this can be set to `()`. type PageData; /// Open a document and read its metadata. /// /// This function has to determine and return the number of pages in the /// document. Zathura will create that number of pages and call the plugin's /// page initialization and rendering methods. fn document_open(doc: DocumentRef<'_>) -> Result<DocumentInfo<Self>, PluginError>; /// Additional hook called before freeing the document resources. /// /// It is not necessary for plugins to implement this. The library will take /// care of freeing the `DocumentData` attached to the document, and Zathura /// itself will free the actual document. fn document_free( doc: DocumentRef<'_>, doc_data: &mut Self::DocumentData, ) -> Result<(), PluginError> { let _ = (doc, doc_data); Ok(()) } /// Initialize a document page and obtain its properties. /// /// This is called once per page when the document is loaded initially. /// /// The plugin has to return a `PageInfo` structure containing page /// properties that will be applied by the library. fn page_init( page: PageRef<'_>, doc_data: &mut Self::DocumentData, ) -> Result<PageInfo<Self>, PluginError>; /// Additional hook called before freeing page resources. /// /// This doesn't have to be implemented by a plugin. The library already /// takes care of freeing the `PageData` associated with the page, and /// Zathura will free the page itself. fn page_free( page: PageRef<'_>, doc_data: &mut Self::DocumentData, page_data: &mut Self::PageData, ) -> Result<(), PluginError> { let _ = (page, doc_data, page_data); Ok(()) } /// Render a document page to a Cairo context. /// /// # Parameters /// /// * **`page`**: Mutable reference to the page to render. /// * **`doc_data`**: Plugin-specific data attached to the document. /// * **`page_data`**: Plugin-specific data attached to the page. /// * **`cairo`**: The Cairo context to render to. /// * **`printing`**: Whether the page is being rendered for printing /// (`true`) or viewing (`false`). fn page_render( page: PageRef<'_>, doc_data: &mut Self::DocumentData, page_data: &mut Self::PageData, cairo: &mut cairo::Context, printing: bool, ) -> Result<(), PluginError>; } /// `extern "C"` functions wrapping the Rust `ZathuraPlugin` functions. /// /// This is not public API and is only intended to be used by the /// `plugin_entry!` macro. #[doc(hidden)] pub mod wrapper { use { crate::{sys::*, *}, cairo, std::{ ffi::c_void, panic::{catch_unwind, AssertUnwindSafe}, }, }; trait ResultExt { fn to_zathura(self) -> zathura_error_t; } impl ResultExt for Result<(), PluginError> { fn to_zathura(self) -> zathura_error_t { match self { Ok(()) => 0, Err(e) => e as zathura_error_t, } } } fn wrap(f: impl FnOnce() -> Result<(), PluginError>) -> Result<(), PluginError> { match catch_unwind(AssertUnwindSafe(f)) { Ok(r) => r, Err(_) => Err(PluginError::Unknown), } } /// Open a document and set the number of pages to create in `document`. pub unsafe extern "C" fn document_open<P: ZathuraPlugin>( document: *mut zathura_document_t, ) -> zathura_error_t { wrap(|| { let doc = DocumentRef::from_raw(document); let info = P::document_open(doc)?; let mut doc = DocumentRef::from_raw(document); doc.set_plugin_data(Box::into_raw(Box::new(info.plugin_data)) as *mut _); doc.set_page_count(info.page_count); Ok(()) }) .to_zathura() } /// Free plugin-specific data in `document`. /// /// This is called by `zathura_document_free` and thus must not attempt to /// free the document again. pub unsafe extern "C" fn
<P: ZathuraPlugin>( document: *mut zathura_document_t, _data: *mut c_void, ) -> zathura_error_t { wrap(|| { let doc = DocumentRef::from_raw(document); let doc_data = &mut *(doc.plugin_data() as *mut P::DocumentData); let result = P::document_free(doc, doc_data); let doc = DocumentRef::from_raw(document); let plugin_data = doc.plugin_data() as *mut P::DocumentData; drop(Box::from_raw(plugin_data)); result }) .to_zathura() } /// Initialize a page and set its dimensions. /// /// If the page size is not set, rendering on it has no effect and the page /// appears invisible. pub unsafe extern "C" fn page_init<P: ZathuraPlugin>( page: *mut zathura_page_t, ) -> zathura_error_t { wrap(|| { let mut p = PageRef::from_raw(page); // Obtaining the document data is safe, since there is no other way to get access to it // while this function executes. let doc_data = p.document().plugin_data() as *mut P::DocumentData; let info = P::page_init(p, &mut *doc_data)?; let mut p = PageRef::from_raw(page); p.set_width(info.width); p.set_height(info.height); p.set_plugin_data(Box::into_raw(Box::new(info.plugin_data)) as *mut _); Ok(()) }) .to_zathura() } /// Deallocate plugin-specific page data. /// /// If this function is missing, the *document* will not be freed. pub unsafe extern "C" fn page_clear<P: ZathuraPlugin>( page: *mut zathura_page_t, _data: *mut c_void, ) -> zathura_error_t { wrap(|| { let result = { let mut p = PageRef::from_raw(page); let doc_data = &mut *(p.document().plugin_data() as *mut P::DocumentData); let page_data = &mut *(p.plugin_data() as *mut P::PageData); P::page_free(p, doc_data, page_data) }; // Free the `PageData` let p = PageRef::from_raw(page); let plugin_data = p.plugin_data() as *mut P::PageData; drop(Box::from_raw(plugin_data)); result }) .to_zathura() } /// Render a page to a Cairo context. pub unsafe extern "C" fn page_render_cairo<P: ZathuraPlugin>( page: *mut zathura_page_t, _data: *mut c_void, cairo: *mut sys::cairo_t, printing: bool, ) -> zathura_error_t { wrap(|| { let mut p = PageRef::from_raw(page); let page_data = &mut *(p.plugin_data() as *mut P::PageData); let doc_data = &mut *(p.document().plugin_data() as *mut P::DocumentData); let mut cairo = cairo::Context::from_raw_borrow(cairo as *mut _); P::page_render(p, doc_data, page_data, &mut cairo, printing) }) .to_zathura() } } /// Declares this library as a Zathura plugin. /// /// A crate can only provide one Zathura plugin, so this macro may only be /// called once per crate. /// /// For this to work, this crate must be built as a `cdylib` and the result put /// somewhere Zathura can find it. An easy way to iterate on a plugin is running /// this in the workspace root after any changes: /// /// ```notrust /// cargo build && zathura -p target/debug/ <file> /// ``` /// /// # Examples /// /// For a usage example of this macro, refer to the crate-level docs. #[macro_export] macro_rules! plugin_entry { ( $name:literal, $plugin_ty:ty, [ $($mime:literal),+ $(,)? ] ) => { #[doc(hidden)] #[repr(transparent)] #[allow(warnings)] pub struct __AssertSync<T>(T); unsafe impl<T> Sync for __AssertSync<T> {} #[doc(hidden)] #[no_mangle] pub static mut zathura_plugin_3_4: /* API=3, ABI=4 */ __AssertSync<$crate::sys::zathura_plugin_definition_t> = __AssertSync({ use $crate::sys::*; use $crate::wrapper::*; zathura_plugin_definition_t { name: concat!($name, "\0").as_ptr() as *const _, version: zathura_plugin_version_t { major: $crate::pkg_version_major!(), minor: $crate::pkg_version_minor!(), rev: $crate::pkg_version_patch!(), }, mime_types_size: { // Sum up as many 1s as there are entries in `$mime`. The // `$mime;` tells the compiler which syntax variable to // iterate over; it is disposed with no effect. 0 $(+ { $mime; 1 })+ }, mime_types: [ $( concat!($mime, "\0").as_ptr() as *const _, )+ ].as_ptr() as *mut _, // assuming Zathura never mutates this functions: zathura_plugin_functions_t { document_open: Some(document_open::<$plugin_ty>), document_free: Some(document_free::<$plugin_ty>), document_index_generate: None, document_save_as: None, document_attachments_get: None, document_attachment_save: None, document_get_information: None, page_init: Some(page_init::<$plugin_ty>), page_clear: Some(page_clear::<$plugin_ty>), page_search_text: None, page_links_get: None, page_form_fields_get: None, page_images_get: None, page_image_get_cairo: None, page_get_text: None, page_render: None, // no longer used? page_render_cairo: Some(page_render_cairo::<$plugin_ty>), page_get_label: None, }, } }); }; } #[cfg(feature = "testplugin")] struct TestPlugin; #[cfg(feature = "testplugin")] impl ZathuraPlugin for TestPlugin { type DocumentData = (); type PageData = (); fn document_open(doc: DocumentRef<'_>) -> Result<DocumentInfo<Self>, PluginError> { println!("open: {:?}", doc.basename_utf8()); println!("path: {:?}", doc.path_utf8()); println!("url: {:?}", doc.uri_utf8()); println!("{} pages", doc.page_count()); Ok(DocumentInfo { page_count: 5, plugin_data: (), }) } fn document_free(doc: DocumentRef<'_>, _doc_data: &mut ()) -> Result<(), PluginError> { println!("free! {:?}", doc); Ok(()) } fn page_init(page: PageRef<'_>, _doc_data: &mut ()) -> Result<PageInfo<Self>, PluginError> { println!("page init: {:?}", page); Ok(PageInfo { width: 75.0, height: 100.0, plugin_data: (), }) } fn page_free( page: PageRef<'_>, _doc_data: &mut (), _page_data: &mut (), ) -> Result<(), PluginError> { println!("page free: {:?}", page); Ok(()) } fn page_render( mut page: PageRef<'_>, _doc_data: &mut Self::DocumentData, _page_data: &mut Self::PageData, cairo: &mut cairo::Context, printing: bool, ) -> Result<(), PluginError> { println!( "render! {:?}, index={:?}, {}x{}, {:?}", page, page.index(), page.width(), page.height(), printing ); { let doc = page.document(); println!( "doc: zoom={}, scale={}, rotation={}°, ppi={}, scale={:?}, cell-size={:?}", doc.zoom(), doc.scale(), doc.rotation(), doc.viewport_ppi(), doc.scaling_factors(), doc.cell_size(), ); } println!( "cairo: scale={:?}, 50,50={:?}", cairo.get_target().get_device_scale(), cairo.user_to_device(50.0, 50.0), ); if page.index() == 0 { cairo.move_to(10.0, 10.0); cairo.show_text("Wello!"); cairo.set_source_rgb(0.0, 1.0, 1.0); cairo.set_line_width(1.0); cairo.move_to(0.0, 0.0); cairo.line_to(10.5, 50.5); cairo.stroke(); } Ok(()) } } #[cfg(feature = "testplugin")] plugin_entry!("TestPlugin", TestPlugin, ["text/plain"]);
document_free
identifier_name
lib.rs
//! A Rust wrapper around [Zathura's] plugin API, allowing plugin development in //! Rust. //! //! This library wraps the plugin interface and exposes the [`ZathuraPlugin`] //! trait and the [`plugin_entry!`] macro as the primary way to implement a Rust //! plugin for Zathura. //! //! # Examples //! //! ``` //! # use zathura_plugin::*; //! struct PluginType {} //! //! impl ZathuraPlugin for PluginType { //! type DocumentData = (); //! type PageData = (); //! //! fn document_open(doc: DocumentRef<'_>) -> Result<DocumentInfo<Self>, PluginError> { //! unimplemented!() //! } //! //! fn page_init(page: PageRef<'_>, doc_data: &mut ()) -> Result<PageInfo<Self>, PluginError> { //! unimplemented!() //! } //! //! fn page_render( //! page: PageRef<'_>, //! doc_data: &mut Self::DocumentData, //! page_data: &mut Self::PageData, //! cairo: &mut cairo::Context, //! printing: bool, //! ) -> Result<(), PluginError> { //! unimplemented!() //! } //! } //! //! plugin_entry!("MyPlugin", PluginType, ["text/plain", "application/pdf"]); //! ``` //! //! [Zathura's]: https://pwmt.org/projects/zathura/ //! [`ZathuraPlugin`]: trait.ZathuraPlugin.html //! [`plugin_entry!`]: macro.plugin_entry.html #![doc(html_root_url = "https://docs.rs/zathura-plugin/0.4.0")] #![warn(missing_debug_implementations, rust_2018_idioms)] mod document; mod error; mod page; pub use { self::{document::*, error::*, page::*}, zathura_plugin_sys as sys, }; // Used by the macro #[doc(hidden)] pub use pkg_version::{pkg_version_major, pkg_version_minor, pkg_version_patch}; /// Information needed to configure a Zathura document. #[derive(Debug)] pub struct DocumentInfo<P: ZathuraPlugin + ?Sized> { /// Number of pages to create in the document. pub page_count: u32, /// Plugin-specific data to attach to the document. pub plugin_data: P::DocumentData, } /// Information needed to configure a document page. #[derive(Debug)] pub struct PageInfo<P: ZathuraPlugin + ?Sized> { pub width: f64, pub height: f64, pub plugin_data: P::PageData, } /// Trait to be implemented by Zathura plugins. pub trait ZathuraPlugin { /// Plugin-specific data attached to Zathura documents. /// /// If the plugin doesn't need to associate custom data with the document, /// this can be set to `()`. type DocumentData; /// Plugin-specific data attached to every document page. /// /// If the plugin doesn't need to associate custom data with every page, /// this can be set to `()`. type PageData; /// Open a document and read its metadata. /// /// This function has to determine and return the number of pages in the /// document. Zathura will create that number of pages and call the plugin's /// page initialization and rendering methods. fn document_open(doc: DocumentRef<'_>) -> Result<DocumentInfo<Self>, PluginError>; /// Additional hook called before freeing the document resources. /// /// It is not necessary for plugins to implement this. The library will take /// care of freeing the `DocumentData` attached to the document, and Zathura /// itself will free the actual document. fn document_free( doc: DocumentRef<'_>, doc_data: &mut Self::DocumentData, ) -> Result<(), PluginError> { let _ = (doc, doc_data); Ok(()) } /// Initialize a document page and obtain its properties. /// /// This is called once per page when the document is loaded initially. /// /// The plugin has to return a `PageInfo` structure containing page /// properties that will be applied by the library. fn page_init( page: PageRef<'_>, doc_data: &mut Self::DocumentData, ) -> Result<PageInfo<Self>, PluginError>; /// Additional hook called before freeing page resources. /// /// This doesn't have to be implemented by a plugin. The library already /// takes care of freeing the `PageData` associated with the page, and /// Zathura will free the page itself. fn page_free( page: PageRef<'_>, doc_data: &mut Self::DocumentData, page_data: &mut Self::PageData, ) -> Result<(), PluginError> { let _ = (page, doc_data, page_data); Ok(()) } /// Render a document page to a Cairo context. /// /// # Parameters /// /// * **`page`**: Mutable reference to the page to render. /// * **`doc_data`**: Plugin-specific data attached to the document. /// * **`page_data`**: Plugin-specific data attached to the page. /// * **`cairo`**: The Cairo context to render to. /// * **`printing`**: Whether the page is being rendered for printing /// (`true`) or viewing (`false`). fn page_render( page: PageRef<'_>, doc_data: &mut Self::DocumentData, page_data: &mut Self::PageData, cairo: &mut cairo::Context, printing: bool, ) -> Result<(), PluginError>; } /// `extern "C"` functions wrapping the Rust `ZathuraPlugin` functions. /// /// This is not public API and is only intended to be used by the /// `plugin_entry!` macro. #[doc(hidden)] pub mod wrapper { use { crate::{sys::*, *}, cairo, std::{ ffi::c_void, panic::{catch_unwind, AssertUnwindSafe}, }, }; trait ResultExt { fn to_zathura(self) -> zathura_error_t; } impl ResultExt for Result<(), PluginError> { fn to_zathura(self) -> zathura_error_t { match self { Ok(()) => 0, Err(e) => e as zathura_error_t, } } } fn wrap(f: impl FnOnce() -> Result<(), PluginError>) -> Result<(), PluginError> { match catch_unwind(AssertUnwindSafe(f)) { Ok(r) => r, Err(_) => Err(PluginError::Unknown), } } /// Open a document and set the number of pages to create in `document`. pub unsafe extern "C" fn document_open<P: ZathuraPlugin>( document: *mut zathura_document_t, ) -> zathura_error_t { wrap(|| { let doc = DocumentRef::from_raw(document); let info = P::document_open(doc)?; let mut doc = DocumentRef::from_raw(document); doc.set_plugin_data(Box::into_raw(Box::new(info.plugin_data)) as *mut _); doc.set_page_count(info.page_count); Ok(()) }) .to_zathura() } /// Free plugin-specific data in `document`. /// /// This is called by `zathura_document_free` and thus must not attempt to /// free the document again. pub unsafe extern "C" fn document_free<P: ZathuraPlugin>( document: *mut zathura_document_t, _data: *mut c_void, ) -> zathura_error_t { wrap(|| { let doc = DocumentRef::from_raw(document); let doc_data = &mut *(doc.plugin_data() as *mut P::DocumentData); let result = P::document_free(doc, doc_data); let doc = DocumentRef::from_raw(document); let plugin_data = doc.plugin_data() as *mut P::DocumentData; drop(Box::from_raw(plugin_data)); result }) .to_zathura() } /// Initialize a page and set its dimensions. /// /// If the page size is not set, rendering on it has no effect and the page /// appears invisible. pub unsafe extern "C" fn page_init<P: ZathuraPlugin>( page: *mut zathura_page_t, ) -> zathura_error_t { wrap(|| { let mut p = PageRef::from_raw(page); // Obtaining the document data is safe, since there is no other way to get access to it // while this function executes. let doc_data = p.document().plugin_data() as *mut P::DocumentData; let info = P::page_init(p, &mut *doc_data)?; let mut p = PageRef::from_raw(page); p.set_width(info.width); p.set_height(info.height); p.set_plugin_data(Box::into_raw(Box::new(info.plugin_data)) as *mut _); Ok(()) }) .to_zathura() } /// Deallocate plugin-specific page data. /// /// If this function is missing, the *document* will not be freed. pub unsafe extern "C" fn page_clear<P: ZathuraPlugin>( page: *mut zathura_page_t, _data: *mut c_void, ) -> zathura_error_t
/// Render a page to a Cairo context. pub unsafe extern "C" fn page_render_cairo<P: ZathuraPlugin>( page: *mut zathura_page_t, _data: *mut c_void, cairo: *mut sys::cairo_t, printing: bool, ) -> zathura_error_t { wrap(|| { let mut p = PageRef::from_raw(page); let page_data = &mut *(p.plugin_data() as *mut P::PageData); let doc_data = &mut *(p.document().plugin_data() as *mut P::DocumentData); let mut cairo = cairo::Context::from_raw_borrow(cairo as *mut _); P::page_render(p, doc_data, page_data, &mut cairo, printing) }) .to_zathura() } } /// Declares this library as a Zathura plugin. /// /// A crate can only provide one Zathura plugin, so this macro may only be /// called once per crate. /// /// For this to work, this crate must be built as a `cdylib` and the result put /// somewhere Zathura can find it. An easy way to iterate on a plugin is running /// this in the workspace root after any changes: /// /// ```notrust /// cargo build && zathura -p target/debug/ <file> /// ``` /// /// # Examples /// /// For a usage example of this macro, refer to the crate-level docs. #[macro_export] macro_rules! plugin_entry { ( $name:literal, $plugin_ty:ty, [ $($mime:literal),+ $(,)? ] ) => { #[doc(hidden)] #[repr(transparent)] #[allow(warnings)] pub struct __AssertSync<T>(T); unsafe impl<T> Sync for __AssertSync<T> {} #[doc(hidden)] #[no_mangle] pub static mut zathura_plugin_3_4: /* API=3, ABI=4 */ __AssertSync<$crate::sys::zathura_plugin_definition_t> = __AssertSync({ use $crate::sys::*; use $crate::wrapper::*; zathura_plugin_definition_t { name: concat!($name, "\0").as_ptr() as *const _, version: zathura_plugin_version_t { major: $crate::pkg_version_major!(), minor: $crate::pkg_version_minor!(), rev: $crate::pkg_version_patch!(), }, mime_types_size: { // Sum up as many 1s as there are entries in `$mime`. The // `$mime;` tells the compiler which syntax variable to // iterate over; it is disposed with no effect. 0 $(+ { $mime; 1 })+ }, mime_types: [ $( concat!($mime, "\0").as_ptr() as *const _, )+ ].as_ptr() as *mut _, // assuming Zathura never mutates this functions: zathura_plugin_functions_t { document_open: Some(document_open::<$plugin_ty>), document_free: Some(document_free::<$plugin_ty>), document_index_generate: None, document_save_as: None, document_attachments_get: None, document_attachment_save: None, document_get_information: None, page_init: Some(page_init::<$plugin_ty>), page_clear: Some(page_clear::<$plugin_ty>), page_search_text: None, page_links_get: None, page_form_fields_get: None, page_images_get: None, page_image_get_cairo: None, page_get_text: None, page_render: None, // no longer used? page_render_cairo: Some(page_render_cairo::<$plugin_ty>), page_get_label: None, }, } }); }; } #[cfg(feature = "testplugin")] struct TestPlugin; #[cfg(feature = "testplugin")] impl ZathuraPlugin for TestPlugin { type DocumentData = (); type PageData = (); fn document_open(doc: DocumentRef<'_>) -> Result<DocumentInfo<Self>, PluginError> { println!("open: {:?}", doc.basename_utf8()); println!("path: {:?}", doc.path_utf8()); println!("url: {:?}", doc.uri_utf8()); println!("{} pages", doc.page_count()); Ok(DocumentInfo { page_count: 5, plugin_data: (), }) } fn document_free(doc: DocumentRef<'_>, _doc_data: &mut ()) -> Result<(), PluginError> { println!("free! {:?}", doc); Ok(()) } fn page_init(page: PageRef<'_>, _doc_data: &mut ()) -> Result<PageInfo<Self>, PluginError> { println!("page init: {:?}", page); Ok(PageInfo { width: 75.0, height: 100.0, plugin_data: (), }) } fn page_free( page: PageRef<'_>, _doc_data: &mut (), _page_data: &mut (), ) -> Result<(), PluginError> { println!("page free: {:?}", page); Ok(()) } fn page_render( mut page: PageRef<'_>, _doc_data: &mut Self::DocumentData, _page_data: &mut Self::PageData, cairo: &mut cairo::Context, printing: bool, ) -> Result<(), PluginError> { println!( "render! {:?}, index={:?}, {}x{}, {:?}", page, page.index(), page.width(), page.height(), printing ); { let doc = page.document(); println!( "doc: zoom={}, scale={}, rotation={}°, ppi={}, scale={:?}, cell-size={:?}", doc.zoom(), doc.scale(), doc.rotation(), doc.viewport_ppi(), doc.scaling_factors(), doc.cell_size(), ); } println!( "cairo: scale={:?}, 50,50={:?}", cairo.get_target().get_device_scale(), cairo.user_to_device(50.0, 50.0), ); if page.index() == 0 { cairo.move_to(10.0, 10.0); cairo.show_text("Wello!"); cairo.set_source_rgb(0.0, 1.0, 1.0); cairo.set_line_width(1.0); cairo.move_to(0.0, 0.0); cairo.line_to(10.5, 50.5); cairo.stroke(); } Ok(()) } } #[cfg(feature = "testplugin")] plugin_entry!("TestPlugin", TestPlugin, ["text/plain"]);
{ wrap(|| { let result = { let mut p = PageRef::from_raw(page); let doc_data = &mut *(p.document().plugin_data() as *mut P::DocumentData); let page_data = &mut *(p.plugin_data() as *mut P::PageData); P::page_free(p, doc_data, page_data) }; // Free the `PageData` let p = PageRef::from_raw(page); let plugin_data = p.plugin_data() as *mut P::PageData; drop(Box::from_raw(plugin_data)); result }) .to_zathura() }
identifier_body
lib.rs
//! A Rust wrapper around [Zathura's] plugin API, allowing plugin development in //! Rust. //! //! This library wraps the plugin interface and exposes the [`ZathuraPlugin`] //! trait and the [`plugin_entry!`] macro as the primary way to implement a Rust //! plugin for Zathura.
//! # use zathura_plugin::*; //! struct PluginType {} //! //! impl ZathuraPlugin for PluginType { //! type DocumentData = (); //! type PageData = (); //! //! fn document_open(doc: DocumentRef<'_>) -> Result<DocumentInfo<Self>, PluginError> { //! unimplemented!() //! } //! //! fn page_init(page: PageRef<'_>, doc_data: &mut ()) -> Result<PageInfo<Self>, PluginError> { //! unimplemented!() //! } //! //! fn page_render( //! page: PageRef<'_>, //! doc_data: &mut Self::DocumentData, //! page_data: &mut Self::PageData, //! cairo: &mut cairo::Context, //! printing: bool, //! ) -> Result<(), PluginError> { //! unimplemented!() //! } //! } //! //! plugin_entry!("MyPlugin", PluginType, ["text/plain", "application/pdf"]); //! ``` //! //! [Zathura's]: https://pwmt.org/projects/zathura/ //! [`ZathuraPlugin`]: trait.ZathuraPlugin.html //! [`plugin_entry!`]: macro.plugin_entry.html #![doc(html_root_url = "https://docs.rs/zathura-plugin/0.4.0")] #![warn(missing_debug_implementations, rust_2018_idioms)] mod document; mod error; mod page; pub use { self::{document::*, error::*, page::*}, zathura_plugin_sys as sys, }; // Used by the macro #[doc(hidden)] pub use pkg_version::{pkg_version_major, pkg_version_minor, pkg_version_patch}; /// Information needed to configure a Zathura document. #[derive(Debug)] pub struct DocumentInfo<P: ZathuraPlugin + ?Sized> { /// Number of pages to create in the document. pub page_count: u32, /// Plugin-specific data to attach to the document. pub plugin_data: P::DocumentData, } /// Information needed to configure a document page. #[derive(Debug)] pub struct PageInfo<P: ZathuraPlugin + ?Sized> { pub width: f64, pub height: f64, pub plugin_data: P::PageData, } /// Trait to be implemented by Zathura plugins. pub trait ZathuraPlugin { /// Plugin-specific data attached to Zathura documents. /// /// If the plugin doesn't need to associate custom data with the document, /// this can be set to `()`. type DocumentData; /// Plugin-specific data attached to every document page. /// /// If the plugin doesn't need to associate custom data with every page, /// this can be set to `()`. type PageData; /// Open a document and read its metadata. /// /// This function has to determine and return the number of pages in the /// document. Zathura will create that number of pages and call the plugin's /// page initialization and rendering methods. fn document_open(doc: DocumentRef<'_>) -> Result<DocumentInfo<Self>, PluginError>; /// Additional hook called before freeing the document resources. /// /// It is not necessary for plugins to implement this. The library will take /// care of freeing the `DocumentData` attached to the document, and Zathura /// itself will free the actual document. fn document_free( doc: DocumentRef<'_>, doc_data: &mut Self::DocumentData, ) -> Result<(), PluginError> { let _ = (doc, doc_data); Ok(()) } /// Initialize a document page and obtain its properties. /// /// This is called once per page when the document is loaded initially. /// /// The plugin has to return a `PageInfo` structure containing page /// properties that will be applied by the library. fn page_init( page: PageRef<'_>, doc_data: &mut Self::DocumentData, ) -> Result<PageInfo<Self>, PluginError>; /// Additional hook called before freeing page resources. /// /// This doesn't have to be implemented by a plugin. The library already /// takes care of freeing the `PageData` associated with the page, and /// Zathura will free the page itself. fn page_free( page: PageRef<'_>, doc_data: &mut Self::DocumentData, page_data: &mut Self::PageData, ) -> Result<(), PluginError> { let _ = (page, doc_data, page_data); Ok(()) } /// Render a document page to a Cairo context. /// /// # Parameters /// /// * **`page`**: Mutable reference to the page to render. /// * **`doc_data`**: Plugin-specific data attached to the document. /// * **`page_data`**: Plugin-specific data attached to the page. /// * **`cairo`**: The Cairo context to render to. /// * **`printing`**: Whether the page is being rendered for printing /// (`true`) or viewing (`false`). fn page_render( page: PageRef<'_>, doc_data: &mut Self::DocumentData, page_data: &mut Self::PageData, cairo: &mut cairo::Context, printing: bool, ) -> Result<(), PluginError>; } /// `extern "C"` functions wrapping the Rust `ZathuraPlugin` functions. /// /// This is not public API and is only intended to be used by the /// `plugin_entry!` macro. #[doc(hidden)] pub mod wrapper { use { crate::{sys::*, *}, cairo, std::{ ffi::c_void, panic::{catch_unwind, AssertUnwindSafe}, }, }; trait ResultExt { fn to_zathura(self) -> zathura_error_t; } impl ResultExt for Result<(), PluginError> { fn to_zathura(self) -> zathura_error_t { match self { Ok(()) => 0, Err(e) => e as zathura_error_t, } } } fn wrap(f: impl FnOnce() -> Result<(), PluginError>) -> Result<(), PluginError> { match catch_unwind(AssertUnwindSafe(f)) { Ok(r) => r, Err(_) => Err(PluginError::Unknown), } } /// Open a document and set the number of pages to create in `document`. pub unsafe extern "C" fn document_open<P: ZathuraPlugin>( document: *mut zathura_document_t, ) -> zathura_error_t { wrap(|| { let doc = DocumentRef::from_raw(document); let info = P::document_open(doc)?; let mut doc = DocumentRef::from_raw(document); doc.set_plugin_data(Box::into_raw(Box::new(info.plugin_data)) as *mut _); doc.set_page_count(info.page_count); Ok(()) }) .to_zathura() } /// Free plugin-specific data in `document`. /// /// This is called by `zathura_document_free` and thus must not attempt to /// free the document again. pub unsafe extern "C" fn document_free<P: ZathuraPlugin>( document: *mut zathura_document_t, _data: *mut c_void, ) -> zathura_error_t { wrap(|| { let doc = DocumentRef::from_raw(document); let doc_data = &mut *(doc.plugin_data() as *mut P::DocumentData); let result = P::document_free(doc, doc_data); let doc = DocumentRef::from_raw(document); let plugin_data = doc.plugin_data() as *mut P::DocumentData; drop(Box::from_raw(plugin_data)); result }) .to_zathura() } /// Initialize a page and set its dimensions. /// /// If the page size is not set, rendering on it has no effect and the page /// appears invisible. pub unsafe extern "C" fn page_init<P: ZathuraPlugin>( page: *mut zathura_page_t, ) -> zathura_error_t { wrap(|| { let mut p = PageRef::from_raw(page); // Obtaining the document data is safe, since there is no other way to get access to it // while this function executes. let doc_data = p.document().plugin_data() as *mut P::DocumentData; let info = P::page_init(p, &mut *doc_data)?; let mut p = PageRef::from_raw(page); p.set_width(info.width); p.set_height(info.height); p.set_plugin_data(Box::into_raw(Box::new(info.plugin_data)) as *mut _); Ok(()) }) .to_zathura() } /// Deallocate plugin-specific page data. /// /// If this function is missing, the *document* will not be freed. pub unsafe extern "C" fn page_clear<P: ZathuraPlugin>( page: *mut zathura_page_t, _data: *mut c_void, ) -> zathura_error_t { wrap(|| { let result = { let mut p = PageRef::from_raw(page); let doc_data = &mut *(p.document().plugin_data() as *mut P::DocumentData); let page_data = &mut *(p.plugin_data() as *mut P::PageData); P::page_free(p, doc_data, page_data) }; // Free the `PageData` let p = PageRef::from_raw(page); let plugin_data = p.plugin_data() as *mut P::PageData; drop(Box::from_raw(plugin_data)); result }) .to_zathura() } /// Render a page to a Cairo context. pub unsafe extern "C" fn page_render_cairo<P: ZathuraPlugin>( page: *mut zathura_page_t, _data: *mut c_void, cairo: *mut sys::cairo_t, printing: bool, ) -> zathura_error_t { wrap(|| { let mut p = PageRef::from_raw(page); let page_data = &mut *(p.plugin_data() as *mut P::PageData); let doc_data = &mut *(p.document().plugin_data() as *mut P::DocumentData); let mut cairo = cairo::Context::from_raw_borrow(cairo as *mut _); P::page_render(p, doc_data, page_data, &mut cairo, printing) }) .to_zathura() } } /// Declares this library as a Zathura plugin. /// /// A crate can only provide one Zathura plugin, so this macro may only be /// called once per crate. /// /// For this to work, this crate must be built as a `cdylib` and the result put /// somewhere Zathura can find it. An easy way to iterate on a plugin is running /// this in the workspace root after any changes: /// /// ```notrust /// cargo build && zathura -p target/debug/ <file> /// ``` /// /// # Examples /// /// For a usage example of this macro, refer to the crate-level docs. #[macro_export] macro_rules! plugin_entry { ( $name:literal, $plugin_ty:ty, [ $($mime:literal),+ $(,)? ] ) => { #[doc(hidden)] #[repr(transparent)] #[allow(warnings)] pub struct __AssertSync<T>(T); unsafe impl<T> Sync for __AssertSync<T> {} #[doc(hidden)] #[no_mangle] pub static mut zathura_plugin_3_4: /* API=3, ABI=4 */ __AssertSync<$crate::sys::zathura_plugin_definition_t> = __AssertSync({ use $crate::sys::*; use $crate::wrapper::*; zathura_plugin_definition_t { name: concat!($name, "\0").as_ptr() as *const _, version: zathura_plugin_version_t { major: $crate::pkg_version_major!(), minor: $crate::pkg_version_minor!(), rev: $crate::pkg_version_patch!(), }, mime_types_size: { // Sum up as many 1s as there are entries in `$mime`. The // `$mime;` tells the compiler which syntax variable to // iterate over; it is disposed with no effect. 0 $(+ { $mime; 1 })+ }, mime_types: [ $( concat!($mime, "\0").as_ptr() as *const _, )+ ].as_ptr() as *mut _, // assuming Zathura never mutates this functions: zathura_plugin_functions_t { document_open: Some(document_open::<$plugin_ty>), document_free: Some(document_free::<$plugin_ty>), document_index_generate: None, document_save_as: None, document_attachments_get: None, document_attachment_save: None, document_get_information: None, page_init: Some(page_init::<$plugin_ty>), page_clear: Some(page_clear::<$plugin_ty>), page_search_text: None, page_links_get: None, page_form_fields_get: None, page_images_get: None, page_image_get_cairo: None, page_get_text: None, page_render: None, // no longer used? page_render_cairo: Some(page_render_cairo::<$plugin_ty>), page_get_label: None, }, } }); }; } #[cfg(feature = "testplugin")] struct TestPlugin; #[cfg(feature = "testplugin")] impl ZathuraPlugin for TestPlugin { type DocumentData = (); type PageData = (); fn document_open(doc: DocumentRef<'_>) -> Result<DocumentInfo<Self>, PluginError> { println!("open: {:?}", doc.basename_utf8()); println!("path: {:?}", doc.path_utf8()); println!("url: {:?}", doc.uri_utf8()); println!("{} pages", doc.page_count()); Ok(DocumentInfo { page_count: 5, plugin_data: (), }) } fn document_free(doc: DocumentRef<'_>, _doc_data: &mut ()) -> Result<(), PluginError> { println!("free! {:?}", doc); Ok(()) } fn page_init(page: PageRef<'_>, _doc_data: &mut ()) -> Result<PageInfo<Self>, PluginError> { println!("page init: {:?}", page); Ok(PageInfo { width: 75.0, height: 100.0, plugin_data: (), }) } fn page_free( page: PageRef<'_>, _doc_data: &mut (), _page_data: &mut (), ) -> Result<(), PluginError> { println!("page free: {:?}", page); Ok(()) } fn page_render( mut page: PageRef<'_>, _doc_data: &mut Self::DocumentData, _page_data: &mut Self::PageData, cairo: &mut cairo::Context, printing: bool, ) -> Result<(), PluginError> { println!( "render! {:?}, index={:?}, {}x{}, {:?}", page, page.index(), page.width(), page.height(), printing ); { let doc = page.document(); println!( "doc: zoom={}, scale={}, rotation={}°, ppi={}, scale={:?}, cell-size={:?}", doc.zoom(), doc.scale(), doc.rotation(), doc.viewport_ppi(), doc.scaling_factors(), doc.cell_size(), ); } println!( "cairo: scale={:?}, 50,50={:?}", cairo.get_target().get_device_scale(), cairo.user_to_device(50.0, 50.0), ); if page.index() == 0 { cairo.move_to(10.0, 10.0); cairo.show_text("Wello!"); cairo.set_source_rgb(0.0, 1.0, 1.0); cairo.set_line_width(1.0); cairo.move_to(0.0, 0.0); cairo.line_to(10.5, 50.5); cairo.stroke(); } Ok(()) } } #[cfg(feature = "testplugin")] plugin_entry!("TestPlugin", TestPlugin, ["text/plain"]);
//! //! # Examples //! //! ```
random_line_split
threads.go
package proc import ( "debug/gosym" "encoding/binary" "errors" "fmt" "go/ast" "path/filepath" "reflect" "strings" "golang.org/x/debug/dwarf" ) // Thread represents a thread. type Thread interface { MemoryReadWriter Location() (*Location, error) // Breakpoint will return the breakpoint that this thread is stopped at or // nil if the thread is not stopped at any breakpoint. // Active will be true if the thread is stopped at a breakpoint and the // breakpoint's condition is met. // If there was an error evaluating the breakpoint's condition it will be // returned as condErr Breakpoint() (breakpoint *Breakpoint, active bool, condErr error) ThreadID() int Registers(floatingPoint bool) (Registers, error) Arch() Arch BinInfo() *BinaryInfo StepInstruction() error // Blocked returns true if the thread is blocked Blocked() bool } // Location represents the location of a thread. // Holds information on the current instruction // address, the source file:line, and the function. type Location struct { PC uint64 File string Line int Fn *gosym.Func } // ThreadBlockedError is returned when the thread // is blocked in the scheduler. type ThreadBlockedError struct{} func (tbe ThreadBlockedError) Error() string { return "" } // returns topmost frame of g or thread if g is nil func topframe(g *G, thread Thread) (Stackframe, error) { var frames []Stackframe var err error if g == nil { if thread.Blocked() { return Stackframe{}, ThreadBlockedError{} } frames, err = ThreadStacktrace(thread, 0) } else { frames, err = g.Stacktrace(0) } if err != nil { return Stackframe{}, err } if len(frames) < 1 { return Stackframe{}, errors.New("empty stack trace") } return frames[0], nil } // Set breakpoints at every line, and the return address. Also look for // a deferred function and set a breakpoint there too. // If stepInto is true it will also set breakpoints inside all // functions called on the current source line, for non-absolute CALLs // a breakpoint of kind StepBreakpoint is set on the CALL instruction, // Continue will take care of setting a breakpoint to the destination // once the CALL is reached. func next(dbp Process, stepInto bool) error { selg := dbp.SelectedGoroutine() curthread := dbp.CurrentThread() topframe, err := topframe(selg, curthread) if err != nil { return err } success := false defer func() { if !success { dbp.ClearInternalBreakpoints() } }() csource := filepath.Ext(topframe.Current.File) != ".go" var thread MemoryReadWriter = curthread var regs Registers if selg != nil && selg.Thread != nil { thread = selg.Thread regs, err = selg.Thread.Registers(false) if err != nil { return err } } text, err := disassemble(thread, regs, dbp.Breakpoints(), dbp.BinInfo(), topframe.FDE.Begin(), topframe.FDE.End()) if err != nil && stepInto { return err } for i := range text { if text[i].Inst == nil { fmt.Printf("error at instruction %d\n", i) } } cond := SameGoroutineCondition(selg) if stepInto { for _, instr := range text { if instr.Loc.File != topframe.Current.File || instr.Loc.Line != topframe.Current.Line || !instr.IsCall() { continue } if instr.DestLoc != nil && instr.DestLoc.Fn != nil { if err := setStepIntoBreakpoint(dbp, []AsmInstruction{instr}, cond); err != nil { return err } } else { // Non-absolute call instruction, set a StepBreakpoint here if _, err := dbp.SetBreakpoint(instr.Loc.PC, StepBreakpoint, cond); err != nil { if _, ok := err.(BreakpointExistsError); !ok { return err } } } } } if !csource { deferreturns := []uint64{} // Find all runtime.deferreturn locations in the function // See documentation of Breakpoint.DeferCond for why this is necessary for _, instr := range text { if instr.IsCall() && instr.DestLoc != nil && instr.DestLoc.Fn != nil && instr.DestLoc.Fn.Name == "runtime.deferreturn" { deferreturns = append(deferreturns, instr.Loc.PC) } } // Set breakpoint on the most recently deferred function (if any) var deferpc uint64 = 0 if selg != nil { deferPCEntry := selg.DeferPC() if deferPCEntry != 0 { _, _, deferfn := dbp.BinInfo().PCToLine(deferPCEntry) var err error deferpc, err = FirstPCAfterPrologue(dbp, deferfn, false) if err != nil { return err } } } if deferpc != 0 && deferpc != topframe.Current.PC { bp, err := dbp.SetBreakpoint(deferpc, NextDeferBreakpoint, cond) if err != nil { if _, ok := err.(BreakpointExistsError); !ok { return err } } if bp != nil { bp.DeferReturns = deferreturns } } } // Add breakpoints on all the lines in the current function pcs, err := dbp.BinInfo().lineInfo.AllPCsBetween(topframe.FDE.Begin(), topframe.FDE.End()-1, topframe.Current.File) if err != nil { return err } if !csource { var covered bool for i := range pcs { if topframe.FDE.Cover(pcs[i]) { covered = true break } } if !covered { fn := dbp.BinInfo().goSymTable.PCToFunc(topframe.Ret) if selg != nil && fn != nil && fn.Name == "runtime.goexit" { return nil } } } // Add a breakpoint on the return address for the current frame pcs = append(pcs, topframe.Ret) success = true return setInternalBreakpoints(dbp, topframe.Current.PC, pcs, NextBreakpoint, cond) } func setStepIntoBreakpoint(dbp Process, text []AsmInstruction, cond ast.Expr) error { if len(text) <= 0 { return nil } instr := text[0] if instr.DestLoc == nil || instr.DestLoc.Fn == nil { return nil } fn := instr.DestLoc.Fn // Ensure PC and Entry match, otherwise StepInto is likely to set // its breakpoint before DestLoc.PC and hence run too far ahead. // Calls to runtime.duffzero and duffcopy have this problem. if fn.Entry != instr.DestLoc.PC { return nil } // Skip unexported runtime functions if strings.HasPrefix(fn.Name, "runtime.") && !isExportedRuntime(fn.Name) { return nil } //TODO(aarzilli): if we want to let users hide functions // or entire packages from being stepped into with 'step' // those extra checks should be done here. // Set a breakpoint after the function's prologue pc, _ := FirstPCAfterPrologue(dbp, fn, false) if _, err := dbp.SetBreakpoint(pc, NextBreakpoint, cond); err != nil { if _, ok := err.(BreakpointExistsError); !ok { return err } } return nil } // setInternalBreakpoints sets a breakpoint to all addresses specified in pcs // skipping over curpc and curpc-1 func setInternalBreakpoints(dbp Process, curpc uint64, pcs []uint64, kind BreakpointKind, cond ast.Expr) error { for i := range pcs { if pcs[i] == curpc || pcs[i] == curpc-1 { continue } if _, err := dbp.SetBreakpoint(pcs[i], kind, cond); err != nil { if _, ok := err.(BreakpointExistsError); !ok { dbp.ClearInternalBreakpoints() return err } } } return nil } func getGVariable(thread Thread) (*Variable, error) { arch := thread.Arch() regs, err := thread.Registers(false) if err != nil { return nil, err } if arch.GStructOffset() == 0 { // GetG was called through SwitchThread / updateThreadList during initialization // thread.dbp.arch isn't setup yet (it needs a current thread to read global variables from) return nil, fmt.Errorf("g struct offset not initialized") } gaddr, hasgaddr := regs.GAddr() if !hasgaddr { gaddrbs := make([]byte, arch.PtrSize()) _, err := thread.ReadMemory(gaddrbs, uintptr(regs.TLS()+arch.GStructOffset())) if err != nil { return nil, err } gaddr = binary.LittleEndian.Uint64(gaddrbs) } return newGVariable(thread, uintptr(gaddr), arch.DerefTLS()) } func newGVariable(thread Thread, gaddr uintptr, deref bool) (*Variable, error) { typ, err := thread.BinInfo().findType("runtime.g") if err != nil { return nil, err } name := "" if deref { typ = &dwarf.PtrType{dwarf.CommonType{int64(thread.Arch().PtrSize()), "", reflect.Ptr, 0}, typ} } else { name = "runtime.curg" } return newVariableFromThread(thread, name, gaddr, typ), nil } // GetG returns information on the G (goroutine) that is executing on this thread. // // The G structure for a thread is stored in thread local storage. Here we simply // calculate the address and read and parse the G struct. // // We cannot simply use the allg linked list in order to find the M that represents // the given OS thread and follow its G pointer because on Darwin mach ports are not // universal, so our port for this thread would not map to the `id` attribute of the M // structure. Also, when linked against libc, Go prefers the libc version of clone as // opposed to the runtime version. This has the consequence of not setting M.id for // any thread, regardless of OS. // // In order to get around all this craziness, we read the address of the G structure for // the current thread from the thread local storage area. func GetG(thread Thread) (g *G, err error) { gaddr, err := getGVariable(thread) if err != nil { return nil, err } g, err = gaddr.parseG() if err == nil { g.Thread = thread if loc, err := thread.Location(); err == nil { g.CurrentLoc = *loc } } return } // ThreadScope returns an EvalScope for this thread. func ThreadScope(thread Thread) (*EvalScope, error) { locations, err := ThreadStacktrace(thread, 0) if err != nil { return nil, err } if len(locations) < 1 { return nil, errors.New("could not decode first frame") } return &EvalScope{locations[0].Current.PC, locations[0].CFA, thread, nil, thread.BinInfo()}, nil } // GoroutineScope returns an EvalScope for the goroutine running on this thread. func GoroutineScope(thread Thread) (*EvalScope, error) { locations, err := ThreadStacktrace(thread, 0) if err != nil { return nil, err } if len(locations) < 1 { return nil, errors.New("could not decode first frame") } gvar, err := getGVariable(thread) if err != nil { return nil, err } return &EvalScope{locations[0].Current.PC, locations[0].CFA, thread, gvar, thread.BinInfo()}, nil } func onRuntimeBreakpoint(thread Thread) bool
// onNextGorutine returns true if this thread is on the goroutine requested by the current 'next' command func onNextGoroutine(thread Thread, breakpoints map[uint64]*Breakpoint) (bool, error) { var bp *Breakpoint for i := range breakpoints { if breakpoints[i].Internal() { bp = breakpoints[i] break } } if bp == nil { return false, nil } if bp.Kind == NextDeferBreakpoint { // we just want to check the condition on the goroutine id here bp.Kind = NextBreakpoint defer func() { bp.Kind = NextDeferBreakpoint }() } return bp.CheckCondition(thread) }
{ loc, err := thread.Location() if err != nil { return false } return loc.Fn != nil && loc.Fn.Name == "runtime.breakpoint" }
identifier_body
threads.go
package proc import ( "debug/gosym" "encoding/binary" "errors" "fmt" "go/ast" "path/filepath" "reflect" "strings" "golang.org/x/debug/dwarf" ) // Thread represents a thread. type Thread interface { MemoryReadWriter Location() (*Location, error) // Breakpoint will return the breakpoint that this thread is stopped at or // nil if the thread is not stopped at any breakpoint. // Active will be true if the thread is stopped at a breakpoint and the // breakpoint's condition is met. // If there was an error evaluating the breakpoint's condition it will be // returned as condErr Breakpoint() (breakpoint *Breakpoint, active bool, condErr error) ThreadID() int Registers(floatingPoint bool) (Registers, error) Arch() Arch BinInfo() *BinaryInfo StepInstruction() error // Blocked returns true if the thread is blocked Blocked() bool } // Location represents the location of a thread. // Holds information on the current instruction // address, the source file:line, and the function. type Location struct { PC uint64 File string Line int Fn *gosym.Func } // ThreadBlockedError is returned when the thread // is blocked in the scheduler. type ThreadBlockedError struct{} func (tbe ThreadBlockedError) Error() string { return "" } // returns topmost frame of g or thread if g is nil func topframe(g *G, thread Thread) (Stackframe, error) { var frames []Stackframe var err error if g == nil { if thread.Blocked() { return Stackframe{}, ThreadBlockedError{} } frames, err = ThreadStacktrace(thread, 0) } else { frames, err = g.Stacktrace(0) } if err != nil { return Stackframe{}, err } if len(frames) < 1 { return Stackframe{}, errors.New("empty stack trace") } return frames[0], nil } // Set breakpoints at every line, and the return address. Also look for // a deferred function and set a breakpoint there too. // If stepInto is true it will also set breakpoints inside all // functions called on the current source line, for non-absolute CALLs // a breakpoint of kind StepBreakpoint is set on the CALL instruction, // Continue will take care of setting a breakpoint to the destination // once the CALL is reached. func next(dbp Process, stepInto bool) error { selg := dbp.SelectedGoroutine() curthread := dbp.CurrentThread() topframe, err := topframe(selg, curthread) if err != nil { return err } success := false defer func() { if !success { dbp.ClearInternalBreakpoints() } }() csource := filepath.Ext(topframe.Current.File) != ".go" var thread MemoryReadWriter = curthread var regs Registers if selg != nil && selg.Thread != nil { thread = selg.Thread regs, err = selg.Thread.Registers(false) if err != nil { return err } } text, err := disassemble(thread, regs, dbp.Breakpoints(), dbp.BinInfo(), topframe.FDE.Begin(), topframe.FDE.End()) if err != nil && stepInto { return err } for i := range text { if text[i].Inst == nil { fmt.Printf("error at instruction %d\n", i) } } cond := SameGoroutineCondition(selg) if stepInto { for _, instr := range text { if instr.Loc.File != topframe.Current.File || instr.Loc.Line != topframe.Current.Line || !instr.IsCall() { continue } if instr.DestLoc != nil && instr.DestLoc.Fn != nil { if err := setStepIntoBreakpoint(dbp, []AsmInstruction{instr}, cond); err != nil { return err } } else { // Non-absolute call instruction, set a StepBreakpoint here if _, err := dbp.SetBreakpoint(instr.Loc.PC, StepBreakpoint, cond); err != nil { if _, ok := err.(BreakpointExistsError); !ok { return err } } } } } if !csource { deferreturns := []uint64{} // Find all runtime.deferreturn locations in the function // See documentation of Breakpoint.DeferCond for why this is necessary for _, instr := range text { if instr.IsCall() && instr.DestLoc != nil && instr.DestLoc.Fn != nil && instr.DestLoc.Fn.Name == "runtime.deferreturn" { deferreturns = append(deferreturns, instr.Loc.PC) } } // Set breakpoint on the most recently deferred function (if any) var deferpc uint64 = 0 if selg != nil { deferPCEntry := selg.DeferPC() if deferPCEntry != 0 { _, _, deferfn := dbp.BinInfo().PCToLine(deferPCEntry) var err error deferpc, err = FirstPCAfterPrologue(dbp, deferfn, false) if err != nil { return err } } } if deferpc != 0 && deferpc != topframe.Current.PC { bp, err := dbp.SetBreakpoint(deferpc, NextDeferBreakpoint, cond) if err != nil { if _, ok := err.(BreakpointExistsError); !ok { return err } } if bp != nil { bp.DeferReturns = deferreturns } } } // Add breakpoints on all the lines in the current function pcs, err := dbp.BinInfo().lineInfo.AllPCsBetween(topframe.FDE.Begin(), topframe.FDE.End()-1, topframe.Current.File) if err != nil { return err } if !csource { var covered bool for i := range pcs { if topframe.FDE.Cover(pcs[i]) { covered = true break } } if !covered { fn := dbp.BinInfo().goSymTable.PCToFunc(topframe.Ret) if selg != nil && fn != nil && fn.Name == "runtime.goexit" { return nil } } } // Add a breakpoint on the return address for the current frame pcs = append(pcs, topframe.Ret) success = true return setInternalBreakpoints(dbp, topframe.Current.PC, pcs, NextBreakpoint, cond) } func setStepIntoBreakpoint(dbp Process, text []AsmInstruction, cond ast.Expr) error { if len(text) <= 0 { return nil } instr := text[0] if instr.DestLoc == nil || instr.DestLoc.Fn == nil { return nil } fn := instr.DestLoc.Fn // Ensure PC and Entry match, otherwise StepInto is likely to set // its breakpoint before DestLoc.PC and hence run too far ahead. // Calls to runtime.duffzero and duffcopy have this problem. if fn.Entry != instr.DestLoc.PC { return nil } // Skip unexported runtime functions if strings.HasPrefix(fn.Name, "runtime.") && !isExportedRuntime(fn.Name) { return nil } //TODO(aarzilli): if we want to let users hide functions // or entire packages from being stepped into with 'step' // those extra checks should be done here. // Set a breakpoint after the function's prologue pc, _ := FirstPCAfterPrologue(dbp, fn, false) if _, err := dbp.SetBreakpoint(pc, NextBreakpoint, cond); err != nil { if _, ok := err.(BreakpointExistsError); !ok { return err } } return nil } // setInternalBreakpoints sets a breakpoint to all addresses specified in pcs // skipping over curpc and curpc-1 func setInternalBreakpoints(dbp Process, curpc uint64, pcs []uint64, kind BreakpointKind, cond ast.Expr) error { for i := range pcs { if pcs[i] == curpc || pcs[i] == curpc-1 { continue } if _, err := dbp.SetBreakpoint(pcs[i], kind, cond); err != nil { if _, ok := err.(BreakpointExistsError); !ok { dbp.ClearInternalBreakpoints() return err } } } return nil } func getGVariable(thread Thread) (*Variable, error) { arch := thread.Arch() regs, err := thread.Registers(false) if err != nil { return nil, err } if arch.GStructOffset() == 0 { // GetG was called through SwitchThread / updateThreadList during initialization // thread.dbp.arch isn't setup yet (it needs a current thread to read global variables from) return nil, fmt.Errorf("g struct offset not initialized") } gaddr, hasgaddr := regs.GAddr() if !hasgaddr { gaddrbs := make([]byte, arch.PtrSize()) _, err := thread.ReadMemory(gaddrbs, uintptr(regs.TLS()+arch.GStructOffset())) if err != nil { return nil, err } gaddr = binary.LittleEndian.Uint64(gaddrbs) } return newGVariable(thread, uintptr(gaddr), arch.DerefTLS()) } func newGVariable(thread Thread, gaddr uintptr, deref bool) (*Variable, error) { typ, err := thread.BinInfo().findType("runtime.g") if err != nil { return nil, err } name := "" if deref { typ = &dwarf.PtrType{dwarf.CommonType{int64(thread.Arch().PtrSize()), "", reflect.Ptr, 0}, typ} } else { name = "runtime.curg" } return newVariableFromThread(thread, name, gaddr, typ), nil } // GetG returns information on the G (goroutine) that is executing on this thread. // // The G structure for a thread is stored in thread local storage. Here we simply // calculate the address and read and parse the G struct. // // We cannot simply use the allg linked list in order to find the M that represents // the given OS thread and follow its G pointer because on Darwin mach ports are not // universal, so our port for this thread would not map to the `id` attribute of the M // structure. Also, when linked against libc, Go prefers the libc version of clone as // opposed to the runtime version. This has the consequence of not setting M.id for // any thread, regardless of OS. // // In order to get around all this craziness, we read the address of the G structure for // the current thread from the thread local storage area. func GetG(thread Thread) (g *G, err error) { gaddr, err := getGVariable(thread) if err != nil { return nil, err } g, err = gaddr.parseG() if err == nil { g.Thread = thread if loc, err := thread.Location(); err == nil { g.CurrentLoc = *loc } } return } // ThreadScope returns an EvalScope for this thread. func
(thread Thread) (*EvalScope, error) { locations, err := ThreadStacktrace(thread, 0) if err != nil { return nil, err } if len(locations) < 1 { return nil, errors.New("could not decode first frame") } return &EvalScope{locations[0].Current.PC, locations[0].CFA, thread, nil, thread.BinInfo()}, nil } // GoroutineScope returns an EvalScope for the goroutine running on this thread. func GoroutineScope(thread Thread) (*EvalScope, error) { locations, err := ThreadStacktrace(thread, 0) if err != nil { return nil, err } if len(locations) < 1 { return nil, errors.New("could not decode first frame") } gvar, err := getGVariable(thread) if err != nil { return nil, err } return &EvalScope{locations[0].Current.PC, locations[0].CFA, thread, gvar, thread.BinInfo()}, nil } func onRuntimeBreakpoint(thread Thread) bool { loc, err := thread.Location() if err != nil { return false } return loc.Fn != nil && loc.Fn.Name == "runtime.breakpoint" } // onNextGorutine returns true if this thread is on the goroutine requested by the current 'next' command func onNextGoroutine(thread Thread, breakpoints map[uint64]*Breakpoint) (bool, error) { var bp *Breakpoint for i := range breakpoints { if breakpoints[i].Internal() { bp = breakpoints[i] break } } if bp == nil { return false, nil } if bp.Kind == NextDeferBreakpoint { // we just want to check the condition on the goroutine id here bp.Kind = NextBreakpoint defer func() { bp.Kind = NextDeferBreakpoint }() } return bp.CheckCondition(thread) }
ThreadScope
identifier_name
threads.go
package proc import ( "debug/gosym" "encoding/binary" "errors" "fmt" "go/ast" "path/filepath" "reflect" "strings" "golang.org/x/debug/dwarf" ) // Thread represents a thread. type Thread interface { MemoryReadWriter Location() (*Location, error) // Breakpoint will return the breakpoint that this thread is stopped at or // nil if the thread is not stopped at any breakpoint. // Active will be true if the thread is stopped at a breakpoint and the // breakpoint's condition is met. // If there was an error evaluating the breakpoint's condition it will be // returned as condErr Breakpoint() (breakpoint *Breakpoint, active bool, condErr error) ThreadID() int Registers(floatingPoint bool) (Registers, error) Arch() Arch BinInfo() *BinaryInfo StepInstruction() error // Blocked returns true if the thread is blocked Blocked() bool } // Location represents the location of a thread. // Holds information on the current instruction // address, the source file:line, and the function. type Location struct { PC uint64 File string Line int Fn *gosym.Func } // ThreadBlockedError is returned when the thread // is blocked in the scheduler. type ThreadBlockedError struct{} func (tbe ThreadBlockedError) Error() string { return "" } // returns topmost frame of g or thread if g is nil func topframe(g *G, thread Thread) (Stackframe, error) { var frames []Stackframe var err error if g == nil { if thread.Blocked() { return Stackframe{}, ThreadBlockedError{} } frames, err = ThreadStacktrace(thread, 0) } else { frames, err = g.Stacktrace(0) } if err != nil { return Stackframe{}, err } if len(frames) < 1 { return Stackframe{}, errors.New("empty stack trace") } return frames[0], nil } // Set breakpoints at every line, and the return address. Also look for // a deferred function and set a breakpoint there too. // If stepInto is true it will also set breakpoints inside all // functions called on the current source line, for non-absolute CALLs // a breakpoint of kind StepBreakpoint is set on the CALL instruction, // Continue will take care of setting a breakpoint to the destination // once the CALL is reached. func next(dbp Process, stepInto bool) error { selg := dbp.SelectedGoroutine() curthread := dbp.CurrentThread() topframe, err := topframe(selg, curthread) if err != nil { return err } success := false defer func() { if !success { dbp.ClearInternalBreakpoints() } }() csource := filepath.Ext(topframe.Current.File) != ".go" var thread MemoryReadWriter = curthread var regs Registers if selg != nil && selg.Thread != nil { thread = selg.Thread regs, err = selg.Thread.Registers(false) if err != nil { return err } } text, err := disassemble(thread, regs, dbp.Breakpoints(), dbp.BinInfo(), topframe.FDE.Begin(), topframe.FDE.End()) if err != nil && stepInto { return err } for i := range text { if text[i].Inst == nil { fmt.Printf("error at instruction %d\n", i) } } cond := SameGoroutineCondition(selg) if stepInto { for _, instr := range text { if instr.Loc.File != topframe.Current.File || instr.Loc.Line != topframe.Current.Line || !instr.IsCall() { continue } if instr.DestLoc != nil && instr.DestLoc.Fn != nil { if err := setStepIntoBreakpoint(dbp, []AsmInstruction{instr}, cond); err != nil { return err } } else { // Non-absolute call instruction, set a StepBreakpoint here
} } } if !csource { deferreturns := []uint64{} // Find all runtime.deferreturn locations in the function // See documentation of Breakpoint.DeferCond for why this is necessary for _, instr := range text { if instr.IsCall() && instr.DestLoc != nil && instr.DestLoc.Fn != nil && instr.DestLoc.Fn.Name == "runtime.deferreturn" { deferreturns = append(deferreturns, instr.Loc.PC) } } // Set breakpoint on the most recently deferred function (if any) var deferpc uint64 = 0 if selg != nil { deferPCEntry := selg.DeferPC() if deferPCEntry != 0 { _, _, deferfn := dbp.BinInfo().PCToLine(deferPCEntry) var err error deferpc, err = FirstPCAfterPrologue(dbp, deferfn, false) if err != nil { return err } } } if deferpc != 0 && deferpc != topframe.Current.PC { bp, err := dbp.SetBreakpoint(deferpc, NextDeferBreakpoint, cond) if err != nil { if _, ok := err.(BreakpointExistsError); !ok { return err } } if bp != nil { bp.DeferReturns = deferreturns } } } // Add breakpoints on all the lines in the current function pcs, err := dbp.BinInfo().lineInfo.AllPCsBetween(topframe.FDE.Begin(), topframe.FDE.End()-1, topframe.Current.File) if err != nil { return err } if !csource { var covered bool for i := range pcs { if topframe.FDE.Cover(pcs[i]) { covered = true break } } if !covered { fn := dbp.BinInfo().goSymTable.PCToFunc(topframe.Ret) if selg != nil && fn != nil && fn.Name == "runtime.goexit" { return nil } } } // Add a breakpoint on the return address for the current frame pcs = append(pcs, topframe.Ret) success = true return setInternalBreakpoints(dbp, topframe.Current.PC, pcs, NextBreakpoint, cond) } func setStepIntoBreakpoint(dbp Process, text []AsmInstruction, cond ast.Expr) error { if len(text) <= 0 { return nil } instr := text[0] if instr.DestLoc == nil || instr.DestLoc.Fn == nil { return nil } fn := instr.DestLoc.Fn // Ensure PC and Entry match, otherwise StepInto is likely to set // its breakpoint before DestLoc.PC and hence run too far ahead. // Calls to runtime.duffzero and duffcopy have this problem. if fn.Entry != instr.DestLoc.PC { return nil } // Skip unexported runtime functions if strings.HasPrefix(fn.Name, "runtime.") && !isExportedRuntime(fn.Name) { return nil } //TODO(aarzilli): if we want to let users hide functions // or entire packages from being stepped into with 'step' // those extra checks should be done here. // Set a breakpoint after the function's prologue pc, _ := FirstPCAfterPrologue(dbp, fn, false) if _, err := dbp.SetBreakpoint(pc, NextBreakpoint, cond); err != nil { if _, ok := err.(BreakpointExistsError); !ok { return err } } return nil } // setInternalBreakpoints sets a breakpoint to all addresses specified in pcs // skipping over curpc and curpc-1 func setInternalBreakpoints(dbp Process, curpc uint64, pcs []uint64, kind BreakpointKind, cond ast.Expr) error { for i := range pcs { if pcs[i] == curpc || pcs[i] == curpc-1 { continue } if _, err := dbp.SetBreakpoint(pcs[i], kind, cond); err != nil { if _, ok := err.(BreakpointExistsError); !ok { dbp.ClearInternalBreakpoints() return err } } } return nil } func getGVariable(thread Thread) (*Variable, error) { arch := thread.Arch() regs, err := thread.Registers(false) if err != nil { return nil, err } if arch.GStructOffset() == 0 { // GetG was called through SwitchThread / updateThreadList during initialization // thread.dbp.arch isn't setup yet (it needs a current thread to read global variables from) return nil, fmt.Errorf("g struct offset not initialized") } gaddr, hasgaddr := regs.GAddr() if !hasgaddr { gaddrbs := make([]byte, arch.PtrSize()) _, err := thread.ReadMemory(gaddrbs, uintptr(regs.TLS()+arch.GStructOffset())) if err != nil { return nil, err } gaddr = binary.LittleEndian.Uint64(gaddrbs) } return newGVariable(thread, uintptr(gaddr), arch.DerefTLS()) } func newGVariable(thread Thread, gaddr uintptr, deref bool) (*Variable, error) { typ, err := thread.BinInfo().findType("runtime.g") if err != nil { return nil, err } name := "" if deref { typ = &dwarf.PtrType{dwarf.CommonType{int64(thread.Arch().PtrSize()), "", reflect.Ptr, 0}, typ} } else { name = "runtime.curg" } return newVariableFromThread(thread, name, gaddr, typ), nil } // GetG returns information on the G (goroutine) that is executing on this thread. // // The G structure for a thread is stored in thread local storage. Here we simply // calculate the address and read and parse the G struct. // // We cannot simply use the allg linked list in order to find the M that represents // the given OS thread and follow its G pointer because on Darwin mach ports are not // universal, so our port for this thread would not map to the `id` attribute of the M // structure. Also, when linked against libc, Go prefers the libc version of clone as // opposed to the runtime version. This has the consequence of not setting M.id for // any thread, regardless of OS. // // In order to get around all this craziness, we read the address of the G structure for // the current thread from the thread local storage area. func GetG(thread Thread) (g *G, err error) { gaddr, err := getGVariable(thread) if err != nil { return nil, err } g, err = gaddr.parseG() if err == nil { g.Thread = thread if loc, err := thread.Location(); err == nil { g.CurrentLoc = *loc } } return } // ThreadScope returns an EvalScope for this thread. func ThreadScope(thread Thread) (*EvalScope, error) { locations, err := ThreadStacktrace(thread, 0) if err != nil { return nil, err } if len(locations) < 1 { return nil, errors.New("could not decode first frame") } return &EvalScope{locations[0].Current.PC, locations[0].CFA, thread, nil, thread.BinInfo()}, nil } // GoroutineScope returns an EvalScope for the goroutine running on this thread. func GoroutineScope(thread Thread) (*EvalScope, error) { locations, err := ThreadStacktrace(thread, 0) if err != nil { return nil, err } if len(locations) < 1 { return nil, errors.New("could not decode first frame") } gvar, err := getGVariable(thread) if err != nil { return nil, err } return &EvalScope{locations[0].Current.PC, locations[0].CFA, thread, gvar, thread.BinInfo()}, nil } func onRuntimeBreakpoint(thread Thread) bool { loc, err := thread.Location() if err != nil { return false } return loc.Fn != nil && loc.Fn.Name == "runtime.breakpoint" } // onNextGorutine returns true if this thread is on the goroutine requested by the current 'next' command func onNextGoroutine(thread Thread, breakpoints map[uint64]*Breakpoint) (bool, error) { var bp *Breakpoint for i := range breakpoints { if breakpoints[i].Internal() { bp = breakpoints[i] break } } if bp == nil { return false, nil } if bp.Kind == NextDeferBreakpoint { // we just want to check the condition on the goroutine id here bp.Kind = NextBreakpoint defer func() { bp.Kind = NextDeferBreakpoint }() } return bp.CheckCondition(thread) }
if _, err := dbp.SetBreakpoint(instr.Loc.PC, StepBreakpoint, cond); err != nil { if _, ok := err.(BreakpointExistsError); !ok { return err } }
random_line_split
threads.go
package proc import ( "debug/gosym" "encoding/binary" "errors" "fmt" "go/ast" "path/filepath" "reflect" "strings" "golang.org/x/debug/dwarf" ) // Thread represents a thread. type Thread interface { MemoryReadWriter Location() (*Location, error) // Breakpoint will return the breakpoint that this thread is stopped at or // nil if the thread is not stopped at any breakpoint. // Active will be true if the thread is stopped at a breakpoint and the // breakpoint's condition is met. // If there was an error evaluating the breakpoint's condition it will be // returned as condErr Breakpoint() (breakpoint *Breakpoint, active bool, condErr error) ThreadID() int Registers(floatingPoint bool) (Registers, error) Arch() Arch BinInfo() *BinaryInfo StepInstruction() error // Blocked returns true if the thread is blocked Blocked() bool } // Location represents the location of a thread. // Holds information on the current instruction // address, the source file:line, and the function. type Location struct { PC uint64 File string Line int Fn *gosym.Func } // ThreadBlockedError is returned when the thread // is blocked in the scheduler. type ThreadBlockedError struct{} func (tbe ThreadBlockedError) Error() string { return "" } // returns topmost frame of g or thread if g is nil func topframe(g *G, thread Thread) (Stackframe, error) { var frames []Stackframe var err error if g == nil { if thread.Blocked() { return Stackframe{}, ThreadBlockedError{} } frames, err = ThreadStacktrace(thread, 0) } else { frames, err = g.Stacktrace(0) } if err != nil { return Stackframe{}, err } if len(frames) < 1 { return Stackframe{}, errors.New("empty stack trace") } return frames[0], nil } // Set breakpoints at every line, and the return address. Also look for // a deferred function and set a breakpoint there too. // If stepInto is true it will also set breakpoints inside all // functions called on the current source line, for non-absolute CALLs // a breakpoint of kind StepBreakpoint is set on the CALL instruction, // Continue will take care of setting a breakpoint to the destination // once the CALL is reached. func next(dbp Process, stepInto bool) error { selg := dbp.SelectedGoroutine() curthread := dbp.CurrentThread() topframe, err := topframe(selg, curthread) if err != nil { return err } success := false defer func() { if !success { dbp.ClearInternalBreakpoints() } }() csource := filepath.Ext(topframe.Current.File) != ".go" var thread MemoryReadWriter = curthread var regs Registers if selg != nil && selg.Thread != nil { thread = selg.Thread regs, err = selg.Thread.Registers(false) if err != nil { return err } } text, err := disassemble(thread, regs, dbp.Breakpoints(), dbp.BinInfo(), topframe.FDE.Begin(), topframe.FDE.End()) if err != nil && stepInto { return err } for i := range text { if text[i].Inst == nil { fmt.Printf("error at instruction %d\n", i) } } cond := SameGoroutineCondition(selg) if stepInto { for _, instr := range text { if instr.Loc.File != topframe.Current.File || instr.Loc.Line != topframe.Current.Line || !instr.IsCall() { continue } if instr.DestLoc != nil && instr.DestLoc.Fn != nil { if err := setStepIntoBreakpoint(dbp, []AsmInstruction{instr}, cond); err != nil { return err } } else { // Non-absolute call instruction, set a StepBreakpoint here if _, err := dbp.SetBreakpoint(instr.Loc.PC, StepBreakpoint, cond); err != nil { if _, ok := err.(BreakpointExistsError); !ok { return err } } } } } if !csource { deferreturns := []uint64{} // Find all runtime.deferreturn locations in the function // See documentation of Breakpoint.DeferCond for why this is necessary for _, instr := range text { if instr.IsCall() && instr.DestLoc != nil && instr.DestLoc.Fn != nil && instr.DestLoc.Fn.Name == "runtime.deferreturn" { deferreturns = append(deferreturns, instr.Loc.PC) } } // Set breakpoint on the most recently deferred function (if any) var deferpc uint64 = 0 if selg != nil { deferPCEntry := selg.DeferPC() if deferPCEntry != 0 { _, _, deferfn := dbp.BinInfo().PCToLine(deferPCEntry) var err error deferpc, err = FirstPCAfterPrologue(dbp, deferfn, false) if err != nil { return err } } } if deferpc != 0 && deferpc != topframe.Current.PC { bp, err := dbp.SetBreakpoint(deferpc, NextDeferBreakpoint, cond) if err != nil { if _, ok := err.(BreakpointExistsError); !ok { return err } } if bp != nil { bp.DeferReturns = deferreturns } } } // Add breakpoints on all the lines in the current function pcs, err := dbp.BinInfo().lineInfo.AllPCsBetween(topframe.FDE.Begin(), topframe.FDE.End()-1, topframe.Current.File) if err != nil { return err } if !csource { var covered bool for i := range pcs { if topframe.FDE.Cover(pcs[i]) { covered = true break } } if !covered { fn := dbp.BinInfo().goSymTable.PCToFunc(topframe.Ret) if selg != nil && fn != nil && fn.Name == "runtime.goexit" { return nil } } } // Add a breakpoint on the return address for the current frame pcs = append(pcs, topframe.Ret) success = true return setInternalBreakpoints(dbp, topframe.Current.PC, pcs, NextBreakpoint, cond) } func setStepIntoBreakpoint(dbp Process, text []AsmInstruction, cond ast.Expr) error { if len(text) <= 0 { return nil } instr := text[0] if instr.DestLoc == nil || instr.DestLoc.Fn == nil { return nil } fn := instr.DestLoc.Fn // Ensure PC and Entry match, otherwise StepInto is likely to set // its breakpoint before DestLoc.PC and hence run too far ahead. // Calls to runtime.duffzero and duffcopy have this problem. if fn.Entry != instr.DestLoc.PC { return nil } // Skip unexported runtime functions if strings.HasPrefix(fn.Name, "runtime.") && !isExportedRuntime(fn.Name) { return nil } //TODO(aarzilli): if we want to let users hide functions // or entire packages from being stepped into with 'step' // those extra checks should be done here. // Set a breakpoint after the function's prologue pc, _ := FirstPCAfterPrologue(dbp, fn, false) if _, err := dbp.SetBreakpoint(pc, NextBreakpoint, cond); err != nil { if _, ok := err.(BreakpointExistsError); !ok { return err } } return nil } // setInternalBreakpoints sets a breakpoint to all addresses specified in pcs // skipping over curpc and curpc-1 func setInternalBreakpoints(dbp Process, curpc uint64, pcs []uint64, kind BreakpointKind, cond ast.Expr) error { for i := range pcs { if pcs[i] == curpc || pcs[i] == curpc-1 { continue } if _, err := dbp.SetBreakpoint(pcs[i], kind, cond); err != nil { if _, ok := err.(BreakpointExistsError); !ok { dbp.ClearInternalBreakpoints() return err } } } return nil } func getGVariable(thread Thread) (*Variable, error) { arch := thread.Arch() regs, err := thread.Registers(false) if err != nil { return nil, err } if arch.GStructOffset() == 0 { // GetG was called through SwitchThread / updateThreadList during initialization // thread.dbp.arch isn't setup yet (it needs a current thread to read global variables from) return nil, fmt.Errorf("g struct offset not initialized") } gaddr, hasgaddr := regs.GAddr() if !hasgaddr { gaddrbs := make([]byte, arch.PtrSize()) _, err := thread.ReadMemory(gaddrbs, uintptr(regs.TLS()+arch.GStructOffset())) if err != nil { return nil, err } gaddr = binary.LittleEndian.Uint64(gaddrbs) } return newGVariable(thread, uintptr(gaddr), arch.DerefTLS()) } func newGVariable(thread Thread, gaddr uintptr, deref bool) (*Variable, error) { typ, err := thread.BinInfo().findType("runtime.g") if err != nil { return nil, err } name := "" if deref { typ = &dwarf.PtrType{dwarf.CommonType{int64(thread.Arch().PtrSize()), "", reflect.Ptr, 0}, typ} } else { name = "runtime.curg" } return newVariableFromThread(thread, name, gaddr, typ), nil } // GetG returns information on the G (goroutine) that is executing on this thread. // // The G structure for a thread is stored in thread local storage. Here we simply // calculate the address and read and parse the G struct. // // We cannot simply use the allg linked list in order to find the M that represents // the given OS thread and follow its G pointer because on Darwin mach ports are not // universal, so our port for this thread would not map to the `id` attribute of the M // structure. Also, when linked against libc, Go prefers the libc version of clone as // opposed to the runtime version. This has the consequence of not setting M.id for // any thread, regardless of OS. // // In order to get around all this craziness, we read the address of the G structure for // the current thread from the thread local storage area. func GetG(thread Thread) (g *G, err error) { gaddr, err := getGVariable(thread) if err != nil { return nil, err } g, err = gaddr.parseG() if err == nil { g.Thread = thread if loc, err := thread.Location(); err == nil { g.CurrentLoc = *loc } } return } // ThreadScope returns an EvalScope for this thread. func ThreadScope(thread Thread) (*EvalScope, error) { locations, err := ThreadStacktrace(thread, 0) if err != nil { return nil, err } if len(locations) < 1 { return nil, errors.New("could not decode first frame") } return &EvalScope{locations[0].Current.PC, locations[0].CFA, thread, nil, thread.BinInfo()}, nil } // GoroutineScope returns an EvalScope for the goroutine running on this thread. func GoroutineScope(thread Thread) (*EvalScope, error) { locations, err := ThreadStacktrace(thread, 0) if err != nil { return nil, err } if len(locations) < 1 { return nil, errors.New("could not decode first frame") } gvar, err := getGVariable(thread) if err != nil { return nil, err } return &EvalScope{locations[0].Current.PC, locations[0].CFA, thread, gvar, thread.BinInfo()}, nil } func onRuntimeBreakpoint(thread Thread) bool { loc, err := thread.Location() if err != nil { return false } return loc.Fn != nil && loc.Fn.Name == "runtime.breakpoint" } // onNextGorutine returns true if this thread is on the goroutine requested by the current 'next' command func onNextGoroutine(thread Thread, breakpoints map[uint64]*Breakpoint) (bool, error) { var bp *Breakpoint for i := range breakpoints { if breakpoints[i].Internal() { bp = breakpoints[i] break } } if bp == nil { return false, nil } if bp.Kind == NextDeferBreakpoint
return bp.CheckCondition(thread) }
{ // we just want to check the condition on the goroutine id here bp.Kind = NextBreakpoint defer func() { bp.Kind = NextDeferBreakpoint }() }
conditional_block
utxo_scanner_task.rs
// Copyright 2021. The Tari Project // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the // following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following // disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the // following disclaimer in the documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote // products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. use chrono::Utc; use futures::StreamExt; use log::*; use std::{ convert::TryFrom, time::{Duration, Instant}, }; use tari_common_types::transaction::TxId; use tari_comms::{ peer_manager::NodeId, protocol::rpc::{RpcError, RpcStatus}, types::CommsPublicKey, PeerConnection, }; use tari_core::{ base_node::sync::rpc::BaseNodeSyncRpcClient, blocks::BlockHeader, crypto::tari_utilities::hex::Hex, proto, proto::base_node::{FindChainSplitRequest, SyncUtxosRequest}, tari_utilities::Hashable, transactions::{ tari_amount::MicroTari, transaction_entities::{TransactionOutput, UnblindedOutput}, }, }; use tari_shutdown::ShutdownSignal; use tokio::{sync::broadcast, time}; use crate::{ error::WalletError, storage::database::WalletBackend, utxo_scanner_service::{ error::UtxoScannerError, handle::UtxoScannerEvent, service::{ScanningMetadata, UtxoScannerResources}, uxto_scanner_service_builder::UtxoScannerMode, }, }; pub const LOG_TARGET: &str = "wallet::utxo_scanning"; pub const RECOVERY_KEY: &str = "recovery_data"; const SCANNING_KEY: &str = "scanning_data"; pub struct UtxoScannerTask<TBackend> where TBackend: WalletBackend + 'static { pub(crate) resources: UtxoScannerResources<TBackend>, pub(crate) event_sender: broadcast::Sender<UtxoScannerEvent>, pub(crate) retry_limit: usize, pub(crate) num_retries: usize, pub(crate) peer_seeds: Vec<CommsPublicKey>, pub(crate) peer_index: usize, pub(crate) mode: UtxoScannerMode, pub(crate) shutdown_signal: ShutdownSignal, } impl<TBackend> UtxoScannerTask<TBackend> where TBackend: WalletBackend + 'static { async fn finalize( &self, total_scanned: u64, final_utxo_pos: u64, elapsed: Duration, ) -> Result<(), UtxoScannerError> { let metadata = self.get_metadata().await?.unwrap_or_default(); self.publish_event(UtxoScannerEvent::Progress { current_index: final_utxo_pos, total_index: final_utxo_pos, }); self.publish_event(UtxoScannerEvent::Completed { number_scanned: total_scanned, number_received: metadata.number_of_utxos, value_received: metadata.total_amount, time_taken: elapsed, }); // Presence of scanning keys are used to determine if a wallet is busy with recovery or not. if self.mode == UtxoScannerMode::Recovery { self.clear_db().await?; } Ok(()) } async fn connect_to_peer(&mut self, peer: NodeId) -> Result<PeerConnection, UtxoScannerError> { self.publish_event(UtxoScannerEvent::ConnectingToBaseNode(peer.clone())); debug!( target: LOG_TARGET, "Attempting UTXO sync with seed peer {} ({})", self.peer_index, peer, ); match self.resources.comms_connectivity.dial_peer(peer.clone()).await { Ok(conn) => Ok(conn), Err(e) => { self.publish_event(UtxoScannerEvent::ConnectionFailedToBaseNode { peer: peer.clone(), num_retries: self.num_retries, retry_limit: self.retry_limit, error: e.to_string(), }); // No use re-dialing a peer that is not responsive for recovery mode if self.mode == UtxoScannerMode::Recovery { if let Ok(Some(connection)) = self.resources.comms_connectivity.get_connection(peer.clone()).await { if connection.clone().disconnect().await.is_ok() { debug!(target: LOG_TARGET, "Disconnected base node peer {}", peer); } }; let _ = time::sleep(Duration::from_secs(30)); } Err(e.into()) }, } } async fn attempt_sync(&mut self, peer: NodeId) -> Result<(u64, u64, Duration), UtxoScannerError> { let mut connection = self.connect_to_peer(peer.clone()).await?; let mut client = connection .connect_rpc_using_builder(BaseNodeSyncRpcClient::builder().with_deadline(Duration::from_secs(60))) .await?; let latency = client.get_last_request_latency(); self.publish_event(UtxoScannerEvent::ConnectedToBaseNode( peer.clone(), latency.unwrap_or_default(), )); let timer = Instant::now(); let mut total_scanned = 0u64; loop { let start_index = self.get_start_utxo_mmr_pos(&mut client).await?; let tip_header = self.get_chain_tip_header(&mut client).await?; let output_mmr_size = tip_header.output_mmr_size; if self.shutdown_signal.is_triggered() { // if running is set to false, we know its been canceled upstream so lets exit the loop return Ok((total_scanned, start_index, timer.elapsed())); } debug!( target: LOG_TARGET, "Scanning UTXO's (start_index = {}, output_mmr_size = {}, height = {}, tip_hash = {})", start_index, output_mmr_size, tip_header.height, tip_header.hash().to_hex() ); // start_index could be greater than output_mmr_size if we switch to a new peer that is behind the original // peer. In the common case, we wait for start index. if start_index >= output_mmr_size - 1 { debug!( target: LOG_TARGET, "Scanning complete UTXO #{} in {:.2?}", start_index, timer.elapsed() ); return Ok((total_scanned, start_index, timer.elapsed())); } let num_scanned = self.scan_utxos(&mut client, start_index, tip_header).await?; if num_scanned == 0 { return Err(UtxoScannerError::UtxoScanningError( "Peer returned 0 UTXOs to scan".to_string(), )); } debug!( target: LOG_TARGET, "Scanning round completed UTXO #{} in {:.2?} ({} scanned)", output_mmr_size, timer.elapsed(), num_scanned ); // let num_scanned = 0; total_scanned += num_scanned; // return Ok((total_scanned, start_index, timer.elapsed())); } } async fn
(&self, client: &mut BaseNodeSyncRpcClient) -> Result<BlockHeader, UtxoScannerError> { let chain_metadata = client.get_chain_metadata().await?; let chain_height = chain_metadata.height_of_longest_chain(); let end_header = client.get_header_by_height(chain_height).await?; let end_header = BlockHeader::try_from(end_header).map_err(|_| UtxoScannerError::ConversionError)?; Ok(end_header) } async fn get_start_utxo_mmr_pos(&self, client: &mut BaseNodeSyncRpcClient) -> Result<u64, UtxoScannerError> { let metadata = match self.get_metadata().await? { None => { let birthday_metadata = self.get_birthday_metadata(client).await?; self.set_metadata(birthday_metadata.clone()).await?; return Ok(birthday_metadata.utxo_index); }, Some(m) => m, }; // if it's none, we return 0 above. let request = FindChainSplitRequest { block_hashes: vec![metadata.height_hash], header_count: 1, }; // this returns the index of the vec of hashes we sent it, that is the last hash it knows of. match client.find_chain_split(request).await { Ok(_) => Ok(metadata.utxo_index + 1), Err(RpcError::RequestFailed(err)) if err.as_status_code().is_not_found() => { warn!(target: LOG_TARGET, "Reorg detected: {}", err); // The node does not know of the last hash we scanned, thus we had a chain split. // We now start at the wallet birthday again let birthday_metdadata = self.get_birthday_metadata(client).await?; Ok(birthday_metdadata.utxo_index) }, Err(err) => Err(err.into()), } } async fn scan_utxos( &mut self, client: &mut BaseNodeSyncRpcClient, start_mmr_leaf_index: u64, end_header: BlockHeader, ) -> Result<u64, UtxoScannerError> { debug!( target: LOG_TARGET, "Scanning UTXO's from #{} to #{} (height {})", start_mmr_leaf_index, end_header.output_mmr_size, end_header.height ); let end_header_hash = end_header.hash(); let output_mmr_size = end_header.output_mmr_size; let mut num_recovered = 0u64; let mut total_amount = MicroTari::from(0); let mut total_scanned = 0; self.publish_event(UtxoScannerEvent::Progress { current_index: start_mmr_leaf_index, total_index: (output_mmr_size - 1), }); let request = SyncUtxosRequest { start: start_mmr_leaf_index, end_header_hash: end_header_hash.clone(), include_pruned_utxos: false, include_deleted_bitmaps: false, }; let start = Instant::now(); let utxo_stream = client.sync_utxos(request).await?; trace!( target: LOG_TARGET, "bulletproof rewind profile - UTXO stream request time {} ms", start.elapsed().as_millis(), ); // We download in chunks for improved streaming efficiency const CHUNK_SIZE: usize = 125; let mut utxo_stream = utxo_stream.chunks(CHUNK_SIZE); const COMMIT_EVERY_N: u64 = (1000_i64 / CHUNK_SIZE as i64) as u64; let mut last_utxo_index = 0u64; let mut iteration_count = 0u64; let mut utxo_next_await_profiling = Vec::new(); let mut scan_for_outputs_profiling = Vec::new(); while let Some(response) = { let start = Instant::now(); let utxo_stream_next = utxo_stream.next().await; utxo_next_await_profiling.push(start.elapsed()); utxo_stream_next } { if self.shutdown_signal.is_triggered() { // if running is set to false, we know its been canceled upstream so lets exit the loop return Ok(total_scanned as u64); } let (outputs, utxo_index) = convert_response_to_transaction_outputs(response, last_utxo_index)?; last_utxo_index = utxo_index; total_scanned += outputs.len(); iteration_count += 1; let start = Instant::now(); let found_outputs = self.scan_for_outputs(outputs).await?; scan_for_outputs_profiling.push(start.elapsed()); // Reduce the number of db hits by only persisting progress every N iterations if iteration_count % COMMIT_EVERY_N == 0 || last_utxo_index >= output_mmr_size - 1 { self.publish_event(UtxoScannerEvent::Progress { current_index: last_utxo_index, total_index: (output_mmr_size - 1), }); self.update_scanning_progress_in_db( last_utxo_index, total_amount, num_recovered, end_header_hash.clone(), ) .await?; } let (count, amount) = self.import_utxos_to_transaction_service(found_outputs).await?; num_recovered = num_recovered.saturating_add(count); total_amount += amount; } trace!( target: LOG_TARGET, "bulletproof rewind profile - streamed {} outputs in {} ms", total_scanned, utxo_next_await_profiling.iter().fold(0, |acc, &x| acc + x.as_millis()), ); trace!( target: LOG_TARGET, "bulletproof rewind profile - scanned {} outputs in {} ms", total_scanned, scan_for_outputs_profiling.iter().fold(0, |acc, &x| acc + x.as_millis()), ); self.update_scanning_progress_in_db(last_utxo_index, total_amount, num_recovered, end_header_hash) .await?; self.publish_event(UtxoScannerEvent::Progress { current_index: (output_mmr_size - 1), total_index: (output_mmr_size - 1), }); Ok(total_scanned as u64) } async fn update_scanning_progress_in_db( &self, last_utxo_index: u64, total_amount: MicroTari, num_recovered: u64, end_header_hash: Vec<u8>, ) -> Result<(), UtxoScannerError> { let mut meta_data = self.get_metadata().await?.unwrap_or_default(); meta_data.height_hash = end_header_hash; meta_data.number_of_utxos += num_recovered; meta_data.utxo_index = last_utxo_index; meta_data.total_amount += total_amount; self.set_metadata(meta_data).await?; Ok(()) } async fn scan_for_outputs( &mut self, outputs: Vec<TransactionOutput>, ) -> Result<Vec<(UnblindedOutput, String)>, UtxoScannerError> { let mut found_outputs: Vec<(UnblindedOutput, String)> = Vec::new(); if self.mode == UtxoScannerMode::Recovery { found_outputs.append( &mut self .resources .output_manager_service .scan_for_recoverable_outputs(outputs.clone()) .await? .into_iter() .map(|v| (v, format!("Recovered on {}.", Utc::now().naive_utc()))) .collect(), ); }; found_outputs.append( &mut self .resources .output_manager_service .scan_outputs_for_one_sided_payments(outputs.clone()) .await? .into_iter() .map(|v| { ( v, format!("Detected one-sided transaction on {}.", Utc::now().naive_utc()), ) }) .collect(), ); Ok(found_outputs) } async fn import_utxos_to_transaction_service( &mut self, utxos: Vec<(UnblindedOutput, String)>, ) -> Result<(u64, MicroTari), UtxoScannerError> { let mut num_recovered = 0u64; let mut total_amount = MicroTari::from(0); let source_public_key = self.resources.node_identity.public_key().clone(); for uo in utxos { match self .import_unblinded_utxo_to_transaction_service(uo.0.clone(), &source_public_key, uo.1) .await { Ok(_) => { num_recovered = num_recovered.saturating_add(1); total_amount += uo.0.value; }, Err(e) => return Err(UtxoScannerError::UtxoImportError(e.to_string())), } } Ok((num_recovered, total_amount)) } fn get_db_mode_key(&self) -> String { match self.mode { UtxoScannerMode::Recovery => RECOVERY_KEY.to_owned(), UtxoScannerMode::Scanning => SCANNING_KEY.to_owned(), } } async fn set_metadata(&self, data: ScanningMetadata) -> Result<(), UtxoScannerError> { let total_key = self.get_db_mode_key(); let db_value = serde_json::to_string(&data)?; self.resources.db.set_client_key_value(total_key, db_value).await?; Ok(()) } async fn get_metadata(&self) -> Result<Option<ScanningMetadata>, UtxoScannerError> { let total_key = self.get_db_mode_key(); let value: Option<String> = self.resources.db.get_client_key_from_str(total_key).await?; match value { None => Ok(None), Some(v) => Ok(serde_json::from_str(&v)?), } } async fn clear_db(&self) -> Result<(), UtxoScannerError> { let total_key = self.get_db_mode_key(); let _ = self.resources.db.clear_client_value(total_key).await?; Ok(()) } fn publish_event(&self, event: UtxoScannerEvent) { let _ = self.event_sender.send(event); } /// A faux incoming transaction will be created to provide a record of the event of importing a UTXO. The TxId of /// the generated transaction is returned. pub async fn import_unblinded_utxo_to_transaction_service( &mut self, unblinded_output: UnblindedOutput, source_public_key: &CommsPublicKey, message: String, ) -> Result<TxId, WalletError> { let tx_id = self .resources .transaction_service .import_utxo( unblinded_output.value, source_public_key.clone(), message, Some(unblinded_output.features.maturity), ) .await?; info!( target: LOG_TARGET, "UTXO (Commitment: {}) imported into wallet", unblinded_output .as_transaction_input(&self.resources.factories.commitment)? .commitment .to_hex() ); Ok(tx_id) } pub async fn run(mut self) -> Result<(), UtxoScannerError> { loop { if self.shutdown_signal.is_triggered() { // if running is set to false, we know its been canceled upstream so lets exit the loop return Ok(()); } match self.get_next_peer() { Some(peer) => match self.attempt_sync(peer.clone()).await { Ok((total_scanned, final_utxo_pos, elapsed)) => { debug!(target: LOG_TARGET, "Scanned to UTXO #{}", final_utxo_pos); self.finalize(total_scanned, final_utxo_pos, elapsed).await?; return Ok(()); }, Err(e) => { warn!( target: LOG_TARGET, "Failed to scan UTXO's from base node {}: {}", peer, e ); self.publish_event(UtxoScannerEvent::ScanningRoundFailed { num_retries: self.num_retries, retry_limit: self.retry_limit, error: e.to_string(), }); continue; }, }, None => { self.publish_event(UtxoScannerEvent::ScanningRoundFailed { num_retries: self.num_retries, retry_limit: self.retry_limit, error: "No new peers to try after this round".to_string(), }); if self.num_retries >= self.retry_limit { self.publish_event(UtxoScannerEvent::ScanningFailed); return Err(UtxoScannerError::UtxoScanningError(format!( "Failed to scan UTXO's after {} attempt(s) using all {} sync peer(s). Aborting...", self.num_retries, self.peer_seeds.len() ))); } self.num_retries += 1; // Reset peer index to try connect to the first peer again self.peer_index = 0; }, } } } fn get_next_peer(&mut self) -> Option<NodeId> { let peer = self.peer_seeds.get(self.peer_index).map(NodeId::from_public_key); self.peer_index += 1; peer } async fn get_birthday_metadata( &self, client: &mut BaseNodeSyncRpcClient, ) -> Result<ScanningMetadata, UtxoScannerError> { let birthday = self.resources.db.get_wallet_birthday().await?; // Calculate the unix epoch time of two days before the wallet birthday. This is to avoid any weird time zone // issues let epoch_time = (birthday.saturating_sub(2) as u64) * 60 * 60 * 24; let block_height = match client.get_height_at_time(epoch_time).await { Ok(b) => b, Err(e) => { warn!( target: LOG_TARGET, "Problem requesting `height_at_time` from Base Node: {}", e ); 0 }, }; let header = client.get_header_by_height(block_height).await?; let header = BlockHeader::try_from(header).map_err(|_| UtxoScannerError::ConversionError)?; info!( target: LOG_TARGET, "Fresh wallet recovery starting at Block {}", block_height ); Ok(ScanningMetadata { total_amount: Default::default(), number_of_utxos: 0, utxo_index: header.output_mmr_size, height_hash: header.hash(), }) } } fn convert_response_to_transaction_outputs( response: Vec<Result<proto::base_node::SyncUtxosResponse, RpcStatus>>, last_utxo_index: u64, ) -> Result<(Vec<TransactionOutput>, u64), UtxoScannerError> { let response: Vec<proto::base_node::SyncUtxosResponse> = response .into_iter() .map(|v| v.map_err(|e| UtxoScannerError::RpcStatus(e.to_string()))) .collect::<Result<Vec<_>, _>>()?; let current_utxo_index = response // Assumes correct ordering which is otherwise not required for this protocol .last() .ok_or_else(|| { UtxoScannerError::BaseNodeResponseError("Invalid response from base node: response was empty".to_string()) })? .mmr_index; if current_utxo_index < last_utxo_index { return Err(UtxoScannerError::BaseNodeResponseError( "Invalid response from base node: mmr index must be non-decreasing".to_string(), )); } let outputs = response .into_iter() .filter_map(|utxo| { utxo.into_utxo() .and_then(|o| o.utxo) .and_then(|utxo| utxo.into_transaction_output()) .map(|output| TransactionOutput::try_from(output).map_err(|_| UtxoScannerError::ConversionError)) }) .collect::<Result<Vec<_>, _>>()?; Ok((outputs, current_utxo_index)) }
get_chain_tip_header
identifier_name
utxo_scanner_task.rs
// Copyright 2021. The Tari Project // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the // following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following // disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the // following disclaimer in the documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote // products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. use chrono::Utc; use futures::StreamExt; use log::*; use std::{ convert::TryFrom, time::{Duration, Instant}, }; use tari_common_types::transaction::TxId; use tari_comms::{ peer_manager::NodeId, protocol::rpc::{RpcError, RpcStatus}, types::CommsPublicKey, PeerConnection, }; use tari_core::{ base_node::sync::rpc::BaseNodeSyncRpcClient, blocks::BlockHeader, crypto::tari_utilities::hex::Hex, proto, proto::base_node::{FindChainSplitRequest, SyncUtxosRequest}, tari_utilities::Hashable, transactions::{ tari_amount::MicroTari, transaction_entities::{TransactionOutput, UnblindedOutput}, }, }; use tari_shutdown::ShutdownSignal; use tokio::{sync::broadcast, time}; use crate::{ error::WalletError, storage::database::WalletBackend, utxo_scanner_service::{ error::UtxoScannerError, handle::UtxoScannerEvent, service::{ScanningMetadata, UtxoScannerResources}, uxto_scanner_service_builder::UtxoScannerMode, }, }; pub const LOG_TARGET: &str = "wallet::utxo_scanning"; pub const RECOVERY_KEY: &str = "recovery_data"; const SCANNING_KEY: &str = "scanning_data"; pub struct UtxoScannerTask<TBackend> where TBackend: WalletBackend + 'static { pub(crate) resources: UtxoScannerResources<TBackend>, pub(crate) event_sender: broadcast::Sender<UtxoScannerEvent>, pub(crate) retry_limit: usize, pub(crate) num_retries: usize, pub(crate) peer_seeds: Vec<CommsPublicKey>, pub(crate) peer_index: usize, pub(crate) mode: UtxoScannerMode, pub(crate) shutdown_signal: ShutdownSignal, } impl<TBackend> UtxoScannerTask<TBackend> where TBackend: WalletBackend + 'static { async fn finalize( &self, total_scanned: u64, final_utxo_pos: u64, elapsed: Duration, ) -> Result<(), UtxoScannerError> { let metadata = self.get_metadata().await?.unwrap_or_default(); self.publish_event(UtxoScannerEvent::Progress { current_index: final_utxo_pos, total_index: final_utxo_pos, }); self.publish_event(UtxoScannerEvent::Completed { number_scanned: total_scanned, number_received: metadata.number_of_utxos, value_received: metadata.total_amount, time_taken: elapsed, }); // Presence of scanning keys are used to determine if a wallet is busy with recovery or not. if self.mode == UtxoScannerMode::Recovery { self.clear_db().await?; } Ok(()) } async fn connect_to_peer(&mut self, peer: NodeId) -> Result<PeerConnection, UtxoScannerError> { self.publish_event(UtxoScannerEvent::ConnectingToBaseNode(peer.clone())); debug!( target: LOG_TARGET, "Attempting UTXO sync with seed peer {} ({})", self.peer_index, peer, ); match self.resources.comms_connectivity.dial_peer(peer.clone()).await { Ok(conn) => Ok(conn), Err(e) => { self.publish_event(UtxoScannerEvent::ConnectionFailedToBaseNode { peer: peer.clone(), num_retries: self.num_retries, retry_limit: self.retry_limit, error: e.to_string(), }); // No use re-dialing a peer that is not responsive for recovery mode if self.mode == UtxoScannerMode::Recovery { if let Ok(Some(connection)) = self.resources.comms_connectivity.get_connection(peer.clone()).await { if connection.clone().disconnect().await.is_ok() { debug!(target: LOG_TARGET, "Disconnected base node peer {}", peer); } }; let _ = time::sleep(Duration::from_secs(30)); } Err(e.into()) }, } } async fn attempt_sync(&mut self, peer: NodeId) -> Result<(u64, u64, Duration), UtxoScannerError> { let mut connection = self.connect_to_peer(peer.clone()).await?; let mut client = connection .connect_rpc_using_builder(BaseNodeSyncRpcClient::builder().with_deadline(Duration::from_secs(60))) .await?; let latency = client.get_last_request_latency(); self.publish_event(UtxoScannerEvent::ConnectedToBaseNode( peer.clone(), latency.unwrap_or_default(), )); let timer = Instant::now(); let mut total_scanned = 0u64; loop { let start_index = self.get_start_utxo_mmr_pos(&mut client).await?; let tip_header = self.get_chain_tip_header(&mut client).await?; let output_mmr_size = tip_header.output_mmr_size; if self.shutdown_signal.is_triggered() { // if running is set to false, we know its been canceled upstream so lets exit the loop return Ok((total_scanned, start_index, timer.elapsed())); } debug!( target: LOG_TARGET, "Scanning UTXO's (start_index = {}, output_mmr_size = {}, height = {}, tip_hash = {})", start_index, output_mmr_size, tip_header.height, tip_header.hash().to_hex() ); // start_index could be greater than output_mmr_size if we switch to a new peer that is behind the original // peer. In the common case, we wait for start index. if start_index >= output_mmr_size - 1 { debug!( target: LOG_TARGET, "Scanning complete UTXO #{} in {:.2?}", start_index, timer.elapsed() ); return Ok((total_scanned, start_index, timer.elapsed())); } let num_scanned = self.scan_utxos(&mut client, start_index, tip_header).await?; if num_scanned == 0 { return Err(UtxoScannerError::UtxoScanningError( "Peer returned 0 UTXOs to scan".to_string(), )); } debug!( target: LOG_TARGET, "Scanning round completed UTXO #{} in {:.2?} ({} scanned)", output_mmr_size, timer.elapsed(), num_scanned ); // let num_scanned = 0; total_scanned += num_scanned; // return Ok((total_scanned, start_index, timer.elapsed())); } } async fn get_chain_tip_header(&self, client: &mut BaseNodeSyncRpcClient) -> Result<BlockHeader, UtxoScannerError> { let chain_metadata = client.get_chain_metadata().await?; let chain_height = chain_metadata.height_of_longest_chain(); let end_header = client.get_header_by_height(chain_height).await?; let end_header = BlockHeader::try_from(end_header).map_err(|_| UtxoScannerError::ConversionError)?; Ok(end_header) } async fn get_start_utxo_mmr_pos(&self, client: &mut BaseNodeSyncRpcClient) -> Result<u64, UtxoScannerError> { let metadata = match self.get_metadata().await? { None => { let birthday_metadata = self.get_birthday_metadata(client).await?; self.set_metadata(birthday_metadata.clone()).await?; return Ok(birthday_metadata.utxo_index); }, Some(m) => m, }; // if it's none, we return 0 above. let request = FindChainSplitRequest { block_hashes: vec![metadata.height_hash], header_count: 1, }; // this returns the index of the vec of hashes we sent it, that is the last hash it knows of. match client.find_chain_split(request).await { Ok(_) => Ok(metadata.utxo_index + 1), Err(RpcError::RequestFailed(err)) if err.as_status_code().is_not_found() => { warn!(target: LOG_TARGET, "Reorg detected: {}", err); // The node does not know of the last hash we scanned, thus we had a chain split. // We now start at the wallet birthday again let birthday_metdadata = self.get_birthday_metadata(client).await?; Ok(birthday_metdadata.utxo_index) }, Err(err) => Err(err.into()), } } async fn scan_utxos( &mut self, client: &mut BaseNodeSyncRpcClient, start_mmr_leaf_index: u64, end_header: BlockHeader, ) -> Result<u64, UtxoScannerError> { debug!( target: LOG_TARGET, "Scanning UTXO's from #{} to #{} (height {})", start_mmr_leaf_index, end_header.output_mmr_size, end_header.height ); let end_header_hash = end_header.hash(); let output_mmr_size = end_header.output_mmr_size; let mut num_recovered = 0u64; let mut total_amount = MicroTari::from(0); let mut total_scanned = 0; self.publish_event(UtxoScannerEvent::Progress { current_index: start_mmr_leaf_index, total_index: (output_mmr_size - 1), }); let request = SyncUtxosRequest { start: start_mmr_leaf_index, end_header_hash: end_header_hash.clone(), include_pruned_utxos: false, include_deleted_bitmaps: false, }; let start = Instant::now(); let utxo_stream = client.sync_utxos(request).await?; trace!( target: LOG_TARGET, "bulletproof rewind profile - UTXO stream request time {} ms", start.elapsed().as_millis(), ); // We download in chunks for improved streaming efficiency const CHUNK_SIZE: usize = 125; let mut utxo_stream = utxo_stream.chunks(CHUNK_SIZE); const COMMIT_EVERY_N: u64 = (1000_i64 / CHUNK_SIZE as i64) as u64; let mut last_utxo_index = 0u64; let mut iteration_count = 0u64; let mut utxo_next_await_profiling = Vec::new(); let mut scan_for_outputs_profiling = Vec::new(); while let Some(response) = { let start = Instant::now(); let utxo_stream_next = utxo_stream.next().await; utxo_next_await_profiling.push(start.elapsed()); utxo_stream_next } { if self.shutdown_signal.is_triggered() { // if running is set to false, we know its been canceled upstream so lets exit the loop return Ok(total_scanned as u64); } let (outputs, utxo_index) = convert_response_to_transaction_outputs(response, last_utxo_index)?; last_utxo_index = utxo_index; total_scanned += outputs.len(); iteration_count += 1; let start = Instant::now(); let found_outputs = self.scan_for_outputs(outputs).await?; scan_for_outputs_profiling.push(start.elapsed()); // Reduce the number of db hits by only persisting progress every N iterations if iteration_count % COMMIT_EVERY_N == 0 || last_utxo_index >= output_mmr_size - 1 { self.publish_event(UtxoScannerEvent::Progress { current_index: last_utxo_index, total_index: (output_mmr_size - 1), }); self.update_scanning_progress_in_db( last_utxo_index, total_amount, num_recovered, end_header_hash.clone(), ) .await?; } let (count, amount) = self.import_utxos_to_transaction_service(found_outputs).await?; num_recovered = num_recovered.saturating_add(count); total_amount += amount; } trace!( target: LOG_TARGET, "bulletproof rewind profile - streamed {} outputs in {} ms", total_scanned, utxo_next_await_profiling.iter().fold(0, |acc, &x| acc + x.as_millis()), ); trace!( target: LOG_TARGET, "bulletproof rewind profile - scanned {} outputs in {} ms", total_scanned, scan_for_outputs_profiling.iter().fold(0, |acc, &x| acc + x.as_millis()), ); self.update_scanning_progress_in_db(last_utxo_index, total_amount, num_recovered, end_header_hash) .await?; self.publish_event(UtxoScannerEvent::Progress { current_index: (output_mmr_size - 1), total_index: (output_mmr_size - 1), }); Ok(total_scanned as u64) } async fn update_scanning_progress_in_db( &self, last_utxo_index: u64, total_amount: MicroTari, num_recovered: u64, end_header_hash: Vec<u8>, ) -> Result<(), UtxoScannerError> { let mut meta_data = self.get_metadata().await?.unwrap_or_default(); meta_data.height_hash = end_header_hash; meta_data.number_of_utxos += num_recovered; meta_data.utxo_index = last_utxo_index; meta_data.total_amount += total_amount; self.set_metadata(meta_data).await?; Ok(()) } async fn scan_for_outputs( &mut self, outputs: Vec<TransactionOutput>, ) -> Result<Vec<(UnblindedOutput, String)>, UtxoScannerError> { let mut found_outputs: Vec<(UnblindedOutput, String)> = Vec::new(); if self.mode == UtxoScannerMode::Recovery { found_outputs.append( &mut self .resources .output_manager_service .scan_for_recoverable_outputs(outputs.clone()) .await? .into_iter() .map(|v| (v, format!("Recovered on {}.", Utc::now().naive_utc()))) .collect(), ); }; found_outputs.append( &mut self .resources .output_manager_service .scan_outputs_for_one_sided_payments(outputs.clone()) .await? .into_iter() .map(|v| { ( v, format!("Detected one-sided transaction on {}.", Utc::now().naive_utc()), ) }) .collect(), ); Ok(found_outputs) } async fn import_utxos_to_transaction_service( &mut self, utxos: Vec<(UnblindedOutput, String)>, ) -> Result<(u64, MicroTari), UtxoScannerError> { let mut num_recovered = 0u64; let mut total_amount = MicroTari::from(0); let source_public_key = self.resources.node_identity.public_key().clone(); for uo in utxos { match self .import_unblinded_utxo_to_transaction_service(uo.0.clone(), &source_public_key, uo.1) .await { Ok(_) => { num_recovered = num_recovered.saturating_add(1); total_amount += uo.0.value; }, Err(e) => return Err(UtxoScannerError::UtxoImportError(e.to_string())), } } Ok((num_recovered, total_amount)) } fn get_db_mode_key(&self) -> String { match self.mode { UtxoScannerMode::Recovery => RECOVERY_KEY.to_owned(), UtxoScannerMode::Scanning => SCANNING_KEY.to_owned(), } } async fn set_metadata(&self, data: ScanningMetadata) -> Result<(), UtxoScannerError> { let total_key = self.get_db_mode_key(); let db_value = serde_json::to_string(&data)?; self.resources.db.set_client_key_value(total_key, db_value).await?; Ok(()) } async fn get_metadata(&self) -> Result<Option<ScanningMetadata>, UtxoScannerError> { let total_key = self.get_db_mode_key(); let value: Option<String> = self.resources.db.get_client_key_from_str(total_key).await?; match value { None => Ok(None), Some(v) => Ok(serde_json::from_str(&v)?), } } async fn clear_db(&self) -> Result<(), UtxoScannerError> { let total_key = self.get_db_mode_key(); let _ = self.resources.db.clear_client_value(total_key).await?; Ok(()) } fn publish_event(&self, event: UtxoScannerEvent) { let _ = self.event_sender.send(event); } /// A faux incoming transaction will be created to provide a record of the event of importing a UTXO. The TxId of /// the generated transaction is returned. pub async fn import_unblinded_utxo_to_transaction_service( &mut self, unblinded_output: UnblindedOutput, source_public_key: &CommsPublicKey, message: String, ) -> Result<TxId, WalletError> { let tx_id = self .resources .transaction_service .import_utxo( unblinded_output.value, source_public_key.clone(), message, Some(unblinded_output.features.maturity), ) .await?; info!( target: LOG_TARGET, "UTXO (Commitment: {}) imported into wallet", unblinded_output .as_transaction_input(&self.resources.factories.commitment)? .commitment .to_hex() ); Ok(tx_id) } pub async fn run(mut self) -> Result<(), UtxoScannerError> { loop { if self.shutdown_signal.is_triggered() { // if running is set to false, we know its been canceled upstream so lets exit the loop return Ok(()); } match self.get_next_peer() { Some(peer) => match self.attempt_sync(peer.clone()).await { Ok((total_scanned, final_utxo_pos, elapsed)) => { debug!(target: LOG_TARGET, "Scanned to UTXO #{}", final_utxo_pos); self.finalize(total_scanned, final_utxo_pos, elapsed).await?; return Ok(()); }, Err(e) => { warn!( target: LOG_TARGET, "Failed to scan UTXO's from base node {}: {}", peer, e ); self.publish_event(UtxoScannerEvent::ScanningRoundFailed { num_retries: self.num_retries, retry_limit: self.retry_limit, error: e.to_string(), }); continue; }, }, None => { self.publish_event(UtxoScannerEvent::ScanningRoundFailed { num_retries: self.num_retries, retry_limit: self.retry_limit, error: "No new peers to try after this round".to_string(), }); if self.num_retries >= self.retry_limit { self.publish_event(UtxoScannerEvent::ScanningFailed); return Err(UtxoScannerError::UtxoScanningError(format!( "Failed to scan UTXO's after {} attempt(s) using all {} sync peer(s). Aborting...", self.num_retries, self.peer_seeds.len() ))); } self.num_retries += 1; // Reset peer index to try connect to the first peer again self.peer_index = 0; }, } } } fn get_next_peer(&mut self) -> Option<NodeId>
async fn get_birthday_metadata( &self, client: &mut BaseNodeSyncRpcClient, ) -> Result<ScanningMetadata, UtxoScannerError> { let birthday = self.resources.db.get_wallet_birthday().await?; // Calculate the unix epoch time of two days before the wallet birthday. This is to avoid any weird time zone // issues let epoch_time = (birthday.saturating_sub(2) as u64) * 60 * 60 * 24; let block_height = match client.get_height_at_time(epoch_time).await { Ok(b) => b, Err(e) => { warn!( target: LOG_TARGET, "Problem requesting `height_at_time` from Base Node: {}", e ); 0 }, }; let header = client.get_header_by_height(block_height).await?; let header = BlockHeader::try_from(header).map_err(|_| UtxoScannerError::ConversionError)?; info!( target: LOG_TARGET, "Fresh wallet recovery starting at Block {}", block_height ); Ok(ScanningMetadata { total_amount: Default::default(), number_of_utxos: 0, utxo_index: header.output_mmr_size, height_hash: header.hash(), }) } } fn convert_response_to_transaction_outputs( response: Vec<Result<proto::base_node::SyncUtxosResponse, RpcStatus>>, last_utxo_index: u64, ) -> Result<(Vec<TransactionOutput>, u64), UtxoScannerError> { let response: Vec<proto::base_node::SyncUtxosResponse> = response .into_iter() .map(|v| v.map_err(|e| UtxoScannerError::RpcStatus(e.to_string()))) .collect::<Result<Vec<_>, _>>()?; let current_utxo_index = response // Assumes correct ordering which is otherwise not required for this protocol .last() .ok_or_else(|| { UtxoScannerError::BaseNodeResponseError("Invalid response from base node: response was empty".to_string()) })? .mmr_index; if current_utxo_index < last_utxo_index { return Err(UtxoScannerError::BaseNodeResponseError( "Invalid response from base node: mmr index must be non-decreasing".to_string(), )); } let outputs = response .into_iter() .filter_map(|utxo| { utxo.into_utxo() .and_then(|o| o.utxo) .and_then(|utxo| utxo.into_transaction_output()) .map(|output| TransactionOutput::try_from(output).map_err(|_| UtxoScannerError::ConversionError)) }) .collect::<Result<Vec<_>, _>>()?; Ok((outputs, current_utxo_index)) }
{ let peer = self.peer_seeds.get(self.peer_index).map(NodeId::from_public_key); self.peer_index += 1; peer }
identifier_body
utxo_scanner_task.rs
// Copyright 2021. The Tari Project // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the // following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following // disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the // following disclaimer in the documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote // products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. use chrono::Utc; use futures::StreamExt; use log::*; use std::{ convert::TryFrom, time::{Duration, Instant}, }; use tari_common_types::transaction::TxId; use tari_comms::{ peer_manager::NodeId, protocol::rpc::{RpcError, RpcStatus}, types::CommsPublicKey, PeerConnection, }; use tari_core::{ base_node::sync::rpc::BaseNodeSyncRpcClient, blocks::BlockHeader, crypto::tari_utilities::hex::Hex, proto, proto::base_node::{FindChainSplitRequest, SyncUtxosRequest}, tari_utilities::Hashable, transactions::{ tari_amount::MicroTari, transaction_entities::{TransactionOutput, UnblindedOutput}, }, }; use tari_shutdown::ShutdownSignal; use tokio::{sync::broadcast, time}; use crate::{ error::WalletError, storage::database::WalletBackend, utxo_scanner_service::{ error::UtxoScannerError, handle::UtxoScannerEvent, service::{ScanningMetadata, UtxoScannerResources}, uxto_scanner_service_builder::UtxoScannerMode, }, }; pub const LOG_TARGET: &str = "wallet::utxo_scanning"; pub const RECOVERY_KEY: &str = "recovery_data"; const SCANNING_KEY: &str = "scanning_data"; pub struct UtxoScannerTask<TBackend> where TBackend: WalletBackend + 'static { pub(crate) resources: UtxoScannerResources<TBackend>, pub(crate) event_sender: broadcast::Sender<UtxoScannerEvent>, pub(crate) retry_limit: usize, pub(crate) num_retries: usize, pub(crate) peer_seeds: Vec<CommsPublicKey>, pub(crate) peer_index: usize, pub(crate) mode: UtxoScannerMode, pub(crate) shutdown_signal: ShutdownSignal, } impl<TBackend> UtxoScannerTask<TBackend> where TBackend: WalletBackend + 'static { async fn finalize( &self, total_scanned: u64, final_utxo_pos: u64, elapsed: Duration, ) -> Result<(), UtxoScannerError> { let metadata = self.get_metadata().await?.unwrap_or_default(); self.publish_event(UtxoScannerEvent::Progress { current_index: final_utxo_pos, total_index: final_utxo_pos, }); self.publish_event(UtxoScannerEvent::Completed { number_scanned: total_scanned, number_received: metadata.number_of_utxos, value_received: metadata.total_amount, time_taken: elapsed, }); // Presence of scanning keys are used to determine if a wallet is busy with recovery or not. if self.mode == UtxoScannerMode::Recovery { self.clear_db().await?; } Ok(()) } async fn connect_to_peer(&mut self, peer: NodeId) -> Result<PeerConnection, UtxoScannerError> { self.publish_event(UtxoScannerEvent::ConnectingToBaseNode(peer.clone())); debug!( target: LOG_TARGET, "Attempting UTXO sync with seed peer {} ({})", self.peer_index, peer, ); match self.resources.comms_connectivity.dial_peer(peer.clone()).await { Ok(conn) => Ok(conn), Err(e) => { self.publish_event(UtxoScannerEvent::ConnectionFailedToBaseNode { peer: peer.clone(), num_retries: self.num_retries, retry_limit: self.retry_limit, error: e.to_string(), }); // No use re-dialing a peer that is not responsive for recovery mode if self.mode == UtxoScannerMode::Recovery { if let Ok(Some(connection)) = self.resources.comms_connectivity.get_connection(peer.clone()).await { if connection.clone().disconnect().await.is_ok() { debug!(target: LOG_TARGET, "Disconnected base node peer {}", peer); } }; let _ = time::sleep(Duration::from_secs(30)); } Err(e.into()) }, } } async fn attempt_sync(&mut self, peer: NodeId) -> Result<(u64, u64, Duration), UtxoScannerError> { let mut connection = self.connect_to_peer(peer.clone()).await?; let mut client = connection .connect_rpc_using_builder(BaseNodeSyncRpcClient::builder().with_deadline(Duration::from_secs(60))) .await?; let latency = client.get_last_request_latency(); self.publish_event(UtxoScannerEvent::ConnectedToBaseNode( peer.clone(), latency.unwrap_or_default(), )); let timer = Instant::now(); let mut total_scanned = 0u64; loop { let start_index = self.get_start_utxo_mmr_pos(&mut client).await?; let tip_header = self.get_chain_tip_header(&mut client).await?; let output_mmr_size = tip_header.output_mmr_size; if self.shutdown_signal.is_triggered() { // if running is set to false, we know its been canceled upstream so lets exit the loop return Ok((total_scanned, start_index, timer.elapsed())); } debug!( target: LOG_TARGET, "Scanning UTXO's (start_index = {}, output_mmr_size = {}, height = {}, tip_hash = {})", start_index, output_mmr_size, tip_header.height, tip_header.hash().to_hex() ); // start_index could be greater than output_mmr_size if we switch to a new peer that is behind the original // peer. In the common case, we wait for start index. if start_index >= output_mmr_size - 1 { debug!( target: LOG_TARGET, "Scanning complete UTXO #{} in {:.2?}", start_index, timer.elapsed() ); return Ok((total_scanned, start_index, timer.elapsed())); } let num_scanned = self.scan_utxos(&mut client, start_index, tip_header).await?; if num_scanned == 0 { return Err(UtxoScannerError::UtxoScanningError( "Peer returned 0 UTXOs to scan".to_string(), )); } debug!( target: LOG_TARGET, "Scanning round completed UTXO #{} in {:.2?} ({} scanned)", output_mmr_size, timer.elapsed(), num_scanned ); // let num_scanned = 0; total_scanned += num_scanned; // return Ok((total_scanned, start_index, timer.elapsed())); } } async fn get_chain_tip_header(&self, client: &mut BaseNodeSyncRpcClient) -> Result<BlockHeader, UtxoScannerError> { let chain_metadata = client.get_chain_metadata().await?; let chain_height = chain_metadata.height_of_longest_chain(); let end_header = client.get_header_by_height(chain_height).await?; let end_header = BlockHeader::try_from(end_header).map_err(|_| UtxoScannerError::ConversionError)?; Ok(end_header) } async fn get_start_utxo_mmr_pos(&self, client: &mut BaseNodeSyncRpcClient) -> Result<u64, UtxoScannerError> { let metadata = match self.get_metadata().await? { None => { let birthday_metadata = self.get_birthday_metadata(client).await?; self.set_metadata(birthday_metadata.clone()).await?; return Ok(birthday_metadata.utxo_index); }, Some(m) => m, }; // if it's none, we return 0 above. let request = FindChainSplitRequest { block_hashes: vec![metadata.height_hash], header_count: 1, }; // this returns the index of the vec of hashes we sent it, that is the last hash it knows of. match client.find_chain_split(request).await { Ok(_) => Ok(metadata.utxo_index + 1), Err(RpcError::RequestFailed(err)) if err.as_status_code().is_not_found() => { warn!(target: LOG_TARGET, "Reorg detected: {}", err); // The node does not know of the last hash we scanned, thus we had a chain split. // We now start at the wallet birthday again let birthday_metdadata = self.get_birthday_metadata(client).await?; Ok(birthday_metdadata.utxo_index) }, Err(err) => Err(err.into()), } } async fn scan_utxos( &mut self, client: &mut BaseNodeSyncRpcClient, start_mmr_leaf_index: u64, end_header: BlockHeader, ) -> Result<u64, UtxoScannerError> { debug!( target: LOG_TARGET, "Scanning UTXO's from #{} to #{} (height {})", start_mmr_leaf_index, end_header.output_mmr_size, end_header.height ); let end_header_hash = end_header.hash(); let output_mmr_size = end_header.output_mmr_size; let mut num_recovered = 0u64; let mut total_amount = MicroTari::from(0); let mut total_scanned = 0; self.publish_event(UtxoScannerEvent::Progress { current_index: start_mmr_leaf_index, total_index: (output_mmr_size - 1), }); let request = SyncUtxosRequest { start: start_mmr_leaf_index, end_header_hash: end_header_hash.clone(), include_pruned_utxos: false, include_deleted_bitmaps: false, }; let start = Instant::now(); let utxo_stream = client.sync_utxos(request).await?; trace!( target: LOG_TARGET, "bulletproof rewind profile - UTXO stream request time {} ms", start.elapsed().as_millis(), ); // We download in chunks for improved streaming efficiency const CHUNK_SIZE: usize = 125; let mut utxo_stream = utxo_stream.chunks(CHUNK_SIZE); const COMMIT_EVERY_N: u64 = (1000_i64 / CHUNK_SIZE as i64) as u64; let mut last_utxo_index = 0u64; let mut iteration_count = 0u64; let mut utxo_next_await_profiling = Vec::new(); let mut scan_for_outputs_profiling = Vec::new(); while let Some(response) = { let start = Instant::now(); let utxo_stream_next = utxo_stream.next().await; utxo_next_await_profiling.push(start.elapsed()); utxo_stream_next } { if self.shutdown_signal.is_triggered() { // if running is set to false, we know its been canceled upstream so lets exit the loop return Ok(total_scanned as u64); } let (outputs, utxo_index) = convert_response_to_transaction_outputs(response, last_utxo_index)?; last_utxo_index = utxo_index; total_scanned += outputs.len(); iteration_count += 1; let start = Instant::now(); let found_outputs = self.scan_for_outputs(outputs).await?; scan_for_outputs_profiling.push(start.elapsed()); // Reduce the number of db hits by only persisting progress every N iterations if iteration_count % COMMIT_EVERY_N == 0 || last_utxo_index >= output_mmr_size - 1 { self.publish_event(UtxoScannerEvent::Progress { current_index: last_utxo_index, total_index: (output_mmr_size - 1), }); self.update_scanning_progress_in_db( last_utxo_index, total_amount, num_recovered, end_header_hash.clone(), ) .await?; } let (count, amount) = self.import_utxos_to_transaction_service(found_outputs).await?; num_recovered = num_recovered.saturating_add(count); total_amount += amount; } trace!( target: LOG_TARGET, "bulletproof rewind profile - streamed {} outputs in {} ms", total_scanned, utxo_next_await_profiling.iter().fold(0, |acc, &x| acc + x.as_millis()), ); trace!( target: LOG_TARGET, "bulletproof rewind profile - scanned {} outputs in {} ms", total_scanned, scan_for_outputs_profiling.iter().fold(0, |acc, &x| acc + x.as_millis()), ); self.update_scanning_progress_in_db(last_utxo_index, total_amount, num_recovered, end_header_hash) .await?; self.publish_event(UtxoScannerEvent::Progress { current_index: (output_mmr_size - 1), total_index: (output_mmr_size - 1), }); Ok(total_scanned as u64) } async fn update_scanning_progress_in_db( &self, last_utxo_index: u64, total_amount: MicroTari, num_recovered: u64, end_header_hash: Vec<u8>, ) -> Result<(), UtxoScannerError> { let mut meta_data = self.get_metadata().await?.unwrap_or_default(); meta_data.height_hash = end_header_hash; meta_data.number_of_utxos += num_recovered; meta_data.utxo_index = last_utxo_index; meta_data.total_amount += total_amount; self.set_metadata(meta_data).await?; Ok(()) } async fn scan_for_outputs( &mut self, outputs: Vec<TransactionOutput>, ) -> Result<Vec<(UnblindedOutput, String)>, UtxoScannerError> { let mut found_outputs: Vec<(UnblindedOutput, String)> = Vec::new(); if self.mode == UtxoScannerMode::Recovery { found_outputs.append( &mut self .resources .output_manager_service .scan_for_recoverable_outputs(outputs.clone()) .await? .into_iter() .map(|v| (v, format!("Recovered on {}.", Utc::now().naive_utc()))) .collect(), ); }; found_outputs.append( &mut self .resources .output_manager_service .scan_outputs_for_one_sided_payments(outputs.clone()) .await? .into_iter() .map(|v| { ( v, format!("Detected one-sided transaction on {}.", Utc::now().naive_utc()), ) }) .collect(), ); Ok(found_outputs) } async fn import_utxos_to_transaction_service( &mut self, utxos: Vec<(UnblindedOutput, String)>, ) -> Result<(u64, MicroTari), UtxoScannerError> { let mut num_recovered = 0u64; let mut total_amount = MicroTari::from(0); let source_public_key = self.resources.node_identity.public_key().clone(); for uo in utxos { match self .import_unblinded_utxo_to_transaction_service(uo.0.clone(), &source_public_key, uo.1) .await { Ok(_) => { num_recovered = num_recovered.saturating_add(1); total_amount += uo.0.value; }, Err(e) => return Err(UtxoScannerError::UtxoImportError(e.to_string())), } } Ok((num_recovered, total_amount)) } fn get_db_mode_key(&self) -> String { match self.mode { UtxoScannerMode::Recovery => RECOVERY_KEY.to_owned(), UtxoScannerMode::Scanning => SCANNING_KEY.to_owned(), } } async fn set_metadata(&self, data: ScanningMetadata) -> Result<(), UtxoScannerError> { let total_key = self.get_db_mode_key(); let db_value = serde_json::to_string(&data)?; self.resources.db.set_client_key_value(total_key, db_value).await?; Ok(()) } async fn get_metadata(&self) -> Result<Option<ScanningMetadata>, UtxoScannerError> { let total_key = self.get_db_mode_key(); let value: Option<String> = self.resources.db.get_client_key_from_str(total_key).await?; match value { None => Ok(None), Some(v) => Ok(serde_json::from_str(&v)?), } } async fn clear_db(&self) -> Result<(), UtxoScannerError> { let total_key = self.get_db_mode_key(); let _ = self.resources.db.clear_client_value(total_key).await?; Ok(()) } fn publish_event(&self, event: UtxoScannerEvent) { let _ = self.event_sender.send(event); } /// A faux incoming transaction will be created to provide a record of the event of importing a UTXO. The TxId of /// the generated transaction is returned. pub async fn import_unblinded_utxo_to_transaction_service( &mut self, unblinded_output: UnblindedOutput, source_public_key: &CommsPublicKey, message: String, ) -> Result<TxId, WalletError> { let tx_id = self .resources .transaction_service .import_utxo( unblinded_output.value, source_public_key.clone(), message, Some(unblinded_output.features.maturity), ) .await?; info!( target: LOG_TARGET, "UTXO (Commitment: {}) imported into wallet", unblinded_output .as_transaction_input(&self.resources.factories.commitment)? .commitment .to_hex() ); Ok(tx_id) } pub async fn run(mut self) -> Result<(), UtxoScannerError> { loop { if self.shutdown_signal.is_triggered() { // if running is set to false, we know its been canceled upstream so lets exit the loop return Ok(()); } match self.get_next_peer() { Some(peer) => match self.attempt_sync(peer.clone()).await { Ok((total_scanned, final_utxo_pos, elapsed)) => { debug!(target: LOG_TARGET, "Scanned to UTXO #{}", final_utxo_pos); self.finalize(total_scanned, final_utxo_pos, elapsed).await?; return Ok(()); }, Err(e) => { warn!( target: LOG_TARGET, "Failed to scan UTXO's from base node {}: {}", peer, e ); self.publish_event(UtxoScannerEvent::ScanningRoundFailed { num_retries: self.num_retries, retry_limit: self.retry_limit, error: e.to_string(), }); continue; }, }, None => { self.publish_event(UtxoScannerEvent::ScanningRoundFailed { num_retries: self.num_retries, retry_limit: self.retry_limit, error: "No new peers to try after this round".to_string(), }); if self.num_retries >= self.retry_limit { self.publish_event(UtxoScannerEvent::ScanningFailed); return Err(UtxoScannerError::UtxoScanningError(format!( "Failed to scan UTXO's after {} attempt(s) using all {} sync peer(s). Aborting...", self.num_retries, self.peer_seeds.len() ))); } self.num_retries += 1; // Reset peer index to try connect to the first peer again self.peer_index = 0; }, } } } fn get_next_peer(&mut self) -> Option<NodeId> { let peer = self.peer_seeds.get(self.peer_index).map(NodeId::from_public_key); self.peer_index += 1; peer } async fn get_birthday_metadata( &self, client: &mut BaseNodeSyncRpcClient, ) -> Result<ScanningMetadata, UtxoScannerError> { let birthday = self.resources.db.get_wallet_birthday().await?; // Calculate the unix epoch time of two days before the wallet birthday. This is to avoid any weird time zone // issues let epoch_time = (birthday.saturating_sub(2) as u64) * 60 * 60 * 24; let block_height = match client.get_height_at_time(epoch_time).await { Ok(b) => b, Err(e) => { warn!( target: LOG_TARGET, "Problem requesting `height_at_time` from Base Node: {}", e ); 0 }, }; let header = client.get_header_by_height(block_height).await?; let header = BlockHeader::try_from(header).map_err(|_| UtxoScannerError::ConversionError)?; info!( target: LOG_TARGET, "Fresh wallet recovery starting at Block {}", block_height ); Ok(ScanningMetadata { total_amount: Default::default(), number_of_utxos: 0, utxo_index: header.output_mmr_size, height_hash: header.hash(), }) } } fn convert_response_to_transaction_outputs( response: Vec<Result<proto::base_node::SyncUtxosResponse, RpcStatus>>, last_utxo_index: u64, ) -> Result<(Vec<TransactionOutput>, u64), UtxoScannerError> { let response: Vec<proto::base_node::SyncUtxosResponse> = response .into_iter() .map(|v| v.map_err(|e| UtxoScannerError::RpcStatus(e.to_string()))) .collect::<Result<Vec<_>, _>>()?;
UtxoScannerError::BaseNodeResponseError("Invalid response from base node: response was empty".to_string()) })? .mmr_index; if current_utxo_index < last_utxo_index { return Err(UtxoScannerError::BaseNodeResponseError( "Invalid response from base node: mmr index must be non-decreasing".to_string(), )); } let outputs = response .into_iter() .filter_map(|utxo| { utxo.into_utxo() .and_then(|o| o.utxo) .and_then(|utxo| utxo.into_transaction_output()) .map(|output| TransactionOutput::try_from(output).map_err(|_| UtxoScannerError::ConversionError)) }) .collect::<Result<Vec<_>, _>>()?; Ok((outputs, current_utxo_index)) }
let current_utxo_index = response // Assumes correct ordering which is otherwise not required for this protocol .last() .ok_or_else(|| {
random_line_split
app.js
require("./js/main.js"); require("./scss/style.scss"); const firebase = require("firebase").default; var firebaseConfig = require("./firebase-config.js"); // Initialize Firebase firebase.initializeApp(firebaseConfig); firebase.analytics(); // initialize a db const db = firebase.database(); // ================== CHAPTER 2: REAL TIME DATABASE =========================================== // push some data to the DB // in firebase a/b will create a folder like structure db.ref("packtpub/tweets").set({ name: "Nevaan Perera", text: "Hello, I am learning firebase!", date: Date.now(), }); // push lets create a new instance of data we are pushing (so the object pushed will have a UUID every time it gets inserted) // ------------------------------ // db.ref("packtpub/chat").push({ // name: "Nevaan Perera!", // message: "Hello All !", // photo_url: "gefgewouhfoewuewbchoiewce", // }); // We just wanna get the data once (no real time capabilities) firebase .database() .ref("/packtpub/tweets") .once("value") .then((snapshot) => { console.log("ONCE SNAPSHOT", snapshot); }); // We want to keep an eye on data that is constantly changing var adminRef = firebase.database().ref("/packtpub/tweets"); adminRef.on("value", (snapshot) => { console.log("REALTIME SNAPSHOT", snapshot); }); // Can we add a reference to something that is not in the DB, but could be added later? -- lets try // ------------- YES, THIS ACTUALLY WORKS ------------------ var packtpubRef1 = firebase.database().ref("packtpub"); const notthere = packtpubRef1.child("notthere"); notthere.on("value", (snapshot) => { console.log("REALTIME NOT THERE", snapshot); }); // Referencing children using the .child() --> same as providing a relative path to .ref() ex: 'packtpub/tweets' var packtpubRef2 = firebase.database().ref("packtpub"); var childRef = packtpubRef2.child("tweets"); console.log("Child Ref", childRef); // The update() function will give us the option to send simultaneous update calls to our database, and won't do anything besides the expected behavior of an update function, that is, updating the data without altering the reference of the record. // The set() function, within its behavior, changes the reference to the data itself while replacing it with a new one. setTimeout(() => { const tweet = { text: "updating the text mates", date: Date(), }; firebase.database().ref("/packtpub/tweets").update(tweet); }, 5000); // Check if we are connected to firebase let miConnected = firebase.database().ref(".info/connected"); miConnected.on("value", function (res) { if (res.val() === true) { console.log("I AM CONNECTED!"); } else { console.log("I AM DIS-CONNECTED!"); } }); // ================== CHAPTER 3: FILE MANAGEMENT =========================================== // Uploading files to Firebase const input = document.getElementById("file-input"); if (input) { const uploadToFirebase = () => { let file = input.files[0]; //Getting the file from the upload if (file) { //Getting the root ref from the Firebase Storage. let rootRef = firebase.storage().ref(); // nameA/nameB/nameC created a folder like structure let fileRef = rootRef.child(`images/${file.name}`);
}) .catch((err) => console.log(err)); } }; input.addEventListener("change", uploadToFirebase); } // Downloading files from Firebase // the filename and its extension need to be grabbed from a custom logic of your own. // That is done by using a local database that holds a small metadata fingerprint of the file after you upload it. // Later on, whenever you want to do any kind of custom logic, it will be with ease. var rootRef = firebase.storage().ref(); var imageRef = rootRef.child("images/one.png"); imageRef .getDownloadURL() .then((url) => { const imageTag = document.getElementById("firebase-image"); if (imageTag) { imageTag.src = url; } console.log("IMAGE URL TO FILE: ", url); }) .catch((err) => console.log(err)); // Deleting a file // just call imageRef.delete() ---> Returns a promise // Getting file meta data //No let's get the file metadata. imageRef .getMetadata() .then((meta) => { //Meta function parameter represent our file metadata. console.log("META DATA", meta); }) .catch((err) => console.log(err)); // Handling Errors // .catch(err => { // switch (err.code) { // case 'storage/unknown': // break; // case 'storage/object_not_found': // breaks; // case : 'storage/project_not_found': // breaks; // case : 'storage/unauthenticated': // breaks; // case : 'storage/unauthorized': // breaks; // .. // ... // .... // } // }); // ================== CHAPTER 4: AUTHENTICATION =========================================== // Went to firebase authintication console --> enabled auth --> selected email, p --> added a user // SIGN IN - this would be inside an event listener after a user has submitted their username / p const email = "nevaan9@gmail.com"; const p = "helloworld123"; // dummy firebase .auth() .signInWithEmailAndPassword(email, p) .then((user) => { console.log("USER: ", user); }) .catch(function (error) { console.error("ERROR GETTING USER", error); }); // SIGN OUT setTimeout(() => { console.log("Logging out!"); firebase .auth() .signOut() .then(() => { console.log("Success Logout!"); }) .catch((e) => { console.error("Error Logout!", e); }); }, 7000); // ------- Anonymous Auth ---------- // firebase // .auth() // .signInAnonymously() // .catch((err) => {}); // Event listener for auth stuff firebase.auth().onAuthStateChanged((user) => { // check the user object to see if signed in or out console.log(user); }); // Logging in with 3rd party providers (most providers are the same logic) // Google // MAKE SURE YOU ADD GOOGLE AS AN ALLOWED AUTH IN FIREBASE let googleLogin = document.getElementById("googleLogin"); if (googleLogin) { googleLogin.addEventListener("click", () => { //1. Get a GoogleAuthProvider instance. var googleProvider = new firebase.auth.GoogleAuthProvider(); firebase .auth() .signInWithPopup(googleProvider) .then(function (result) { console.log("GOOGLE AUTH RESULT: ", result); var user = result.user; console.log("GOOGLE AUTH USER: ", user); }) .catch(function (error) { //TODO: Handle Errors here. console.log("Google auth error: ", error); }); }); } // Implementing user meta retrieval let currentUserInfo = document.getElementById("currentUserInfo"); if (currentUserInfo) { currentUserInfo.addEventListener("click", () => { var user = firebase.auth().currentUser; var currentUser = null; if (user != null) { var currentUser = {}; currentUser.name = user.displayName; currentUser.email = user.email; currentUser.photoUrl = user.photoURL; currentUser.emailVerified = user.emailVerified; currentUser.uid = user.uid; } console.log("CURRENT USER INFO", currentUser); }); } // ---------- We also can LINK ACCOUND TOGETHER ---------------------------- // This is important so the same uuid is used across there multiple accounts // let facebookProvider = new firebase.auth.FacebookAuthProvider(); // let twitterProvider = new firebase.auth.TwitterAuthProvider(); // let googleProvider = new firebase.auth.GoogleAuthProvider(); // auth.currentUser.linkWithPopup(facebookProvider).then(function(result) { // // handle success res // }).catch(function(error) { // // handle error res // }); // ================================= CHAPTER 5. SECURING APPLICATION FLOW WITH FIREBASE RULES (AUTHORIZATION) ================================ // Firebase used the BOLT Language for this // Need to install the bolt language -- npm i firebase-bolt // Can compile any file that has the .bolt ext using `firebase-bolt <filename>.bolt` in the terminal --> this will generate a .json file // We can secure all firebase services (database, storage, messaging etc) // 1. // ----- Securing data base using bolt (example) ----- // path /articles/{uid}/drafts { // /create { // create() { // isCreator(uid) // } // } // /publish { // update() { // isCreator(uid) // } // } // /delete { // delete() { // isCreator(uid) // } // } // } // isCreator(uid) { // uid == auth.uid // } // We're setting a new path for our Articles awesome website in the drafts section for a specific user, represented in the uid dynamically changed value. // Under that specific path or route, we're securing the sub-routes and check the create, public, and delete routes by checking that the currently authenticated user uid is the same as the one who is to manipulate that data within our database. // We're setting the isCreator function with uid as a parameter for privileges checking. // 2. // ----- securing storage (example) ------ // ----- Add the following in the storage rules section ----- // service firebase.storage { // match /b/{bucket}/o { // match /catgifs { // match /{allGifs=**} { // allow read; // } // match /secret/superfunny/{imageId} { // allow read, write:if request.auth !=null; // } // } // } // } // service firebase.storage: This line is essential; we're simply telling Firebase about the service we're trying to secure, in our case it will be the Firebase/storage service. // match /b/{bucket}/o: This rule combines another powerful system, we're speaking mainly about the matching system, the Storage Rules uses this keyword to filter through files path, and what Firebase calls wildcards path also the match system supports nested matching, which is exactly what we're using in this example. Another interesting point is the matching against in this line: /b/{bucket}/o, this is simply another match we're evaluating to make sure that we're securing files within the Cloud Storage bucket. // We previously spoke about the wildcards paths. They are simply a matching pattern, so let's decompose it. The path we're matching against in this case will be the following: "/catgifs/**" which means for every single path variation within it we're using another rule, speaking of allow which will simply allow whether read or write operations or both. // Over the last match we had, we're making sure that no user will have the writing privileges except the authenticated one, in this case, where we will be using the wildcard--A simple matcher that represent each element id within that resource--represented in {imageId} and allowing both read and write in case the sent request holds an auth property within, besides those objects are global so you don't need to define them. // 2.1 // ------ Securing contnet based on userId (example) ----- // match /secured/personal/{userId}/images/{imageId} { // allow read:if request.auth.uid == userId; // } // match /secured/personal/{userId}/books/{bookId} { // allow read:if request.auth.uid == userId; // } // match /secured/personal/{userId}/images/{imageId} { // allow write:if request.auth.uid == userId && request.resource.size < 15*1024*1024 && request.resource.contentType.matches('image/.*'); // } // match /secured/personal/{userId}/books/{bookId} { // allow write:if request.auth.uid == userId && request.resource.size < 100*1024*1024 && request.resource.contentType.matches('application/pdf'); // } // We're trying to protect user-related media, so to do that we've created a new route with two dynamic parameters: the usersId for authentication management, and image id as well. In the first two match we're using the allow rule so we can simply allow the reading of our images and book in case we're authenticated and the request uid matched the one from the user asking for them. // In the second two-match we're doing some content type management, so if we're securing the images, we need to make sure that images inside that section of the bucket are in fact images and the same thing with books. We're also making some size management, and checking if the image or the book won't exceed the allowed files predefined size.
fileRef .put(file) .then(() => { console.log("your images was uploaded !");
random_line_split
app.js
require("./js/main.js"); require("./scss/style.scss"); const firebase = require("firebase").default; var firebaseConfig = require("./firebase-config.js"); // Initialize Firebase firebase.initializeApp(firebaseConfig); firebase.analytics(); // initialize a db const db = firebase.database(); // ================== CHAPTER 2: REAL TIME DATABASE =========================================== // push some data to the DB // in firebase a/b will create a folder like structure db.ref("packtpub/tweets").set({ name: "Nevaan Perera", text: "Hello, I am learning firebase!", date: Date.now(), }); // push lets create a new instance of data we are pushing (so the object pushed will have a UUID every time it gets inserted) // ------------------------------ // db.ref("packtpub/chat").push({ // name: "Nevaan Perera!", // message: "Hello All !", // photo_url: "gefgewouhfoewuewbchoiewce", // }); // We just wanna get the data once (no real time capabilities) firebase .database() .ref("/packtpub/tweets") .once("value") .then((snapshot) => { console.log("ONCE SNAPSHOT", snapshot); }); // We want to keep an eye on data that is constantly changing var adminRef = firebase.database().ref("/packtpub/tweets"); adminRef.on("value", (snapshot) => { console.log("REALTIME SNAPSHOT", snapshot); }); // Can we add a reference to something that is not in the DB, but could be added later? -- lets try // ------------- YES, THIS ACTUALLY WORKS ------------------ var packtpubRef1 = firebase.database().ref("packtpub"); const notthere = packtpubRef1.child("notthere"); notthere.on("value", (snapshot) => { console.log("REALTIME NOT THERE", snapshot); }); // Referencing children using the .child() --> same as providing a relative path to .ref() ex: 'packtpub/tweets' var packtpubRef2 = firebase.database().ref("packtpub"); var childRef = packtpubRef2.child("tweets"); console.log("Child Ref", childRef); // The update() function will give us the option to send simultaneous update calls to our database, and won't do anything besides the expected behavior of an update function, that is, updating the data without altering the reference of the record. // The set() function, within its behavior, changes the reference to the data itself while replacing it with a new one. setTimeout(() => { const tweet = { text: "updating the text mates", date: Date(), }; firebase.database().ref("/packtpub/tweets").update(tweet); }, 5000); // Check if we are connected to firebase let miConnected = firebase.database().ref(".info/connected"); miConnected.on("value", function (res) { if (res.val() === true) { console.log("I AM CONNECTED!"); } else { console.log("I AM DIS-CONNECTED!"); } }); // ================== CHAPTER 3: FILE MANAGEMENT =========================================== // Uploading files to Firebase const input = document.getElementById("file-input"); if (input) { const uploadToFirebase = () => { let file = input.files[0]; //Getting the file from the upload if (file) { //Getting the root ref from the Firebase Storage. let rootRef = firebase.storage().ref(); // nameA/nameB/nameC created a folder like structure let fileRef = rootRef.child(`images/${file.name}`); fileRef .put(file) .then(() => { console.log("your images was uploaded !"); }) .catch((err) => console.log(err)); } }; input.addEventListener("change", uploadToFirebase); } // Downloading files from Firebase // the filename and its extension need to be grabbed from a custom logic of your own. // That is done by using a local database that holds a small metadata fingerprint of the file after you upload it. // Later on, whenever you want to do any kind of custom logic, it will be with ease. var rootRef = firebase.storage().ref(); var imageRef = rootRef.child("images/one.png"); imageRef .getDownloadURL() .then((url) => { const imageTag = document.getElementById("firebase-image"); if (imageTag)
console.log("IMAGE URL TO FILE: ", url); }) .catch((err) => console.log(err)); // Deleting a file // just call imageRef.delete() ---> Returns a promise // Getting file meta data //No let's get the file metadata. imageRef .getMetadata() .then((meta) => { //Meta function parameter represent our file metadata. console.log("META DATA", meta); }) .catch((err) => console.log(err)); // Handling Errors // .catch(err => { // switch (err.code) { // case 'storage/unknown': // break; // case 'storage/object_not_found': // breaks; // case : 'storage/project_not_found': // breaks; // case : 'storage/unauthenticated': // breaks; // case : 'storage/unauthorized': // breaks; // .. // ... // .... // } // }); // ================== CHAPTER 4: AUTHENTICATION =========================================== // Went to firebase authintication console --> enabled auth --> selected email, p --> added a user // SIGN IN - this would be inside an event listener after a user has submitted their username / p const email = "nevaan9@gmail.com"; const p = "helloworld123"; // dummy firebase .auth() .signInWithEmailAndPassword(email, p) .then((user) => { console.log("USER: ", user); }) .catch(function (error) { console.error("ERROR GETTING USER", error); }); // SIGN OUT setTimeout(() => { console.log("Logging out!"); firebase .auth() .signOut() .then(() => { console.log("Success Logout!"); }) .catch((e) => { console.error("Error Logout!", e); }); }, 7000); // ------- Anonymous Auth ---------- // firebase // .auth() // .signInAnonymously() // .catch((err) => {}); // Event listener for auth stuff firebase.auth().onAuthStateChanged((user) => { // check the user object to see if signed in or out console.log(user); }); // Logging in with 3rd party providers (most providers are the same logic) // Google // MAKE SURE YOU ADD GOOGLE AS AN ALLOWED AUTH IN FIREBASE let googleLogin = document.getElementById("googleLogin"); if (googleLogin) { googleLogin.addEventListener("click", () => { //1. Get a GoogleAuthProvider instance. var googleProvider = new firebase.auth.GoogleAuthProvider(); firebase .auth() .signInWithPopup(googleProvider) .then(function (result) { console.log("GOOGLE AUTH RESULT: ", result); var user = result.user; console.log("GOOGLE AUTH USER: ", user); }) .catch(function (error) { //TODO: Handle Errors here. console.log("Google auth error: ", error); }); }); } // Implementing user meta retrieval let currentUserInfo = document.getElementById("currentUserInfo"); if (currentUserInfo) { currentUserInfo.addEventListener("click", () => { var user = firebase.auth().currentUser; var currentUser = null; if (user != null) { var currentUser = {}; currentUser.name = user.displayName; currentUser.email = user.email; currentUser.photoUrl = user.photoURL; currentUser.emailVerified = user.emailVerified; currentUser.uid = user.uid; } console.log("CURRENT USER INFO", currentUser); }); } // ---------- We also can LINK ACCOUND TOGETHER ---------------------------- // This is important so the same uuid is used across there multiple accounts // let facebookProvider = new firebase.auth.FacebookAuthProvider(); // let twitterProvider = new firebase.auth.TwitterAuthProvider(); // let googleProvider = new firebase.auth.GoogleAuthProvider(); // auth.currentUser.linkWithPopup(facebookProvider).then(function(result) { // // handle success res // }).catch(function(error) { // // handle error res // }); // ================================= CHAPTER 5. SECURING APPLICATION FLOW WITH FIREBASE RULES (AUTHORIZATION) ================================ // Firebase used the BOLT Language for this // Need to install the bolt language -- npm i firebase-bolt // Can compile any file that has the .bolt ext using `firebase-bolt <filename>.bolt` in the terminal --> this will generate a .json file // We can secure all firebase services (database, storage, messaging etc) // 1. // ----- Securing data base using bolt (example) ----- // path /articles/{uid}/drafts { // /create { // create() { // isCreator(uid) // } // } // /publish { // update() { // isCreator(uid) // } // } // /delete { // delete() { // isCreator(uid) // } // } // } // isCreator(uid) { // uid == auth.uid // } // We're setting a new path for our Articles awesome website in the drafts section for a specific user, represented in the uid dynamically changed value. // Under that specific path or route, we're securing the sub-routes and check the create, public, and delete routes by checking that the currently authenticated user uid is the same as the one who is to manipulate that data within our database. // We're setting the isCreator function with uid as a parameter for privileges checking. // 2. // ----- securing storage (example) ------ // ----- Add the following in the storage rules section ----- // service firebase.storage { // match /b/{bucket}/o { // match /catgifs { // match /{allGifs=**} { // allow read; // } // match /secret/superfunny/{imageId} { // allow read, write:if request.auth !=null; // } // } // } // } // service firebase.storage: This line is essential; we're simply telling Firebase about the service we're trying to secure, in our case it will be the Firebase/storage service. // match /b/{bucket}/o: This rule combines another powerful system, we're speaking mainly about the matching system, the Storage Rules uses this keyword to filter through files path, and what Firebase calls wildcards path also the match system supports nested matching, which is exactly what we're using in this example. Another interesting point is the matching against in this line: /b/{bucket}/o, this is simply another match we're evaluating to make sure that we're securing files within the Cloud Storage bucket. // We previously spoke about the wildcards paths. They are simply a matching pattern, so let's decompose it. The path we're matching against in this case will be the following: "/catgifs/**" which means for every single path variation within it we're using another rule, speaking of allow which will simply allow whether read or write operations or both. // Over the last match we had, we're making sure that no user will have the writing privileges except the authenticated one, in this case, where we will be using the wildcard--A simple matcher that represent each element id within that resource--represented in {imageId} and allowing both read and write in case the sent request holds an auth property within, besides those objects are global so you don't need to define them. // 2.1 // ------ Securing contnet based on userId (example) ----- // match /secured/personal/{userId}/images/{imageId} { // allow read:if request.auth.uid == userId; // } // match /secured/personal/{userId}/books/{bookId} { // allow read:if request.auth.uid == userId; // } // match /secured/personal/{userId}/images/{imageId} { // allow write:if request.auth.uid == userId && request.resource.size < 15*1024*1024 && request.resource.contentType.matches('image/.*'); // } // match /secured/personal/{userId}/books/{bookId} { // allow write:if request.auth.uid == userId && request.resource.size < 100*1024*1024 && request.resource.contentType.matches('application/pdf'); // } // We're trying to protect user-related media, so to do that we've created a new route with two dynamic parameters: the usersId for authentication management, and image id as well. In the first two match we're using the allow rule so we can simply allow the reading of our images and book in case we're authenticated and the request uid matched the one from the user asking for them. // In the second two-match we're doing some content type management, so if we're securing the images, we need to make sure that images inside that section of the bucket are in fact images and the same thing with books. We're also making some size management, and checking if the image or the book won't exceed the allowed files predefined size.
{ imageTag.src = url; }
conditional_block
cli.rs
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this 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. ==============================================================================*/ //! Command-line interface for the main entry point. use clap::Clap; use log::{debug, error, info, LevelFilter}; use std::fs::File; use std::io::{Read, Write}; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::sync::Arc; use std::thread; use std::time::{Duration, Instant}; use tokio::net::TcpListener; use tokio_stream::wrappers::TcpListenerStream; use tonic::transport::Server; use crate::commit::Commit; use crate::logdir::LogdirLoader; use crate::proto::tensorboard::data; use crate::server::DataProviderHandler; use crate::types::PluginSamplingHint; use data::tensor_board_data_provider_server::TensorBoardDataProviderServer; pub mod dynamic_logdir; use dynamic_logdir::DynLogdir; #[derive(Clap, Debug)] #[clap(name = "rustboard", version = crate::VERSION)] struct Opts { /// Log directory to load /// /// Directory to recursively scan for event files (files matching the `*tfevents*` glob). This /// directory, its descendants, and its event files will be periodically polled for new data. /// /// If this log directory is invalid or unsupported, exits with status 8. #[clap(long, setting(clap::ArgSettings::AllowEmptyValues))] logdir: PathBuf, /// Bind to this host name /// /// Host to bind this server to. May be an IPv4 address (e.g., 127.0.0.1 or 0.0.0.0), an IPv6 /// address (e.g., ::1 or ::0), or a string like `localhost` to pass to `getaddrinfo(3)`. #[clap(long, default_value = "localhost")] host: String, /// Bind to this port /// /// Port to bind this server to. Use `0` to request an arbitrary free port from the OS. #[clap(long, default_value = "6806")] port: u16, /// Seconds to sleep between reloads, or "once" /// /// Number of seconds to wait between finishing one load cycle and starting the next one. This /// does not include the time for the reload itself. If "once", data will be loaded only once. #[clap(long, default_value = "5", value_name = "secs")] reload: ReloadStrategy, /// Use verbose output (-vv for very verbose output) #[clap(long = "verbose", short, parse(from_occurrences))] verbosity: u32, /// Kill this server once stdin is closed /// /// While this server is running, read stdin to end of file and then kill the server. Used to /// portably ensure that the server exits when the parent process dies, even due to a crash. /// Don't set this if stdin is connected to a tty and the process will be backgrounded, since /// then the server will receive `SIGTTIN` and its process will be stopped (in the `SIGSTOP` /// sense) but not killed. #[clap(long)] die_after_stdin: bool, /// Write bound port to this file /// /// Once a server socket is opened, write the port on which it's listening to the file at this /// path. Useful with `--port 0`. Port will be written as ASCII decimal followed by a newline /// (e.g., "6806\n"). If the server fails to start, this file may not be written at all. If the /// port file is specified but cannot be written, the server will die. /// /// This also suppresses the "listening on HOST:PORT" line that is otherwise written to stderr /// when the server starts. #[clap(long)] port_file: Option<PathBuf>, /// Write startup errors to this file /// /// If the logdir is invalid or unsupported, write the error message to this file instead of to /// stderr. That way, you can capture this output while still keeping stderr open for normal /// logging. #[clap(long)] error_file: Option<PathBuf>, /// Checksum all records (negate with `--no-checksum`) /// /// With `--checksum`, every record will be checksummed before being parsed. With /// `--no-checksum` (the default), records are only checksummed if parsing fails. Skipping /// checksums for records that successfully parse can be significantly faster, but also means /// that some bit flips may not be detected. #[clap(long, multiple_occurrences = true, overrides_with = "no_checksum")] checksum: bool, /// Only checksum records that fail to parse /// /// Negates `--checksum`. This is the default. #[clap( long, multiple_occurrences = true, overrides_with = "checksum", hidden = true )] #[allow(unused)] no_checksum: bool, /// Set explicit series sampling /// /// A comma separated list of `plugin_name=num_samples` pairs to explicitly specify how many /// samples to keep per tag for the specified plugin. For unspecified plugins, series are /// randomly downsampled to reasonable values to prevent out-of-memory errors in long-running /// jobs. Each `num_samples` may be the special token `all` to retain all data without /// downsampling. For instance, `--samples_per_plugin=scalars=500,images=all,audio=0` keeps 500 /// events in each scalar series, all of the images, and none of the audio. #[clap(long, default_value = "", setting(clap::ArgSettings::AllowEmptyValues))] samples_per_plugin: PluginSamplingHint, } #[derive(Debug, Copy, Clone, PartialEq, Eq)] enum ReloadStrategy { Loop { delay: Duration }, Once, } impl FromStr for ReloadStrategy { type Err = <u64 as FromStr>::Err; fn from_str(s: &str) -> Result<Self, Self::Err> { if s == "once" { Ok(ReloadStrategy::Once) } else { Ok(ReloadStrategy::Loop { delay: Duration::from_secs(s.parse()?), }) } } } /// Exit code for failure of [`DynLogdir::new`]. // Keep in sync with docs on `Opts::logdir`. const EXIT_BAD_LOGDIR: i32 = 8; const EXIT_FAILED_TO_BIND: i32 = 9; #[tokio::main] pub async fn main() -> Result<(), Box<dyn std::error::Error>> { let opts = Opts::parse(); init_logging(match opts.verbosity { 0 => LevelFilter::Warn, 1 => LevelFilter::Info, _ => LevelFilter::max(), }); debug!("Parsed options: {:?}", opts); let data_location = opts.logdir.display().to_string(); let error_file_path = opts.error_file.as_ref().map(PathBuf::as_ref); let reflection = tonic_reflection::server::Builder::configure() .register_encoded_file_descriptor_set(crate::proto::FILE_DESCRIPTOR_SET) .build() .expect("failed to create gRPC reflection servicer"); // Create the logdir outside an async runtime (see docs for `DynLogdir::new`). let raw_logdir = opts.logdir; let logdir = tokio::task::spawn_blocking(|| DynLogdir::new(raw_logdir)) .await? .unwrap_or_else(|e| { write_startup_error(error_file_path, &e.to_string()); std::process::exit(EXIT_BAD_LOGDIR); }); if opts.die_after_stdin { thread::Builder::new() .name("StdinWatcher".to_string()) .spawn(die_after_stdin) .expect("failed to spawn stdin watcher thread"); } let addr = (opts.host.as_str(), opts.port); let listener = TcpListener::bind(addr).await.unwrap_or_else(|e| { let msg = format!("failed to bind to {:?}: {}", addr, e); write_startup_error(error_file_path, &msg); std::process::exit(EXIT_FAILED_TO_BIND); }); let bound = listener.local_addr()?; if let Some(port_file) = opts.port_file { let port = bound.port(); if let Err(e) = write_port_file(&port_file, port) { error!( "Failed to write port \"{}\" to {}: {}", port, port_file.display(), e ); std::process::exit(1); } info!("Wrote port \"{}\" to {}", port, port_file.display()); } else { eprintln!("listening on {:?}", bound); } let commit = Arc::new(Commit::new()); let psh_ref = Arc::new(opts.samples_per_plugin); thread::Builder::new() .name("Reloader".to_string()) .spawn({ let reload_strategy = opts.reload; let checksum = opts.checksum; let commit = Arc::clone(&commit); move || { let mut loader = LogdirLoader::new(&commit, logdir, 0, psh_ref); // Checksum only if `--checksum` given (i.e., off by default). loader.checksum(checksum); loop { info!("Starting load cycle"); let start = Instant::now(); loader.reload(); let end = Instant::now(); info!("Finished load cycle ({:?})", end - start); match reload_strategy { ReloadStrategy::Loop { delay } => thread::sleep(delay), ReloadStrategy::Once => break, }; } } }) .expect("failed to spawn reloader thread"); let handler = DataProviderHandler { data_location, commit, }; Server::builder() .add_service(TensorBoardDataProviderServer::new(handler)) .add_service(reflection) .serve_with_incoming(TcpListenerStream::new(listener)) .await?; Ok(()) } /// Installs a logging handler whose behavior is determined by the `RUST_LOG` environment variable /// (per <https://docs.rs/env_logger> semantics), or by including all logs at `default_log_level` /// or above if `RUST_LOG_LEVEL` is not given. fn init_logging(default_log_level: LevelFilter) { use env_logger::{Builder, Env}; Builder::from_env(Env::default().default_filter_or(default_log_level.to_string())).init(); } /// Locks stdin and reads it to EOF, then exits the process. fn die_after_stdin() { let stdin = std::io::stdin(); let stdin_lock = stdin.lock(); for _ in stdin_lock.bytes() {} info!("Stdin closed; exiting"); std::process::exit(0); } /// Writes `port` to file `path` as an ASCII decimal followed by newline. fn write_port_file(path: &Path, port: u16) -> std::io::Result<()> { let mut f = File::create(path)?; writeln!(f, "{}", port)?; f.flush()?; Ok(()) } /// Writes error to the given file, or to stderr as a fallback. fn write_startup_error(path: Option<&Path>, error: &str) { let write_to_file = |path: &Path| -> std::io::Result<()> { let mut f = File::create(path)?; writeln!(f, "{}", error)?; f.flush()?; Ok(()) }; if let Some(p) = path { if let Err(e) = write_to_file(p)
else { return; } } // fall back to stderr if no path given or if write failed eprintln!("fatal: {}", error); } #[cfg(test)] mod tests { use super::*; #[test] fn test_parse_reload() { assert_eq!("once".parse::<ReloadStrategy>(), Ok(ReloadStrategy::Once)); assert_eq!( "5".parse::<ReloadStrategy>(), Ok(ReloadStrategy::Loop { delay: Duration::from_secs(5) }) ); "5s".parse::<ReloadStrategy>() .expect_err("explicit \"s\" trailer should be forbidden"); } }
{ info!("Failed to write error to {:?}: {}", p, e); }
conditional_block
cli.rs
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this 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. ==============================================================================*/ //! Command-line interface for the main entry point. use clap::Clap; use log::{debug, error, info, LevelFilter}; use std::fs::File; use std::io::{Read, Write}; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::sync::Arc; use std::thread; use std::time::{Duration, Instant}; use tokio::net::TcpListener; use tokio_stream::wrappers::TcpListenerStream; use tonic::transport::Server; use crate::commit::Commit; use crate::logdir::LogdirLoader; use crate::proto::tensorboard::data; use crate::server::DataProviderHandler; use crate::types::PluginSamplingHint; use data::tensor_board_data_provider_server::TensorBoardDataProviderServer; pub mod dynamic_logdir; use dynamic_logdir::DynLogdir; #[derive(Clap, Debug)] #[clap(name = "rustboard", version = crate::VERSION)] struct Opts { /// Log directory to load /// /// Directory to recursively scan for event files (files matching the `*tfevents*` glob). This /// directory, its descendants, and its event files will be periodically polled for new data. /// /// If this log directory is invalid or unsupported, exits with status 8. #[clap(long, setting(clap::ArgSettings::AllowEmptyValues))] logdir: PathBuf, /// Bind to this host name /// /// Host to bind this server to. May be an IPv4 address (e.g., 127.0.0.1 or 0.0.0.0), an IPv6 /// address (e.g., ::1 or ::0), or a string like `localhost` to pass to `getaddrinfo(3)`. #[clap(long, default_value = "localhost")] host: String, /// Bind to this port /// /// Port to bind this server to. Use `0` to request an arbitrary free port from the OS. #[clap(long, default_value = "6806")] port: u16, /// Seconds to sleep between reloads, or "once" /// /// Number of seconds to wait between finishing one load cycle and starting the next one. This /// does not include the time for the reload itself. If "once", data will be loaded only once. #[clap(long, default_value = "5", value_name = "secs")] reload: ReloadStrategy, /// Use verbose output (-vv for very verbose output) #[clap(long = "verbose", short, parse(from_occurrences))] verbosity: u32, /// Kill this server once stdin is closed /// /// While this server is running, read stdin to end of file and then kill the server. Used to /// portably ensure that the server exits when the parent process dies, even due to a crash. /// Don't set this if stdin is connected to a tty and the process will be backgrounded, since /// then the server will receive `SIGTTIN` and its process will be stopped (in the `SIGSTOP` /// sense) but not killed. #[clap(long)] die_after_stdin: bool, /// Write bound port to this file /// /// Once a server socket is opened, write the port on which it's listening to the file at this /// path. Useful with `--port 0`. Port will be written as ASCII decimal followed by a newline /// (e.g., "6806\n"). If the server fails to start, this file may not be written at all. If the /// port file is specified but cannot be written, the server will die. /// /// This also suppresses the "listening on HOST:PORT" line that is otherwise written to stderr /// when the server starts. #[clap(long)] port_file: Option<PathBuf>, /// Write startup errors to this file /// /// If the logdir is invalid or unsupported, write the error message to this file instead of to /// stderr. That way, you can capture this output while still keeping stderr open for normal /// logging. #[clap(long)] error_file: Option<PathBuf>, /// Checksum all records (negate with `--no-checksum`) /// /// With `--checksum`, every record will be checksummed before being parsed. With /// `--no-checksum` (the default), records are only checksummed if parsing fails. Skipping /// checksums for records that successfully parse can be significantly faster, but also means /// that some bit flips may not be detected. #[clap(long, multiple_occurrences = true, overrides_with = "no_checksum")] checksum: bool, /// Only checksum records that fail to parse /// /// Negates `--checksum`. This is the default. #[clap( long, multiple_occurrences = true, overrides_with = "checksum", hidden = true )] #[allow(unused)] no_checksum: bool, /// Set explicit series sampling /// /// A comma separated list of `plugin_name=num_samples` pairs to explicitly specify how many /// samples to keep per tag for the specified plugin. For unspecified plugins, series are /// randomly downsampled to reasonable values to prevent out-of-memory errors in long-running /// jobs. Each `num_samples` may be the special token `all` to retain all data without /// downsampling. For instance, `--samples_per_plugin=scalars=500,images=all,audio=0` keeps 500 /// events in each scalar series, all of the images, and none of the audio. #[clap(long, default_value = "", setting(clap::ArgSettings::AllowEmptyValues))] samples_per_plugin: PluginSamplingHint, } #[derive(Debug, Copy, Clone, PartialEq, Eq)] enum ReloadStrategy { Loop { delay: Duration }, Once, } impl FromStr for ReloadStrategy { type Err = <u64 as FromStr>::Err; fn from_str(s: &str) -> Result<Self, Self::Err>
} /// Exit code for failure of [`DynLogdir::new`]. // Keep in sync with docs on `Opts::logdir`. const EXIT_BAD_LOGDIR: i32 = 8; const EXIT_FAILED_TO_BIND: i32 = 9; #[tokio::main] pub async fn main() -> Result<(), Box<dyn std::error::Error>> { let opts = Opts::parse(); init_logging(match opts.verbosity { 0 => LevelFilter::Warn, 1 => LevelFilter::Info, _ => LevelFilter::max(), }); debug!("Parsed options: {:?}", opts); let data_location = opts.logdir.display().to_string(); let error_file_path = opts.error_file.as_ref().map(PathBuf::as_ref); let reflection = tonic_reflection::server::Builder::configure() .register_encoded_file_descriptor_set(crate::proto::FILE_DESCRIPTOR_SET) .build() .expect("failed to create gRPC reflection servicer"); // Create the logdir outside an async runtime (see docs for `DynLogdir::new`). let raw_logdir = opts.logdir; let logdir = tokio::task::spawn_blocking(|| DynLogdir::new(raw_logdir)) .await? .unwrap_or_else(|e| { write_startup_error(error_file_path, &e.to_string()); std::process::exit(EXIT_BAD_LOGDIR); }); if opts.die_after_stdin { thread::Builder::new() .name("StdinWatcher".to_string()) .spawn(die_after_stdin) .expect("failed to spawn stdin watcher thread"); } let addr = (opts.host.as_str(), opts.port); let listener = TcpListener::bind(addr).await.unwrap_or_else(|e| { let msg = format!("failed to bind to {:?}: {}", addr, e); write_startup_error(error_file_path, &msg); std::process::exit(EXIT_FAILED_TO_BIND); }); let bound = listener.local_addr()?; if let Some(port_file) = opts.port_file { let port = bound.port(); if let Err(e) = write_port_file(&port_file, port) { error!( "Failed to write port \"{}\" to {}: {}", port, port_file.display(), e ); std::process::exit(1); } info!("Wrote port \"{}\" to {}", port, port_file.display()); } else { eprintln!("listening on {:?}", bound); } let commit = Arc::new(Commit::new()); let psh_ref = Arc::new(opts.samples_per_plugin); thread::Builder::new() .name("Reloader".to_string()) .spawn({ let reload_strategy = opts.reload; let checksum = opts.checksum; let commit = Arc::clone(&commit); move || { let mut loader = LogdirLoader::new(&commit, logdir, 0, psh_ref); // Checksum only if `--checksum` given (i.e., off by default). loader.checksum(checksum); loop { info!("Starting load cycle"); let start = Instant::now(); loader.reload(); let end = Instant::now(); info!("Finished load cycle ({:?})", end - start); match reload_strategy { ReloadStrategy::Loop { delay } => thread::sleep(delay), ReloadStrategy::Once => break, }; } } }) .expect("failed to spawn reloader thread"); let handler = DataProviderHandler { data_location, commit, }; Server::builder() .add_service(TensorBoardDataProviderServer::new(handler)) .add_service(reflection) .serve_with_incoming(TcpListenerStream::new(listener)) .await?; Ok(()) } /// Installs a logging handler whose behavior is determined by the `RUST_LOG` environment variable /// (per <https://docs.rs/env_logger> semantics), or by including all logs at `default_log_level` /// or above if `RUST_LOG_LEVEL` is not given. fn init_logging(default_log_level: LevelFilter) { use env_logger::{Builder, Env}; Builder::from_env(Env::default().default_filter_or(default_log_level.to_string())).init(); } /// Locks stdin and reads it to EOF, then exits the process. fn die_after_stdin() { let stdin = std::io::stdin(); let stdin_lock = stdin.lock(); for _ in stdin_lock.bytes() {} info!("Stdin closed; exiting"); std::process::exit(0); } /// Writes `port` to file `path` as an ASCII decimal followed by newline. fn write_port_file(path: &Path, port: u16) -> std::io::Result<()> { let mut f = File::create(path)?; writeln!(f, "{}", port)?; f.flush()?; Ok(()) } /// Writes error to the given file, or to stderr as a fallback. fn write_startup_error(path: Option<&Path>, error: &str) { let write_to_file = |path: &Path| -> std::io::Result<()> { let mut f = File::create(path)?; writeln!(f, "{}", error)?; f.flush()?; Ok(()) }; if let Some(p) = path { if let Err(e) = write_to_file(p) { info!("Failed to write error to {:?}: {}", p, e); } else { return; } } // fall back to stderr if no path given or if write failed eprintln!("fatal: {}", error); } #[cfg(test)] mod tests { use super::*; #[test] fn test_parse_reload() { assert_eq!("once".parse::<ReloadStrategy>(), Ok(ReloadStrategy::Once)); assert_eq!( "5".parse::<ReloadStrategy>(), Ok(ReloadStrategy::Loop { delay: Duration::from_secs(5) }) ); "5s".parse::<ReloadStrategy>() .expect_err("explicit \"s\" trailer should be forbidden"); } }
{ if s == "once" { Ok(ReloadStrategy::Once) } else { Ok(ReloadStrategy::Loop { delay: Duration::from_secs(s.parse()?), }) } }
identifier_body
cli.rs
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this 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. ==============================================================================*/ //! Command-line interface for the main entry point. use clap::Clap; use log::{debug, error, info, LevelFilter}; use std::fs::File; use std::io::{Read, Write}; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::sync::Arc; use std::thread; use std::time::{Duration, Instant}; use tokio::net::TcpListener; use tokio_stream::wrappers::TcpListenerStream; use tonic::transport::Server; use crate::commit::Commit; use crate::logdir::LogdirLoader; use crate::proto::tensorboard::data; use crate::server::DataProviderHandler; use crate::types::PluginSamplingHint; use data::tensor_board_data_provider_server::TensorBoardDataProviderServer; pub mod dynamic_logdir; use dynamic_logdir::DynLogdir; #[derive(Clap, Debug)] #[clap(name = "rustboard", version = crate::VERSION)] struct Opts { /// Log directory to load /// /// Directory to recursively scan for event files (files matching the `*tfevents*` glob). This /// directory, its descendants, and its event files will be periodically polled for new data. /// /// If this log directory is invalid or unsupported, exits with status 8. #[clap(long, setting(clap::ArgSettings::AllowEmptyValues))] logdir: PathBuf, /// Bind to this host name /// /// Host to bind this server to. May be an IPv4 address (e.g., 127.0.0.1 or 0.0.0.0), an IPv6 /// address (e.g., ::1 or ::0), or a string like `localhost` to pass to `getaddrinfo(3)`. #[clap(long, default_value = "localhost")] host: String, /// Bind to this port /// /// Port to bind this server to. Use `0` to request an arbitrary free port from the OS. #[clap(long, default_value = "6806")] port: u16, /// Seconds to sleep between reloads, or "once" /// /// Number of seconds to wait between finishing one load cycle and starting the next one. This /// does not include the time for the reload itself. If "once", data will be loaded only once. #[clap(long, default_value = "5", value_name = "secs")] reload: ReloadStrategy, /// Use verbose output (-vv for very verbose output) #[clap(long = "verbose", short, parse(from_occurrences))] verbosity: u32, /// Kill this server once stdin is closed /// /// While this server is running, read stdin to end of file and then kill the server. Used to /// portably ensure that the server exits when the parent process dies, even due to a crash. /// Don't set this if stdin is connected to a tty and the process will be backgrounded, since /// then the server will receive `SIGTTIN` and its process will be stopped (in the `SIGSTOP` /// sense) but not killed. #[clap(long)] die_after_stdin: bool, /// Write bound port to this file /// /// Once a server socket is opened, write the port on which it's listening to the file at this /// path. Useful with `--port 0`. Port will be written as ASCII decimal followed by a newline /// (e.g., "6806\n"). If the server fails to start, this file may not be written at all. If the /// port file is specified but cannot be written, the server will die. /// /// This also suppresses the "listening on HOST:PORT" line that is otherwise written to stderr /// when the server starts. #[clap(long)] port_file: Option<PathBuf>, /// Write startup errors to this file /// /// If the logdir is invalid or unsupported, write the error message to this file instead of to /// stderr. That way, you can capture this output while still keeping stderr open for normal /// logging. #[clap(long)] error_file: Option<PathBuf>, /// Checksum all records (negate with `--no-checksum`) /// /// With `--checksum`, every record will be checksummed before being parsed. With /// `--no-checksum` (the default), records are only checksummed if parsing fails. Skipping /// checksums for records that successfully parse can be significantly faster, but also means /// that some bit flips may not be detected. #[clap(long, multiple_occurrences = true, overrides_with = "no_checksum")] checksum: bool, /// Only checksum records that fail to parse /// /// Negates `--checksum`. This is the default. #[clap( long, multiple_occurrences = true, overrides_with = "checksum", hidden = true )] #[allow(unused)] no_checksum: bool, /// Set explicit series sampling /// /// A comma separated list of `plugin_name=num_samples` pairs to explicitly specify how many /// samples to keep per tag for the specified plugin. For unspecified plugins, series are /// randomly downsampled to reasonable values to prevent out-of-memory errors in long-running /// jobs. Each `num_samples` may be the special token `all` to retain all data without /// downsampling. For instance, `--samples_per_plugin=scalars=500,images=all,audio=0` keeps 500 /// events in each scalar series, all of the images, and none of the audio. #[clap(long, default_value = "", setting(clap::ArgSettings::AllowEmptyValues))] samples_per_plugin: PluginSamplingHint, } #[derive(Debug, Copy, Clone, PartialEq, Eq)] enum ReloadStrategy { Loop { delay: Duration }, Once, } impl FromStr for ReloadStrategy { type Err = <u64 as FromStr>::Err; fn from_str(s: &str) -> Result<Self, Self::Err> { if s == "once" { Ok(ReloadStrategy::Once) } else { Ok(ReloadStrategy::Loop {
delay: Duration::from_secs(s.parse()?), }) } } } /// Exit code for failure of [`DynLogdir::new`]. // Keep in sync with docs on `Opts::logdir`. const EXIT_BAD_LOGDIR: i32 = 8; const EXIT_FAILED_TO_BIND: i32 = 9; #[tokio::main] pub async fn main() -> Result<(), Box<dyn std::error::Error>> { let opts = Opts::parse(); init_logging(match opts.verbosity { 0 => LevelFilter::Warn, 1 => LevelFilter::Info, _ => LevelFilter::max(), }); debug!("Parsed options: {:?}", opts); let data_location = opts.logdir.display().to_string(); let error_file_path = opts.error_file.as_ref().map(PathBuf::as_ref); let reflection = tonic_reflection::server::Builder::configure() .register_encoded_file_descriptor_set(crate::proto::FILE_DESCRIPTOR_SET) .build() .expect("failed to create gRPC reflection servicer"); // Create the logdir outside an async runtime (see docs for `DynLogdir::new`). let raw_logdir = opts.logdir; let logdir = tokio::task::spawn_blocking(|| DynLogdir::new(raw_logdir)) .await? .unwrap_or_else(|e| { write_startup_error(error_file_path, &e.to_string()); std::process::exit(EXIT_BAD_LOGDIR); }); if opts.die_after_stdin { thread::Builder::new() .name("StdinWatcher".to_string()) .spawn(die_after_stdin) .expect("failed to spawn stdin watcher thread"); } let addr = (opts.host.as_str(), opts.port); let listener = TcpListener::bind(addr).await.unwrap_or_else(|e| { let msg = format!("failed to bind to {:?}: {}", addr, e); write_startup_error(error_file_path, &msg); std::process::exit(EXIT_FAILED_TO_BIND); }); let bound = listener.local_addr()?; if let Some(port_file) = opts.port_file { let port = bound.port(); if let Err(e) = write_port_file(&port_file, port) { error!( "Failed to write port \"{}\" to {}: {}", port, port_file.display(), e ); std::process::exit(1); } info!("Wrote port \"{}\" to {}", port, port_file.display()); } else { eprintln!("listening on {:?}", bound); } let commit = Arc::new(Commit::new()); let psh_ref = Arc::new(opts.samples_per_plugin); thread::Builder::new() .name("Reloader".to_string()) .spawn({ let reload_strategy = opts.reload; let checksum = opts.checksum; let commit = Arc::clone(&commit); move || { let mut loader = LogdirLoader::new(&commit, logdir, 0, psh_ref); // Checksum only if `--checksum` given (i.e., off by default). loader.checksum(checksum); loop { info!("Starting load cycle"); let start = Instant::now(); loader.reload(); let end = Instant::now(); info!("Finished load cycle ({:?})", end - start); match reload_strategy { ReloadStrategy::Loop { delay } => thread::sleep(delay), ReloadStrategy::Once => break, }; } } }) .expect("failed to spawn reloader thread"); let handler = DataProviderHandler { data_location, commit, }; Server::builder() .add_service(TensorBoardDataProviderServer::new(handler)) .add_service(reflection) .serve_with_incoming(TcpListenerStream::new(listener)) .await?; Ok(()) } /// Installs a logging handler whose behavior is determined by the `RUST_LOG` environment variable /// (per <https://docs.rs/env_logger> semantics), or by including all logs at `default_log_level` /// or above if `RUST_LOG_LEVEL` is not given. fn init_logging(default_log_level: LevelFilter) { use env_logger::{Builder, Env}; Builder::from_env(Env::default().default_filter_or(default_log_level.to_string())).init(); } /// Locks stdin and reads it to EOF, then exits the process. fn die_after_stdin() { let stdin = std::io::stdin(); let stdin_lock = stdin.lock(); for _ in stdin_lock.bytes() {} info!("Stdin closed; exiting"); std::process::exit(0); } /// Writes `port` to file `path` as an ASCII decimal followed by newline. fn write_port_file(path: &Path, port: u16) -> std::io::Result<()> { let mut f = File::create(path)?; writeln!(f, "{}", port)?; f.flush()?; Ok(()) } /// Writes error to the given file, or to stderr as a fallback. fn write_startup_error(path: Option<&Path>, error: &str) { let write_to_file = |path: &Path| -> std::io::Result<()> { let mut f = File::create(path)?; writeln!(f, "{}", error)?; f.flush()?; Ok(()) }; if let Some(p) = path { if let Err(e) = write_to_file(p) { info!("Failed to write error to {:?}: {}", p, e); } else { return; } } // fall back to stderr if no path given or if write failed eprintln!("fatal: {}", error); } #[cfg(test)] mod tests { use super::*; #[test] fn test_parse_reload() { assert_eq!("once".parse::<ReloadStrategy>(), Ok(ReloadStrategy::Once)); assert_eq!( "5".parse::<ReloadStrategy>(), Ok(ReloadStrategy::Loop { delay: Duration::from_secs(5) }) ); "5s".parse::<ReloadStrategy>() .expect_err("explicit \"s\" trailer should be forbidden"); } }
random_line_split
cli.rs
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this 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. ==============================================================================*/ //! Command-line interface for the main entry point. use clap::Clap; use log::{debug, error, info, LevelFilter}; use std::fs::File; use std::io::{Read, Write}; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::sync::Arc; use std::thread; use std::time::{Duration, Instant}; use tokio::net::TcpListener; use tokio_stream::wrappers::TcpListenerStream; use tonic::transport::Server; use crate::commit::Commit; use crate::logdir::LogdirLoader; use crate::proto::tensorboard::data; use crate::server::DataProviderHandler; use crate::types::PluginSamplingHint; use data::tensor_board_data_provider_server::TensorBoardDataProviderServer; pub mod dynamic_logdir; use dynamic_logdir::DynLogdir; #[derive(Clap, Debug)] #[clap(name = "rustboard", version = crate::VERSION)] struct Opts { /// Log directory to load /// /// Directory to recursively scan for event files (files matching the `*tfevents*` glob). This /// directory, its descendants, and its event files will be periodically polled for new data. /// /// If this log directory is invalid or unsupported, exits with status 8. #[clap(long, setting(clap::ArgSettings::AllowEmptyValues))] logdir: PathBuf, /// Bind to this host name /// /// Host to bind this server to. May be an IPv4 address (e.g., 127.0.0.1 or 0.0.0.0), an IPv6 /// address (e.g., ::1 or ::0), or a string like `localhost` to pass to `getaddrinfo(3)`. #[clap(long, default_value = "localhost")] host: String, /// Bind to this port /// /// Port to bind this server to. Use `0` to request an arbitrary free port from the OS. #[clap(long, default_value = "6806")] port: u16, /// Seconds to sleep between reloads, or "once" /// /// Number of seconds to wait between finishing one load cycle and starting the next one. This /// does not include the time for the reload itself. If "once", data will be loaded only once. #[clap(long, default_value = "5", value_name = "secs")] reload: ReloadStrategy, /// Use verbose output (-vv for very verbose output) #[clap(long = "verbose", short, parse(from_occurrences))] verbosity: u32, /// Kill this server once stdin is closed /// /// While this server is running, read stdin to end of file and then kill the server. Used to /// portably ensure that the server exits when the parent process dies, even due to a crash. /// Don't set this if stdin is connected to a tty and the process will be backgrounded, since /// then the server will receive `SIGTTIN` and its process will be stopped (in the `SIGSTOP` /// sense) but not killed. #[clap(long)] die_after_stdin: bool, /// Write bound port to this file /// /// Once a server socket is opened, write the port on which it's listening to the file at this /// path. Useful with `--port 0`. Port will be written as ASCII decimal followed by a newline /// (e.g., "6806\n"). If the server fails to start, this file may not be written at all. If the /// port file is specified but cannot be written, the server will die. /// /// This also suppresses the "listening on HOST:PORT" line that is otherwise written to stderr /// when the server starts. #[clap(long)] port_file: Option<PathBuf>, /// Write startup errors to this file /// /// If the logdir is invalid or unsupported, write the error message to this file instead of to /// stderr. That way, you can capture this output while still keeping stderr open for normal /// logging. #[clap(long)] error_file: Option<PathBuf>, /// Checksum all records (negate with `--no-checksum`) /// /// With `--checksum`, every record will be checksummed before being parsed. With /// `--no-checksum` (the default), records are only checksummed if parsing fails. Skipping /// checksums for records that successfully parse can be significantly faster, but also means /// that some bit flips may not be detected. #[clap(long, multiple_occurrences = true, overrides_with = "no_checksum")] checksum: bool, /// Only checksum records that fail to parse /// /// Negates `--checksum`. This is the default. #[clap( long, multiple_occurrences = true, overrides_with = "checksum", hidden = true )] #[allow(unused)] no_checksum: bool, /// Set explicit series sampling /// /// A comma separated list of `plugin_name=num_samples` pairs to explicitly specify how many /// samples to keep per tag for the specified plugin. For unspecified plugins, series are /// randomly downsampled to reasonable values to prevent out-of-memory errors in long-running /// jobs. Each `num_samples` may be the special token `all` to retain all data without /// downsampling. For instance, `--samples_per_plugin=scalars=500,images=all,audio=0` keeps 500 /// events in each scalar series, all of the images, and none of the audio. #[clap(long, default_value = "", setting(clap::ArgSettings::AllowEmptyValues))] samples_per_plugin: PluginSamplingHint, } #[derive(Debug, Copy, Clone, PartialEq, Eq)] enum ReloadStrategy { Loop { delay: Duration }, Once, } impl FromStr for ReloadStrategy { type Err = <u64 as FromStr>::Err; fn from_str(s: &str) -> Result<Self, Self::Err> { if s == "once" { Ok(ReloadStrategy::Once) } else { Ok(ReloadStrategy::Loop { delay: Duration::from_secs(s.parse()?), }) } } } /// Exit code for failure of [`DynLogdir::new`]. // Keep in sync with docs on `Opts::logdir`. const EXIT_BAD_LOGDIR: i32 = 8; const EXIT_FAILED_TO_BIND: i32 = 9; #[tokio::main] pub async fn main() -> Result<(), Box<dyn std::error::Error>> { let opts = Opts::parse(); init_logging(match opts.verbosity { 0 => LevelFilter::Warn, 1 => LevelFilter::Info, _ => LevelFilter::max(), }); debug!("Parsed options: {:?}", opts); let data_location = opts.logdir.display().to_string(); let error_file_path = opts.error_file.as_ref().map(PathBuf::as_ref); let reflection = tonic_reflection::server::Builder::configure() .register_encoded_file_descriptor_set(crate::proto::FILE_DESCRIPTOR_SET) .build() .expect("failed to create gRPC reflection servicer"); // Create the logdir outside an async runtime (see docs for `DynLogdir::new`). let raw_logdir = opts.logdir; let logdir = tokio::task::spawn_blocking(|| DynLogdir::new(raw_logdir)) .await? .unwrap_or_else(|e| { write_startup_error(error_file_path, &e.to_string()); std::process::exit(EXIT_BAD_LOGDIR); }); if opts.die_after_stdin { thread::Builder::new() .name("StdinWatcher".to_string()) .spawn(die_after_stdin) .expect("failed to spawn stdin watcher thread"); } let addr = (opts.host.as_str(), opts.port); let listener = TcpListener::bind(addr).await.unwrap_or_else(|e| { let msg = format!("failed to bind to {:?}: {}", addr, e); write_startup_error(error_file_path, &msg); std::process::exit(EXIT_FAILED_TO_BIND); }); let bound = listener.local_addr()?; if let Some(port_file) = opts.port_file { let port = bound.port(); if let Err(e) = write_port_file(&port_file, port) { error!( "Failed to write port \"{}\" to {}: {}", port, port_file.display(), e ); std::process::exit(1); } info!("Wrote port \"{}\" to {}", port, port_file.display()); } else { eprintln!("listening on {:?}", bound); } let commit = Arc::new(Commit::new()); let psh_ref = Arc::new(opts.samples_per_plugin); thread::Builder::new() .name("Reloader".to_string()) .spawn({ let reload_strategy = opts.reload; let checksum = opts.checksum; let commit = Arc::clone(&commit); move || { let mut loader = LogdirLoader::new(&commit, logdir, 0, psh_ref); // Checksum only if `--checksum` given (i.e., off by default). loader.checksum(checksum); loop { info!("Starting load cycle"); let start = Instant::now(); loader.reload(); let end = Instant::now(); info!("Finished load cycle ({:?})", end - start); match reload_strategy { ReloadStrategy::Loop { delay } => thread::sleep(delay), ReloadStrategy::Once => break, }; } } }) .expect("failed to spawn reloader thread"); let handler = DataProviderHandler { data_location, commit, }; Server::builder() .add_service(TensorBoardDataProviderServer::new(handler)) .add_service(reflection) .serve_with_incoming(TcpListenerStream::new(listener)) .await?; Ok(()) } /// Installs a logging handler whose behavior is determined by the `RUST_LOG` environment variable /// (per <https://docs.rs/env_logger> semantics), or by including all logs at `default_log_level` /// or above if `RUST_LOG_LEVEL` is not given. fn
(default_log_level: LevelFilter) { use env_logger::{Builder, Env}; Builder::from_env(Env::default().default_filter_or(default_log_level.to_string())).init(); } /// Locks stdin and reads it to EOF, then exits the process. fn die_after_stdin() { let stdin = std::io::stdin(); let stdin_lock = stdin.lock(); for _ in stdin_lock.bytes() {} info!("Stdin closed; exiting"); std::process::exit(0); } /// Writes `port` to file `path` as an ASCII decimal followed by newline. fn write_port_file(path: &Path, port: u16) -> std::io::Result<()> { let mut f = File::create(path)?; writeln!(f, "{}", port)?; f.flush()?; Ok(()) } /// Writes error to the given file, or to stderr as a fallback. fn write_startup_error(path: Option<&Path>, error: &str) { let write_to_file = |path: &Path| -> std::io::Result<()> { let mut f = File::create(path)?; writeln!(f, "{}", error)?; f.flush()?; Ok(()) }; if let Some(p) = path { if let Err(e) = write_to_file(p) { info!("Failed to write error to {:?}: {}", p, e); } else { return; } } // fall back to stderr if no path given or if write failed eprintln!("fatal: {}", error); } #[cfg(test)] mod tests { use super::*; #[test] fn test_parse_reload() { assert_eq!("once".parse::<ReloadStrategy>(), Ok(ReloadStrategy::Once)); assert_eq!( "5".parse::<ReloadStrategy>(), Ok(ReloadStrategy::Loop { delay: Duration::from_secs(5) }) ); "5s".parse::<ReloadStrategy>() .expect_err("explicit \"s\" trailer should be forbidden"); } }
init_logging
identifier_name
client.js
var options = {fontName: "georgia", lineWidth: 2, pointSize: 3, colors: ["blue"], curveType: "function", lines: ["Some data"], title: "Some title"}; var lastData, lastAggregateData; var charts = {}; var viewMode = false; function baseURL() { return location.protocol + '//' + location.host + location.pathname; } function gaSSDSLoad (acct) { // from http://liveweb.archive.org/web/20121005211251/http://lyncd.com/2009/03/better-google-analytics-javascript/ var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."), pageTracker, s; s = document.createElement('script'); s.src = gaJsHost + 'google-analytics.com/ga.js'; s.type = 'text/javascript'; s.onloadDone = false; function init () { pageTracker = _gat._getTracker(acct); pageTracker._trackPageview(); } s.onload = function () { s.onloadDone = true; init(); }; s.onreadystatechange = function() { if (('loaded' === s.readyState || 'complete' === s.readyState) && !s.onloadDone) { s.onloadDone = true; init(); } }; document.getElementsByTagName('head')[0].appendChild(s); } function urlParams() { if (typeof urlParamsReturnValue == 'undefined') { var vars = {}; var parts = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); for (var i = 0; i < parts.length; i++) { if (parts[i].indexOf("=") >= 0) { kv = parts[i].split('='); vars[kv[0]] = decodeURIComponent(kv[1]); } else { if (parts[i].indexOf("http://") == 0 || parts[i].indexOf("https://") == 0) continue; vars[parts[i]] = true; } } urlParamsReturnValue = vars; } return urlParamsReturnValue; } function init() { document.title = location.pathname.substring(1) + " - Plotserver"; var chartConstructors = { "lineChart": function(e) { return new google.visualization.LineChart(e) }, "columnChart": function(e) { return new google.visualization.ColumnChart(e) }, "areaChart": function(e) { return new google.visualization.AreaChart(e) }, "pieChart": function(e) { return new google.visualization.PieChart(e) } }; for (var type in chartConstructors) charts[type] = chartConstructors[type](document.getElementById(type)); setOptions(); get(); getOptions(); setViewMode(); if (Config.googleAnalyticsTrackingCode != "") gaSSDSLoad(Config.googleAnalyticsTrackingCode); } function toggleEditMode() { if ($("#editView").html() == "Edit plot") { $("#editContainer").show(); $("#editView").html("Back to plot only"); } else { $("#editContainer").hide(); $("#editView").html("Edit plot") } draw(lastData); } function aggregate(data) { var aggregateFunc = Aggregate.id; if (options["group"] == "week") aggregateFunc = Aggregate.toYearWeek; else if (options["group"] == "month") aggregateFunc = Aggregate.toYearMonth; else if (options["group"] == "year") aggregateFunc = Aggregate.toYear; var aggregate = {}; // aggregate => [[],[],[]...] for (var i = 0; i < data[0].length; i++) { for (var j = 0; j < Object.keys(data).length; j++) { var val = data[j][i]; if (j == 0) key = aggregateFunc(val) else { var multiValues = aggregate[key] || []; // default is [] var values = multiValues[j - 1] || []; // default is [] values.push(val); multiValues[j - 1] = values; aggregate[key] = multiValues; } } } var metricFunc = null; if (options["metric"] == "count") metricFunc = Aggregate.count; else if (options["metric"] == "min") metricFunc = Aggregate.min; else if (options["metric"] == "max") metricFunc = Aggregate.max; else if (options["metric"] == "sum") metricFunc = Aggregate.sum; else if (options["metric"] == "avg") metricFunc = Aggregate.avg; else if (options["metric"] == "median") metricFunc = Aggregate.median; if (metricFunc == null) return; var sorted_keys = Object.keys(aggregate).sort() rows = [] for (var i = 0; i < sorted_keys.length; i++) { var key = sorted_keys[i]; row = [] row.push(key); var multiValues = aggregate[key]; for (var j = 0; j < multiValues.length; j++) { var values = multiValues[j]; var metric = metricFunc(values); row.push(metric); } rows.push(row); } // convert to column format for draw() var columns = [] for (var i = 0; i < rows[0].length; i++) { var column = []; for (var j = 0; j < rows.length; j++) { column.push(rows[j][i]); } columns.push(column); } return columns; } function onOptionsChanged() { try { var tryObj = eval('(' + document.getElementById("options").value + ')'); options = tryObj; optionsText = document.getElementById("options").value; if (options["group"]) { lastAggregateData = aggregate(lastData); drawPlot(lastAggregateData); } else { drawPlot(lastData); } } catch (error) { console.log(error) } } function setOptions() { optionsText = JSON.stringify(options, null, 4); document.getElementById("options").value = optionsText; } function get() { $.getJSON(baseURL() + "?get&jsonp=?", function(data) { onData(data); }); } function getOptions() { $.getJSON(baseURL() + "?getOptions&jsonp=?", function(data) { onOptions(data); }); } function poll() { $.getJSON(baseURL() + "?poll&jsonp=?", function(data) { onData(data); }); } function onData(data) { if (data == "NOT FOUND") { toggleEditMode(); } else { draw(data); lastData = data; if (Config.useLongPoll) setTimeout(function() { poll() }, 1*1000); // long poll for new data } } function onOptions(data) { if (data == null) return; optionsText = JSON.stringify(data, undefined, 2); document.getElementById("options").value = optionsText; onOptionsChanged(); } function draw(data) { if ($("#editContainer").is(':hidden')) { $("#plotContainer").width(0.9 * $(window).width()); } else { $("#plotContainer").width(0.45 * $(window).width()); $("#editContainer").width(0.45 * $(window).width()); } if (viewMode) { $("#plot").height($("#plotContainer").height()); $("#viewContainer").height($(window).height()); $("#plotContainer").height($(window).height()); $("#plotContainer").width($(window).width()); } else { $("#plotContainer").height(0.8 * $(window).height()); $("#plot").height($("#plotContainer").height()); $("#editContainer").height($("#viewContainer").height()); $("#numbers").height($("#plotContainer").height() - $("#options").height() - 2); // magic number $("#optionsHelp").css("top", $("#options").height() * 1.1); $("#optionsHelp").css("right", 60); $("#numbersHelp").css("top", $("#numbers").position().top + $("#numbers").height() - 20); $("#numbersHelp").css("right", 60); } // --- if (data == undefined) return; document.getElementById("numbers").innerHTML = Format.serialize(data); if (options["group"]) { lastAggregateData = aggregate(data); drawPlot(lastAggregateData); } else { drawPlot(data); } } function drawPlot(data) { var chartTypes = { "lineChart": ["number", "date", "datetime", "string"], "columnChart": ["number", "date", "datetime", "string"], "areaChart": ["number", "date", "datetime", "string"], "pieChart": ["string"] }; for (var type in chartTypes) document.getElementById(type).style.display = "none"; try { document.getElementById(options["chart"] + "Chart").style.display = "block"; } catch(err) { document.getElementById("lineChart").style.display = "block"; } if (options["chart"] == "area") options["isStacked"] = true; if (urlParams().hasOwnProperty("ratio")) { if (!options.hasOwnProperty("vAxis")) options["vAxis"] = {}; options["vAxis"].format = "# '%'"; } if (urlParams().hasOwnProperty("title")) options["title"] = urlParams()["title"]; for (var type in chartTypes) { var xtypes = chartTypes[type]; xtypes.map(function(xtype) { try { var dataTable = new google.visualization.DataTable(); dataTable.addColumn(xtype, "x"); for (var j = 0; j < Object.keys(data).length - 1; j++) { if (options.lines[j] === undefined) options.lines[j] = "Line " + (j + 1); if (options.colors[j] === undefined) options.colors[j] = ["blue", "green", "red", "purple", "black", "orange"][j]; dataTable.addColumn("number", options.lines[j]); } for (var i = 0; i < data[0].length; i++) { var row = []; var sum = 0; for (var j = 0; j < Object.keys(data).length; j++) { val = data[j][i]; if (j == 0) { if (typeof val == "number") ; else if (val.indexOf("w") >= 0) ; // weekly else if (val.indexOf("-") > 0 && val.indexOf(" ") == -1) ; // monthly else if (val.indexOf("y") >= 0) ; // yearly else if (val.indexOf("-") > 0 || val.indexOf(" ") >= 0) val = new Date(Date.parse(val)); else { val = parseFloat(val); if (urlParams().hasOwnProperty("ratio")) sum += val; } } else { val = parseFloat(val); if (urlParams().hasOwnProperty("ratio")) sum += val; } if (type == "pieChart" && j == 0) val = "" + data[j][i]; row.push(val); } if (urlParams().hasOwnProperty("ratio")) { for (var j = 1; j < row.length; j++) { row[j] /= sum; row[j] *= 100; } } dataTable.addRow(row); } charts[type].draw(dataTable, options); } catch(error) { console.log(error); } }); } } function save(fileContents, optionsContents) { $("#save").html("Saving..."); var data = Format.parse(fileContents); if (!Model.verify(data)) { alert("Error: The data you sent me in the HTTP POST request is malformed. Accepted format: k1,v1 \\n k2,v2 \\n ...\n"); return; } $.post(baseURL() + "?set", fileContents, function(result) { result = result.trim(); if (result == "File written.") saveOptions(optionsContents); else alert(result); }, "text") } function
(optionsContents) { try { eval('(' + optionsContents + ')') } catch(error) { alert("The options are not valid JSON."); return; } $.post(baseURL() + "?setOptions", optionsContents, function(result) { result = result.trim(); if (result != "Options written.") alert(result); }, "text"); $("#save").html("Saving... Done!"); window.setInterval(function () { $("#save").html("Save") }, 500); } function onNumbersChanged(fileContents) { var data = Format.parse(fileContents); if (!Model.verify(data)) return; lastData = data; var drawData = lastData; if (options["group"]) drawData = lastAggregateData = aggregate(data); drawPlot(drawData); } function setViewMode() { if (urlParams().hasOwnProperty("view")) { viewMode = true; $("#viewAsImage").hide(); $("#editView").hide(); $("html").css("margin", "0"); $("body").css("margin", "0"); $("#viewContainer").css("height", "100%"); $("#plotContainer").css("height", "100%"); $("#plotContainer").css("margin", "0"); $("#plotContainer").css("padding", "0"); $("#plotContainer").css("border", "0"); if (urlParams().hasOwnProperty("link")) { $("#viewContainer").append("<a class='downloadLink' target='top_' href='" + baseURL() + "?download'>data</a> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a class='downloadLink' target='top_' href='" + baseURL() + "'>view</a>"); } if (urlParams().hasOwnProperty("clickable")) { $("#viewContainer").click(function () { window.open(baseURL()); }); } } }
saveOptions
identifier_name
client.js
var options = {fontName: "georgia", lineWidth: 2, pointSize: 3, colors: ["blue"], curveType: "function", lines: ["Some data"], title: "Some title"}; var lastData, lastAggregateData; var charts = {}; var viewMode = false; function baseURL() { return location.protocol + '//' + location.host + location.pathname; } function gaSSDSLoad (acct) { // from http://liveweb.archive.org/web/20121005211251/http://lyncd.com/2009/03/better-google-analytics-javascript/ var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."), pageTracker, s; s = document.createElement('script'); s.src = gaJsHost + 'google-analytics.com/ga.js'; s.type = 'text/javascript'; s.onloadDone = false; function init () { pageTracker = _gat._getTracker(acct); pageTracker._trackPageview(); } s.onload = function () { s.onloadDone = true; init(); }; s.onreadystatechange = function() { if (('loaded' === s.readyState || 'complete' === s.readyState) && !s.onloadDone) { s.onloadDone = true; init(); } }; document.getElementsByTagName('head')[0].appendChild(s); } function urlParams() { if (typeof urlParamsReturnValue == 'undefined') { var vars = {}; var parts = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); for (var i = 0; i < parts.length; i++) { if (parts[i].indexOf("=") >= 0) { kv = parts[i].split('='); vars[kv[0]] = decodeURIComponent(kv[1]); } else { if (parts[i].indexOf("http://") == 0 || parts[i].indexOf("https://") == 0) continue; vars[parts[i]] = true; } } urlParamsReturnValue = vars; } return urlParamsReturnValue; } function init() { document.title = location.pathname.substring(1) + " - Plotserver"; var chartConstructors = { "lineChart": function(e) { return new google.visualization.LineChart(e) }, "columnChart": function(e) { return new google.visualization.ColumnChart(e) }, "areaChart": function(e) { return new google.visualization.AreaChart(e) }, "pieChart": function(e) { return new google.visualization.PieChart(e) } }; for (var type in chartConstructors) charts[type] = chartConstructors[type](document.getElementById(type)); setOptions(); get(); getOptions(); setViewMode(); if (Config.googleAnalyticsTrackingCode != "") gaSSDSLoad(Config.googleAnalyticsTrackingCode); } function toggleEditMode() { if ($("#editView").html() == "Edit plot") { $("#editContainer").show(); $("#editView").html("Back to plot only"); } else { $("#editContainer").hide(); $("#editView").html("Edit plot") } draw(lastData); } function aggregate(data) { var aggregateFunc = Aggregate.id; if (options["group"] == "week") aggregateFunc = Aggregate.toYearWeek; else if (options["group"] == "month") aggregateFunc = Aggregate.toYearMonth; else if (options["group"] == "year") aggregateFunc = Aggregate.toYear; var aggregate = {}; // aggregate => [[],[],[]...] for (var i = 0; i < data[0].length; i++) { for (var j = 0; j < Object.keys(data).length; j++)
} var metricFunc = null; if (options["metric"] == "count") metricFunc = Aggregate.count; else if (options["metric"] == "min") metricFunc = Aggregate.min; else if (options["metric"] == "max") metricFunc = Aggregate.max; else if (options["metric"] == "sum") metricFunc = Aggregate.sum; else if (options["metric"] == "avg") metricFunc = Aggregate.avg; else if (options["metric"] == "median") metricFunc = Aggregate.median; if (metricFunc == null) return; var sorted_keys = Object.keys(aggregate).sort() rows = [] for (var i = 0; i < sorted_keys.length; i++) { var key = sorted_keys[i]; row = [] row.push(key); var multiValues = aggregate[key]; for (var j = 0; j < multiValues.length; j++) { var values = multiValues[j]; var metric = metricFunc(values); row.push(metric); } rows.push(row); } // convert to column format for draw() var columns = [] for (var i = 0; i < rows[0].length; i++) { var column = []; for (var j = 0; j < rows.length; j++) { column.push(rows[j][i]); } columns.push(column); } return columns; } function onOptionsChanged() { try { var tryObj = eval('(' + document.getElementById("options").value + ')'); options = tryObj; optionsText = document.getElementById("options").value; if (options["group"]) { lastAggregateData = aggregate(lastData); drawPlot(lastAggregateData); } else { drawPlot(lastData); } } catch (error) { console.log(error) } } function setOptions() { optionsText = JSON.stringify(options, null, 4); document.getElementById("options").value = optionsText; } function get() { $.getJSON(baseURL() + "?get&jsonp=?", function(data) { onData(data); }); } function getOptions() { $.getJSON(baseURL() + "?getOptions&jsonp=?", function(data) { onOptions(data); }); } function poll() { $.getJSON(baseURL() + "?poll&jsonp=?", function(data) { onData(data); }); } function onData(data) { if (data == "NOT FOUND") { toggleEditMode(); } else { draw(data); lastData = data; if (Config.useLongPoll) setTimeout(function() { poll() }, 1*1000); // long poll for new data } } function onOptions(data) { if (data == null) return; optionsText = JSON.stringify(data, undefined, 2); document.getElementById("options").value = optionsText; onOptionsChanged(); } function draw(data) { if ($("#editContainer").is(':hidden')) { $("#plotContainer").width(0.9 * $(window).width()); } else { $("#plotContainer").width(0.45 * $(window).width()); $("#editContainer").width(0.45 * $(window).width()); } if (viewMode) { $("#plot").height($("#plotContainer").height()); $("#viewContainer").height($(window).height()); $("#plotContainer").height($(window).height()); $("#plotContainer").width($(window).width()); } else { $("#plotContainer").height(0.8 * $(window).height()); $("#plot").height($("#plotContainer").height()); $("#editContainer").height($("#viewContainer").height()); $("#numbers").height($("#plotContainer").height() - $("#options").height() - 2); // magic number $("#optionsHelp").css("top", $("#options").height() * 1.1); $("#optionsHelp").css("right", 60); $("#numbersHelp").css("top", $("#numbers").position().top + $("#numbers").height() - 20); $("#numbersHelp").css("right", 60); } // --- if (data == undefined) return; document.getElementById("numbers").innerHTML = Format.serialize(data); if (options["group"]) { lastAggregateData = aggregate(data); drawPlot(lastAggregateData); } else { drawPlot(data); } } function drawPlot(data) { var chartTypes = { "lineChart": ["number", "date", "datetime", "string"], "columnChart": ["number", "date", "datetime", "string"], "areaChart": ["number", "date", "datetime", "string"], "pieChart": ["string"] }; for (var type in chartTypes) document.getElementById(type).style.display = "none"; try { document.getElementById(options["chart"] + "Chart").style.display = "block"; } catch(err) { document.getElementById("lineChart").style.display = "block"; } if (options["chart"] == "area") options["isStacked"] = true; if (urlParams().hasOwnProperty("ratio")) { if (!options.hasOwnProperty("vAxis")) options["vAxis"] = {}; options["vAxis"].format = "# '%'"; } if (urlParams().hasOwnProperty("title")) options["title"] = urlParams()["title"]; for (var type in chartTypes) { var xtypes = chartTypes[type]; xtypes.map(function(xtype) { try { var dataTable = new google.visualization.DataTable(); dataTable.addColumn(xtype, "x"); for (var j = 0; j < Object.keys(data).length - 1; j++) { if (options.lines[j] === undefined) options.lines[j] = "Line " + (j + 1); if (options.colors[j] === undefined) options.colors[j] = ["blue", "green", "red", "purple", "black", "orange"][j]; dataTable.addColumn("number", options.lines[j]); } for (var i = 0; i < data[0].length; i++) { var row = []; var sum = 0; for (var j = 0; j < Object.keys(data).length; j++) { val = data[j][i]; if (j == 0) { if (typeof val == "number") ; else if (val.indexOf("w") >= 0) ; // weekly else if (val.indexOf("-") > 0 && val.indexOf(" ") == -1) ; // monthly else if (val.indexOf("y") >= 0) ; // yearly else if (val.indexOf("-") > 0 || val.indexOf(" ") >= 0) val = new Date(Date.parse(val)); else { val = parseFloat(val); if (urlParams().hasOwnProperty("ratio")) sum += val; } } else { val = parseFloat(val); if (urlParams().hasOwnProperty("ratio")) sum += val; } if (type == "pieChart" && j == 0) val = "" + data[j][i]; row.push(val); } if (urlParams().hasOwnProperty("ratio")) { for (var j = 1; j < row.length; j++) { row[j] /= sum; row[j] *= 100; } } dataTable.addRow(row); } charts[type].draw(dataTable, options); } catch(error) { console.log(error); } }); } } function save(fileContents, optionsContents) { $("#save").html("Saving..."); var data = Format.parse(fileContents); if (!Model.verify(data)) { alert("Error: The data you sent me in the HTTP POST request is malformed. Accepted format: k1,v1 \\n k2,v2 \\n ...\n"); return; } $.post(baseURL() + "?set", fileContents, function(result) { result = result.trim(); if (result == "File written.") saveOptions(optionsContents); else alert(result); }, "text") } function saveOptions(optionsContents) { try { eval('(' + optionsContents + ')') } catch(error) { alert("The options are not valid JSON."); return; } $.post(baseURL() + "?setOptions", optionsContents, function(result) { result = result.trim(); if (result != "Options written.") alert(result); }, "text"); $("#save").html("Saving... Done!"); window.setInterval(function () { $("#save").html("Save") }, 500); } function onNumbersChanged(fileContents) { var data = Format.parse(fileContents); if (!Model.verify(data)) return; lastData = data; var drawData = lastData; if (options["group"]) drawData = lastAggregateData = aggregate(data); drawPlot(drawData); } function setViewMode() { if (urlParams().hasOwnProperty("view")) { viewMode = true; $("#viewAsImage").hide(); $("#editView").hide(); $("html").css("margin", "0"); $("body").css("margin", "0"); $("#viewContainer").css("height", "100%"); $("#plotContainer").css("height", "100%"); $("#plotContainer").css("margin", "0"); $("#plotContainer").css("padding", "0"); $("#plotContainer").css("border", "0"); if (urlParams().hasOwnProperty("link")) { $("#viewContainer").append("<a class='downloadLink' target='top_' href='" + baseURL() + "?download'>data</a> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a class='downloadLink' target='top_' href='" + baseURL() + "'>view</a>"); } if (urlParams().hasOwnProperty("clickable")) { $("#viewContainer").click(function () { window.open(baseURL()); }); } } }
{ var val = data[j][i]; if (j == 0) key = aggregateFunc(val) else { var multiValues = aggregate[key] || []; // default is [] var values = multiValues[j - 1] || []; // default is [] values.push(val); multiValues[j - 1] = values; aggregate[key] = multiValues; } }
conditional_block
client.js
var options = {fontName: "georgia", lineWidth: 2, pointSize: 3, colors: ["blue"], curveType: "function", lines: ["Some data"], title: "Some title"}; var lastData, lastAggregateData; var charts = {}; var viewMode = false; function baseURL() { return location.protocol + '//' + location.host + location.pathname; } function gaSSDSLoad (acct) { // from http://liveweb.archive.org/web/20121005211251/http://lyncd.com/2009/03/better-google-analytics-javascript/ var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."), pageTracker, s; s = document.createElement('script'); s.src = gaJsHost + 'google-analytics.com/ga.js'; s.type = 'text/javascript'; s.onloadDone = false; function init () { pageTracker = _gat._getTracker(acct); pageTracker._trackPageview(); } s.onload = function () { s.onloadDone = true; init(); }; s.onreadystatechange = function() { if (('loaded' === s.readyState || 'complete' === s.readyState) && !s.onloadDone) { s.onloadDone = true; init(); } }; document.getElementsByTagName('head')[0].appendChild(s); } function urlParams() { if (typeof urlParamsReturnValue == 'undefined') { var vars = {}; var parts = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); for (var i = 0; i < parts.length; i++) { if (parts[i].indexOf("=") >= 0) { kv = parts[i].split('='); vars[kv[0]] = decodeURIComponent(kv[1]); } else { if (parts[i].indexOf("http://") == 0 || parts[i].indexOf("https://") == 0) continue; vars[parts[i]] = true; } } urlParamsReturnValue = vars; } return urlParamsReturnValue; } function init() { document.title = location.pathname.substring(1) + " - Plotserver"; var chartConstructors = { "lineChart": function(e) { return new google.visualization.LineChart(e) }, "columnChart": function(e) { return new google.visualization.ColumnChart(e) }, "areaChart": function(e) { return new google.visualization.AreaChart(e) }, "pieChart": function(e) { return new google.visualization.PieChart(e) } }; for (var type in chartConstructors) charts[type] = chartConstructors[type](document.getElementById(type)); setOptions(); get(); getOptions(); setViewMode(); if (Config.googleAnalyticsTrackingCode != "") gaSSDSLoad(Config.googleAnalyticsTrackingCode); } function toggleEditMode() { if ($("#editView").html() == "Edit plot") { $("#editContainer").show(); $("#editView").html("Back to plot only"); } else { $("#editContainer").hide(); $("#editView").html("Edit plot") } draw(lastData); } function aggregate(data) { var aggregateFunc = Aggregate.id; if (options["group"] == "week") aggregateFunc = Aggregate.toYearWeek; else if (options["group"] == "month") aggregateFunc = Aggregate.toYearMonth; else if (options["group"] == "year") aggregateFunc = Aggregate.toYear; var aggregate = {}; // aggregate => [[],[],[]...] for (var i = 0; i < data[0].length; i++) { for (var j = 0; j < Object.keys(data).length; j++) { var val = data[j][i]; if (j == 0) key = aggregateFunc(val) else { var multiValues = aggregate[key] || []; // default is [] var values = multiValues[j - 1] || []; // default is [] values.push(val); multiValues[j - 1] = values; aggregate[key] = multiValues; } } } var metricFunc = null; if (options["metric"] == "count") metricFunc = Aggregate.count; else if (options["metric"] == "min") metricFunc = Aggregate.min; else if (options["metric"] == "max") metricFunc = Aggregate.max; else if (options["metric"] == "sum") metricFunc = Aggregate.sum; else if (options["metric"] == "avg") metricFunc = Aggregate.avg; else if (options["metric"] == "median") metricFunc = Aggregate.median; if (metricFunc == null) return; var sorted_keys = Object.keys(aggregate).sort() rows = [] for (var i = 0; i < sorted_keys.length; i++) { var key = sorted_keys[i]; row = [] row.push(key); var multiValues = aggregate[key]; for (var j = 0; j < multiValues.length; j++) { var values = multiValues[j]; var metric = metricFunc(values); row.push(metric); } rows.push(row); } // convert to column format for draw() var columns = [] for (var i = 0; i < rows[0].length; i++) { var column = []; for (var j = 0; j < rows.length; j++) { column.push(rows[j][i]); } columns.push(column); } return columns; } function onOptionsChanged() { try { var tryObj = eval('(' + document.getElementById("options").value + ')'); options = tryObj; optionsText = document.getElementById("options").value; if (options["group"]) { lastAggregateData = aggregate(lastData); drawPlot(lastAggregateData); } else { drawPlot(lastData); } } catch (error) { console.log(error) } } function setOptions() { optionsText = JSON.stringify(options, null, 4); document.getElementById("options").value = optionsText; } function get() { $.getJSON(baseURL() + "?get&jsonp=?", function(data) { onData(data); }); } function getOptions() { $.getJSON(baseURL() + "?getOptions&jsonp=?", function(data) { onOptions(data); }); } function poll() { $.getJSON(baseURL() + "?poll&jsonp=?", function(data) { onData(data); }); } function onData(data) { if (data == "NOT FOUND") { toggleEditMode(); } else { draw(data); lastData = data; if (Config.useLongPoll) setTimeout(function() { poll() }, 1*1000); // long poll for new data } } function onOptions(data) { if (data == null) return; optionsText = JSON.stringify(data, undefined, 2); document.getElementById("options").value = optionsText; onOptionsChanged(); } function draw(data) { if ($("#editContainer").is(':hidden')) { $("#plotContainer").width(0.9 * $(window).width()); } else { $("#plotContainer").width(0.45 * $(window).width()); $("#editContainer").width(0.45 * $(window).width()); } if (viewMode) { $("#plot").height($("#plotContainer").height()); $("#viewContainer").height($(window).height()); $("#plotContainer").height($(window).height()); $("#plotContainer").width($(window).width()); } else { $("#plotContainer").height(0.8 * $(window).height()); $("#plot").height($("#plotContainer").height()); $("#editContainer").height($("#viewContainer").height()); $("#numbers").height($("#plotContainer").height() - $("#options").height() - 2); // magic number $("#optionsHelp").css("top", $("#options").height() * 1.1); $("#optionsHelp").css("right", 60); $("#numbersHelp").css("top", $("#numbers").position().top + $("#numbers").height() - 20); $("#numbersHelp").css("right", 60); } // --- if (data == undefined) return; document.getElementById("numbers").innerHTML = Format.serialize(data); if (options["group"]) { lastAggregateData = aggregate(data); drawPlot(lastAggregateData); } else { drawPlot(data); } } function drawPlot(data) { var chartTypes = { "lineChart": ["number", "date", "datetime", "string"], "columnChart": ["number", "date", "datetime", "string"], "areaChart": ["number", "date", "datetime", "string"], "pieChart": ["string"] }; for (var type in chartTypes) document.getElementById(type).style.display = "none"; try { document.getElementById(options["chart"] + "Chart").style.display = "block"; } catch(err) { document.getElementById("lineChart").style.display = "block"; } if (options["chart"] == "area") options["isStacked"] = true; if (urlParams().hasOwnProperty("ratio")) { if (!options.hasOwnProperty("vAxis")) options["vAxis"] = {}; options["vAxis"].format = "# '%'"; } if (urlParams().hasOwnProperty("title")) options["title"] = urlParams()["title"]; for (var type in chartTypes) { var xtypes = chartTypes[type]; xtypes.map(function(xtype) { try { var dataTable = new google.visualization.DataTable(); dataTable.addColumn(xtype, "x"); for (var j = 0; j < Object.keys(data).length - 1; j++) { if (options.lines[j] === undefined) options.lines[j] = "Line " + (j + 1); if (options.colors[j] === undefined) options.colors[j] = ["blue", "green", "red", "purple", "black", "orange"][j]; dataTable.addColumn("number", options.lines[j]); } for (var i = 0; i < data[0].length; i++) {
var row = []; var sum = 0; for (var j = 0; j < Object.keys(data).length; j++) { val = data[j][i]; if (j == 0) { if (typeof val == "number") ; else if (val.indexOf("w") >= 0) ; // weekly else if (val.indexOf("-") > 0 && val.indexOf(" ") == -1) ; // monthly else if (val.indexOf("y") >= 0) ; // yearly else if (val.indexOf("-") > 0 || val.indexOf(" ") >= 0) val = new Date(Date.parse(val)); else { val = parseFloat(val); if (urlParams().hasOwnProperty("ratio")) sum += val; } } else { val = parseFloat(val); if (urlParams().hasOwnProperty("ratio")) sum += val; } if (type == "pieChart" && j == 0) val = "" + data[j][i]; row.push(val); } if (urlParams().hasOwnProperty("ratio")) { for (var j = 1; j < row.length; j++) { row[j] /= sum; row[j] *= 100; } } dataTable.addRow(row); } charts[type].draw(dataTable, options); } catch(error) { console.log(error); } }); } } function save(fileContents, optionsContents) { $("#save").html("Saving..."); var data = Format.parse(fileContents); if (!Model.verify(data)) { alert("Error: The data you sent me in the HTTP POST request is malformed. Accepted format: k1,v1 \\n k2,v2 \\n ...\n"); return; } $.post(baseURL() + "?set", fileContents, function(result) { result = result.trim(); if (result == "File written.") saveOptions(optionsContents); else alert(result); }, "text") } function saveOptions(optionsContents) { try { eval('(' + optionsContents + ')') } catch(error) { alert("The options are not valid JSON."); return; } $.post(baseURL() + "?setOptions", optionsContents, function(result) { result = result.trim(); if (result != "Options written.") alert(result); }, "text"); $("#save").html("Saving... Done!"); window.setInterval(function () { $("#save").html("Save") }, 500); } function onNumbersChanged(fileContents) { var data = Format.parse(fileContents); if (!Model.verify(data)) return; lastData = data; var drawData = lastData; if (options["group"]) drawData = lastAggregateData = aggregate(data); drawPlot(drawData); } function setViewMode() { if (urlParams().hasOwnProperty("view")) { viewMode = true; $("#viewAsImage").hide(); $("#editView").hide(); $("html").css("margin", "0"); $("body").css("margin", "0"); $("#viewContainer").css("height", "100%"); $("#plotContainer").css("height", "100%"); $("#plotContainer").css("margin", "0"); $("#plotContainer").css("padding", "0"); $("#plotContainer").css("border", "0"); if (urlParams().hasOwnProperty("link")) { $("#viewContainer").append("<a class='downloadLink' target='top_' href='" + baseURL() + "?download'>data</a> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a class='downloadLink' target='top_' href='" + baseURL() + "'>view</a>"); } if (urlParams().hasOwnProperty("clickable")) { $("#viewContainer").click(function () { window.open(baseURL()); }); } } }
random_line_split
client.js
var options = {fontName: "georgia", lineWidth: 2, pointSize: 3, colors: ["blue"], curveType: "function", lines: ["Some data"], title: "Some title"}; var lastData, lastAggregateData; var charts = {}; var viewMode = false; function baseURL() { return location.protocol + '//' + location.host + location.pathname; } function gaSSDSLoad (acct) { // from http://liveweb.archive.org/web/20121005211251/http://lyncd.com/2009/03/better-google-analytics-javascript/ var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."), pageTracker, s; s = document.createElement('script'); s.src = gaJsHost + 'google-analytics.com/ga.js'; s.type = 'text/javascript'; s.onloadDone = false; function init () { pageTracker = _gat._getTracker(acct); pageTracker._trackPageview(); } s.onload = function () { s.onloadDone = true; init(); }; s.onreadystatechange = function() { if (('loaded' === s.readyState || 'complete' === s.readyState) && !s.onloadDone) { s.onloadDone = true; init(); } }; document.getElementsByTagName('head')[0].appendChild(s); } function urlParams() { if (typeof urlParamsReturnValue == 'undefined') { var vars = {}; var parts = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); for (var i = 0; i < parts.length; i++) { if (parts[i].indexOf("=") >= 0) { kv = parts[i].split('='); vars[kv[0]] = decodeURIComponent(kv[1]); } else { if (parts[i].indexOf("http://") == 0 || parts[i].indexOf("https://") == 0) continue; vars[parts[i]] = true; } } urlParamsReturnValue = vars; } return urlParamsReturnValue; } function init() { document.title = location.pathname.substring(1) + " - Plotserver"; var chartConstructors = { "lineChart": function(e) { return new google.visualization.LineChart(e) }, "columnChart": function(e) { return new google.visualization.ColumnChart(e) }, "areaChart": function(e) { return new google.visualization.AreaChart(e) }, "pieChart": function(e) { return new google.visualization.PieChart(e) } }; for (var type in chartConstructors) charts[type] = chartConstructors[type](document.getElementById(type)); setOptions(); get(); getOptions(); setViewMode(); if (Config.googleAnalyticsTrackingCode != "") gaSSDSLoad(Config.googleAnalyticsTrackingCode); } function toggleEditMode() { if ($("#editView").html() == "Edit plot") { $("#editContainer").show(); $("#editView").html("Back to plot only"); } else { $("#editContainer").hide(); $("#editView").html("Edit plot") } draw(lastData); } function aggregate(data) { var aggregateFunc = Aggregate.id; if (options["group"] == "week") aggregateFunc = Aggregate.toYearWeek; else if (options["group"] == "month") aggregateFunc = Aggregate.toYearMonth; else if (options["group"] == "year") aggregateFunc = Aggregate.toYear; var aggregate = {}; // aggregate => [[],[],[]...] for (var i = 0; i < data[0].length; i++) { for (var j = 0; j < Object.keys(data).length; j++) { var val = data[j][i]; if (j == 0) key = aggregateFunc(val) else { var multiValues = aggregate[key] || []; // default is [] var values = multiValues[j - 1] || []; // default is [] values.push(val); multiValues[j - 1] = values; aggregate[key] = multiValues; } } } var metricFunc = null; if (options["metric"] == "count") metricFunc = Aggregate.count; else if (options["metric"] == "min") metricFunc = Aggregate.min; else if (options["metric"] == "max") metricFunc = Aggregate.max; else if (options["metric"] == "sum") metricFunc = Aggregate.sum; else if (options["metric"] == "avg") metricFunc = Aggregate.avg; else if (options["metric"] == "median") metricFunc = Aggregate.median; if (metricFunc == null) return; var sorted_keys = Object.keys(aggregate).sort() rows = [] for (var i = 0; i < sorted_keys.length; i++) { var key = sorted_keys[i]; row = [] row.push(key); var multiValues = aggregate[key]; for (var j = 0; j < multiValues.length; j++) { var values = multiValues[j]; var metric = metricFunc(values); row.push(metric); } rows.push(row); } // convert to column format for draw() var columns = [] for (var i = 0; i < rows[0].length; i++) { var column = []; for (var j = 0; j < rows.length; j++) { column.push(rows[j][i]); } columns.push(column); } return columns; } function onOptionsChanged() { try { var tryObj = eval('(' + document.getElementById("options").value + ')'); options = tryObj; optionsText = document.getElementById("options").value; if (options["group"]) { lastAggregateData = aggregate(lastData); drawPlot(lastAggregateData); } else { drawPlot(lastData); } } catch (error) { console.log(error) } } function setOptions() { optionsText = JSON.stringify(options, null, 4); document.getElementById("options").value = optionsText; } function get() { $.getJSON(baseURL() + "?get&jsonp=?", function(data) { onData(data); }); } function getOptions() { $.getJSON(baseURL() + "?getOptions&jsonp=?", function(data) { onOptions(data); }); } function poll() { $.getJSON(baseURL() + "?poll&jsonp=?", function(data) { onData(data); }); } function onData(data) { if (data == "NOT FOUND") { toggleEditMode(); } else { draw(data); lastData = data; if (Config.useLongPoll) setTimeout(function() { poll() }, 1*1000); // long poll for new data } } function onOptions(data) { if (data == null) return; optionsText = JSON.stringify(data, undefined, 2); document.getElementById("options").value = optionsText; onOptionsChanged(); } function draw(data) { if ($("#editContainer").is(':hidden')) { $("#plotContainer").width(0.9 * $(window).width()); } else { $("#plotContainer").width(0.45 * $(window).width()); $("#editContainer").width(0.45 * $(window).width()); } if (viewMode) { $("#plot").height($("#plotContainer").height()); $("#viewContainer").height($(window).height()); $("#plotContainer").height($(window).height()); $("#plotContainer").width($(window).width()); } else { $("#plotContainer").height(0.8 * $(window).height()); $("#plot").height($("#plotContainer").height()); $("#editContainer").height($("#viewContainer").height()); $("#numbers").height($("#plotContainer").height() - $("#options").height() - 2); // magic number $("#optionsHelp").css("top", $("#options").height() * 1.1); $("#optionsHelp").css("right", 60); $("#numbersHelp").css("top", $("#numbers").position().top + $("#numbers").height() - 20); $("#numbersHelp").css("right", 60); } // --- if (data == undefined) return; document.getElementById("numbers").innerHTML = Format.serialize(data); if (options["group"]) { lastAggregateData = aggregate(data); drawPlot(lastAggregateData); } else { drawPlot(data); } } function drawPlot(data) { var chartTypes = { "lineChart": ["number", "date", "datetime", "string"], "columnChart": ["number", "date", "datetime", "string"], "areaChart": ["number", "date", "datetime", "string"], "pieChart": ["string"] }; for (var type in chartTypes) document.getElementById(type).style.display = "none"; try { document.getElementById(options["chart"] + "Chart").style.display = "block"; } catch(err) { document.getElementById("lineChart").style.display = "block"; } if (options["chart"] == "area") options["isStacked"] = true; if (urlParams().hasOwnProperty("ratio")) { if (!options.hasOwnProperty("vAxis")) options["vAxis"] = {}; options["vAxis"].format = "# '%'"; } if (urlParams().hasOwnProperty("title")) options["title"] = urlParams()["title"]; for (var type in chartTypes) { var xtypes = chartTypes[type]; xtypes.map(function(xtype) { try { var dataTable = new google.visualization.DataTable(); dataTable.addColumn(xtype, "x"); for (var j = 0; j < Object.keys(data).length - 1; j++) { if (options.lines[j] === undefined) options.lines[j] = "Line " + (j + 1); if (options.colors[j] === undefined) options.colors[j] = ["blue", "green", "red", "purple", "black", "orange"][j]; dataTable.addColumn("number", options.lines[j]); } for (var i = 0; i < data[0].length; i++) { var row = []; var sum = 0; for (var j = 0; j < Object.keys(data).length; j++) { val = data[j][i]; if (j == 0) { if (typeof val == "number") ; else if (val.indexOf("w") >= 0) ; // weekly else if (val.indexOf("-") > 0 && val.indexOf(" ") == -1) ; // monthly else if (val.indexOf("y") >= 0) ; // yearly else if (val.indexOf("-") > 0 || val.indexOf(" ") >= 0) val = new Date(Date.parse(val)); else { val = parseFloat(val); if (urlParams().hasOwnProperty("ratio")) sum += val; } } else { val = parseFloat(val); if (urlParams().hasOwnProperty("ratio")) sum += val; } if (type == "pieChart" && j == 0) val = "" + data[j][i]; row.push(val); } if (urlParams().hasOwnProperty("ratio")) { for (var j = 1; j < row.length; j++) { row[j] /= sum; row[j] *= 100; } } dataTable.addRow(row); } charts[type].draw(dataTable, options); } catch(error) { console.log(error); } }); } } function save(fileContents, optionsContents) { $("#save").html("Saving..."); var data = Format.parse(fileContents); if (!Model.verify(data)) { alert("Error: The data you sent me in the HTTP POST request is malformed. Accepted format: k1,v1 \\n k2,v2 \\n ...\n"); return; } $.post(baseURL() + "?set", fileContents, function(result) { result = result.trim(); if (result == "File written.") saveOptions(optionsContents); else alert(result); }, "text") } function saveOptions(optionsContents) { try { eval('(' + optionsContents + ')') } catch(error) { alert("The options are not valid JSON."); return; } $.post(baseURL() + "?setOptions", optionsContents, function(result) { result = result.trim(); if (result != "Options written.") alert(result); }, "text"); $("#save").html("Saving... Done!"); window.setInterval(function () { $("#save").html("Save") }, 500); } function onNumbersChanged(fileContents)
function setViewMode() { if (urlParams().hasOwnProperty("view")) { viewMode = true; $("#viewAsImage").hide(); $("#editView").hide(); $("html").css("margin", "0"); $("body").css("margin", "0"); $("#viewContainer").css("height", "100%"); $("#plotContainer").css("height", "100%"); $("#plotContainer").css("margin", "0"); $("#plotContainer").css("padding", "0"); $("#plotContainer").css("border", "0"); if (urlParams().hasOwnProperty("link")) { $("#viewContainer").append("<a class='downloadLink' target='top_' href='" + baseURL() + "?download'>data</a> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a class='downloadLink' target='top_' href='" + baseURL() + "'>view</a>"); } if (urlParams().hasOwnProperty("clickable")) { $("#viewContainer").click(function () { window.open(baseURL()); }); } } }
{ var data = Format.parse(fileContents); if (!Model.verify(data)) return; lastData = data; var drawData = lastData; if (options["group"]) drawData = lastAggregateData = aggregate(data); drawPlot(drawData); }
identifier_body
tcp_client.go
// Copyright (c) 2020 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package client import ( "errors" "fmt" "math" "time" "github.com/uber-go/tally" "github.com/m3db/m3/src/aggregator/sharding" "github.com/m3db/m3/src/cluster/placement" "github.com/m3db/m3/src/cluster/shard" "github.com/m3db/m3/src/metrics/metadata" "github.com/m3db/m3/src/metrics/metric/aggregated" "github.com/m3db/m3/src/metrics/metric/id" "github.com/m3db/m3/src/metrics/metric/unaggregated" "github.com/m3db/m3/src/metrics/policy" "github.com/m3db/m3/src/x/clock" xerrors "github.com/m3db/m3/src/x/errors" ) var ( _ AdminClient = (*TCPClient)(nil) errNilPlacement = errors.New("placement is nil") ) // TCPClient sends metrics to M3 Aggregator via over custom TCP protocol. type TCPClient struct { nowFn clock.NowFn shardCutoverWarmupDuration time.Duration shardCutoffLingerDuration time.Duration writerMgr instanceWriterManager shardFn sharding.ShardFn placementWatcher placement.Watcher metrics tcpClientMetrics } // NewTCPClient returns new Protobuf over TCP M3 Aggregator client. func NewTCPClient(opts Options) (*TCPClient, error) { if err := opts.Validate(); err != nil { return nil, err } var ( instrumentOpts = opts.InstrumentOptions() writerMgr instanceWriterManager placementWatcher placement.Watcher ) writerMgrScope := instrumentOpts.MetricsScope().SubScope("writer-manager") writerMgrOpts := opts.SetInstrumentOptions(instrumentOpts.SetMetricsScope(writerMgrScope)) writerMgr, err := newInstanceWriterManager(writerMgrOpts) if err != nil { return nil, err } onPlacementChangedFn := func(prev, curr placement.Placement) { writerMgr.AddInstances(curr.Instances()) // nolint: errcheck if prev != nil { writerMgr.RemoveInstances(prev.Instances()) // nolint: errcheck } } placementWatcher = placement.NewPlacementsWatcher( opts.WatcherOptions(). SetOnPlacementChangedFn(onPlacementChangedFn)) return &TCPClient{ nowFn: opts.ClockOptions().NowFn(), shardCutoverWarmupDuration: opts.ShardCutoverWarmupDuration(), shardCutoffLingerDuration: opts.ShardCutoffLingerDuration(), writerMgr: writerMgr, shardFn: opts.ShardFn(), placementWatcher: placementWatcher, metrics: newTCPClientMetrics(instrumentOpts.MetricsScope()), }, nil } // Init initializes TCPClient. func (c *TCPClient) Init() error { return c.placementWatcher.Watch() } // WriteUntimedCounter writes untimed counter metrics. func (c *TCPClient) WriteUntimedCounter( counter unaggregated.Counter, metadatas metadata.StagedMetadatas, ) error { payload := payloadUnion{ payloadType: untimedType, untimed: untimedPayload{ metric: counter.ToUnion(), metadatas: metadatas, }, } c.metrics.writeUntimedCounter.Inc(1) return c.write(counter.ID, c.nowFn().UnixNano(), payload) } // WriteUntimedBatchTimer writes untimed batch timer metrics. func (c *TCPClient) WriteUntimedBatchTimer( batchTimer unaggregated.BatchTimer, metadatas metadata.StagedMetadatas, ) error { payload := payloadUnion{ payloadType: untimedType, untimed: untimedPayload{ metric: batchTimer.ToUnion(), metadatas: metadatas, }, } c.metrics.writeUntimedBatchTimer.Inc(1) return c.write(batchTimer.ID, c.nowFn().UnixNano(), payload) } // WriteUntimedGauge writes untimed gauge metrics. func (c *TCPClient) WriteUntimedGauge( gauge unaggregated.Gauge, metadatas metadata.StagedMetadatas, ) error { payload := payloadUnion{ payloadType: untimedType, untimed: untimedPayload{ metric: gauge.ToUnion(), metadatas: metadatas, }, } c.metrics.writeUntimedGauge.Inc(1) return c.write(gauge.ID, c.nowFn().UnixNano(), payload) } // WriteTimed writes timed metrics. func (c *TCPClient) WriteTimed( metric aggregated.Metric, metadata metadata.TimedMetadata, ) error { payload := payloadUnion{ payloadType: timedType, timed: timedPayload{ metric: metric, metadata: metadata, }, } c.metrics.writeForwarded.Inc(1) return c.write(metric.ID, metric.TimeNanos, payload) } // WritePassthrough writes passthrough metrics. func (c *TCPClient) WritePassthrough( metric aggregated.Metric, storagePolicy policy.StoragePolicy, ) error { payload := payloadUnion{ payloadType: passthroughType, passthrough: passthroughPayload{ metric: metric, storagePolicy: storagePolicy, }, } c.metrics.writePassthrough.Inc(1) return c.write(metric.ID, metric.TimeNanos, payload) } // WriteTimedWithStagedMetadatas writes timed metrics with staged metadatas. func (c *TCPClient) WriteTimedWithStagedMetadatas( metric aggregated.Metric, metadatas metadata.StagedMetadatas, ) error { payload := payloadUnion{ payloadType: timedWithStagedMetadatasType, timedWithStagedMetadatas: timedWithStagedMetadatas{ metric: metric, metadatas: metadatas, }, } c.metrics.writeForwarded.Inc(1) return c.write(metric.ID, metric.TimeNanos, payload) } // WriteForwarded writes forwarded metrics. func (c *TCPClient) WriteForwarded( metric aggregated.ForwardedMetric, metadata metadata.ForwardMetadata, ) error { payload := payloadUnion{ payloadType: forwardedType, forwarded: forwardedPayload{ metric: metric, metadata: metadata, }, } c.metrics.writeForwarded.Inc(1) return c.write(metric.ID, metric.TimeNanos, payload) } // ActivePlacement returns a copy of the currently active placement and its version. func (c *TCPClient) ActivePlacement() (placement.Placement, int, error) { placement, err := c.placementWatcher.Get() if err != nil { return nil, 0, err } if placement == nil { return nil, 0, errNilPlacement } return placement.Clone(), placement.Version(), nil } // ActivePlacementVersion returns a copy of the currently active placement version. It is a far less expensive call // than ActivePlacement, as it does not clone the placement. func (c *TCPClient) ActivePlacementVersion() (int, error) { placement, err := c.placementWatcher.Get() if err != nil { return 0, err } if placement == nil { return 0, errNilPlacement } return placement.Version(), nil } // Flush flushes any remaining data buffered by the client. func (c *TCPClient) Flush() error { c.metrics.flush.Inc(1) return c.writerMgr.Flush() } // Close closes the client. func (c *TCPClient) Close() error { c.writerMgr.Flush() //nolint:errcheck c.placementWatcher.Unwatch() //nolint:errcheck // writerMgr errors out if trying to close twice return c.writerMgr.Close() } //nolint:gocritic func (c *TCPClient) write( metricID id.RawID, timeNanos int64, payload payloadUnion, ) error { placement, err := c.placementWatcher.Get() if err != nil { return err } if placement == nil { return errNilPlacement } var ( shardID = c.shardFn(metricID, uint32(placement.NumShards())) instances = placement.InstancesForShard(shardID) multiErr = xerrors.NewMultiError() oneOrMoreSucceeded = false ) for _, instance := range instances { // NB(xichen): the shard should technically always be found because the instances // are computed from the placement, but protect against errors here regardless. shard, ok := instance.Shards().Shard(shardID)
c.metrics.shardNotOwned.Inc(1) continue } if !c.shouldWriteForShard(timeNanos, shard) { c.metrics.shardNotWriteable.Inc(1) continue } if err = c.writerMgr.Write(instance, shardID, payload); err != nil { multiErr = multiErr.Add(err) continue } oneOrMoreSucceeded = true } if !oneOrMoreSucceeded { // unrectifiable loss c.metrics.dropped.Inc(1) } return multiErr.FinalError() } func (c *TCPClient) shouldWriteForShard(nowNanos int64, shard shard.Shard) bool { writeEarliestNanos, writeLatestNanos := c.writeTimeRangeFor(shard) return nowNanos >= writeEarliestNanos && nowNanos <= writeLatestNanos } // writeTimeRangeFor returns the time range for writes going to a given shard. func (c *TCPClient) writeTimeRangeFor(shard shard.Shard) (int64, int64) { var ( cutoverNanos = shard.CutoverNanos() cutoffNanos = shard.CutoffNanos() earliestNanos = int64(0) latestNanos = int64(math.MaxInt64) ) if cutoverNanos >= int64(c.shardCutoverWarmupDuration) { earliestNanos = cutoverNanos - int64(c.shardCutoverWarmupDuration) } if cutoffNanos <= math.MaxInt64-int64(c.shardCutoffLingerDuration) { latestNanos = cutoffNanos + int64(c.shardCutoffLingerDuration) } return earliestNanos, latestNanos } type tcpClientMetrics struct { writeUntimedCounter tally.Counter writeUntimedBatchTimer tally.Counter writeUntimedGauge tally.Counter writePassthrough tally.Counter writeForwarded tally.Counter flush tally.Counter shardNotOwned tally.Counter shardNotWriteable tally.Counter dropped tally.Counter } func newTCPClientMetrics( scope tally.Scope, ) tcpClientMetrics { return tcpClientMetrics{ writeUntimedCounter: scope.Counter("writeUntimedCounter"), writeUntimedBatchTimer: scope.Counter("writeUntimedBatchTimer"), writeUntimedGauge: scope.Counter("writeUntimedGauge"), writePassthrough: scope.Counter("writePassthrough"), writeForwarded: scope.Counter("writeForwarded"), flush: scope.Counter("flush"), shardNotOwned: scope.Counter("shard-not-owned"), shardNotWriteable: scope.Counter("shard-not-writeable"), dropped: scope.Counter("dropped"), } }
if !ok { err = fmt.Errorf("instance %s does not own shard %d", instance.ID(), shardID) multiErr = multiErr.Add(err)
random_line_split
tcp_client.go
// Copyright (c) 2020 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package client import ( "errors" "fmt" "math" "time" "github.com/uber-go/tally" "github.com/m3db/m3/src/aggregator/sharding" "github.com/m3db/m3/src/cluster/placement" "github.com/m3db/m3/src/cluster/shard" "github.com/m3db/m3/src/metrics/metadata" "github.com/m3db/m3/src/metrics/metric/aggregated" "github.com/m3db/m3/src/metrics/metric/id" "github.com/m3db/m3/src/metrics/metric/unaggregated" "github.com/m3db/m3/src/metrics/policy" "github.com/m3db/m3/src/x/clock" xerrors "github.com/m3db/m3/src/x/errors" ) var ( _ AdminClient = (*TCPClient)(nil) errNilPlacement = errors.New("placement is nil") ) // TCPClient sends metrics to M3 Aggregator via over custom TCP protocol. type TCPClient struct { nowFn clock.NowFn shardCutoverWarmupDuration time.Duration shardCutoffLingerDuration time.Duration writerMgr instanceWriterManager shardFn sharding.ShardFn placementWatcher placement.Watcher metrics tcpClientMetrics } // NewTCPClient returns new Protobuf over TCP M3 Aggregator client. func NewTCPClient(opts Options) (*TCPClient, error) { if err := opts.Validate(); err != nil { return nil, err } var ( instrumentOpts = opts.InstrumentOptions() writerMgr instanceWriterManager placementWatcher placement.Watcher ) writerMgrScope := instrumentOpts.MetricsScope().SubScope("writer-manager") writerMgrOpts := opts.SetInstrumentOptions(instrumentOpts.SetMetricsScope(writerMgrScope)) writerMgr, err := newInstanceWriterManager(writerMgrOpts) if err != nil { return nil, err } onPlacementChangedFn := func(prev, curr placement.Placement) { writerMgr.AddInstances(curr.Instances()) // nolint: errcheck if prev != nil { writerMgr.RemoveInstances(prev.Instances()) // nolint: errcheck } } placementWatcher = placement.NewPlacementsWatcher( opts.WatcherOptions(). SetOnPlacementChangedFn(onPlacementChangedFn)) return &TCPClient{ nowFn: opts.ClockOptions().NowFn(), shardCutoverWarmupDuration: opts.ShardCutoverWarmupDuration(), shardCutoffLingerDuration: opts.ShardCutoffLingerDuration(), writerMgr: writerMgr, shardFn: opts.ShardFn(), placementWatcher: placementWatcher, metrics: newTCPClientMetrics(instrumentOpts.MetricsScope()), }, nil } // Init initializes TCPClient. func (c *TCPClient) Init() error { return c.placementWatcher.Watch() } // WriteUntimedCounter writes untimed counter metrics. func (c *TCPClient) WriteUntimedCounter( counter unaggregated.Counter, metadatas metadata.StagedMetadatas, ) error { payload := payloadUnion{ payloadType: untimedType, untimed: untimedPayload{ metric: counter.ToUnion(), metadatas: metadatas, }, } c.metrics.writeUntimedCounter.Inc(1) return c.write(counter.ID, c.nowFn().UnixNano(), payload) } // WriteUntimedBatchTimer writes untimed batch timer metrics. func (c *TCPClient) WriteUntimedBatchTimer( batchTimer unaggregated.BatchTimer, metadatas metadata.StagedMetadatas, ) error { payload := payloadUnion{ payloadType: untimedType, untimed: untimedPayload{ metric: batchTimer.ToUnion(), metadatas: metadatas, }, } c.metrics.writeUntimedBatchTimer.Inc(1) return c.write(batchTimer.ID, c.nowFn().UnixNano(), payload) } // WriteUntimedGauge writes untimed gauge metrics. func (c *TCPClient) WriteUntimedGauge( gauge unaggregated.Gauge, metadatas metadata.StagedMetadatas, ) error { payload := payloadUnion{ payloadType: untimedType, untimed: untimedPayload{ metric: gauge.ToUnion(), metadatas: metadatas, }, } c.metrics.writeUntimedGauge.Inc(1) return c.write(gauge.ID, c.nowFn().UnixNano(), payload) } // WriteTimed writes timed metrics. func (c *TCPClient) WriteTimed( metric aggregated.Metric, metadata metadata.TimedMetadata, ) error { payload := payloadUnion{ payloadType: timedType, timed: timedPayload{ metric: metric, metadata: metadata, }, } c.metrics.writeForwarded.Inc(1) return c.write(metric.ID, metric.TimeNanos, payload) } // WritePassthrough writes passthrough metrics. func (c *TCPClient) WritePassthrough( metric aggregated.Metric, storagePolicy policy.StoragePolicy, ) error { payload := payloadUnion{ payloadType: passthroughType, passthrough: passthroughPayload{ metric: metric, storagePolicy: storagePolicy, }, } c.metrics.writePassthrough.Inc(1) return c.write(metric.ID, metric.TimeNanos, payload) } // WriteTimedWithStagedMetadatas writes timed metrics with staged metadatas. func (c *TCPClient) WriteTimedWithStagedMetadatas( metric aggregated.Metric, metadatas metadata.StagedMetadatas, ) error { payload := payloadUnion{ payloadType: timedWithStagedMetadatasType, timedWithStagedMetadatas: timedWithStagedMetadatas{ metric: metric, metadatas: metadatas, }, } c.metrics.writeForwarded.Inc(1) return c.write(metric.ID, metric.TimeNanos, payload) } // WriteForwarded writes forwarded metrics. func (c *TCPClient) WriteForwarded( metric aggregated.ForwardedMetric, metadata metadata.ForwardMetadata, ) error { payload := payloadUnion{ payloadType: forwardedType, forwarded: forwardedPayload{ metric: metric, metadata: metadata, }, } c.metrics.writeForwarded.Inc(1) return c.write(metric.ID, metric.TimeNanos, payload) } // ActivePlacement returns a copy of the currently active placement and its version. func (c *TCPClient) ActivePlacement() (placement.Placement, int, error) { placement, err := c.placementWatcher.Get() if err != nil { return nil, 0, err } if placement == nil { return nil, 0, errNilPlacement } return placement.Clone(), placement.Version(), nil } // ActivePlacementVersion returns a copy of the currently active placement version. It is a far less expensive call // than ActivePlacement, as it does not clone the placement. func (c *TCPClient)
() (int, error) { placement, err := c.placementWatcher.Get() if err != nil { return 0, err } if placement == nil { return 0, errNilPlacement } return placement.Version(), nil } // Flush flushes any remaining data buffered by the client. func (c *TCPClient) Flush() error { c.metrics.flush.Inc(1) return c.writerMgr.Flush() } // Close closes the client. func (c *TCPClient) Close() error { c.writerMgr.Flush() //nolint:errcheck c.placementWatcher.Unwatch() //nolint:errcheck // writerMgr errors out if trying to close twice return c.writerMgr.Close() } //nolint:gocritic func (c *TCPClient) write( metricID id.RawID, timeNanos int64, payload payloadUnion, ) error { placement, err := c.placementWatcher.Get() if err != nil { return err } if placement == nil { return errNilPlacement } var ( shardID = c.shardFn(metricID, uint32(placement.NumShards())) instances = placement.InstancesForShard(shardID) multiErr = xerrors.NewMultiError() oneOrMoreSucceeded = false ) for _, instance := range instances { // NB(xichen): the shard should technically always be found because the instances // are computed from the placement, but protect against errors here regardless. shard, ok := instance.Shards().Shard(shardID) if !ok { err = fmt.Errorf("instance %s does not own shard %d", instance.ID(), shardID) multiErr = multiErr.Add(err) c.metrics.shardNotOwned.Inc(1) continue } if !c.shouldWriteForShard(timeNanos, shard) { c.metrics.shardNotWriteable.Inc(1) continue } if err = c.writerMgr.Write(instance, shardID, payload); err != nil { multiErr = multiErr.Add(err) continue } oneOrMoreSucceeded = true } if !oneOrMoreSucceeded { // unrectifiable loss c.metrics.dropped.Inc(1) } return multiErr.FinalError() } func (c *TCPClient) shouldWriteForShard(nowNanos int64, shard shard.Shard) bool { writeEarliestNanos, writeLatestNanos := c.writeTimeRangeFor(shard) return nowNanos >= writeEarliestNanos && nowNanos <= writeLatestNanos } // writeTimeRangeFor returns the time range for writes going to a given shard. func (c *TCPClient) writeTimeRangeFor(shard shard.Shard) (int64, int64) { var ( cutoverNanos = shard.CutoverNanos() cutoffNanos = shard.CutoffNanos() earliestNanos = int64(0) latestNanos = int64(math.MaxInt64) ) if cutoverNanos >= int64(c.shardCutoverWarmupDuration) { earliestNanos = cutoverNanos - int64(c.shardCutoverWarmupDuration) } if cutoffNanos <= math.MaxInt64-int64(c.shardCutoffLingerDuration) { latestNanos = cutoffNanos + int64(c.shardCutoffLingerDuration) } return earliestNanos, latestNanos } type tcpClientMetrics struct { writeUntimedCounter tally.Counter writeUntimedBatchTimer tally.Counter writeUntimedGauge tally.Counter writePassthrough tally.Counter writeForwarded tally.Counter flush tally.Counter shardNotOwned tally.Counter shardNotWriteable tally.Counter dropped tally.Counter } func newTCPClientMetrics( scope tally.Scope, ) tcpClientMetrics { return tcpClientMetrics{ writeUntimedCounter: scope.Counter("writeUntimedCounter"), writeUntimedBatchTimer: scope.Counter("writeUntimedBatchTimer"), writeUntimedGauge: scope.Counter("writeUntimedGauge"), writePassthrough: scope.Counter("writePassthrough"), writeForwarded: scope.Counter("writeForwarded"), flush: scope.Counter("flush"), shardNotOwned: scope.Counter("shard-not-owned"), shardNotWriteable: scope.Counter("shard-not-writeable"), dropped: scope.Counter("dropped"), } }
ActivePlacementVersion
identifier_name
tcp_client.go
// Copyright (c) 2020 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package client import ( "errors" "fmt" "math" "time" "github.com/uber-go/tally" "github.com/m3db/m3/src/aggregator/sharding" "github.com/m3db/m3/src/cluster/placement" "github.com/m3db/m3/src/cluster/shard" "github.com/m3db/m3/src/metrics/metadata" "github.com/m3db/m3/src/metrics/metric/aggregated" "github.com/m3db/m3/src/metrics/metric/id" "github.com/m3db/m3/src/metrics/metric/unaggregated" "github.com/m3db/m3/src/metrics/policy" "github.com/m3db/m3/src/x/clock" xerrors "github.com/m3db/m3/src/x/errors" ) var ( _ AdminClient = (*TCPClient)(nil) errNilPlacement = errors.New("placement is nil") ) // TCPClient sends metrics to M3 Aggregator via over custom TCP protocol. type TCPClient struct { nowFn clock.NowFn shardCutoverWarmupDuration time.Duration shardCutoffLingerDuration time.Duration writerMgr instanceWriterManager shardFn sharding.ShardFn placementWatcher placement.Watcher metrics tcpClientMetrics } // NewTCPClient returns new Protobuf over TCP M3 Aggregator client. func NewTCPClient(opts Options) (*TCPClient, error) { if err := opts.Validate(); err != nil
var ( instrumentOpts = opts.InstrumentOptions() writerMgr instanceWriterManager placementWatcher placement.Watcher ) writerMgrScope := instrumentOpts.MetricsScope().SubScope("writer-manager") writerMgrOpts := opts.SetInstrumentOptions(instrumentOpts.SetMetricsScope(writerMgrScope)) writerMgr, err := newInstanceWriterManager(writerMgrOpts) if err != nil { return nil, err } onPlacementChangedFn := func(prev, curr placement.Placement) { writerMgr.AddInstances(curr.Instances()) // nolint: errcheck if prev != nil { writerMgr.RemoveInstances(prev.Instances()) // nolint: errcheck } } placementWatcher = placement.NewPlacementsWatcher( opts.WatcherOptions(). SetOnPlacementChangedFn(onPlacementChangedFn)) return &TCPClient{ nowFn: opts.ClockOptions().NowFn(), shardCutoverWarmupDuration: opts.ShardCutoverWarmupDuration(), shardCutoffLingerDuration: opts.ShardCutoffLingerDuration(), writerMgr: writerMgr, shardFn: opts.ShardFn(), placementWatcher: placementWatcher, metrics: newTCPClientMetrics(instrumentOpts.MetricsScope()), }, nil } // Init initializes TCPClient. func (c *TCPClient) Init() error { return c.placementWatcher.Watch() } // WriteUntimedCounter writes untimed counter metrics. func (c *TCPClient) WriteUntimedCounter( counter unaggregated.Counter, metadatas metadata.StagedMetadatas, ) error { payload := payloadUnion{ payloadType: untimedType, untimed: untimedPayload{ metric: counter.ToUnion(), metadatas: metadatas, }, } c.metrics.writeUntimedCounter.Inc(1) return c.write(counter.ID, c.nowFn().UnixNano(), payload) } // WriteUntimedBatchTimer writes untimed batch timer metrics. func (c *TCPClient) WriteUntimedBatchTimer( batchTimer unaggregated.BatchTimer, metadatas metadata.StagedMetadatas, ) error { payload := payloadUnion{ payloadType: untimedType, untimed: untimedPayload{ metric: batchTimer.ToUnion(), metadatas: metadatas, }, } c.metrics.writeUntimedBatchTimer.Inc(1) return c.write(batchTimer.ID, c.nowFn().UnixNano(), payload) } // WriteUntimedGauge writes untimed gauge metrics. func (c *TCPClient) WriteUntimedGauge( gauge unaggregated.Gauge, metadatas metadata.StagedMetadatas, ) error { payload := payloadUnion{ payloadType: untimedType, untimed: untimedPayload{ metric: gauge.ToUnion(), metadatas: metadatas, }, } c.metrics.writeUntimedGauge.Inc(1) return c.write(gauge.ID, c.nowFn().UnixNano(), payload) } // WriteTimed writes timed metrics. func (c *TCPClient) WriteTimed( metric aggregated.Metric, metadata metadata.TimedMetadata, ) error { payload := payloadUnion{ payloadType: timedType, timed: timedPayload{ metric: metric, metadata: metadata, }, } c.metrics.writeForwarded.Inc(1) return c.write(metric.ID, metric.TimeNanos, payload) } // WritePassthrough writes passthrough metrics. func (c *TCPClient) WritePassthrough( metric aggregated.Metric, storagePolicy policy.StoragePolicy, ) error { payload := payloadUnion{ payloadType: passthroughType, passthrough: passthroughPayload{ metric: metric, storagePolicy: storagePolicy, }, } c.metrics.writePassthrough.Inc(1) return c.write(metric.ID, metric.TimeNanos, payload) } // WriteTimedWithStagedMetadatas writes timed metrics with staged metadatas. func (c *TCPClient) WriteTimedWithStagedMetadatas( metric aggregated.Metric, metadatas metadata.StagedMetadatas, ) error { payload := payloadUnion{ payloadType: timedWithStagedMetadatasType, timedWithStagedMetadatas: timedWithStagedMetadatas{ metric: metric, metadatas: metadatas, }, } c.metrics.writeForwarded.Inc(1) return c.write(metric.ID, metric.TimeNanos, payload) } // WriteForwarded writes forwarded metrics. func (c *TCPClient) WriteForwarded( metric aggregated.ForwardedMetric, metadata metadata.ForwardMetadata, ) error { payload := payloadUnion{ payloadType: forwardedType, forwarded: forwardedPayload{ metric: metric, metadata: metadata, }, } c.metrics.writeForwarded.Inc(1) return c.write(metric.ID, metric.TimeNanos, payload) } // ActivePlacement returns a copy of the currently active placement and its version. func (c *TCPClient) ActivePlacement() (placement.Placement, int, error) { placement, err := c.placementWatcher.Get() if err != nil { return nil, 0, err } if placement == nil { return nil, 0, errNilPlacement } return placement.Clone(), placement.Version(), nil } // ActivePlacementVersion returns a copy of the currently active placement version. It is a far less expensive call // than ActivePlacement, as it does not clone the placement. func (c *TCPClient) ActivePlacementVersion() (int, error) { placement, err := c.placementWatcher.Get() if err != nil { return 0, err } if placement == nil { return 0, errNilPlacement } return placement.Version(), nil } // Flush flushes any remaining data buffered by the client. func (c *TCPClient) Flush() error { c.metrics.flush.Inc(1) return c.writerMgr.Flush() } // Close closes the client. func (c *TCPClient) Close() error { c.writerMgr.Flush() //nolint:errcheck c.placementWatcher.Unwatch() //nolint:errcheck // writerMgr errors out if trying to close twice return c.writerMgr.Close() } //nolint:gocritic func (c *TCPClient) write( metricID id.RawID, timeNanos int64, payload payloadUnion, ) error { placement, err := c.placementWatcher.Get() if err != nil { return err } if placement == nil { return errNilPlacement } var ( shardID = c.shardFn(metricID, uint32(placement.NumShards())) instances = placement.InstancesForShard(shardID) multiErr = xerrors.NewMultiError() oneOrMoreSucceeded = false ) for _, instance := range instances { // NB(xichen): the shard should technically always be found because the instances // are computed from the placement, but protect against errors here regardless. shard, ok := instance.Shards().Shard(shardID) if !ok { err = fmt.Errorf("instance %s does not own shard %d", instance.ID(), shardID) multiErr = multiErr.Add(err) c.metrics.shardNotOwned.Inc(1) continue } if !c.shouldWriteForShard(timeNanos, shard) { c.metrics.shardNotWriteable.Inc(1) continue } if err = c.writerMgr.Write(instance, shardID, payload); err != nil { multiErr = multiErr.Add(err) continue } oneOrMoreSucceeded = true } if !oneOrMoreSucceeded { // unrectifiable loss c.metrics.dropped.Inc(1) } return multiErr.FinalError() } func (c *TCPClient) shouldWriteForShard(nowNanos int64, shard shard.Shard) bool { writeEarliestNanos, writeLatestNanos := c.writeTimeRangeFor(shard) return nowNanos >= writeEarliestNanos && nowNanos <= writeLatestNanos } // writeTimeRangeFor returns the time range for writes going to a given shard. func (c *TCPClient) writeTimeRangeFor(shard shard.Shard) (int64, int64) { var ( cutoverNanos = shard.CutoverNanos() cutoffNanos = shard.CutoffNanos() earliestNanos = int64(0) latestNanos = int64(math.MaxInt64) ) if cutoverNanos >= int64(c.shardCutoverWarmupDuration) { earliestNanos = cutoverNanos - int64(c.shardCutoverWarmupDuration) } if cutoffNanos <= math.MaxInt64-int64(c.shardCutoffLingerDuration) { latestNanos = cutoffNanos + int64(c.shardCutoffLingerDuration) } return earliestNanos, latestNanos } type tcpClientMetrics struct { writeUntimedCounter tally.Counter writeUntimedBatchTimer tally.Counter writeUntimedGauge tally.Counter writePassthrough tally.Counter writeForwarded tally.Counter flush tally.Counter shardNotOwned tally.Counter shardNotWriteable tally.Counter dropped tally.Counter } func newTCPClientMetrics( scope tally.Scope, ) tcpClientMetrics { return tcpClientMetrics{ writeUntimedCounter: scope.Counter("writeUntimedCounter"), writeUntimedBatchTimer: scope.Counter("writeUntimedBatchTimer"), writeUntimedGauge: scope.Counter("writeUntimedGauge"), writePassthrough: scope.Counter("writePassthrough"), writeForwarded: scope.Counter("writeForwarded"), flush: scope.Counter("flush"), shardNotOwned: scope.Counter("shard-not-owned"), shardNotWriteable: scope.Counter("shard-not-writeable"), dropped: scope.Counter("dropped"), } }
{ return nil, err }
conditional_block
tcp_client.go
// Copyright (c) 2020 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package client import ( "errors" "fmt" "math" "time" "github.com/uber-go/tally" "github.com/m3db/m3/src/aggregator/sharding" "github.com/m3db/m3/src/cluster/placement" "github.com/m3db/m3/src/cluster/shard" "github.com/m3db/m3/src/metrics/metadata" "github.com/m3db/m3/src/metrics/metric/aggregated" "github.com/m3db/m3/src/metrics/metric/id" "github.com/m3db/m3/src/metrics/metric/unaggregated" "github.com/m3db/m3/src/metrics/policy" "github.com/m3db/m3/src/x/clock" xerrors "github.com/m3db/m3/src/x/errors" ) var ( _ AdminClient = (*TCPClient)(nil) errNilPlacement = errors.New("placement is nil") ) // TCPClient sends metrics to M3 Aggregator via over custom TCP protocol. type TCPClient struct { nowFn clock.NowFn shardCutoverWarmupDuration time.Duration shardCutoffLingerDuration time.Duration writerMgr instanceWriterManager shardFn sharding.ShardFn placementWatcher placement.Watcher metrics tcpClientMetrics } // NewTCPClient returns new Protobuf over TCP M3 Aggregator client. func NewTCPClient(opts Options) (*TCPClient, error) { if err := opts.Validate(); err != nil { return nil, err } var ( instrumentOpts = opts.InstrumentOptions() writerMgr instanceWriterManager placementWatcher placement.Watcher ) writerMgrScope := instrumentOpts.MetricsScope().SubScope("writer-manager") writerMgrOpts := opts.SetInstrumentOptions(instrumentOpts.SetMetricsScope(writerMgrScope)) writerMgr, err := newInstanceWriterManager(writerMgrOpts) if err != nil { return nil, err } onPlacementChangedFn := func(prev, curr placement.Placement) { writerMgr.AddInstances(curr.Instances()) // nolint: errcheck if prev != nil { writerMgr.RemoveInstances(prev.Instances()) // nolint: errcheck } } placementWatcher = placement.NewPlacementsWatcher( opts.WatcherOptions(). SetOnPlacementChangedFn(onPlacementChangedFn)) return &TCPClient{ nowFn: opts.ClockOptions().NowFn(), shardCutoverWarmupDuration: opts.ShardCutoverWarmupDuration(), shardCutoffLingerDuration: opts.ShardCutoffLingerDuration(), writerMgr: writerMgr, shardFn: opts.ShardFn(), placementWatcher: placementWatcher, metrics: newTCPClientMetrics(instrumentOpts.MetricsScope()), }, nil } // Init initializes TCPClient. func (c *TCPClient) Init() error { return c.placementWatcher.Watch() } // WriteUntimedCounter writes untimed counter metrics. func (c *TCPClient) WriteUntimedCounter( counter unaggregated.Counter, metadatas metadata.StagedMetadatas, ) error { payload := payloadUnion{ payloadType: untimedType, untimed: untimedPayload{ metric: counter.ToUnion(), metadatas: metadatas, }, } c.metrics.writeUntimedCounter.Inc(1) return c.write(counter.ID, c.nowFn().UnixNano(), payload) } // WriteUntimedBatchTimer writes untimed batch timer metrics. func (c *TCPClient) WriteUntimedBatchTimer( batchTimer unaggregated.BatchTimer, metadatas metadata.StagedMetadatas, ) error { payload := payloadUnion{ payloadType: untimedType, untimed: untimedPayload{ metric: batchTimer.ToUnion(), metadatas: metadatas, }, } c.metrics.writeUntimedBatchTimer.Inc(1) return c.write(batchTimer.ID, c.nowFn().UnixNano(), payload) } // WriteUntimedGauge writes untimed gauge metrics. func (c *TCPClient) WriteUntimedGauge( gauge unaggregated.Gauge, metadatas metadata.StagedMetadatas, ) error { payload := payloadUnion{ payloadType: untimedType, untimed: untimedPayload{ metric: gauge.ToUnion(), metadatas: metadatas, }, } c.metrics.writeUntimedGauge.Inc(1) return c.write(gauge.ID, c.nowFn().UnixNano(), payload) } // WriteTimed writes timed metrics. func (c *TCPClient) WriteTimed( metric aggregated.Metric, metadata metadata.TimedMetadata, ) error { payload := payloadUnion{ payloadType: timedType, timed: timedPayload{ metric: metric, metadata: metadata, }, } c.metrics.writeForwarded.Inc(1) return c.write(metric.ID, metric.TimeNanos, payload) } // WritePassthrough writes passthrough metrics. func (c *TCPClient) WritePassthrough( metric aggregated.Metric, storagePolicy policy.StoragePolicy, ) error { payload := payloadUnion{ payloadType: passthroughType, passthrough: passthroughPayload{ metric: metric, storagePolicy: storagePolicy, }, } c.metrics.writePassthrough.Inc(1) return c.write(metric.ID, metric.TimeNanos, payload) } // WriteTimedWithStagedMetadatas writes timed metrics with staged metadatas. func (c *TCPClient) WriteTimedWithStagedMetadatas( metric aggregated.Metric, metadatas metadata.StagedMetadatas, ) error { payload := payloadUnion{ payloadType: timedWithStagedMetadatasType, timedWithStagedMetadatas: timedWithStagedMetadatas{ metric: metric, metadatas: metadatas, }, } c.metrics.writeForwarded.Inc(1) return c.write(metric.ID, metric.TimeNanos, payload) } // WriteForwarded writes forwarded metrics. func (c *TCPClient) WriteForwarded( metric aggregated.ForwardedMetric, metadata metadata.ForwardMetadata, ) error { payload := payloadUnion{ payloadType: forwardedType, forwarded: forwardedPayload{ metric: metric, metadata: metadata, }, } c.metrics.writeForwarded.Inc(1) return c.write(metric.ID, metric.TimeNanos, payload) } // ActivePlacement returns a copy of the currently active placement and its version. func (c *TCPClient) ActivePlacement() (placement.Placement, int, error)
// ActivePlacementVersion returns a copy of the currently active placement version. It is a far less expensive call // than ActivePlacement, as it does not clone the placement. func (c *TCPClient) ActivePlacementVersion() (int, error) { placement, err := c.placementWatcher.Get() if err != nil { return 0, err } if placement == nil { return 0, errNilPlacement } return placement.Version(), nil } // Flush flushes any remaining data buffered by the client. func (c *TCPClient) Flush() error { c.metrics.flush.Inc(1) return c.writerMgr.Flush() } // Close closes the client. func (c *TCPClient) Close() error { c.writerMgr.Flush() //nolint:errcheck c.placementWatcher.Unwatch() //nolint:errcheck // writerMgr errors out if trying to close twice return c.writerMgr.Close() } //nolint:gocritic func (c *TCPClient) write( metricID id.RawID, timeNanos int64, payload payloadUnion, ) error { placement, err := c.placementWatcher.Get() if err != nil { return err } if placement == nil { return errNilPlacement } var ( shardID = c.shardFn(metricID, uint32(placement.NumShards())) instances = placement.InstancesForShard(shardID) multiErr = xerrors.NewMultiError() oneOrMoreSucceeded = false ) for _, instance := range instances { // NB(xichen): the shard should technically always be found because the instances // are computed from the placement, but protect against errors here regardless. shard, ok := instance.Shards().Shard(shardID) if !ok { err = fmt.Errorf("instance %s does not own shard %d", instance.ID(), shardID) multiErr = multiErr.Add(err) c.metrics.shardNotOwned.Inc(1) continue } if !c.shouldWriteForShard(timeNanos, shard) { c.metrics.shardNotWriteable.Inc(1) continue } if err = c.writerMgr.Write(instance, shardID, payload); err != nil { multiErr = multiErr.Add(err) continue } oneOrMoreSucceeded = true } if !oneOrMoreSucceeded { // unrectifiable loss c.metrics.dropped.Inc(1) } return multiErr.FinalError() } func (c *TCPClient) shouldWriteForShard(nowNanos int64, shard shard.Shard) bool { writeEarliestNanos, writeLatestNanos := c.writeTimeRangeFor(shard) return nowNanos >= writeEarliestNanos && nowNanos <= writeLatestNanos } // writeTimeRangeFor returns the time range for writes going to a given shard. func (c *TCPClient) writeTimeRangeFor(shard shard.Shard) (int64, int64) { var ( cutoverNanos = shard.CutoverNanos() cutoffNanos = shard.CutoffNanos() earliestNanos = int64(0) latestNanos = int64(math.MaxInt64) ) if cutoverNanos >= int64(c.shardCutoverWarmupDuration) { earliestNanos = cutoverNanos - int64(c.shardCutoverWarmupDuration) } if cutoffNanos <= math.MaxInt64-int64(c.shardCutoffLingerDuration) { latestNanos = cutoffNanos + int64(c.shardCutoffLingerDuration) } return earliestNanos, latestNanos } type tcpClientMetrics struct { writeUntimedCounter tally.Counter writeUntimedBatchTimer tally.Counter writeUntimedGauge tally.Counter writePassthrough tally.Counter writeForwarded tally.Counter flush tally.Counter shardNotOwned tally.Counter shardNotWriteable tally.Counter dropped tally.Counter } func newTCPClientMetrics( scope tally.Scope, ) tcpClientMetrics { return tcpClientMetrics{ writeUntimedCounter: scope.Counter("writeUntimedCounter"), writeUntimedBatchTimer: scope.Counter("writeUntimedBatchTimer"), writeUntimedGauge: scope.Counter("writeUntimedGauge"), writePassthrough: scope.Counter("writePassthrough"), writeForwarded: scope.Counter("writeForwarded"), flush: scope.Counter("flush"), shardNotOwned: scope.Counter("shard-not-owned"), shardNotWriteable: scope.Counter("shard-not-writeable"), dropped: scope.Counter("dropped"), } }
{ placement, err := c.placementWatcher.Get() if err != nil { return nil, 0, err } if placement == nil { return nil, 0, errNilPlacement } return placement.Clone(), placement.Version(), nil }
identifier_body
functions.js
var $bl=jQuery.noConflict();if(!bLink){var bLink = {};}; (function($) { $.fn.jslider = function(o) { return this.each(function(){ new $js(this, o).init(); }); }; $.jslider = function(e, o) { var c = $(e).children(".content"); var crsl = c.find(".carousel") var ctrls = c.find(".controls") var con = crsl.find(".container") var hld = con.find(".holder") var w = hld.children("li"); var sliding = 0; var position = 0; // Add jse class to the element: JavaScript enabled c.addClass("jse"); hld.attr('tabindex',0); w.css('position','absolute'); w.attr('tabindex',-1); //add tabIndexes to li elements w.find('a').attr('tabindex','-1'); //remove tabIndex from links inside //need to add a controls container ctrls.addClass("clearfix"); ctrls.append('<p class="left"><a class="previous" href="#previous" title="previous">prev</a></p>') ctrls.append('<span id="carouselCounter"></span>'); ctrls.append('<p class="right"><a class="next" href="#next" title="next">next</a></p>') var counter = ctrls.find("#carouselCounter"); var btnPrev = ctrls.find(".previous"); var btnNext = ctrls.find(".next"); //setup the carousel's initial state this.init = function() { w.each(function(i) { switch (i) { case 0: $(this).css("left", 0); break; case w.size() - 1: $(this).css("left", parseInt(w.eq(0).css("left")) - w.eq(0).width() - parseInt(w.eq(0).css("marginRight"))); break; default: $(this).css("left", parseInt(w.eq(i - 1).css("left")) + w.eq(i - 1).width() + parseInt(w.eq(i - 1).css("marginRight"))); break; } }); setCounter(); }; $(hld).keydown(function(e){ var firstOffset = getCellOffset(0); var lastOffset = getCellOffset(w.size() - 1); //need to check the control state to see if we need to tab out or not. if not, return false to cancel the tab. otherwise, return true switch (e.which) { case 9: switch (e.shiftKey) { case true: switch (firstOffset) { case 0: return true; default: move(1, true); return false; } default: switch (lastOffset) { case 0: return true; default: move(-1, true); return false; } } default: return true; } }); btnPrev.click(function(e){ move(1, false); return false; }); btnNext.click(function(e){ move(-1, false); return false; }); move = function(direction) { if (sliding>0) return; //force immediate return if we are still animating sliding=w.size(); hideCounter(); for (i=0; i<w.size(); i++) { var index = ((i + direction) % w.size() + w.size()) % w.size(); //get index of element with position to which element index i should move var left = getCellOffset(index); //set new position in pixels if (left * direction < 0) w.eq(i).css("visibility", "hidden"); $(w.eq(i)).animate({left:left + "px"}, "medium", null, function(i){sliding--;$(this).css("visibility","visible");if ($bl(w).index(this)==w.size()-1) {setCounter();showCounter();}}); } }; hideCounter = function() {$bl(counter).fadeOut("fast");} showCounter = function() {$bl(counter).fadeIn("fast");} setCounter = function() {$bl(counter).text(getCurrentCell() + 1 + "/" + w.size());} getCellOffset = function(i) { return parseInt($bl(w).eq(i).css("left"));} getCurrentCell = function() { var index = -1; $bl(w).each(function(i, el) { if (getCellOffset(i)==0) index = i; }); return index; } }; var $js = $.jslider; })(jQuery); // accordion using jQuery accordion (function($) {$.fn.jaccordion = function(o) { var a = $bl(this).children(".content"); var ls = a.find("li"); var hd = a.find("h4"); var p = a.find("pnl"); ls.removeClass("active"); a.addClass("jse"); a.accordion({ header: 'li h4', collapsible: true, autoHeight: false })}; })(jQuery); // Submit button replacement (function($) { $.fn.replaceSubmit = function(){ return this.each(function(index){ new $rs(this, index); }); }; $.replaceSubmit = function(e, i) { var page, varData, vars = ""; var thisSubmit = $(e); var submitID = thisSubmit.attr('id'); var submitName = thisSubmit.attr('name').length?thisSubmit.attr('name'):'defaultSubmit'; var submitClass = thisSubmit.attr('className'); var submitValue = thisSubmit.attr('value'); var formAction = thisSubmit.parents("form").attr("action"); if (submitClass == "btnBig") { thisSubmit.after('<span class="' + submitClass + ' btnReplaced"><a rel="' + submitName + '" href="' + formAction + '"><span>' + submitValue + '</span></a></span>'); } else { thisSubmit.after('<span class="btn clearfix btnReplaced"><a rel="' + submitName + '" class="' + submitClass + '" href="' + formAction + '"><span>' + submitValue + '</span></a></span>'); } $(".btnReplaced").not(".norm").eq(i).click(function(){ $(this).parents('form').append('<input type="hidden" name="' + $(this).find('a').attr('rel') + '" value="' + $(this).find('span').text() + '"'); $(this).parents("form").submit(); return false; }); $(".btnReplaced").not(".norm").eq(i).bind("contextmenu",function(e){ $(this).css("text-decoration", "none"); return false; }); thisSubmit.hide(); //we have to hide, not remove the submit button as this, in conjunction with bad xhtml crashes ie6 for some, weird, bizarre, unknowable reason. }; var $rs = $.replaceSubmit; })(jQuery); // Plugin: Panel Toggle Function (function($) { $.fn.toggler = function(o){ //Extend function will replace the defualt object if they do not match var opt = $.extend({ toggleClick: '.toggle', togglePanel: '.toggleChild', toggleOpenMsg: 'Close', toggleClosedMsg: 'Open' }, o); return this.each(function(){ new $tg(this, opt); }); }; $.toggler = function(e, o) { //Show all toggle buttons, CSS for toggle is set to diplay: none var tc = $(e).find(o.toggleClick); var tp = $(e).find(o.togglePanel); tc.css("display","inline"); //Toggle Functionality tc.toggle( function(){ //add toggle functionality here $(this).addClass("closed"); $(this).removeClass("open"); $(this).text(o.toggleClosedMsg); tp.toggle("slow"); return false; }, function(){ //add toggle functionality here $(this).addClass("open"); $(this).removeClass("closed"); $(this).text(o.toggleOpenMsg); tp.toggle("slow"); return false; } ) }; var $tg = $.toggler; })(jQuery); // Plugin: Panel Toggle Function (function($) { $.fn.panels = function(o){ //Extend function will replace the defualt object if they do not match var opt = $.extend({ toggleClick: '.panelToggle', togglePanel: '.panelToggleChild' }, o); return this.each(function(){ new $pn(this, opt); }); }; $.panels = function(e, o) { var tc = $(e).find(o.toggleClick); var tp = $(e).find(o.togglePanel); //Javascript styling tc.css("cursor", "pointer"); //Toggle Functionality tc.toggle( function(){ $(this).addClass("closed"); $(this).removeClass("open"); tp.slideUp("slow"); return false; }, function(){ $(this).addClass("open"); $(this).removeClass("closed"); tp.slideDown("slow"); return false; } ) if (tp.hasClass("initClosed")) {tc.trigger('click');}; }; var $pn = $.panels; })(jQuery); function triggerPanels(pageControlClass,pccLC) { //Javascript styling $bl(".triggerAllPanels").css("display","inline"); //Collapse / Expand all panels if (pageControlClass == ".TP1") { $bl(pccLC).toggle(function(){ $bl("div." + pageControlClass + " .open").trigger('click'); $bl(this).text("Show all"); return false; }, function(){ $bl("div." + pageControlClass + " .closed").trigger('click'); $bl(this).text("Hide all"); return false; }) } else { $bl(pccLC).toggle(function(){ $bl("div." + pageControlClass + " .closed").trigger('click'); $bl(this).text("Hide all"); return false; }, function(){ $bl("div." + pageControlClass + " .open").trigger('click'); $bl(this).text("Show all"); return false; }) } }; /* PopUp Windows */ function popUp () { //Pop up Window Links $bl("a[rel='popUp']").click(function () { var features = "height=350,width=470,scrollTo,resizable=1,scrollbars=1,location=0"; newwindow=window.open(this.href, 'Popup', features); return false; }); //Javascript styling $bl("#popUpClose a").css("visibility","visible"); }; (function($) { $.fn.form = function(o){ var opt = $.extend({ keyboardSubmit: 'form' }, o); return this.each(function(){ new $form(this, opt); }); }; $.forms = function(object, opt) { $(object).keypress( function(e) { e.which==13?this.submit():null; } ); }; var $form = $.forms; })(jQuery); //style for hiding classes to be added dynamically. we want the objects visible when JS is off! document.write('<style type="text/css">.toggleClosed {display:none;}</style>'); //check if array contains a value function
(a, e) { for(j=0;j<a.length;j++)if(a[j]==e)return true; return false; } //this function decides which objects should be visible according to which radio control they are related (use the class attribute [name]_related, where [name] is the name attribute oif the associated radio button/checkbox ) //a radio control may control multiple DOM elements //a DOM object will be visible if any of the controls that can control it have a value of "yes" //be warned - this function is a loop within a loop. if many radio buttons are used, this may be problematic to the user experience :( function toggleRows() { var objNameRoot = this.name; var relatedObjs = $bl("." + objNameRoot + "_related"); relatedObjs.each(function(i) { //find which objects are related to the control the user just clicked on var isVisible = []; var classNames = $bl(relatedObjs[i]).attr("class").split(" "); $bl(classNames).each(function(j) { //find which controls are related to the objects which are related to the control the user just clicked on... classNames[j].match(/.*_related/)?isVisible.push($bl("*[name=" + classNames[j].replace(/(.*)_related/, "$1") + "][checked]").attr("value")):null; }); contains(isVisible, "true")?$(relatedObjs[i]).removeClass("toggleClosed"):$(relatedObjs[i]).addClass("toggleClosed"); //check if any of those controls are switched on. if so, show the related objects for only those controls }); } function attachToggleEvents() { $bl("input.toggleOn").bind("click", toggleRows); $bl("input.toggleOff").bind("click", toggleRows); //now we display any objects that need to be visible which were hidden by dynamically added css $bl("input.toggleOn:checked").trigger("click"); } $bl(document).ready(function() { //$bl('input[type=submit][:eq=0]').replaceSubmit(); $bl('form').form(); $bl(".pnlMyBusiness").jaccordion(); $bl(".pnlCaseStudy").jslider(); $bl(".toggler").toggler(); $bl(".panels").panels(); $bl("#fullPage #txtDescription").focus(); attachToggleEvents(); triggerPanels(".TP1",".tp1"); triggerPanels(".TP2",".tp2"); triggerPanels(".TP3",".tp3"); triggerPanels(".TP4",".tp4"); triggerPanels(".TP5",".tp5"); popUp(); });
contains
identifier_name
functions.js
var $bl=jQuery.noConflict();if(!bLink){var bLink = {};}; (function($) { $.fn.jslider = function(o) { return this.each(function(){ new $js(this, o).init(); }); }; $.jslider = function(e, o) { var c = $(e).children(".content"); var crsl = c.find(".carousel") var ctrls = c.find(".controls") var con = crsl.find(".container") var hld = con.find(".holder") var w = hld.children("li"); var sliding = 0; var position = 0; // Add jse class to the element: JavaScript enabled c.addClass("jse"); hld.attr('tabindex',0); w.css('position','absolute'); w.attr('tabindex',-1); //add tabIndexes to li elements w.find('a').attr('tabindex','-1'); //remove tabIndex from links inside //need to add a controls container ctrls.addClass("clearfix"); ctrls.append('<p class="left"><a class="previous" href="#previous" title="previous">prev</a></p>') ctrls.append('<span id="carouselCounter"></span>'); ctrls.append('<p class="right"><a class="next" href="#next" title="next">next</a></p>') var counter = ctrls.find("#carouselCounter"); var btnPrev = ctrls.find(".previous"); var btnNext = ctrls.find(".next"); //setup the carousel's initial state this.init = function() { w.each(function(i) { switch (i) { case 0: $(this).css("left", 0); break; case w.size() - 1: $(this).css("left", parseInt(w.eq(0).css("left")) - w.eq(0).width() - parseInt(w.eq(0).css("marginRight"))); break; default: $(this).css("left", parseInt(w.eq(i - 1).css("left")) + w.eq(i - 1).width() + parseInt(w.eq(i - 1).css("marginRight"))); break; } }); setCounter(); }; $(hld).keydown(function(e){ var firstOffset = getCellOffset(0); var lastOffset = getCellOffset(w.size() - 1); //need to check the control state to see if we need to tab out or not. if not, return false to cancel the tab. otherwise, return true switch (e.which) { case 9: switch (e.shiftKey) { case true: switch (firstOffset) { case 0: return true; default: move(1, true); return false; } default: switch (lastOffset) { case 0: return true; default: move(-1, true); return false; } } default: return true; } }); btnPrev.click(function(e){ move(1, false); return false; }); btnNext.click(function(e){ move(-1, false); return false; }); move = function(direction) { if (sliding>0) return; //force immediate return if we are still animating sliding=w.size(); hideCounter(); for (i=0; i<w.size(); i++) { var index = ((i + direction) % w.size() + w.size()) % w.size(); //get index of element with position to which element index i should move var left = getCellOffset(index); //set new position in pixels if (left * direction < 0) w.eq(i).css("visibility", "hidden"); $(w.eq(i)).animate({left:left + "px"}, "medium", null, function(i){sliding--;$(this).css("visibility","visible");if ($bl(w).index(this)==w.size()-1) {setCounter();showCounter();}}); } }; hideCounter = function() {$bl(counter).fadeOut("fast");} showCounter = function() {$bl(counter).fadeIn("fast");} setCounter = function() {$bl(counter).text(getCurrentCell() + 1 + "/" + w.size());} getCellOffset = function(i) { return parseInt($bl(w).eq(i).css("left"));} getCurrentCell = function() { var index = -1; $bl(w).each(function(i, el) { if (getCellOffset(i)==0) index = i; }); return index; } }; var $js = $.jslider; })(jQuery); // accordion using jQuery accordion (function($) {$.fn.jaccordion = function(o) { var a = $bl(this).children(".content"); var ls = a.find("li"); var hd = a.find("h4"); var p = a.find("pnl"); ls.removeClass("active"); a.addClass("jse"); a.accordion({ header: 'li h4', collapsible: true, autoHeight: false })}; })(jQuery); // Submit button replacement (function($) { $.fn.replaceSubmit = function(){ return this.each(function(index){ new $rs(this, index); }); }; $.replaceSubmit = function(e, i) { var page, varData, vars = ""; var thisSubmit = $(e); var submitID = thisSubmit.attr('id'); var submitName = thisSubmit.attr('name').length?thisSubmit.attr('name'):'defaultSubmit'; var submitClass = thisSubmit.attr('className'); var submitValue = thisSubmit.attr('value'); var formAction = thisSubmit.parents("form").attr("action"); if (submitClass == "btnBig") { thisSubmit.after('<span class="' + submitClass + ' btnReplaced"><a rel="' + submitName + '" href="' + formAction + '"><span>' + submitValue + '</span></a></span>'); } else { thisSubmit.after('<span class="btn clearfix btnReplaced"><a rel="' + submitName + '" class="' + submitClass + '" href="' + formAction + '"><span>' + submitValue + '</span></a></span>'); } $(".btnReplaced").not(".norm").eq(i).click(function(){ $(this).parents('form').append('<input type="hidden" name="' + $(this).find('a').attr('rel') + '" value="' + $(this).find('span').text() + '"'); $(this).parents("form").submit(); return false; }); $(".btnReplaced").not(".norm").eq(i).bind("contextmenu",function(e){ $(this).css("text-decoration", "none"); return false; }); thisSubmit.hide(); //we have to hide, not remove the submit button as this, in conjunction with bad xhtml crashes ie6 for some, weird, bizarre, unknowable reason. }; var $rs = $.replaceSubmit; })(jQuery); // Plugin: Panel Toggle Function (function($) { $.fn.toggler = function(o){ //Extend function will replace the defualt object if they do not match var opt = $.extend({ toggleClick: '.toggle', togglePanel: '.toggleChild', toggleOpenMsg: 'Close', toggleClosedMsg: 'Open' }, o); return this.each(function(){ new $tg(this, opt); }); }; $.toggler = function(e, o) { //Show all toggle buttons, CSS for toggle is set to diplay: none var tc = $(e).find(o.toggleClick); var tp = $(e).find(o.togglePanel); tc.css("display","inline"); //Toggle Functionality tc.toggle( function(){ //add toggle functionality here $(this).addClass("closed"); $(this).removeClass("open"); $(this).text(o.toggleClosedMsg); tp.toggle("slow"); return false; }, function(){ //add toggle functionality here $(this).addClass("open"); $(this).removeClass("closed"); $(this).text(o.toggleOpenMsg); tp.toggle("slow"); return false; } ) }; var $tg = $.toggler; })(jQuery); // Plugin: Panel Toggle Function (function($) { $.fn.panels = function(o){ //Extend function will replace the defualt object if they do not match var opt = $.extend({ toggleClick: '.panelToggle', togglePanel: '.panelToggleChild' }, o); return this.each(function(){ new $pn(this, opt); }); }; $.panels = function(e, o) { var tc = $(e).find(o.toggleClick); var tp = $(e).find(o.togglePanel); //Javascript styling tc.css("cursor", "pointer"); //Toggle Functionality tc.toggle( function(){ $(this).addClass("closed"); $(this).removeClass("open"); tp.slideUp("slow"); return false; }, function(){ $(this).addClass("open"); $(this).removeClass("closed"); tp.slideDown("slow"); return false; } ) if (tp.hasClass("initClosed")) {tc.trigger('click');}; }; var $pn = $.panels; })(jQuery); function triggerPanels(pageControlClass,pccLC) { //Javascript styling $bl(".triggerAllPanels").css("display","inline"); //Collapse / Expand all panels if (pageControlClass == ".TP1") { $bl(pccLC).toggle(function(){ $bl("div." + pageControlClass + " .open").trigger('click'); $bl(this).text("Show all"); return false; }, function(){ $bl("div." + pageControlClass + " .closed").trigger('click'); $bl(this).text("Hide all"); return false; }) } else { $bl(pccLC).toggle(function(){ $bl("div." + pageControlClass + " .closed").trigger('click'); $bl(this).text("Hide all"); return false; }, function(){ $bl("div." + pageControlClass + " .open").trigger('click'); $bl(this).text("Show all"); return false; }) } }; /* PopUp Windows */ function popUp () { //Pop up Window Links $bl("a[rel='popUp']").click(function () { var features = "height=350,width=470,scrollTo,resizable=1,scrollbars=1,location=0"; newwindow=window.open(this.href, 'Popup', features); return false; }); //Javascript styling $bl("#popUpClose a").css("visibility","visible"); }; (function($) { $.fn.form = function(o){ var opt = $.extend({ keyboardSubmit: 'form' }, o); return this.each(function(){ new $form(this, opt); }); }; $.forms = function(object, opt) { $(object).keypress( function(e) { e.which==13?this.submit():null; } ); }; var $form = $.forms; })(jQuery); //style for hiding classes to be added dynamically. we want the objects visible when JS is off! document.write('<style type="text/css">.toggleClosed {display:none;}</style>'); //check if array contains a value function contains(a, e) { for(j=0;j<a.length;j++)if(a[j]==e)return true; return false; } //this function decides which objects should be visible according to which radio control they are related (use the class attribute [name]_related, where [name] is the name attribute oif the associated radio button/checkbox ) //a radio control may control multiple DOM elements //a DOM object will be visible if any of the controls that can control it have a value of "yes" //be warned - this function is a loop within a loop. if many radio buttons are used, this may be problematic to the user experience :( function toggleRows()
function attachToggleEvents() { $bl("input.toggleOn").bind("click", toggleRows); $bl("input.toggleOff").bind("click", toggleRows); //now we display any objects that need to be visible which were hidden by dynamically added css $bl("input.toggleOn:checked").trigger("click"); } $bl(document).ready(function() { //$bl('input[type=submit][:eq=0]').replaceSubmit(); $bl('form').form(); $bl(".pnlMyBusiness").jaccordion(); $bl(".pnlCaseStudy").jslider(); $bl(".toggler").toggler(); $bl(".panels").panels(); $bl("#fullPage #txtDescription").focus(); attachToggleEvents(); triggerPanels(".TP1",".tp1"); triggerPanels(".TP2",".tp2"); triggerPanels(".TP3",".tp3"); triggerPanels(".TP4",".tp4"); triggerPanels(".TP5",".tp5"); popUp(); });
{ var objNameRoot = this.name; var relatedObjs = $bl("." + objNameRoot + "_related"); relatedObjs.each(function(i) { //find which objects are related to the control the user just clicked on var isVisible = []; var classNames = $bl(relatedObjs[i]).attr("class").split(" "); $bl(classNames).each(function(j) { //find which controls are related to the objects which are related to the control the user just clicked on... classNames[j].match(/.*_related/)?isVisible.push($bl("*[name=" + classNames[j].replace(/(.*)_related/, "$1") + "][checked]").attr("value")):null; }); contains(isVisible, "true")?$(relatedObjs[i]).removeClass("toggleClosed"):$(relatedObjs[i]).addClass("toggleClosed"); //check if any of those controls are switched on. if so, show the related objects for only those controls }); }
identifier_body
functions.js
var $bl=jQuery.noConflict();if(!bLink){var bLink = {};}; (function($) { $.fn.jslider = function(o) { return this.each(function(){ new $js(this, o).init(); }); }; $.jslider = function(e, o) { var c = $(e).children(".content"); var crsl = c.find(".carousel") var ctrls = c.find(".controls") var con = crsl.find(".container") var hld = con.find(".holder") var w = hld.children("li"); var sliding = 0; var position = 0; // Add jse class to the element: JavaScript enabled c.addClass("jse"); hld.attr('tabindex',0); w.css('position','absolute'); w.attr('tabindex',-1); //add tabIndexes to li elements w.find('a').attr('tabindex','-1'); //remove tabIndex from links inside //need to add a controls container ctrls.addClass("clearfix"); ctrls.append('<p class="left"><a class="previous" href="#previous" title="previous">prev</a></p>') ctrls.append('<span id="carouselCounter"></span>'); ctrls.append('<p class="right"><a class="next" href="#next" title="next">next</a></p>') var counter = ctrls.find("#carouselCounter"); var btnPrev = ctrls.find(".previous"); var btnNext = ctrls.find(".next"); //setup the carousel's initial state this.init = function() { w.each(function(i) { switch (i) { case 0: $(this).css("left", 0); break; case w.size() - 1: $(this).css("left", parseInt(w.eq(0).css("left")) - w.eq(0).width() - parseInt(w.eq(0).css("marginRight"))); break; default: $(this).css("left", parseInt(w.eq(i - 1).css("left")) + w.eq(i - 1).width() + parseInt(w.eq(i - 1).css("marginRight"))); break; } }); setCounter(); }; $(hld).keydown(function(e){ var firstOffset = getCellOffset(0); var lastOffset = getCellOffset(w.size() - 1); //need to check the control state to see if we need to tab out or not. if not, return false to cancel the tab. otherwise, return true switch (e.which) { case 9: switch (e.shiftKey) { case true: switch (firstOffset) { case 0: return true; default: move(1, true); return false; } default: switch (lastOffset) { case 0: return true; default: move(-1, true); return false; } } default: return true; } }); btnPrev.click(function(e){ move(1, false); return false; }); btnNext.click(function(e){ move(-1, false); return false; }); move = function(direction) { if (sliding>0) return; //force immediate return if we are still animating sliding=w.size(); hideCounter(); for (i=0; i<w.size(); i++) { var index = ((i + direction) % w.size() + w.size()) % w.size(); //get index of element with position to which element index i should move var left = getCellOffset(index); //set new position in pixels if (left * direction < 0) w.eq(i).css("visibility", "hidden"); $(w.eq(i)).animate({left:left + "px"}, "medium", null, function(i){sliding--;$(this).css("visibility","visible");if ($bl(w).index(this)==w.size()-1) {setCounter();showCounter();}}); } }; hideCounter = function() {$bl(counter).fadeOut("fast");} showCounter = function() {$bl(counter).fadeIn("fast");} setCounter = function() {$bl(counter).text(getCurrentCell() + 1 + "/" + w.size());} getCellOffset = function(i) { return parseInt($bl(w).eq(i).css("left"));} getCurrentCell = function() { var index = -1; $bl(w).each(function(i, el) { if (getCellOffset(i)==0) index = i; }); return index; } }; var $js = $.jslider; })(jQuery); // accordion using jQuery accordion (function($) {$.fn.jaccordion = function(o) { var a = $bl(this).children(".content"); var ls = a.find("li"); var hd = a.find("h4"); var p = a.find("pnl"); ls.removeClass("active"); a.addClass("jse"); a.accordion({ header: 'li h4', collapsible: true, autoHeight: false })}; })(jQuery); // Submit button replacement (function($) { $.fn.replaceSubmit = function(){ return this.each(function(index){ new $rs(this, index); }); }; $.replaceSubmit = function(e, i) { var page, varData, vars = ""; var thisSubmit = $(e); var submitID = thisSubmit.attr('id'); var submitName = thisSubmit.attr('name').length?thisSubmit.attr('name'):'defaultSubmit'; var submitClass = thisSubmit.attr('className'); var submitValue = thisSubmit.attr('value'); var formAction = thisSubmit.parents("form").attr("action"); if (submitClass == "btnBig") { thisSubmit.after('<span class="' + submitClass + ' btnReplaced"><a rel="' + submitName + '" href="' + formAction + '"><span>' + submitValue + '</span></a></span>');
$(".btnReplaced").not(".norm").eq(i).click(function(){ $(this).parents('form').append('<input type="hidden" name="' + $(this).find('a').attr('rel') + '" value="' + $(this).find('span').text() + '"'); $(this).parents("form").submit(); return false; }); $(".btnReplaced").not(".norm").eq(i).bind("contextmenu",function(e){ $(this).css("text-decoration", "none"); return false; }); thisSubmit.hide(); //we have to hide, not remove the submit button as this, in conjunction with bad xhtml crashes ie6 for some, weird, bizarre, unknowable reason. }; var $rs = $.replaceSubmit; })(jQuery); // Plugin: Panel Toggle Function (function($) { $.fn.toggler = function(o){ //Extend function will replace the defualt object if they do not match var opt = $.extend({ toggleClick: '.toggle', togglePanel: '.toggleChild', toggleOpenMsg: 'Close', toggleClosedMsg: 'Open' }, o); return this.each(function(){ new $tg(this, opt); }); }; $.toggler = function(e, o) { //Show all toggle buttons, CSS for toggle is set to diplay: none var tc = $(e).find(o.toggleClick); var tp = $(e).find(o.togglePanel); tc.css("display","inline"); //Toggle Functionality tc.toggle( function(){ //add toggle functionality here $(this).addClass("closed"); $(this).removeClass("open"); $(this).text(o.toggleClosedMsg); tp.toggle("slow"); return false; }, function(){ //add toggle functionality here $(this).addClass("open"); $(this).removeClass("closed"); $(this).text(o.toggleOpenMsg); tp.toggle("slow"); return false; } ) }; var $tg = $.toggler; })(jQuery); // Plugin: Panel Toggle Function (function($) { $.fn.panels = function(o){ //Extend function will replace the defualt object if they do not match var opt = $.extend({ toggleClick: '.panelToggle', togglePanel: '.panelToggleChild' }, o); return this.each(function(){ new $pn(this, opt); }); }; $.panels = function(e, o) { var tc = $(e).find(o.toggleClick); var tp = $(e).find(o.togglePanel); //Javascript styling tc.css("cursor", "pointer"); //Toggle Functionality tc.toggle( function(){ $(this).addClass("closed"); $(this).removeClass("open"); tp.slideUp("slow"); return false; }, function(){ $(this).addClass("open"); $(this).removeClass("closed"); tp.slideDown("slow"); return false; } ) if (tp.hasClass("initClosed")) {tc.trigger('click');}; }; var $pn = $.panels; })(jQuery); function triggerPanels(pageControlClass,pccLC) { //Javascript styling $bl(".triggerAllPanels").css("display","inline"); //Collapse / Expand all panels if (pageControlClass == ".TP1") { $bl(pccLC).toggle(function(){ $bl("div." + pageControlClass + " .open").trigger('click'); $bl(this).text("Show all"); return false; }, function(){ $bl("div." + pageControlClass + " .closed").trigger('click'); $bl(this).text("Hide all"); return false; }) } else { $bl(pccLC).toggle(function(){ $bl("div." + pageControlClass + " .closed").trigger('click'); $bl(this).text("Hide all"); return false; }, function(){ $bl("div." + pageControlClass + " .open").trigger('click'); $bl(this).text("Show all"); return false; }) } }; /* PopUp Windows */ function popUp () { //Pop up Window Links $bl("a[rel='popUp']").click(function () { var features = "height=350,width=470,scrollTo,resizable=1,scrollbars=1,location=0"; newwindow=window.open(this.href, 'Popup', features); return false; }); //Javascript styling $bl("#popUpClose a").css("visibility","visible"); }; (function($) { $.fn.form = function(o){ var opt = $.extend({ keyboardSubmit: 'form' }, o); return this.each(function(){ new $form(this, opt); }); }; $.forms = function(object, opt) { $(object).keypress( function(e) { e.which==13?this.submit():null; } ); }; var $form = $.forms; })(jQuery); //style for hiding classes to be added dynamically. we want the objects visible when JS is off! document.write('<style type="text/css">.toggleClosed {display:none;}</style>'); //check if array contains a value function contains(a, e) { for(j=0;j<a.length;j++)if(a[j]==e)return true; return false; } //this function decides which objects should be visible according to which radio control they are related (use the class attribute [name]_related, where [name] is the name attribute oif the associated radio button/checkbox ) //a radio control may control multiple DOM elements //a DOM object will be visible if any of the controls that can control it have a value of "yes" //be warned - this function is a loop within a loop. if many radio buttons are used, this may be problematic to the user experience :( function toggleRows() { var objNameRoot = this.name; var relatedObjs = $bl("." + objNameRoot + "_related"); relatedObjs.each(function(i) { //find which objects are related to the control the user just clicked on var isVisible = []; var classNames = $bl(relatedObjs[i]).attr("class").split(" "); $bl(classNames).each(function(j) { //find which controls are related to the objects which are related to the control the user just clicked on... classNames[j].match(/.*_related/)?isVisible.push($bl("*[name=" + classNames[j].replace(/(.*)_related/, "$1") + "][checked]").attr("value")):null; }); contains(isVisible, "true")?$(relatedObjs[i]).removeClass("toggleClosed"):$(relatedObjs[i]).addClass("toggleClosed"); //check if any of those controls are switched on. if so, show the related objects for only those controls }); } function attachToggleEvents() { $bl("input.toggleOn").bind("click", toggleRows); $bl("input.toggleOff").bind("click", toggleRows); //now we display any objects that need to be visible which were hidden by dynamically added css $bl("input.toggleOn:checked").trigger("click"); } $bl(document).ready(function() { //$bl('input[type=submit][:eq=0]').replaceSubmit(); $bl('form').form(); $bl(".pnlMyBusiness").jaccordion(); $bl(".pnlCaseStudy").jslider(); $bl(".toggler").toggler(); $bl(".panels").panels(); $bl("#fullPage #txtDescription").focus(); attachToggleEvents(); triggerPanels(".TP1",".tp1"); triggerPanels(".TP2",".tp2"); triggerPanels(".TP3",".tp3"); triggerPanels(".TP4",".tp4"); triggerPanels(".TP5",".tp5"); popUp(); });
} else { thisSubmit.after('<span class="btn clearfix btnReplaced"><a rel="' + submitName + '" class="' + submitClass + '" href="' + formAction + '"><span>' + submitValue + '</span></a></span>'); }
random_line_split
wamrobot.py
#!/usr/bin/env python # Copyright (c) 2013, Carnegie Mellon University # All rights reserved. # Authors: Michael Koval <mkoval@cs.cmu.edu> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # - Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # - Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # - Neither the name of Carnegie Mellon University nor the names of its # contributors may be used to endorse or promote products derived from this # software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. import logging, openravepy, numpy from .. import util from robot import Robot import prpy.rave from .. import exceptions class WAMRobot(Robot): def __init__(self, robot_name=None): Robot.__init__(self, robot_name=robot_name) # Optional MacTrajectory retimer. If this fails, we'll fall back on # executing generic trajectories. self.mac_retimer = openravepy.RaveCreatePlanner(self.GetEnv(), 'MacRetimer') # Trajectory blending. self.trajectory_module = prpy.rave.load_module(self.GetEnv(), 'Trajectory', self.GetName()) import manipulation2.trajectory manipulation2.trajectory.bind(self.trajectory_module) def CloneBindings(self, parent): Robot.CloneBindings(self, parent) self.mac_retimer = None trajectory_module = prpy.rave.load_module(self.GetEnv(), 'Trajectory', self.GetName()) import manipulation2.trajectory #manipulation2.trajectory.bind(self.trajectory_module) def myFun(x): pass import types class Object(): pass self.trajectory_module = Object() self.trajectory_module.module = trajectory_module self.trajectory_module.blendtrajectory = types.MethodType(manipulation2.trajectory.blendtrajectory, trajectory_module) self.trajectory_module.executeblendedtrajectory = types.MethodType(manipulation2.trajectory.executeblendedtrajectory, trajectory_module) def RetimeTrajectory(self, traj, max_jerk=30.0, synchronize=False, stop_on_stall=True, stop_on_ft=False, force_direction=None, force_magnitude=None, torque=None, **kw_args): """Retime a generic OpenRAVE trajectory into a timed for OWD. First, try to retime the trajectory into a MacTrajectory using OWD's MacRetimer. If MacRetimer is not available, then fall back on the default OpenRAVE retimer. @param traj input trajectory @param max_jerk maximum jerk allowed during retiming @param synchronize enable synchronization between multiple OWD processes @param stop_on_stall cancel the trajectory if stall torques are exceeded @param stop_on_ft cancel the trajectory on force/torque input @param force_direction direction vector used for stop_on_ft @param force_magnitude force threshold for stop_on_ft @param torque torque threshold for stop_on_ft @return timed trajectory """ # Fall back on the standard OpenRAVE retimer if MacTrajectory is not # available. if self.mac_retimer is None: return Robot.RetimeTrajectory(self, traj, **kw_args) # check the number of num_waypoints = traj.GetNumWaypoints() if num_waypoints < 2: logging.warn('RetimeTrajectory received trajectory with less than 2 waypoints. Skipping retime.') return traj # Create a MacTrajectory with timestamps, joint values, velocities, # accelerations, and blend radii. generic_config_spec = traj.GetConfigurationSpecification() generic_angle_group = generic_config_spec.GetGroupFromName('joint_values') path_config_spec = openravepy.ConfigurationSpecification() path_config_spec.AddDeltaTimeGroup() path_config_spec.AddGroup(generic_angle_group.name, generic_angle_group.dof, '') path_config_spec.AddDerivativeGroups(1, False); path_config_spec.AddDerivativeGroups(2, False); path_config_spec.AddGroup('owd_blend_radius', 1, 'next') path_config_spec.ResetGroupOffsets() # Initialize the MacTrajectory. mac_traj = openravepy.RaveCreateTrajectory(self.GetEnv(), 'MacTrajectory') mac_traj.Init(path_config_spec) # Copy the joint values and blend radii into the MacTrajectory. for i in xrange(num_waypoints): waypoint = traj.GetWaypoint(i, path_config_spec) mac_traj.Insert(i, waypoint, path_config_spec) # Serialize the planner parameters. params = [ 'max_jerk', str(max_jerk) ] if stop_on_stall: params += [ 'cancel_on_stall' ] if stop_on_ft: force_threshold = force_magnitude * numpy.array(force_direction) params += [ 'cancel_on_ft' ] params += [ 'force_threshold' ] + map(str, force_threshold) params += [ 'torque_threshold' ] + map(str, torque) if synchronize: params += [ 'synchronize' ] # Retime the MacTrajectory with the MacRetimer. params_str = ' '.join(params) retimer_params = openravepy.Planner.PlannerParameters() retimer_params.SetExtraParameters(params_str) with self: self.mac_retimer.InitPlan(self, retimer_params) self.mac_retimer.PlanPath(mac_traj) return mac_traj def BlendTrajectory(self, traj, maxsmoothiter=None, resolution=None, blend_radius=0.2, blend_attempts=4, blend_step_size=0.05, linearity_threshold=0.1, ignore_collisions=None, **kw_args): """Blend a trajectory for execution in OWD. Blending a trajectory allows the MacRetimer to smoothly accelerate through waypoints. If a blend radius is not specified, it defaults to
the \tt blend_radius group to the input trajectory. @param traj input trajectory @return blended trajectory """ with self: return self.trajectory_module.blendtrajectory(traj=traj, execute=False, maxsmoothiter=maxsmoothiter, resolution=resolution, blend_radius=blend_radius, blend_attempts=blend_attempts, blend_step_size=blend_step_size, linearity_threshold=linearity_threshold, ignore_collisions=ignore_collisions) def ExecuteTrajectory(self, traj, timeout=None, blend=True, retime=True, limit_tolerance=1e-3, synchronize=True, **kw_args): """Execute a trajectory. By default, this function retimes, blends, and adds the stop_on_stall flag to all trajectories. This behavior can be overriden using the \tt blend and \tt retime flags or by passing the appropriate \tt **kw_args arguments to the blender and retimer. By default, this function blocks until trajectory execution finishes. This can be changed by changing the timeout parameter to a maximum number of seconds. Pass a timeout of zero to return instantly. @param traj trajectory to execute @param timeout blocking execution timeout @param blend flag for computing blend radii before execution @param retime flag for retiming the trajectory before execution @return executed_traj including blending and retiming """ # Query the active manipulators based on which DOF indices are # included in the trajectory. active_manipulators = self.GetTrajectoryManipulators(traj) needs_synchronization = synchronize and len(active_manipulators) > 1 sim_flags = [ manipulator.simulated for manipulator in active_manipulators ] if needs_synchronization and any(sim_flags) and not all(sim_flags): raise exceptions.SynchronizationException( 'Unable to execute synchronized trajectory with' ' a mixture of simulated and real controllers.') # Disallow trajectories that include both the base and the arms when # not in simulation mode. We can't guarantee synchronization in this case. def has_affine_dofs(traj): def has_group(cspec, group_name): try: cspec.GetGroupFromName(group_name) return True except openravepy.openrave_exception: return False cspec = traj.GetConfigurationSpecification() return (has_group(cspec, 'affine_transform') or has_group(cspec, 'affine_velocities') or has_group(cspec, 'affine_accelerations')) needs_arms = bool(active_manipulators) needs_base = has_affine_dofs(traj) arms_simulated = all(sim_flags) if needs_base and needs_arms and not arms_simulated and not self.base.simulated: raise NotImplementedError('Joint arm-base trajectories are not supported on hardware.') # Optionally blend and retime the trajectory before execution. Retiming # creates a MacTrajectory that can be directly executed by OWD. if needs_arms: active_indices = util.GetTrajectoryIndices(traj) with self: self.SetActiveDOFs(active_indices) if blend: traj = self.BlendTrajectory(traj) # Check if the first point is not in limits. unclamped_dof_values = self.GetActiveDOFValues() first_waypoint = traj.GetWaypoint(0) cspec = traj.GetConfigurationSpecification() first_dof_values = cspec.ExtractJointValues(first_waypoint, self, active_indices, 0) lower_limits, upper_limits = self.GetActiveDOFLimits() for i in xrange(len(first_dof_values)): if numpy.allclose(first_dof_values[i], lower_limits[i], atol=limit_tolerance) and unclamped_dof_values[i] < lower_limits[i]: first_dof_values[i] = unclamped_dof_values[i] logging.warn('Unclamped DOF %d from lower limit.', active_indices[i]) elif numpy.allclose(first_dof_values[i], upper_limits[i], atol=limit_tolerance) and unclamped_dof_values[i] > upper_limits[i]: first_dof_values[i] = unclamped_dof_values[i] logging.warn('Unclamped DOF %d from upper limit.', active_indices[i]) # Snap the first point to the current configuration. cspec.InsertJointValues(first_waypoint, first_dof_values, self, active_indices, 0) traj.Insert(0, first_waypoint, True) # This must be last because MacTrajectories are immutable. # TODO: This may break if the retimer clamps DOF values to the joint limits. if retime: traj = self.RetimeTrajectory(traj, synchronize=needs_synchronization, **kw_args) if needs_base: # Retime the base trajectory in simulation. if retime:# and self.base.simulated: max_vel = numpy.concatenate((self.GetAffineTranslationMaxVels()[:2], [ self.GetAffineRotationQuatMaxVels() ])) max_accel = 3 * max_vel openravepy.planningutils.RetimeAffineTrajectory(traj, max_vel, max_accel, False) # Can't execute trajectories with less than two waypoints if traj.GetNumWaypoints() < 2: logging.warn('Unable to execute trajectories with less than 2 waypoints. Skipping execution.') return traj # Synchronization implicitly executes on all manipulators. if needs_synchronization: running_manipulators = set(self.manipulators) else: running_manipulators = set(active_manipulators) # Reset old trajectory execution flags for manipulator in active_manipulators: manipulator.ClearTrajectoryStatus() # FIXME: The IdealController attempts to sample the MacTrajectory in simulation. # self.GetController().SetPath(traj) # Wait for trajectory execution to finish. running_controllers = [ manipulator.controller for manipulator in running_manipulators ] if needs_base: running_controllers += [ self.base.controller ] for controller in running_controllers: controller.SetPath(traj) is_done = util.WaitForControllers(running_controllers, timeout=timeout) # Request the controller status from each manipulator. if is_done: with self.GetEnv(): for manipulator in active_manipulators: status = manipulator.GetTrajectoryStatus() if status == 'aborted': raise exceptions.TrajectoryAborted('Trajectory aborted for %s' % manipulator.GetName()) elif status == 'stalled': raise exceptions.TrajectoryStalled('Trajectory stalled for %s' % manipulator.GetName()) if manipulator.simulated: manipulator.controller.Reset() return traj
zero and the controller must come to a stop at each waypoint. This adds
random_line_split
wamrobot.py
#!/usr/bin/env python # Copyright (c) 2013, Carnegie Mellon University # All rights reserved. # Authors: Michael Koval <mkoval@cs.cmu.edu> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # - Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # - Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # - Neither the name of Carnegie Mellon University nor the names of its # contributors may be used to endorse or promote products derived from this # software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. import logging, openravepy, numpy from .. import util from robot import Robot import prpy.rave from .. import exceptions class WAMRobot(Robot): def __init__(self, robot_name=None): Robot.__init__(self, robot_name=robot_name) # Optional MacTrajectory retimer. If this fails, we'll fall back on # executing generic trajectories. self.mac_retimer = openravepy.RaveCreatePlanner(self.GetEnv(), 'MacRetimer') # Trajectory blending. self.trajectory_module = prpy.rave.load_module(self.GetEnv(), 'Trajectory', self.GetName()) import manipulation2.trajectory manipulation2.trajectory.bind(self.trajectory_module) def CloneBindings(self, parent): Robot.CloneBindings(self, parent) self.mac_retimer = None trajectory_module = prpy.rave.load_module(self.GetEnv(), 'Trajectory', self.GetName()) import manipulation2.trajectory #manipulation2.trajectory.bind(self.trajectory_module) def myFun(x): pass import types class Object(): pass self.trajectory_module = Object() self.trajectory_module.module = trajectory_module self.trajectory_module.blendtrajectory = types.MethodType(manipulation2.trajectory.blendtrajectory, trajectory_module) self.trajectory_module.executeblendedtrajectory = types.MethodType(manipulation2.trajectory.executeblendedtrajectory, trajectory_module) def RetimeTrajectory(self, traj, max_jerk=30.0, synchronize=False, stop_on_stall=True, stop_on_ft=False, force_direction=None, force_magnitude=None, torque=None, **kw_args): """Retime a generic OpenRAVE trajectory into a timed for OWD. First, try to retime the trajectory into a MacTrajectory using OWD's MacRetimer. If MacRetimer is not available, then fall back on the default OpenRAVE retimer. @param traj input trajectory @param max_jerk maximum jerk allowed during retiming @param synchronize enable synchronization between multiple OWD processes @param stop_on_stall cancel the trajectory if stall torques are exceeded @param stop_on_ft cancel the trajectory on force/torque input @param force_direction direction vector used for stop_on_ft @param force_magnitude force threshold for stop_on_ft @param torque torque threshold for stop_on_ft @return timed trajectory """ # Fall back on the standard OpenRAVE retimer if MacTrajectory is not # available. if self.mac_retimer is None: return Robot.RetimeTrajectory(self, traj, **kw_args) # check the number of num_waypoints = traj.GetNumWaypoints() if num_waypoints < 2: logging.warn('RetimeTrajectory received trajectory with less than 2 waypoints. Skipping retime.') return traj # Create a MacTrajectory with timestamps, joint values, velocities, # accelerations, and blend radii. generic_config_spec = traj.GetConfigurationSpecification() generic_angle_group = generic_config_spec.GetGroupFromName('joint_values') path_config_spec = openravepy.ConfigurationSpecification() path_config_spec.AddDeltaTimeGroup() path_config_spec.AddGroup(generic_angle_group.name, generic_angle_group.dof, '') path_config_spec.AddDerivativeGroups(1, False); path_config_spec.AddDerivativeGroups(2, False); path_config_spec.AddGroup('owd_blend_radius', 1, 'next') path_config_spec.ResetGroupOffsets() # Initialize the MacTrajectory. mac_traj = openravepy.RaveCreateTrajectory(self.GetEnv(), 'MacTrajectory') mac_traj.Init(path_config_spec) # Copy the joint values and blend radii into the MacTrajectory. for i in xrange(num_waypoints): waypoint = traj.GetWaypoint(i, path_config_spec) mac_traj.Insert(i, waypoint, path_config_spec) # Serialize the planner parameters. params = [ 'max_jerk', str(max_jerk) ] if stop_on_stall: params += [ 'cancel_on_stall' ] if stop_on_ft: force_threshold = force_magnitude * numpy.array(force_direction) params += [ 'cancel_on_ft' ] params += [ 'force_threshold' ] + map(str, force_threshold) params += [ 'torque_threshold' ] + map(str, torque) if synchronize: params += [ 'synchronize' ] # Retime the MacTrajectory with the MacRetimer. params_str = ' '.join(params) retimer_params = openravepy.Planner.PlannerParameters() retimer_params.SetExtraParameters(params_str) with self: self.mac_retimer.InitPlan(self, retimer_params) self.mac_retimer.PlanPath(mac_traj) return mac_traj def BlendTrajectory(self, traj, maxsmoothiter=None, resolution=None, blend_radius=0.2, blend_attempts=4, blend_step_size=0.05, linearity_threshold=0.1, ignore_collisions=None, **kw_args): """Blend a trajectory for execution in OWD. Blending a trajectory allows the MacRetimer to smoothly accelerate through waypoints. If a blend radius is not specified, it defaults to zero and the controller must come to a stop at each waypoint. This adds the \tt blend_radius group to the input trajectory. @param traj input trajectory @return blended trajectory """ with self: return self.trajectory_module.blendtrajectory(traj=traj, execute=False, maxsmoothiter=maxsmoothiter, resolution=resolution, blend_radius=blend_radius, blend_attempts=blend_attempts, blend_step_size=blend_step_size, linearity_threshold=linearity_threshold, ignore_collisions=ignore_collisions) def
(self, traj, timeout=None, blend=True, retime=True, limit_tolerance=1e-3, synchronize=True, **kw_args): """Execute a trajectory. By default, this function retimes, blends, and adds the stop_on_stall flag to all trajectories. This behavior can be overriden using the \tt blend and \tt retime flags or by passing the appropriate \tt **kw_args arguments to the blender and retimer. By default, this function blocks until trajectory execution finishes. This can be changed by changing the timeout parameter to a maximum number of seconds. Pass a timeout of zero to return instantly. @param traj trajectory to execute @param timeout blocking execution timeout @param blend flag for computing blend radii before execution @param retime flag for retiming the trajectory before execution @return executed_traj including blending and retiming """ # Query the active manipulators based on which DOF indices are # included in the trajectory. active_manipulators = self.GetTrajectoryManipulators(traj) needs_synchronization = synchronize and len(active_manipulators) > 1 sim_flags = [ manipulator.simulated for manipulator in active_manipulators ] if needs_synchronization and any(sim_flags) and not all(sim_flags): raise exceptions.SynchronizationException( 'Unable to execute synchronized trajectory with' ' a mixture of simulated and real controllers.') # Disallow trajectories that include both the base and the arms when # not in simulation mode. We can't guarantee synchronization in this case. def has_affine_dofs(traj): def has_group(cspec, group_name): try: cspec.GetGroupFromName(group_name) return True except openravepy.openrave_exception: return False cspec = traj.GetConfigurationSpecification() return (has_group(cspec, 'affine_transform') or has_group(cspec, 'affine_velocities') or has_group(cspec, 'affine_accelerations')) needs_arms = bool(active_manipulators) needs_base = has_affine_dofs(traj) arms_simulated = all(sim_flags) if needs_base and needs_arms and not arms_simulated and not self.base.simulated: raise NotImplementedError('Joint arm-base trajectories are not supported on hardware.') # Optionally blend and retime the trajectory before execution. Retiming # creates a MacTrajectory that can be directly executed by OWD. if needs_arms: active_indices = util.GetTrajectoryIndices(traj) with self: self.SetActiveDOFs(active_indices) if blend: traj = self.BlendTrajectory(traj) # Check if the first point is not in limits. unclamped_dof_values = self.GetActiveDOFValues() first_waypoint = traj.GetWaypoint(0) cspec = traj.GetConfigurationSpecification() first_dof_values = cspec.ExtractJointValues(first_waypoint, self, active_indices, 0) lower_limits, upper_limits = self.GetActiveDOFLimits() for i in xrange(len(first_dof_values)): if numpy.allclose(first_dof_values[i], lower_limits[i], atol=limit_tolerance) and unclamped_dof_values[i] < lower_limits[i]: first_dof_values[i] = unclamped_dof_values[i] logging.warn('Unclamped DOF %d from lower limit.', active_indices[i]) elif numpy.allclose(first_dof_values[i], upper_limits[i], atol=limit_tolerance) and unclamped_dof_values[i] > upper_limits[i]: first_dof_values[i] = unclamped_dof_values[i] logging.warn('Unclamped DOF %d from upper limit.', active_indices[i]) # Snap the first point to the current configuration. cspec.InsertJointValues(first_waypoint, first_dof_values, self, active_indices, 0) traj.Insert(0, first_waypoint, True) # This must be last because MacTrajectories are immutable. # TODO: This may break if the retimer clamps DOF values to the joint limits. if retime: traj = self.RetimeTrajectory(traj, synchronize=needs_synchronization, **kw_args) if needs_base: # Retime the base trajectory in simulation. if retime:# and self.base.simulated: max_vel = numpy.concatenate((self.GetAffineTranslationMaxVels()[:2], [ self.GetAffineRotationQuatMaxVels() ])) max_accel = 3 * max_vel openravepy.planningutils.RetimeAffineTrajectory(traj, max_vel, max_accel, False) # Can't execute trajectories with less than two waypoints if traj.GetNumWaypoints() < 2: logging.warn('Unable to execute trajectories with less than 2 waypoints. Skipping execution.') return traj # Synchronization implicitly executes on all manipulators. if needs_synchronization: running_manipulators = set(self.manipulators) else: running_manipulators = set(active_manipulators) # Reset old trajectory execution flags for manipulator in active_manipulators: manipulator.ClearTrajectoryStatus() # FIXME: The IdealController attempts to sample the MacTrajectory in simulation. # self.GetController().SetPath(traj) # Wait for trajectory execution to finish. running_controllers = [ manipulator.controller for manipulator in running_manipulators ] if needs_base: running_controllers += [ self.base.controller ] for controller in running_controllers: controller.SetPath(traj) is_done = util.WaitForControllers(running_controllers, timeout=timeout) # Request the controller status from each manipulator. if is_done: with self.GetEnv(): for manipulator in active_manipulators: status = manipulator.GetTrajectoryStatus() if status == 'aborted': raise exceptions.TrajectoryAborted('Trajectory aborted for %s' % manipulator.GetName()) elif status == 'stalled': raise exceptions.TrajectoryStalled('Trajectory stalled for %s' % manipulator.GetName()) if manipulator.simulated: manipulator.controller.Reset() return traj
ExecuteTrajectory
identifier_name
wamrobot.py
#!/usr/bin/env python # Copyright (c) 2013, Carnegie Mellon University # All rights reserved. # Authors: Michael Koval <mkoval@cs.cmu.edu> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # - Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # - Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # - Neither the name of Carnegie Mellon University nor the names of its # contributors may be used to endorse or promote products derived from this # software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. import logging, openravepy, numpy from .. import util from robot import Robot import prpy.rave from .. import exceptions class WAMRobot(Robot): def __init__(self, robot_name=None): Robot.__init__(self, robot_name=robot_name) # Optional MacTrajectory retimer. If this fails, we'll fall back on # executing generic trajectories. self.mac_retimer = openravepy.RaveCreatePlanner(self.GetEnv(), 'MacRetimer') # Trajectory blending. self.trajectory_module = prpy.rave.load_module(self.GetEnv(), 'Trajectory', self.GetName()) import manipulation2.trajectory manipulation2.trajectory.bind(self.trajectory_module) def CloneBindings(self, parent): Robot.CloneBindings(self, parent) self.mac_retimer = None trajectory_module = prpy.rave.load_module(self.GetEnv(), 'Trajectory', self.GetName()) import manipulation2.trajectory #manipulation2.trajectory.bind(self.trajectory_module) def myFun(x): pass import types class Object(): pass self.trajectory_module = Object() self.trajectory_module.module = trajectory_module self.trajectory_module.blendtrajectory = types.MethodType(manipulation2.trajectory.blendtrajectory, trajectory_module) self.trajectory_module.executeblendedtrajectory = types.MethodType(manipulation2.trajectory.executeblendedtrajectory, trajectory_module) def RetimeTrajectory(self, traj, max_jerk=30.0, synchronize=False, stop_on_stall=True, stop_on_ft=False, force_direction=None, force_magnitude=None, torque=None, **kw_args): """Retime a generic OpenRAVE trajectory into a timed for OWD. First, try to retime the trajectory into a MacTrajectory using OWD's MacRetimer. If MacRetimer is not available, then fall back on the default OpenRAVE retimer. @param traj input trajectory @param max_jerk maximum jerk allowed during retiming @param synchronize enable synchronization between multiple OWD processes @param stop_on_stall cancel the trajectory if stall torques are exceeded @param stop_on_ft cancel the trajectory on force/torque input @param force_direction direction vector used for stop_on_ft @param force_magnitude force threshold for stop_on_ft @param torque torque threshold for stop_on_ft @return timed trajectory """ # Fall back on the standard OpenRAVE retimer if MacTrajectory is not # available. if self.mac_retimer is None: return Robot.RetimeTrajectory(self, traj, **kw_args) # check the number of num_waypoints = traj.GetNumWaypoints() if num_waypoints < 2: logging.warn('RetimeTrajectory received trajectory with less than 2 waypoints. Skipping retime.') return traj # Create a MacTrajectory with timestamps, joint values, velocities, # accelerations, and blend radii. generic_config_spec = traj.GetConfigurationSpecification() generic_angle_group = generic_config_spec.GetGroupFromName('joint_values') path_config_spec = openravepy.ConfigurationSpecification() path_config_spec.AddDeltaTimeGroup() path_config_spec.AddGroup(generic_angle_group.name, generic_angle_group.dof, '') path_config_spec.AddDerivativeGroups(1, False); path_config_spec.AddDerivativeGroups(2, False); path_config_spec.AddGroup('owd_blend_radius', 1, 'next') path_config_spec.ResetGroupOffsets() # Initialize the MacTrajectory. mac_traj = openravepy.RaveCreateTrajectory(self.GetEnv(), 'MacTrajectory') mac_traj.Init(path_config_spec) # Copy the joint values and blend radii into the MacTrajectory. for i in xrange(num_waypoints): waypoint = traj.GetWaypoint(i, path_config_spec) mac_traj.Insert(i, waypoint, path_config_spec) # Serialize the planner parameters. params = [ 'max_jerk', str(max_jerk) ] if stop_on_stall: params += [ 'cancel_on_stall' ] if stop_on_ft: force_threshold = force_magnitude * numpy.array(force_direction) params += [ 'cancel_on_ft' ] params += [ 'force_threshold' ] + map(str, force_threshold) params += [ 'torque_threshold' ] + map(str, torque) if synchronize: params += [ 'synchronize' ] # Retime the MacTrajectory with the MacRetimer. params_str = ' '.join(params) retimer_params = openravepy.Planner.PlannerParameters() retimer_params.SetExtraParameters(params_str) with self: self.mac_retimer.InitPlan(self, retimer_params) self.mac_retimer.PlanPath(mac_traj) return mac_traj def BlendTrajectory(self, traj, maxsmoothiter=None, resolution=None, blend_radius=0.2, blend_attempts=4, blend_step_size=0.05, linearity_threshold=0.1, ignore_collisions=None, **kw_args): """Blend a trajectory for execution in OWD. Blending a trajectory allows the MacRetimer to smoothly accelerate through waypoints. If a blend radius is not specified, it defaults to zero and the controller must come to a stop at each waypoint. This adds the \tt blend_radius group to the input trajectory. @param traj input trajectory @return blended trajectory """ with self: return self.trajectory_module.blendtrajectory(traj=traj, execute=False, maxsmoothiter=maxsmoothiter, resolution=resolution, blend_radius=blend_radius, blend_attempts=blend_attempts, blend_step_size=blend_step_size, linearity_threshold=linearity_threshold, ignore_collisions=ignore_collisions) def ExecuteTrajectory(self, traj, timeout=None, blend=True, retime=True, limit_tolerance=1e-3, synchronize=True, **kw_args): """Execute a trajectory. By default, this function retimes, blends, and adds the stop_on_stall flag to all trajectories. This behavior can be overriden using the \tt blend and \tt retime flags or by passing the appropriate \tt **kw_args arguments to the blender and retimer. By default, this function blocks until trajectory execution finishes. This can be changed by changing the timeout parameter to a maximum number of seconds. Pass a timeout of zero to return instantly. @param traj trajectory to execute @param timeout blocking execution timeout @param blend flag for computing blend radii before execution @param retime flag for retiming the trajectory before execution @return executed_traj including blending and retiming """ # Query the active manipulators based on which DOF indices are # included in the trajectory. active_manipulators = self.GetTrajectoryManipulators(traj) needs_synchronization = synchronize and len(active_manipulators) > 1 sim_flags = [ manipulator.simulated for manipulator in active_manipulators ] if needs_synchronization and any(sim_flags) and not all(sim_flags): raise exceptions.SynchronizationException( 'Unable to execute synchronized trajectory with' ' a mixture of simulated and real controllers.') # Disallow trajectories that include both the base and the arms when # not in simulation mode. We can't guarantee synchronization in this case. def has_affine_dofs(traj): def has_group(cspec, group_name):
cspec = traj.GetConfigurationSpecification() return (has_group(cspec, 'affine_transform') or has_group(cspec, 'affine_velocities') or has_group(cspec, 'affine_accelerations')) needs_arms = bool(active_manipulators) needs_base = has_affine_dofs(traj) arms_simulated = all(sim_flags) if needs_base and needs_arms and not arms_simulated and not self.base.simulated: raise NotImplementedError('Joint arm-base trajectories are not supported on hardware.') # Optionally blend and retime the trajectory before execution. Retiming # creates a MacTrajectory that can be directly executed by OWD. if needs_arms: active_indices = util.GetTrajectoryIndices(traj) with self: self.SetActiveDOFs(active_indices) if blend: traj = self.BlendTrajectory(traj) # Check if the first point is not in limits. unclamped_dof_values = self.GetActiveDOFValues() first_waypoint = traj.GetWaypoint(0) cspec = traj.GetConfigurationSpecification() first_dof_values = cspec.ExtractJointValues(first_waypoint, self, active_indices, 0) lower_limits, upper_limits = self.GetActiveDOFLimits() for i in xrange(len(first_dof_values)): if numpy.allclose(first_dof_values[i], lower_limits[i], atol=limit_tolerance) and unclamped_dof_values[i] < lower_limits[i]: first_dof_values[i] = unclamped_dof_values[i] logging.warn('Unclamped DOF %d from lower limit.', active_indices[i]) elif numpy.allclose(first_dof_values[i], upper_limits[i], atol=limit_tolerance) and unclamped_dof_values[i] > upper_limits[i]: first_dof_values[i] = unclamped_dof_values[i] logging.warn('Unclamped DOF %d from upper limit.', active_indices[i]) # Snap the first point to the current configuration. cspec.InsertJointValues(first_waypoint, first_dof_values, self, active_indices, 0) traj.Insert(0, first_waypoint, True) # This must be last because MacTrajectories are immutable. # TODO: This may break if the retimer clamps DOF values to the joint limits. if retime: traj = self.RetimeTrajectory(traj, synchronize=needs_synchronization, **kw_args) if needs_base: # Retime the base trajectory in simulation. if retime:# and self.base.simulated: max_vel = numpy.concatenate((self.GetAffineTranslationMaxVels()[:2], [ self.GetAffineRotationQuatMaxVels() ])) max_accel = 3 * max_vel openravepy.planningutils.RetimeAffineTrajectory(traj, max_vel, max_accel, False) # Can't execute trajectories with less than two waypoints if traj.GetNumWaypoints() < 2: logging.warn('Unable to execute trajectories with less than 2 waypoints. Skipping execution.') return traj # Synchronization implicitly executes on all manipulators. if needs_synchronization: running_manipulators = set(self.manipulators) else: running_manipulators = set(active_manipulators) # Reset old trajectory execution flags for manipulator in active_manipulators: manipulator.ClearTrajectoryStatus() # FIXME: The IdealController attempts to sample the MacTrajectory in simulation. # self.GetController().SetPath(traj) # Wait for trajectory execution to finish. running_controllers = [ manipulator.controller for manipulator in running_manipulators ] if needs_base: running_controllers += [ self.base.controller ] for controller in running_controllers: controller.SetPath(traj) is_done = util.WaitForControllers(running_controllers, timeout=timeout) # Request the controller status from each manipulator. if is_done: with self.GetEnv(): for manipulator in active_manipulators: status = manipulator.GetTrajectoryStatus() if status == 'aborted': raise exceptions.TrajectoryAborted('Trajectory aborted for %s' % manipulator.GetName()) elif status == 'stalled': raise exceptions.TrajectoryStalled('Trajectory stalled for %s' % manipulator.GetName()) if manipulator.simulated: manipulator.controller.Reset() return traj
try: cspec.GetGroupFromName(group_name) return True except openravepy.openrave_exception: return False
identifier_body
wamrobot.py
#!/usr/bin/env python # Copyright (c) 2013, Carnegie Mellon University # All rights reserved. # Authors: Michael Koval <mkoval@cs.cmu.edu> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # - Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # - Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # - Neither the name of Carnegie Mellon University nor the names of its # contributors may be used to endorse or promote products derived from this # software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. import logging, openravepy, numpy from .. import util from robot import Robot import prpy.rave from .. import exceptions class WAMRobot(Robot): def __init__(self, robot_name=None): Robot.__init__(self, robot_name=robot_name) # Optional MacTrajectory retimer. If this fails, we'll fall back on # executing generic trajectories. self.mac_retimer = openravepy.RaveCreatePlanner(self.GetEnv(), 'MacRetimer') # Trajectory blending. self.trajectory_module = prpy.rave.load_module(self.GetEnv(), 'Trajectory', self.GetName()) import manipulation2.trajectory manipulation2.trajectory.bind(self.trajectory_module) def CloneBindings(self, parent): Robot.CloneBindings(self, parent) self.mac_retimer = None trajectory_module = prpy.rave.load_module(self.GetEnv(), 'Trajectory', self.GetName()) import manipulation2.trajectory #manipulation2.trajectory.bind(self.trajectory_module) def myFun(x): pass import types class Object(): pass self.trajectory_module = Object() self.trajectory_module.module = trajectory_module self.trajectory_module.blendtrajectory = types.MethodType(manipulation2.trajectory.blendtrajectory, trajectory_module) self.trajectory_module.executeblendedtrajectory = types.MethodType(manipulation2.trajectory.executeblendedtrajectory, trajectory_module) def RetimeTrajectory(self, traj, max_jerk=30.0, synchronize=False, stop_on_stall=True, stop_on_ft=False, force_direction=None, force_magnitude=None, torque=None, **kw_args): """Retime a generic OpenRAVE trajectory into a timed for OWD. First, try to retime the trajectory into a MacTrajectory using OWD's MacRetimer. If MacRetimer is not available, then fall back on the default OpenRAVE retimer. @param traj input trajectory @param max_jerk maximum jerk allowed during retiming @param synchronize enable synchronization between multiple OWD processes @param stop_on_stall cancel the trajectory if stall torques are exceeded @param stop_on_ft cancel the trajectory on force/torque input @param force_direction direction vector used for stop_on_ft @param force_magnitude force threshold for stop_on_ft @param torque torque threshold for stop_on_ft @return timed trajectory """ # Fall back on the standard OpenRAVE retimer if MacTrajectory is not # available. if self.mac_retimer is None: return Robot.RetimeTrajectory(self, traj, **kw_args) # check the number of num_waypoints = traj.GetNumWaypoints() if num_waypoints < 2: logging.warn('RetimeTrajectory received trajectory with less than 2 waypoints. Skipping retime.') return traj # Create a MacTrajectory with timestamps, joint values, velocities, # accelerations, and blend radii. generic_config_spec = traj.GetConfigurationSpecification() generic_angle_group = generic_config_spec.GetGroupFromName('joint_values') path_config_spec = openravepy.ConfigurationSpecification() path_config_spec.AddDeltaTimeGroup() path_config_spec.AddGroup(generic_angle_group.name, generic_angle_group.dof, '') path_config_spec.AddDerivativeGroups(1, False); path_config_spec.AddDerivativeGroups(2, False); path_config_spec.AddGroup('owd_blend_radius', 1, 'next') path_config_spec.ResetGroupOffsets() # Initialize the MacTrajectory. mac_traj = openravepy.RaveCreateTrajectory(self.GetEnv(), 'MacTrajectory') mac_traj.Init(path_config_spec) # Copy the joint values and blend radii into the MacTrajectory. for i in xrange(num_waypoints): waypoint = traj.GetWaypoint(i, path_config_spec) mac_traj.Insert(i, waypoint, path_config_spec) # Serialize the planner parameters. params = [ 'max_jerk', str(max_jerk) ] if stop_on_stall: params += [ 'cancel_on_stall' ] if stop_on_ft: force_threshold = force_magnitude * numpy.array(force_direction) params += [ 'cancel_on_ft' ] params += [ 'force_threshold' ] + map(str, force_threshold) params += [ 'torque_threshold' ] + map(str, torque) if synchronize: params += [ 'synchronize' ] # Retime the MacTrajectory with the MacRetimer. params_str = ' '.join(params) retimer_params = openravepy.Planner.PlannerParameters() retimer_params.SetExtraParameters(params_str) with self: self.mac_retimer.InitPlan(self, retimer_params) self.mac_retimer.PlanPath(mac_traj) return mac_traj def BlendTrajectory(self, traj, maxsmoothiter=None, resolution=None, blend_radius=0.2, blend_attempts=4, blend_step_size=0.05, linearity_threshold=0.1, ignore_collisions=None, **kw_args): """Blend a trajectory for execution in OWD. Blending a trajectory allows the MacRetimer to smoothly accelerate through waypoints. If a blend radius is not specified, it defaults to zero and the controller must come to a stop at each waypoint. This adds the \tt blend_radius group to the input trajectory. @param traj input trajectory @return blended trajectory """ with self: return self.trajectory_module.blendtrajectory(traj=traj, execute=False, maxsmoothiter=maxsmoothiter, resolution=resolution, blend_radius=blend_radius, blend_attempts=blend_attempts, blend_step_size=blend_step_size, linearity_threshold=linearity_threshold, ignore_collisions=ignore_collisions) def ExecuteTrajectory(self, traj, timeout=None, blend=True, retime=True, limit_tolerance=1e-3, synchronize=True, **kw_args): """Execute a trajectory. By default, this function retimes, blends, and adds the stop_on_stall flag to all trajectories. This behavior can be overriden using the \tt blend and \tt retime flags or by passing the appropriate \tt **kw_args arguments to the blender and retimer. By default, this function blocks until trajectory execution finishes. This can be changed by changing the timeout parameter to a maximum number of seconds. Pass a timeout of zero to return instantly. @param traj trajectory to execute @param timeout blocking execution timeout @param blend flag for computing blend radii before execution @param retime flag for retiming the trajectory before execution @return executed_traj including blending and retiming """ # Query the active manipulators based on which DOF indices are # included in the trajectory. active_manipulators = self.GetTrajectoryManipulators(traj) needs_synchronization = synchronize and len(active_manipulators) > 1 sim_flags = [ manipulator.simulated for manipulator in active_manipulators ] if needs_synchronization and any(sim_flags) and not all(sim_flags): raise exceptions.SynchronizationException( 'Unable to execute synchronized trajectory with' ' a mixture of simulated and real controllers.') # Disallow trajectories that include both the base and the arms when # not in simulation mode. We can't guarantee synchronization in this case. def has_affine_dofs(traj): def has_group(cspec, group_name): try: cspec.GetGroupFromName(group_name) return True except openravepy.openrave_exception: return False cspec = traj.GetConfigurationSpecification() return (has_group(cspec, 'affine_transform') or has_group(cspec, 'affine_velocities') or has_group(cspec, 'affine_accelerations')) needs_arms = bool(active_manipulators) needs_base = has_affine_dofs(traj) arms_simulated = all(sim_flags) if needs_base and needs_arms and not arms_simulated and not self.base.simulated: raise NotImplementedError('Joint arm-base trajectories are not supported on hardware.') # Optionally blend and retime the trajectory before execution. Retiming # creates a MacTrajectory that can be directly executed by OWD. if needs_arms: active_indices = util.GetTrajectoryIndices(traj) with self: self.SetActiveDOFs(active_indices) if blend: traj = self.BlendTrajectory(traj) # Check if the first point is not in limits. unclamped_dof_values = self.GetActiveDOFValues() first_waypoint = traj.GetWaypoint(0) cspec = traj.GetConfigurationSpecification() first_dof_values = cspec.ExtractJointValues(first_waypoint, self, active_indices, 0) lower_limits, upper_limits = self.GetActiveDOFLimits() for i in xrange(len(first_dof_values)): if numpy.allclose(first_dof_values[i], lower_limits[i], atol=limit_tolerance) and unclamped_dof_values[i] < lower_limits[i]: first_dof_values[i] = unclamped_dof_values[i] logging.warn('Unclamped DOF %d from lower limit.', active_indices[i]) elif numpy.allclose(first_dof_values[i], upper_limits[i], atol=limit_tolerance) and unclamped_dof_values[i] > upper_limits[i]: first_dof_values[i] = unclamped_dof_values[i] logging.warn('Unclamped DOF %d from upper limit.', active_indices[i]) # Snap the first point to the current configuration. cspec.InsertJointValues(first_waypoint, first_dof_values, self, active_indices, 0) traj.Insert(0, first_waypoint, True) # This must be last because MacTrajectories are immutable. # TODO: This may break if the retimer clamps DOF values to the joint limits. if retime: traj = self.RetimeTrajectory(traj, synchronize=needs_synchronization, **kw_args) if needs_base: # Retime the base trajectory in simulation. if retime:# and self.base.simulated: max_vel = numpy.concatenate((self.GetAffineTranslationMaxVels()[:2], [ self.GetAffineRotationQuatMaxVels() ])) max_accel = 3 * max_vel openravepy.planningutils.RetimeAffineTrajectory(traj, max_vel, max_accel, False) # Can't execute trajectories with less than two waypoints if traj.GetNumWaypoints() < 2: logging.warn('Unable to execute trajectories with less than 2 waypoints. Skipping execution.') return traj # Synchronization implicitly executes on all manipulators. if needs_synchronization: running_manipulators = set(self.manipulators) else: running_manipulators = set(active_manipulators) # Reset old trajectory execution flags for manipulator in active_manipulators: manipulator.ClearTrajectoryStatus() # FIXME: The IdealController attempts to sample the MacTrajectory in simulation. # self.GetController().SetPath(traj) # Wait for trajectory execution to finish. running_controllers = [ manipulator.controller for manipulator in running_manipulators ] if needs_base: running_controllers += [ self.base.controller ] for controller in running_controllers: controller.SetPath(traj) is_done = util.WaitForControllers(running_controllers, timeout=timeout) # Request the controller status from each manipulator. if is_done: with self.GetEnv(): for manipulator in active_manipulators: status = manipulator.GetTrajectoryStatus() if status == 'aborted': raise exceptions.TrajectoryAborted('Trajectory aborted for %s' % manipulator.GetName()) elif status == 'stalled': raise exceptions.TrajectoryStalled('Trajectory stalled for %s' % manipulator.GetName()) if manipulator.simulated:
return traj
manipulator.controller.Reset()
conditional_block
VerificationCtrl.js
'use strict'; angular.module('taurus.verificationModule') .controller('VerificationCtrl', ["$state", "$mdExpansionPanel", "verificationService", "$scope", "toastMessagesService", "Upload", "$timeout", "$http", function($state, $mdExpansionPanel, verificationService, $scope, toastMessagesService, Upload, $timeout, $http) { 'use strict'; var vm = this; vm.checkVerifiedStatus = checkVerifiedStatus; // vm.clearOtherInput = clearOtherInput; vm.getVerification = getVerification; vm.goToTrade = goToTrade; vm.showUploadSuccess = showUploadSuccess; vm.submitVerificationOne = submitVerificationOne; vm.submitVerificationTwo = submitVerificationTwo; vm.minDob; vm.verificationOneForm; vm.photoForm; vm.billUtilityForm; vm.verificationTwoForm; vm.getVerificationData; vm.verificationLevelTwo = false; vm.verificationOneProgressBar = true; vm.verificationTwoProgressBar = true; vm.triggerFileBrowser = triggerFileBrowser; // Max birth date (min age) to register for taurus var today = new Date(); vm.maxDob = new Date(today.getFullYear() - 18, today.getMonth(), today.getDate()); vm.verificationOne = { firstName: "", lastName: "", dob: "", address: "", city: "", province: "", country: "", postalCode: "", photoId: "", utilityBill: "", phone: "", occupation: "", }; vm.allowedCountries = [ 'Afghanistan', 'Åland Islands', 'Albania', 'Algeria', 'Andorra', 'Angola', 'Anguilla', 'Antarctica', 'Antigua and Barbuda', 'Argentina', 'Armenia', 'Aruba', 'Australia', 'Austria', 'Azerbaijan', 'Bahamas (the)', 'Bahrain', 'Bangladesh', 'Barbados', 'Belarus', 'Belgium', 'Belize', 'Benin', 'Bermuda', 'Bhutan', 'Bolivia (Plurinational State of)', 'Bonaire, Sint Eustatius and Saba', 'Bosnia and Herzegovina', 'Botswana', 'Bouvet Island', 'Brazil', 'British Indian Ocean Territory (the)', 'Brunei Darussalam', 'Bulgaria', 'Burkina Faso', 'Burundi', 'Cabo Verde', 'Cambodia', 'Cameroon', 'Canada', 'Cayman Islands (the)', 'Central African Republic (the)', 'Chad', 'Chile', 'China', 'Christmas Island', 'Cocos (Keeling) Islands (the)', 'Colombia', 'Comoros (the)', 'Congo (the)', 'Congo (the Democratic Republic of the)', 'Cook Islands (the)', 'Costa Rica', 'Côte d\'Ivoire', 'Croatia', 'Cuba', 'Curaçao', 'Cyprus', 'Czech Republic (the)', 'Denmark', 'Djibouti', 'Dominica', 'Dominican Republic (the)', 'Ecuador', 'Egypt', 'El Salvador', 'Equatorial Guinea', 'Eritrea', 'Estonia', 'Ethiopia', 'Falkland Islands (the) [Malvinas]', 'Faroe Islands (the)', 'Fiji', 'Finland', 'France', 'French Guiana', 'French Polynesia', 'French Southern Territories (the)', 'Gabon', 'Gambia (the)', 'Georgia', 'Ghana', 'Gibraltar', 'Greece', 'Greenland', 'Grenada', 'Guadeloupe', 'Guatemala', 'Guernsey', 'Guinea', 'Guinea-Bissau', 'Guyana', 'Haiti', 'Heard Island and McDonald Islands', 'Holy See (the)', 'Honduras', 'Hong Kong', 'Hungary', 'Iceland', 'India', 'Indonesia', 'Ireland', 'Isle of Man', 'Israel', 'Italy', 'Jamaica', 'Japan', 'Jersey', 'Jordan', 'Kazakhstan', 'Kenya', 'Kiribati', 'Korea (the Democratic People\'s Republic of)', 'Korea (the Republic of)', 'Kuwait', 'Kyrgyzstan', 'Lao People\'s Democratic Republic (the)', 'Latvia', 'Lebanon', 'Lesotho', 'Liberia', 'Libya', 'Liechtenstein', 'Lithuania', 'Luxembourg', 'Macao', 'Macedonia (the former Yugoslav Republic of)', 'Madagascar', 'Malawi', 'Malaysia', 'Maldives', 'Mali', 'Malta', 'Marshall Islands (the)', 'Martinique', 'Mauritania', 'Mauritius', 'Mayotte', 'Mexico', 'Micronesia (Federated States of)', 'Moldova (the Republic of)', 'Monaco', 'Mongolia', 'Montenegro', 'Montserrat', 'Morocco', 'Mozambique', 'Myanmar', 'Namibia', 'Nauru', 'Nepal', 'Netherlands (the)', 'New Caledonia', 'New Zealand', 'Nicaragua', 'Niger (the)', 'Nigeria', 'Niue', 'Norfolk Island', 'Norway', 'Oman', 'Pakistan', 'Palau', 'Palestine, State of', 'Panama', 'Papua New Guinea', 'Paraguay', 'Peru', 'Philippines (the)', 'Pitcairn', 'Poland', 'Portugal', 'Qatar', 'Réunion', 'Romania', 'Russian Federation (the)', 'Rwanda', 'Saint Barthélemy', 'Saint Helena, Ascension and Tristan da Cunha', 'Saint Kitts and Nevis', 'Saint Lucia', 'Saint Martin (French part)', 'Saint Pierre and Miquelon', 'Saint Vincent and the Grenadines', 'Samoa', 'San Marino', 'Sao Tome and Principe', 'Saudi Arabia', 'Senegal', 'Serbia', 'Seychelles', 'Sierra Leone', 'Singapore', 'Sint Maarten (Dutch part)', 'Slovakia', 'Slovenia', 'Solomon Islands', 'Somalia', 'South Africa', 'South Georgia and the South Sandwich Islands', 'South Sudan ', 'Spain', 'Sri Lanka', 'Sudan (the)', 'Suriname', 'Svalbard and Jan Mayen', 'Swaziland', 'Sweden', 'Switzerland', 'Taiwan (Province of China)', 'Tajikistan', 'Tanzania, United Republic of', 'Thailand', 'Timor-Leste', 'Togo', 'Tokelau', 'Tonga', 'Trinidad and Tobago', 'Tunisia', 'Turkey', 'Turkmenistan', 'Turks and Caicos Islands (the)', 'Tuvalu', 'Uganda', 'Ukraine', 'United Arab Emirates (the)', 'United Kingdom of Great Britain and Northern Ireland (the)', 'Uruguay', 'Uzbekistan', 'Vanuatu', 'Venezuela (Bolivarian Republic of)', 'Vietnam', 'Virgin Islands (British)', 'Wallis and Futuna', 'Western Sahara', 'Yemen', 'Zambia', 'Zimbabwe' ]; function triggerFileBrowser(inputId) { $('#' + inputId).trigger('click'); } vm.verificationTwo = { verificationTwoDocument: "" }; function goToTrade() { $state.go('trade'); } vm.validateVerificationForm = validateVerificationForm; function validateVerificationForm(data) { console.log(data); console.log(data.$valid); return data.$valid; } // If the form input error object is empty (file input is valid) // it will show a green checkmark. Otherwise hides the checkmark function showUploadSuccess(formInputErrorObject, elementIdToAdjust) { if (jQuery.isEmptyObject(formInputErrorObject)) { $('#' + elementIdToAdjust).parent().children('md-icon').css('opacity', '1'); // $('#utility-bill-input').parent().children().first().css('opacity', '1'); } else { $('#' + elementIdToAdjust).parent().children('md-icon').css('opacity', '0'); } } // VerificationTwo has optional input: Void Cheque or Bank Letter/Statement. // When either upload button is clicked, this function clears the model and hides the checkmark, if visible // So that both uploads are not used // function clearOtherInput() { // vm.verificationTwo = { // bankLetter: "", // voidCheque: "" // }; // $('#bank-letter-btn').parent().children('md-icon').css('opacity', '0'); // $('#void-cheque-btn').parent().children('md-icon').css('opacity', '0'); // } // function trade(data) { // $state.go(data); // }; var verificationFailureToast = function(code) { switch (code) { case 1161: toastMessagesService.failureToast('First name missing'); break; case 1162: toastMessagesService.failureToast('Last name missing'); break; case 1163: toastMessagesService.failureToast('Date of birth missing'); break; case 1164: toastMessagesService.failureToast('Address Missing'); break; case 1165: toastMessagesService.failureToast('City Missing'); break; case 1166: toastMessagesService.failureToast('Province/state Missing'); break; case 1167: toastMessagesService.failureToast('Country Missing'); break; case 1168: toastMessagesService.failureToast('Postal code/ZIP Missing'); break; case 1169: toastMessagesService.failureToast('Occupation Missing'); break; case 1171: toastMessagesService.failureToast('Phone Missing'); break; default: console.log(code); toastMessagesService.failureToast('Verification error'); }; } /*******************Verification Level 1***********************/ function getVerification() { var data = {'test': 'true'}; verificationService.getVerification(data,function successBlock(data) { vm.getVerificationData = data; // console.log(data.verification_level) if(data.verification_level == 1) { }; }, function failureBlock(error) { console.log(error); } ); } vm.getLevelOneDetails = getLevelOneDetails; function getLevelOneDetails() { verificationService.getLevelOneDetails(function successBlock(data) { console.log(data); vm.verificationOne = { firstName: data.firstName, lastName: data.lastName, dob: new Date(data.birthDate), address: data.address, city: data.city, province: data.state, country: data.country, postalCode: data.zip, phone: data.phone, occupation: data.occupation, }; }, function failureBlock(error) { console.log(error); }); } $(document).ready(function () { getVerification(); }); getLevelOneDetails(); function check
if(vm.getVerificationData.verification_level == 1) { vm.verificationLevelTwo = true; } else { vm.verificationLevelTwo = true; //toastMessagesService.failureToast('You must be an approved, verified level one user before you can access the verification level two form.'); } } /************************************* Upload + Submit ********************************/ var verificationOneUploadSuccessCount = 0; var verificationTwoUploadSuccessCount = 0; var verificationUploadSuccess = function () { if (verificationOneUploadSuccessCount === 2) { toastMessagesService.successToast('Verification Level One data and files submitted successfully'); vm.verificationOneProgressBar = true; } else if (verificationTwoUploadSuccessCount === 1) { toastMessagesService.successToast('Verification Level Two submitted successfully'); vm.verificationTwoProgressBar = true; }; }; var uploadSingleFile = function (formId, inputId, verificationTwo) { $('#' + inputId).attr('name', 'uploaded_files'); var formData = new FormData($('form#'+formId)[0]); var action = $('form#'+formId).attr("action"); $.ajax({ url: action, type: 'POST', data: formData, // async: false, success: function (data) { console.log(data); verificationOneUploadSuccessCount++; verificationTwo ? verificationTwoUploadSuccessCount++ : ""; verificationUploadSuccess(); }, error: function (error) { console.log(error); toastMessagesService.failureToast('Verification upload failure'); vm.verificationOneProgressBar = true; vm.verificationTwoProgressBar = true; }, cache: false, contentType: false, processData: false }); } function submitVerificationOne(verificationOneData) { console.log(verificationOneData); verificationOneUploadSuccessCount = 0; verificationTwoUploadSuccessCount = 0; vm.verificationOneForm.$setSubmitted(); vm.photoForm.photoId.$dirty = true; vm.billUtilityForm.utilityBill.$dirty = true; if (vm.verificationOneForm.$valid && vm.photoForm.$valid && vm.billUtilityForm.$valid) { vm.verificationOneProgressBar = false; console.log(verificationOneData); var verificationOneSubmitData = { first_name: verificationOneData.firstName, last_name: verificationOneData.lastName, dob: verificationOneData.dob, address: verificationOneData.address, city: verificationOneData.city, state: verificationOneData.province, country: verificationOneData.country, zip: verificationOneData.postalCode, occupation: verificationOneData.occupation, phone: verificationOneData.phone, }; verificationService.verification_first(verificationOneSubmitData, function successBlock(data) { console.log('success'); // toastMessagesService.successToast('Verification information submitted.'); if (data.code == 1180) { console.log(data); $("form#photoForm").attr("action", data.photo_upload_url) uploadSingleFile("photoForm", "photo-id-input"); $("form#billUtilityForm").attr("action", data.utility_bill_url); uploadSingleFile("billUtilityForm", "utility-bill-input"); }; // vm.verificationOneProgressBar = true; }, function failureBlock(error) { console.log(error); verificationFailureToast(error.data.code); vm.verificationOneProgressBar = true; }); }; } function submitVerificationTwo(verificationTwoData) { verificationOneUploadSuccessCount = 0; verificationTwoUploadSuccessCount = 0; console.log(verificationTwoData); vm.verificationTwoForm.verificationTwoDocument.$dirty = true; vm.verificationTwoProgressBar = false; var dataToSend = {'test': 'true'}; verificationService.getVerification(dataToSend, function successBlock(data) { // vm.getVerificationData = data; console.log(data); // console.log("level: " + data.verification_level); // console.log("bank_letter_upload:" + data.bank_letter_upload); // if(data.verification_level == 1) { $("form#verificationTwoForm").attr("action", data.bank_letter_upload); uploadSingleFile("verificationTwoForm", "verification-two-document-input", true); // }; // vm.verificationTwoProgressBar = true; }, function failureBlock(error) { console.log(error); vm.verificationTwoProgressBar = true; }) /* verificationService.getVerification if (verificationTwoData.bankLetter) { $("form#verificationTwoForm").attr("action",data.bank_letter_upload); console.log("Bank letter"); dataToSend = verificationTwoData.bankLetter } else if (verificationTwoData.voidCheque) { console.log("Cheque"); dataToSend = verificationTwoData.voidCheque; }; if (vm.getVerificationData.verification_level == 0 || vm.getVerificationData.verification_level == 1) { uploadSingleFile(dataToSend, vm.getVerificationData.bank_letter_upload); }; */ }; //************************************************************* $scope.init = function() { $scope.user_id = localStorage.getItem('client'); var verification_level = localStorage.getItem('verification_level'); if(verification_level == 0) { $mdExpansionPanel().waitFor('verificationFirst').then(function (instance) { instance.expand(); }); } else { if(verification_level==1) { $mdExpansionPanel().waitFor('verificationSecond').then(function (instance) { instance.expand(); }); vm.getVerification(); } else { if(verification_level>2){ $('.trade1').show(); $('.trade2').show(); }else{ $('.rightIcon1').show(); $('.rightIcon2').show(); } } }; }; $scope.init(); //bank account $scope.choices = [{id: 'choice1'}]; $scope.addNewChoice = function() { var newItemNo = $scope.choices.length+1; $scope.choices.push({'id':'choice'+newItemNo}); }; $scope.removeChoice = function() { var lastItem = $scope.choices.length-1; $scope.choices.splice(lastItem); }; }]); //controller
VerifiedStatus() {
identifier_name
VerificationCtrl.js
'use strict'; angular.module('taurus.verificationModule') .controller('VerificationCtrl', ["$state", "$mdExpansionPanel", "verificationService", "$scope", "toastMessagesService", "Upload", "$timeout", "$http", function($state, $mdExpansionPanel, verificationService, $scope, toastMessagesService, Upload, $timeout, $http) { 'use strict'; var vm = this; vm.checkVerifiedStatus = checkVerifiedStatus; // vm.clearOtherInput = clearOtherInput; vm.getVerification = getVerification; vm.goToTrade = goToTrade; vm.showUploadSuccess = showUploadSuccess; vm.submitVerificationOne = submitVerificationOne; vm.submitVerificationTwo = submitVerificationTwo; vm.minDob; vm.verificationOneForm; vm.photoForm; vm.billUtilityForm; vm.verificationTwoForm; vm.getVerificationData; vm.verificationLevelTwo = false; vm.verificationOneProgressBar = true; vm.verificationTwoProgressBar = true; vm.triggerFileBrowser = triggerFileBrowser; // Max birth date (min age) to register for taurus var today = new Date(); vm.maxDob = new Date(today.getFullYear() - 18, today.getMonth(), today.getDate()); vm.verificationOne = { firstName: "", lastName: "", dob: "", address: "", city: "", province: "", country: "", postalCode: "", photoId: "", utilityBill: "", phone: "", occupation: "", }; vm.allowedCountries = [ 'Afghanistan', 'Åland Islands', 'Albania', 'Algeria', 'Andorra', 'Angola', 'Anguilla', 'Antarctica', 'Antigua and Barbuda', 'Argentina', 'Armenia', 'Aruba', 'Australia', 'Austria', 'Azerbaijan', 'Bahamas (the)', 'Bahrain', 'Bangladesh', 'Barbados', 'Belarus', 'Belgium', 'Belize', 'Benin', 'Bermuda', 'Bhutan', 'Bolivia (Plurinational State of)', 'Bonaire, Sint Eustatius and Saba', 'Bosnia and Herzegovina', 'Botswana', 'Bouvet Island', 'Brazil', 'British Indian Ocean Territory (the)', 'Brunei Darussalam', 'Bulgaria', 'Burkina Faso', 'Burundi', 'Cabo Verde', 'Cambodia', 'Cameroon', 'Canada', 'Cayman Islands (the)', 'Central African Republic (the)', 'Chad', 'Chile', 'China', 'Christmas Island', 'Cocos (Keeling) Islands (the)', 'Colombia', 'Comoros (the)', 'Congo (the)', 'Congo (the Democratic Republic of the)', 'Cook Islands (the)', 'Costa Rica', 'Côte d\'Ivoire', 'Croatia', 'Cuba', 'Curaçao', 'Cyprus', 'Czech Republic (the)', 'Denmark', 'Djibouti', 'Dominica', 'Dominican Republic (the)', 'Ecuador', 'Egypt', 'El Salvador', 'Equatorial Guinea', 'Eritrea', 'Estonia', 'Ethiopia', 'Falkland Islands (the) [Malvinas]', 'Faroe Islands (the)', 'Fiji', 'Finland', 'France', 'French Guiana', 'French Polynesia', 'French Southern Territories (the)', 'Gabon', 'Gambia (the)', 'Georgia', 'Ghana', 'Gibraltar', 'Greece', 'Greenland', 'Grenada', 'Guadeloupe', 'Guatemala', 'Guernsey', 'Guinea', 'Guinea-Bissau', 'Guyana', 'Haiti', 'Heard Island and McDonald Islands', 'Holy See (the)', 'Honduras', 'Hong Kong', 'Hungary', 'Iceland', 'India', 'Indonesia', 'Ireland', 'Isle of Man', 'Israel', 'Italy', 'Jamaica', 'Japan', 'Jersey', 'Jordan', 'Kazakhstan', 'Kenya', 'Kiribati', 'Korea (the Democratic People\'s Republic of)', 'Korea (the Republic of)', 'Kuwait', 'Kyrgyzstan', 'Lao People\'s Democratic Republic (the)', 'Latvia', 'Lebanon', 'Lesotho', 'Liberia', 'Libya', 'Liechtenstein', 'Lithuania', 'Luxembourg', 'Macao', 'Macedonia (the former Yugoslav Republic of)', 'Madagascar', 'Malawi', 'Malaysia', 'Maldives', 'Mali', 'Malta', 'Marshall Islands (the)', 'Martinique', 'Mauritania', 'Mauritius', 'Mayotte', 'Mexico', 'Micronesia (Federated States of)', 'Moldova (the Republic of)', 'Monaco', 'Mongolia', 'Montenegro', 'Montserrat', 'Morocco', 'Mozambique', 'Myanmar', 'Namibia', 'Nauru', 'Nepal', 'Netherlands (the)', 'New Caledonia', 'New Zealand', 'Nicaragua', 'Niger (the)', 'Nigeria', 'Niue', 'Norfolk Island', 'Norway', 'Oman', 'Pakistan', 'Palau', 'Palestine, State of', 'Panama', 'Papua New Guinea', 'Paraguay', 'Peru', 'Philippines (the)', 'Pitcairn', 'Poland', 'Portugal', 'Qatar', 'Réunion', 'Romania', 'Russian Federation (the)', 'Rwanda', 'Saint Barthélemy', 'Saint Helena, Ascension and Tristan da Cunha', 'Saint Kitts and Nevis', 'Saint Lucia', 'Saint Martin (French part)', 'Saint Pierre and Miquelon', 'Saint Vincent and the Grenadines', 'Samoa', 'San Marino', 'Sao Tome and Principe', 'Saudi Arabia', 'Senegal', 'Serbia', 'Seychelles', 'Sierra Leone', 'Singapore', 'Sint Maarten (Dutch part)', 'Slovakia', 'Slovenia', 'Solomon Islands', 'Somalia', 'South Africa', 'South Georgia and the South Sandwich Islands', 'South Sudan ', 'Spain', 'Sri Lanka', 'Sudan (the)', 'Suriname', 'Svalbard and Jan Mayen', 'Swaziland', 'Sweden', 'Switzerland', 'Taiwan (Province of China)', 'Tajikistan', 'Tanzania, United Republic of', 'Thailand', 'Timor-Leste', 'Togo', 'Tokelau', 'Tonga', 'Trinidad and Tobago', 'Tunisia', 'Turkey', 'Turkmenistan', 'Turks and Caicos Islands (the)', 'Tuvalu', 'Uganda', 'Ukraine', 'United Arab Emirates (the)', 'United Kingdom of Great Britain and Northern Ireland (the)', 'Uruguay', 'Uzbekistan', 'Vanuatu', 'Venezuela (Bolivarian Republic of)', 'Vietnam', 'Virgin Islands (British)', 'Wallis and Futuna', 'Western Sahara', 'Yemen', 'Zambia', 'Zimbabwe' ]; function triggerFileBrowser(inputId) { $('#' + inputId).trigger('click'); } vm.verificationTwo = { verificationTwoDocument: "" }; function goToTrade() { $state.go('trade'); } vm.validateVerificationForm = validateVerificationForm; function validateVerificationForm(data) { console.log(data); console.log(data.$valid); return data.$valid; } // If the form input error object is empty (file input is valid) // it will show a green checkmark. Otherwise hides the checkmark function showUploadSuccess(formInputErrorObject, elementIdToAdjust) { if (jQuery.isEmptyObject(formInputErrorObject)) { $('#' + elementIdToAdjust).parent().children('md-icon').css('opacity', '1'); // $('#utility-bill-input').parent().children().first().css('opacity', '1'); } else { $('#' + elementIdToAdjust).parent().children('md-icon').css('opacity', '0'); } } // VerificationTwo has optional input: Void Cheque or Bank Letter/Statement. // When either upload button is clicked, this function clears the model and hides the checkmark, if visible // So that both uploads are not used // function clearOtherInput() { // vm.verificationTwo = { // bankLetter: "", // voidCheque: "" // }; // $('#bank-letter-btn').parent().children('md-icon').css('opacity', '0'); // $('#void-cheque-btn').parent().children('md-icon').css('opacity', '0'); // } // function trade(data) { // $state.go(data); // }; var verificationFailureToast = function(code) { switch (code) { case 1161: toastMessagesService.failureToast('First name missing'); break; case 1162: toastMessagesService.failureToast('Last name missing'); break; case 1163: toastMessagesService.failureToast('Date of birth missing'); break; case 1164: toastMessagesService.failureToast('Address Missing'); break; case 1165: toastMessagesService.failureToast('City Missing'); break; case 1166: toastMessagesService.failureToast('Province/state Missing'); break; case 1167: toastMessagesService.failureToast('Country Missing'); break; case 1168: toastMessagesService.failureToast('Postal code/ZIP Missing'); break; case 1169: toastMessagesService.failureToast('Occupation Missing'); break; case 1171: toastMessagesService.failureToast('Phone Missing'); break; default: console.log(code); toastMessagesService.failureToast('Verification error'); }; } /*******************Verification Level 1***********************/ function getVerification() { var data = {'test': 'true'}; verificationService.getVerification(data,function successBlock(data) { vm.getVerificationData = data; // console.log(data.verification_level) if(data.verification_level == 1) { }; }, function failureBlock(error) { console.log(error); } ); } vm.getLevelOneDetails = getLevelOneDetails; function getLevelOneDetails() { verificationService.getLevelOneDetails(function successBlock(data) { console.log(data); vm.verificationOne = { firstName: data.firstName, lastName: data.lastName, dob: new Date(data.birthDate), address: data.address, city: data.city, province: data.state, country: data.country, postalCode: data.zip, phone: data.phone, occupation: data.occupation, }; }, function failureBlock(error) { console.log(error); }); } $(document).ready(function () { getVerification(); }); getLevelOneDetails(); function checkVerifiedStatus() { if(vm.getVerificationData.verification_level == 1) { vm.verificationLevelTwo = true; } else { vm.verificationLevelTwo = true; //toastMessagesService.failureToast('You must be an approved, verified level one user before you can access the verification level two form.'); } } /************************************* Upload + Submit ********************************/ var verificationOneUploadSuccessCount = 0; var verificationTwoUploadSuccessCount = 0; var verificationUploadSuccess = function () { if (verificationOneUploadSuccessCount === 2) { toastMessagesService.successToast('Verification Level One data and files submitted successfully'); vm.verificationOneProgressBar = true; } else if (verificationTwoUploadSuccessCount === 1) { toastMessagesService.successToast('Verification Level Two submitted successfully'); vm.verificationTwoProgressBar = true; }; }; var uploadSingleFile = function (formId, inputId, verificationTwo) { $('#' + inputId).attr('name', 'uploaded_files'); var formData = new FormData($('form#'+formId)[0]); var action = $('form#'+formId).attr("action"); $.ajax({ url: action, type: 'POST', data: formData, // async: false, success: function (data) { console.log(data); verificationOneUploadSuccessCount++; verificationTwo ? verificationTwoUploadSuccessCount++ : ""; verificationUploadSuccess(); }, error: function (error) { console.log(error); toastMessagesService.failureToast('Verification upload failure'); vm.verificationOneProgressBar = true; vm.verificationTwoProgressBar = true; }, cache: false, contentType: false, processData: false }); } function submitVerificationOne(verificationOneData) { console.log(verificationOneData); verificationOneUploadSuccessCount = 0; verificationTwoUploadSuccessCount = 0; vm.verificationOneForm.$setSubmitted(); vm.photoForm.photoId.$dirty = true; vm.billUtilityForm.utilityBill.$dirty = true; if (vm.verificationOneForm.$valid && vm.photoForm.$valid && vm.billUtilityForm.$valid) { vm.verificationOneProgressBar = false; console.log(verificationOneData); var verificationOneSubmitData = { first_name: verificationOneData.firstName, last_name: verificationOneData.lastName, dob: verificationOneData.dob, address: verificationOneData.address, city: verificationOneData.city, state: verificationOneData.province, country: verificationOneData.country, zip: verificationOneData.postalCode, occupation: verificationOneData.occupation, phone: verificationOneData.phone, }; verificationService.verification_first(verificationOneSubmitData, function successBlock(data) { console.log('success'); // toastMessagesService.successToast('Verification information submitted.'); if (data.code == 1180) { console.log(data); $("form#photoForm").attr("action", data.photo_upload_url) uploadSingleFile("photoForm", "photo-id-input"); $("form#billUtilityForm").attr("action", data.utility_bill_url); uploadSingleFile("billUtilityForm", "utility-bill-input"); }; // vm.verificationOneProgressBar = true; }, function failureBlock(error) { console.log(error); verificationFailureToast(error.data.code); vm.verificationOneProgressBar = true; }); }; } function submitVerificationTwo(verificationTwoData) { verificationOneUploadSuccessCount = 0; verificationTwoUploadSuccessCount = 0; console.log(verificationTwoData); vm.verificationTwoForm.verificationTwoDocument.$dirty = true; vm.verificationTwoProgressBar = false; var dataToSend = {'test': 'true'}; verificationService.getVerification(dataToSend, function successBlock(data) { // vm.getVerificationData = data; console.log(data); // console.log("level: " + data.verification_level); // console.log("bank_letter_upload:" + data.bank_letter_upload); // if(data.verification_level == 1) { $("form#verificationTwoForm").attr("action", data.bank_letter_upload); uploadSingleFile("verificationTwoForm", "verification-two-document-input", true); // }; // vm.verificationTwoProgressBar = true; }, function failureBlock(error) { console.log(error); vm.verificationTwoProgressBar = true; }) /* verificationService.getVerification if (verificationTwoData.bankLetter) { $("form#verificationTwoForm").attr("action",data.bank_letter_upload); console.log("Bank letter"); dataToSend = verificationTwoData.bankLetter } else if (verificationTwoData.voidCheque) { console.log("Cheque"); dataToSend = verificationTwoData.voidCheque; }; if (vm.getVerificationData.verification_level == 0 || vm.getVerificationData.verification_level == 1) { uploadSingleFile(dataToSend, vm.getVerificationData.bank_letter_upload); }; */ }; //************************************************************* $scope.init = function() { $scope.user_id = localStorage.getItem('client'); var verification_level = localStorage.getItem('verification_level'); if(verification_level == 0) { $mdExpansionPanel().waitFor('verificationFirst').then(function (instance) { instance.expand(); }); } else { if(verification_level==1) { $mdExpansionPanel().waitFor('verificationSecond').then(function (instance) { instance.expand(); }); vm.getVerification(); } else { if(verification_level>2){
$('.rightIcon1').show(); $('.rightIcon2').show(); } } }; }; $scope.init(); //bank account $scope.choices = [{id: 'choice1'}]; $scope.addNewChoice = function() { var newItemNo = $scope.choices.length+1; $scope.choices.push({'id':'choice'+newItemNo}); }; $scope.removeChoice = function() { var lastItem = $scope.choices.length-1; $scope.choices.splice(lastItem); }; }]); //controller
$('.trade1').show(); $('.trade2').show(); }else{
conditional_block
VerificationCtrl.js
'use strict'; angular.module('taurus.verificationModule') .controller('VerificationCtrl', ["$state", "$mdExpansionPanel", "verificationService", "$scope", "toastMessagesService", "Upload", "$timeout", "$http", function($state, $mdExpansionPanel, verificationService, $scope, toastMessagesService, Upload, $timeout, $http) { 'use strict'; var vm = this; vm.checkVerifiedStatus = checkVerifiedStatus; // vm.clearOtherInput = clearOtherInput; vm.getVerification = getVerification; vm.goToTrade = goToTrade; vm.showUploadSuccess = showUploadSuccess; vm.submitVerificationOne = submitVerificationOne; vm.submitVerificationTwo = submitVerificationTwo; vm.minDob; vm.verificationOneForm; vm.photoForm; vm.billUtilityForm; vm.verificationTwoForm; vm.getVerificationData; vm.verificationLevelTwo = false; vm.verificationOneProgressBar = true; vm.verificationTwoProgressBar = true; vm.triggerFileBrowser = triggerFileBrowser; // Max birth date (min age) to register for taurus var today = new Date(); vm.maxDob = new Date(today.getFullYear() - 18, today.getMonth(), today.getDate()); vm.verificationOne = { firstName: "", lastName: "", dob: "", address: "", city: "", province: "", country: "", postalCode: "", photoId: "", utilityBill: "", phone: "", occupation: "", }; vm.allowedCountries = [ 'Afghanistan', 'Åland Islands', 'Albania', 'Algeria', 'Andorra', 'Angola', 'Anguilla', 'Antarctica', 'Antigua and Barbuda', 'Argentina', 'Armenia', 'Aruba', 'Australia', 'Austria', 'Azerbaijan', 'Bahamas (the)', 'Bahrain', 'Bangladesh', 'Barbados', 'Belarus', 'Belgium', 'Belize', 'Benin', 'Bermuda', 'Bhutan', 'Bolivia (Plurinational State of)', 'Bonaire, Sint Eustatius and Saba', 'Bosnia and Herzegovina', 'Botswana', 'Bouvet Island', 'Brazil', 'British Indian Ocean Territory (the)', 'Brunei Darussalam', 'Bulgaria', 'Burkina Faso', 'Burundi', 'Cabo Verde', 'Cambodia', 'Cameroon', 'Canada', 'Cayman Islands (the)', 'Central African Republic (the)', 'Chad', 'Chile', 'China', 'Christmas Island', 'Cocos (Keeling) Islands (the)', 'Colombia', 'Comoros (the)', 'Congo (the)', 'Congo (the Democratic Republic of the)', 'Cook Islands (the)', 'Costa Rica', 'Côte d\'Ivoire', 'Croatia', 'Cuba', 'Curaçao', 'Cyprus', 'Czech Republic (the)', 'Denmark', 'Djibouti', 'Dominica', 'Dominican Republic (the)', 'Ecuador', 'Egypt', 'El Salvador', 'Equatorial Guinea', 'Eritrea', 'Estonia', 'Ethiopia', 'Falkland Islands (the) [Malvinas]', 'Faroe Islands (the)', 'Fiji', 'Finland', 'France', 'French Guiana', 'French Polynesia', 'French Southern Territories (the)', 'Gabon', 'Gambia (the)', 'Georgia', 'Ghana', 'Gibraltar', 'Greece', 'Greenland', 'Grenada', 'Guadeloupe', 'Guatemala', 'Guernsey', 'Guinea', 'Guinea-Bissau', 'Guyana', 'Haiti', 'Heard Island and McDonald Islands', 'Holy See (the)', 'Honduras', 'Hong Kong', 'Hungary', 'Iceland', 'India', 'Indonesia', 'Ireland', 'Isle of Man', 'Israel', 'Italy', 'Jamaica', 'Japan', 'Jersey', 'Jordan', 'Kazakhstan', 'Kenya', 'Kiribati', 'Korea (the Democratic People\'s Republic of)', 'Korea (the Republic of)', 'Kuwait', 'Kyrgyzstan', 'Lao People\'s Democratic Republic (the)', 'Latvia', 'Lebanon', 'Lesotho', 'Liberia', 'Libya', 'Liechtenstein', 'Lithuania', 'Luxembourg', 'Macao', 'Macedonia (the former Yugoslav Republic of)', 'Madagascar', 'Malawi', 'Malaysia', 'Maldives', 'Mali', 'Malta', 'Marshall Islands (the)', 'Martinique', 'Mauritania', 'Mauritius', 'Mayotte', 'Mexico', 'Micronesia (Federated States of)', 'Moldova (the Republic of)', 'Monaco', 'Mongolia', 'Montenegro', 'Montserrat', 'Morocco', 'Mozambique', 'Myanmar', 'Namibia', 'Nauru', 'Nepal', 'Netherlands (the)', 'New Caledonia', 'New Zealand', 'Nicaragua', 'Niger (the)', 'Nigeria', 'Niue', 'Norfolk Island', 'Norway', 'Oman', 'Pakistan', 'Palau', 'Palestine, State of', 'Panama', 'Papua New Guinea', 'Paraguay', 'Peru', 'Philippines (the)', 'Pitcairn', 'Poland', 'Portugal', 'Qatar', 'Réunion', 'Romania', 'Russian Federation (the)', 'Rwanda', 'Saint Barthélemy', 'Saint Helena, Ascension and Tristan da Cunha', 'Saint Kitts and Nevis', 'Saint Lucia', 'Saint Martin (French part)', 'Saint Pierre and Miquelon', 'Saint Vincent and the Grenadines', 'Samoa', 'San Marino', 'Sao Tome and Principe',
'Seychelles', 'Sierra Leone', 'Singapore', 'Sint Maarten (Dutch part)', 'Slovakia', 'Slovenia', 'Solomon Islands', 'Somalia', 'South Africa', 'South Georgia and the South Sandwich Islands', 'South Sudan ', 'Spain', 'Sri Lanka', 'Sudan (the)', 'Suriname', 'Svalbard and Jan Mayen', 'Swaziland', 'Sweden', 'Switzerland', 'Taiwan (Province of China)', 'Tajikistan', 'Tanzania, United Republic of', 'Thailand', 'Timor-Leste', 'Togo', 'Tokelau', 'Tonga', 'Trinidad and Tobago', 'Tunisia', 'Turkey', 'Turkmenistan', 'Turks and Caicos Islands (the)', 'Tuvalu', 'Uganda', 'Ukraine', 'United Arab Emirates (the)', 'United Kingdom of Great Britain and Northern Ireland (the)', 'Uruguay', 'Uzbekistan', 'Vanuatu', 'Venezuela (Bolivarian Republic of)', 'Vietnam', 'Virgin Islands (British)', 'Wallis and Futuna', 'Western Sahara', 'Yemen', 'Zambia', 'Zimbabwe' ]; function triggerFileBrowser(inputId) { $('#' + inputId).trigger('click'); } vm.verificationTwo = { verificationTwoDocument: "" }; function goToTrade() { $state.go('trade'); } vm.validateVerificationForm = validateVerificationForm; function validateVerificationForm(data) { console.log(data); console.log(data.$valid); return data.$valid; } // If the form input error object is empty (file input is valid) // it will show a green checkmark. Otherwise hides the checkmark function showUploadSuccess(formInputErrorObject, elementIdToAdjust) { if (jQuery.isEmptyObject(formInputErrorObject)) { $('#' + elementIdToAdjust).parent().children('md-icon').css('opacity', '1'); // $('#utility-bill-input').parent().children().first().css('opacity', '1'); } else { $('#' + elementIdToAdjust).parent().children('md-icon').css('opacity', '0'); } } // VerificationTwo has optional input: Void Cheque or Bank Letter/Statement. // When either upload button is clicked, this function clears the model and hides the checkmark, if visible // So that both uploads are not used // function clearOtherInput() { // vm.verificationTwo = { // bankLetter: "", // voidCheque: "" // }; // $('#bank-letter-btn').parent().children('md-icon').css('opacity', '0'); // $('#void-cheque-btn').parent().children('md-icon').css('opacity', '0'); // } // function trade(data) { // $state.go(data); // }; var verificationFailureToast = function(code) { switch (code) { case 1161: toastMessagesService.failureToast('First name missing'); break; case 1162: toastMessagesService.failureToast('Last name missing'); break; case 1163: toastMessagesService.failureToast('Date of birth missing'); break; case 1164: toastMessagesService.failureToast('Address Missing'); break; case 1165: toastMessagesService.failureToast('City Missing'); break; case 1166: toastMessagesService.failureToast('Province/state Missing'); break; case 1167: toastMessagesService.failureToast('Country Missing'); break; case 1168: toastMessagesService.failureToast('Postal code/ZIP Missing'); break; case 1169: toastMessagesService.failureToast('Occupation Missing'); break; case 1171: toastMessagesService.failureToast('Phone Missing'); break; default: console.log(code); toastMessagesService.failureToast('Verification error'); }; } /*******************Verification Level 1***********************/ function getVerification() { var data = {'test': 'true'}; verificationService.getVerification(data,function successBlock(data) { vm.getVerificationData = data; // console.log(data.verification_level) if(data.verification_level == 1) { }; }, function failureBlock(error) { console.log(error); } ); } vm.getLevelOneDetails = getLevelOneDetails; function getLevelOneDetails() { verificationService.getLevelOneDetails(function successBlock(data) { console.log(data); vm.verificationOne = { firstName: data.firstName, lastName: data.lastName, dob: new Date(data.birthDate), address: data.address, city: data.city, province: data.state, country: data.country, postalCode: data.zip, phone: data.phone, occupation: data.occupation, }; }, function failureBlock(error) { console.log(error); }); } $(document).ready(function () { getVerification(); }); getLevelOneDetails(); function checkVerifiedStatus() { if(vm.getVerificationData.verification_level == 1) { vm.verificationLevelTwo = true; } else { vm.verificationLevelTwo = true; //toastMessagesService.failureToast('You must be an approved, verified level one user before you can access the verification level two form.'); } } /************************************* Upload + Submit ********************************/ var verificationOneUploadSuccessCount = 0; var verificationTwoUploadSuccessCount = 0; var verificationUploadSuccess = function () { if (verificationOneUploadSuccessCount === 2) { toastMessagesService.successToast('Verification Level One data and files submitted successfully'); vm.verificationOneProgressBar = true; } else if (verificationTwoUploadSuccessCount === 1) { toastMessagesService.successToast('Verification Level Two submitted successfully'); vm.verificationTwoProgressBar = true; }; }; var uploadSingleFile = function (formId, inputId, verificationTwo) { $('#' + inputId).attr('name', 'uploaded_files'); var formData = new FormData($('form#'+formId)[0]); var action = $('form#'+formId).attr("action"); $.ajax({ url: action, type: 'POST', data: formData, // async: false, success: function (data) { console.log(data); verificationOneUploadSuccessCount++; verificationTwo ? verificationTwoUploadSuccessCount++ : ""; verificationUploadSuccess(); }, error: function (error) { console.log(error); toastMessagesService.failureToast('Verification upload failure'); vm.verificationOneProgressBar = true; vm.verificationTwoProgressBar = true; }, cache: false, contentType: false, processData: false }); } function submitVerificationOne(verificationOneData) { console.log(verificationOneData); verificationOneUploadSuccessCount = 0; verificationTwoUploadSuccessCount = 0; vm.verificationOneForm.$setSubmitted(); vm.photoForm.photoId.$dirty = true; vm.billUtilityForm.utilityBill.$dirty = true; if (vm.verificationOneForm.$valid && vm.photoForm.$valid && vm.billUtilityForm.$valid) { vm.verificationOneProgressBar = false; console.log(verificationOneData); var verificationOneSubmitData = { first_name: verificationOneData.firstName, last_name: verificationOneData.lastName, dob: verificationOneData.dob, address: verificationOneData.address, city: verificationOneData.city, state: verificationOneData.province, country: verificationOneData.country, zip: verificationOneData.postalCode, occupation: verificationOneData.occupation, phone: verificationOneData.phone, }; verificationService.verification_first(verificationOneSubmitData, function successBlock(data) { console.log('success'); // toastMessagesService.successToast('Verification information submitted.'); if (data.code == 1180) { console.log(data); $("form#photoForm").attr("action", data.photo_upload_url) uploadSingleFile("photoForm", "photo-id-input"); $("form#billUtilityForm").attr("action", data.utility_bill_url); uploadSingleFile("billUtilityForm", "utility-bill-input"); }; // vm.verificationOneProgressBar = true; }, function failureBlock(error) { console.log(error); verificationFailureToast(error.data.code); vm.verificationOneProgressBar = true; }); }; } function submitVerificationTwo(verificationTwoData) { verificationOneUploadSuccessCount = 0; verificationTwoUploadSuccessCount = 0; console.log(verificationTwoData); vm.verificationTwoForm.verificationTwoDocument.$dirty = true; vm.verificationTwoProgressBar = false; var dataToSend = {'test': 'true'}; verificationService.getVerification(dataToSend, function successBlock(data) { // vm.getVerificationData = data; console.log(data); // console.log("level: " + data.verification_level); // console.log("bank_letter_upload:" + data.bank_letter_upload); // if(data.verification_level == 1) { $("form#verificationTwoForm").attr("action", data.bank_letter_upload); uploadSingleFile("verificationTwoForm", "verification-two-document-input", true); // }; // vm.verificationTwoProgressBar = true; }, function failureBlock(error) { console.log(error); vm.verificationTwoProgressBar = true; }) /* verificationService.getVerification if (verificationTwoData.bankLetter) { $("form#verificationTwoForm").attr("action",data.bank_letter_upload); console.log("Bank letter"); dataToSend = verificationTwoData.bankLetter } else if (verificationTwoData.voidCheque) { console.log("Cheque"); dataToSend = verificationTwoData.voidCheque; }; if (vm.getVerificationData.verification_level == 0 || vm.getVerificationData.verification_level == 1) { uploadSingleFile(dataToSend, vm.getVerificationData.bank_letter_upload); }; */ }; //************************************************************* $scope.init = function() { $scope.user_id = localStorage.getItem('client'); var verification_level = localStorage.getItem('verification_level'); if(verification_level == 0) { $mdExpansionPanel().waitFor('verificationFirst').then(function (instance) { instance.expand(); }); } else { if(verification_level==1) { $mdExpansionPanel().waitFor('verificationSecond').then(function (instance) { instance.expand(); }); vm.getVerification(); } else { if(verification_level>2){ $('.trade1').show(); $('.trade2').show(); }else{ $('.rightIcon1').show(); $('.rightIcon2').show(); } } }; }; $scope.init(); //bank account $scope.choices = [{id: 'choice1'}]; $scope.addNewChoice = function() { var newItemNo = $scope.choices.length+1; $scope.choices.push({'id':'choice'+newItemNo}); }; $scope.removeChoice = function() { var lastItem = $scope.choices.length-1; $scope.choices.splice(lastItem); }; }]); //controller
'Saudi Arabia', 'Senegal', 'Serbia',
random_line_split
VerificationCtrl.js
'use strict'; angular.module('taurus.verificationModule') .controller('VerificationCtrl', ["$state", "$mdExpansionPanel", "verificationService", "$scope", "toastMessagesService", "Upload", "$timeout", "$http", function($state, $mdExpansionPanel, verificationService, $scope, toastMessagesService, Upload, $timeout, $http) { 'use strict'; var vm = this; vm.checkVerifiedStatus = checkVerifiedStatus; // vm.clearOtherInput = clearOtherInput; vm.getVerification = getVerification; vm.goToTrade = goToTrade; vm.showUploadSuccess = showUploadSuccess; vm.submitVerificationOne = submitVerificationOne; vm.submitVerificationTwo = submitVerificationTwo; vm.minDob; vm.verificationOneForm; vm.photoForm; vm.billUtilityForm; vm.verificationTwoForm; vm.getVerificationData; vm.verificationLevelTwo = false; vm.verificationOneProgressBar = true; vm.verificationTwoProgressBar = true; vm.triggerFileBrowser = triggerFileBrowser; // Max birth date (min age) to register for taurus var today = new Date(); vm.maxDob = new Date(today.getFullYear() - 18, today.getMonth(), today.getDate()); vm.verificationOne = { firstName: "", lastName: "", dob: "", address: "", city: "", province: "", country: "", postalCode: "", photoId: "", utilityBill: "", phone: "", occupation: "", }; vm.allowedCountries = [ 'Afghanistan', 'Åland Islands', 'Albania', 'Algeria', 'Andorra', 'Angola', 'Anguilla', 'Antarctica', 'Antigua and Barbuda', 'Argentina', 'Armenia', 'Aruba', 'Australia', 'Austria', 'Azerbaijan', 'Bahamas (the)', 'Bahrain', 'Bangladesh', 'Barbados', 'Belarus', 'Belgium', 'Belize', 'Benin', 'Bermuda', 'Bhutan', 'Bolivia (Plurinational State of)', 'Bonaire, Sint Eustatius and Saba', 'Bosnia and Herzegovina', 'Botswana', 'Bouvet Island', 'Brazil', 'British Indian Ocean Territory (the)', 'Brunei Darussalam', 'Bulgaria', 'Burkina Faso', 'Burundi', 'Cabo Verde', 'Cambodia', 'Cameroon', 'Canada', 'Cayman Islands (the)', 'Central African Republic (the)', 'Chad', 'Chile', 'China', 'Christmas Island', 'Cocos (Keeling) Islands (the)', 'Colombia', 'Comoros (the)', 'Congo (the)', 'Congo (the Democratic Republic of the)', 'Cook Islands (the)', 'Costa Rica', 'Côte d\'Ivoire', 'Croatia', 'Cuba', 'Curaçao', 'Cyprus', 'Czech Republic (the)', 'Denmark', 'Djibouti', 'Dominica', 'Dominican Republic (the)', 'Ecuador', 'Egypt', 'El Salvador', 'Equatorial Guinea', 'Eritrea', 'Estonia', 'Ethiopia', 'Falkland Islands (the) [Malvinas]', 'Faroe Islands (the)', 'Fiji', 'Finland', 'France', 'French Guiana', 'French Polynesia', 'French Southern Territories (the)', 'Gabon', 'Gambia (the)', 'Georgia', 'Ghana', 'Gibraltar', 'Greece', 'Greenland', 'Grenada', 'Guadeloupe', 'Guatemala', 'Guernsey', 'Guinea', 'Guinea-Bissau', 'Guyana', 'Haiti', 'Heard Island and McDonald Islands', 'Holy See (the)', 'Honduras', 'Hong Kong', 'Hungary', 'Iceland', 'India', 'Indonesia', 'Ireland', 'Isle of Man', 'Israel', 'Italy', 'Jamaica', 'Japan', 'Jersey', 'Jordan', 'Kazakhstan', 'Kenya', 'Kiribati', 'Korea (the Democratic People\'s Republic of)', 'Korea (the Republic of)', 'Kuwait', 'Kyrgyzstan', 'Lao People\'s Democratic Republic (the)', 'Latvia', 'Lebanon', 'Lesotho', 'Liberia', 'Libya', 'Liechtenstein', 'Lithuania', 'Luxembourg', 'Macao', 'Macedonia (the former Yugoslav Republic of)', 'Madagascar', 'Malawi', 'Malaysia', 'Maldives', 'Mali', 'Malta', 'Marshall Islands (the)', 'Martinique', 'Mauritania', 'Mauritius', 'Mayotte', 'Mexico', 'Micronesia (Federated States of)', 'Moldova (the Republic of)', 'Monaco', 'Mongolia', 'Montenegro', 'Montserrat', 'Morocco', 'Mozambique', 'Myanmar', 'Namibia', 'Nauru', 'Nepal', 'Netherlands (the)', 'New Caledonia', 'New Zealand', 'Nicaragua', 'Niger (the)', 'Nigeria', 'Niue', 'Norfolk Island', 'Norway', 'Oman', 'Pakistan', 'Palau', 'Palestine, State of', 'Panama', 'Papua New Guinea', 'Paraguay', 'Peru', 'Philippines (the)', 'Pitcairn', 'Poland', 'Portugal', 'Qatar', 'Réunion', 'Romania', 'Russian Federation (the)', 'Rwanda', 'Saint Barthélemy', 'Saint Helena, Ascension and Tristan da Cunha', 'Saint Kitts and Nevis', 'Saint Lucia', 'Saint Martin (French part)', 'Saint Pierre and Miquelon', 'Saint Vincent and the Grenadines', 'Samoa', 'San Marino', 'Sao Tome and Principe', 'Saudi Arabia', 'Senegal', 'Serbia', 'Seychelles', 'Sierra Leone', 'Singapore', 'Sint Maarten (Dutch part)', 'Slovakia', 'Slovenia', 'Solomon Islands', 'Somalia', 'South Africa', 'South Georgia and the South Sandwich Islands', 'South Sudan ', 'Spain', 'Sri Lanka', 'Sudan (the)', 'Suriname', 'Svalbard and Jan Mayen', 'Swaziland', 'Sweden', 'Switzerland', 'Taiwan (Province of China)', 'Tajikistan', 'Tanzania, United Republic of', 'Thailand', 'Timor-Leste', 'Togo', 'Tokelau', 'Tonga', 'Trinidad and Tobago', 'Tunisia', 'Turkey', 'Turkmenistan', 'Turks and Caicos Islands (the)', 'Tuvalu', 'Uganda', 'Ukraine', 'United Arab Emirates (the)', 'United Kingdom of Great Britain and Northern Ireland (the)', 'Uruguay', 'Uzbekistan', 'Vanuatu', 'Venezuela (Bolivarian Republic of)', 'Vietnam', 'Virgin Islands (British)', 'Wallis and Futuna', 'Western Sahara', 'Yemen', 'Zambia', 'Zimbabwe' ]; function triggerFileBrowser(inputId) { $('#' + inputId).trigger('click'); } vm.verificationTwo = { verificationTwoDocument: "" }; function goToTrade() { $state.go('trade'); } vm.validateVerificationForm = validateVerificationForm; function validateVerificationForm(data) { console.log(data); console.log(data.$valid); return data.$valid; } // If the form input error object is empty (file input is valid) // it will show a green checkmark. Otherwise hides the checkmark function showUploadSuccess(formInputErrorObject, elementIdToAdjust) { if (jQuery.isEmptyObject(formInputErrorObject)) { $('#' + elementIdToAdjust).parent().children('md-icon').css('opacity', '1'); // $('#utility-bill-input').parent().children().first().css('opacity', '1'); } else { $('#' + elementIdToAdjust).parent().children('md-icon').css('opacity', '0'); } } // VerificationTwo has optional input: Void Cheque or Bank Letter/Statement. // When either upload button is clicked, this function clears the model and hides the checkmark, if visible // So that both uploads are not used // function clearOtherInput() { // vm.verificationTwo = { // bankLetter: "", // voidCheque: "" // }; // $('#bank-letter-btn').parent().children('md-icon').css('opacity', '0'); // $('#void-cheque-btn').parent().children('md-icon').css('opacity', '0'); // } // function trade(data) { // $state.go(data); // }; var verificationFailureToast = function(code) { switch (code) { case 1161: toastMessagesService.failureToast('First name missing'); break; case 1162: toastMessagesService.failureToast('Last name missing'); break; case 1163: toastMessagesService.failureToast('Date of birth missing'); break; case 1164: toastMessagesService.failureToast('Address Missing'); break; case 1165: toastMessagesService.failureToast('City Missing'); break; case 1166: toastMessagesService.failureToast('Province/state Missing'); break; case 1167: toastMessagesService.failureToast('Country Missing'); break; case 1168: toastMessagesService.failureToast('Postal code/ZIP Missing'); break; case 1169: toastMessagesService.failureToast('Occupation Missing'); break; case 1171: toastMessagesService.failureToast('Phone Missing'); break; default: console.log(code); toastMessagesService.failureToast('Verification error'); }; } /*******************Verification Level 1***********************/ function getVerification() {
vm.getLevelOneDetails = getLevelOneDetails; function getLevelOneDetails() { verificationService.getLevelOneDetails(function successBlock(data) { console.log(data); vm.verificationOne = { firstName: data.firstName, lastName: data.lastName, dob: new Date(data.birthDate), address: data.address, city: data.city, province: data.state, country: data.country, postalCode: data.zip, phone: data.phone, occupation: data.occupation, }; }, function failureBlock(error) { console.log(error); }); } $(document).ready(function () { getVerification(); }); getLevelOneDetails(); function checkVerifiedStatus() { if(vm.getVerificationData.verification_level == 1) { vm.verificationLevelTwo = true; } else { vm.verificationLevelTwo = true; //toastMessagesService.failureToast('You must be an approved, verified level one user before you can access the verification level two form.'); } } /************************************* Upload + Submit ********************************/ var verificationOneUploadSuccessCount = 0; var verificationTwoUploadSuccessCount = 0; var verificationUploadSuccess = function () { if (verificationOneUploadSuccessCount === 2) { toastMessagesService.successToast('Verification Level One data and files submitted successfully'); vm.verificationOneProgressBar = true; } else if (verificationTwoUploadSuccessCount === 1) { toastMessagesService.successToast('Verification Level Two submitted successfully'); vm.verificationTwoProgressBar = true; }; }; var uploadSingleFile = function (formId, inputId, verificationTwo) { $('#' + inputId).attr('name', 'uploaded_files'); var formData = new FormData($('form#'+formId)[0]); var action = $('form#'+formId).attr("action"); $.ajax({ url: action, type: 'POST', data: formData, // async: false, success: function (data) { console.log(data); verificationOneUploadSuccessCount++; verificationTwo ? verificationTwoUploadSuccessCount++ : ""; verificationUploadSuccess(); }, error: function (error) { console.log(error); toastMessagesService.failureToast('Verification upload failure'); vm.verificationOneProgressBar = true; vm.verificationTwoProgressBar = true; }, cache: false, contentType: false, processData: false }); } function submitVerificationOne(verificationOneData) { console.log(verificationOneData); verificationOneUploadSuccessCount = 0; verificationTwoUploadSuccessCount = 0; vm.verificationOneForm.$setSubmitted(); vm.photoForm.photoId.$dirty = true; vm.billUtilityForm.utilityBill.$dirty = true; if (vm.verificationOneForm.$valid && vm.photoForm.$valid && vm.billUtilityForm.$valid) { vm.verificationOneProgressBar = false; console.log(verificationOneData); var verificationOneSubmitData = { first_name: verificationOneData.firstName, last_name: verificationOneData.lastName, dob: verificationOneData.dob, address: verificationOneData.address, city: verificationOneData.city, state: verificationOneData.province, country: verificationOneData.country, zip: verificationOneData.postalCode, occupation: verificationOneData.occupation, phone: verificationOneData.phone, }; verificationService.verification_first(verificationOneSubmitData, function successBlock(data) { console.log('success'); // toastMessagesService.successToast('Verification information submitted.'); if (data.code == 1180) { console.log(data); $("form#photoForm").attr("action", data.photo_upload_url) uploadSingleFile("photoForm", "photo-id-input"); $("form#billUtilityForm").attr("action", data.utility_bill_url); uploadSingleFile("billUtilityForm", "utility-bill-input"); }; // vm.verificationOneProgressBar = true; }, function failureBlock(error) { console.log(error); verificationFailureToast(error.data.code); vm.verificationOneProgressBar = true; }); }; } function submitVerificationTwo(verificationTwoData) { verificationOneUploadSuccessCount = 0; verificationTwoUploadSuccessCount = 0; console.log(verificationTwoData); vm.verificationTwoForm.verificationTwoDocument.$dirty = true; vm.verificationTwoProgressBar = false; var dataToSend = {'test': 'true'}; verificationService.getVerification(dataToSend, function successBlock(data) { // vm.getVerificationData = data; console.log(data); // console.log("level: " + data.verification_level); // console.log("bank_letter_upload:" + data.bank_letter_upload); // if(data.verification_level == 1) { $("form#verificationTwoForm").attr("action", data.bank_letter_upload); uploadSingleFile("verificationTwoForm", "verification-two-document-input", true); // }; // vm.verificationTwoProgressBar = true; }, function failureBlock(error) { console.log(error); vm.verificationTwoProgressBar = true; }) /* verificationService.getVerification if (verificationTwoData.bankLetter) { $("form#verificationTwoForm").attr("action",data.bank_letter_upload); console.log("Bank letter"); dataToSend = verificationTwoData.bankLetter } else if (verificationTwoData.voidCheque) { console.log("Cheque"); dataToSend = verificationTwoData.voidCheque; }; if (vm.getVerificationData.verification_level == 0 || vm.getVerificationData.verification_level == 1) { uploadSingleFile(dataToSend, vm.getVerificationData.bank_letter_upload); }; */ }; //************************************************************* $scope.init = function() { $scope.user_id = localStorage.getItem('client'); var verification_level = localStorage.getItem('verification_level'); if(verification_level == 0) { $mdExpansionPanel().waitFor('verificationFirst').then(function (instance) { instance.expand(); }); } else { if(verification_level==1) { $mdExpansionPanel().waitFor('verificationSecond').then(function (instance) { instance.expand(); }); vm.getVerification(); } else { if(verification_level>2){ $('.trade1').show(); $('.trade2').show(); }else{ $('.rightIcon1').show(); $('.rightIcon2').show(); } } }; }; $scope.init(); //bank account $scope.choices = [{id: 'choice1'}]; $scope.addNewChoice = function() { var newItemNo = $scope.choices.length+1; $scope.choices.push({'id':'choice'+newItemNo}); }; $scope.removeChoice = function() { var lastItem = $scope.choices.length-1; $scope.choices.splice(lastItem); }; }]); //controller
var data = {'test': 'true'}; verificationService.getVerification(data,function successBlock(data) { vm.getVerificationData = data; // console.log(data.verification_level) if(data.verification_level == 1) { }; }, function failureBlock(error) { console.log(error); } ); }
identifier_body
runner.rs
use diesel::prelude::*; #[cfg(feature = "r2d2")] use diesel::r2d2; use std::any::Any; use std::error::Error; use std::panic::{catch_unwind, AssertUnwindSafe, PanicInfo, RefUnwindSafe, UnwindSafe}; use std::sync::Arc; use std::time::Duration; use threadpool::ThreadPool; use crate::db::*; use crate::errors::*; use crate::{storage, Registry}; use event::*; mod channel; mod event; pub struct NoConnectionPoolGiven; #[allow(missing_debug_implementations)] pub struct Builder<Env, ConnectionPoolBuilder> { connection_pool_or_builder: ConnectionPoolBuilder, environment: Env, thread_count: Option<usize>, job_start_timeout: Option<Duration>, } impl<Env, ConnectionPoolBuilder> Builder<Env, ConnectionPoolBuilder> { /// Set the number of threads to be used to run jobs concurrently. /// /// Defaults to 5 pub fn thread_count(mut self, thread_count: usize) -> Self { self.thread_count = Some(thread_count); self } fn get_thread_count(&self) -> usize { self.thread_count.unwrap_or(5) } /// The amount of time to wait for a job to start before assuming an error /// has occurred. /// /// Defaults to 10 seconds. pub fn job_start_timeout(mut self, timeout: Duration) -> Self { self.job_start_timeout = Some(timeout); self } /// Provide a connection pool to be used by the runner pub fn connection_pool<NewPool>(self, pool: NewPool) -> Builder<Env, NewPool> { Builder { connection_pool_or_builder: pool, environment: self.environment, thread_count: self.thread_count, job_start_timeout: self.job_start_timeout, } } } #[cfg(feature = "r2d2")] impl<Env, ConnectionPoolBuilder> Builder<Env, ConnectionPoolBuilder> { /// Build the runner with an r2d2 connection pool /// /// This will override any connection pool previously provided pub fn database_url<S: Into<String>>(self, database_url: S) -> Builder<Env, R2d2Builder> { self.connection_pool_builder(database_url, r2d2::Builder::new()) } /// Provide a connection pool builder. /// /// This will override any connection pool previously provided. /// /// You should call this method if you want to provide additional /// configuration for the database connection pool. The builder will be /// configured to have its max size set to the value given to `2 * thread_count`. /// To override this behavior, call [`connection_count`](Self::connection_count) pub fn connection_pool_builder<S: Into<String>>( self, database_url: S, builder: r2d2::Builder<r2d2::ConnectionManager<PgConnection>>, ) -> Builder<Env, R2d2Builder> { self.connection_pool(R2d2Builder::new(database_url.into(), builder)) } } #[cfg(feature = "r2d2")] impl<Env> Builder<Env, R2d2Builder> { /// Set the max size of the database connection pool pub fn connection_count(mut self, connection_count: u32) -> Self { self.connection_pool_or_builder .connection_count(connection_count); self } /// Build the runner with an r2d2 connection pool. pub fn build(self) -> Runner<Env, r2d2::Pool<r2d2::ConnectionManager<PgConnection>>> { let thread_count = self.get_thread_count(); let connection_pool_size = thread_count as u32 * 2; let connection_pool = self.connection_pool_or_builder.build(connection_pool_size); Runner { connection_pool, thread_pool: ThreadPool::new(thread_count), environment: Arc::new(self.environment), registry: Arc::new(Registry::load()), job_start_timeout: self.job_start_timeout.unwrap_or(Duration::from_secs(10)), } } } impl<Env, ConnectionPool> Builder<Env, ConnectionPool> where ConnectionPool: DieselPool, { /// Build the runner pub fn build(self) -> Runner<Env, ConnectionPool> { Runner { thread_pool: ThreadPool::new(self.get_thread_count()), connection_pool: self.connection_pool_or_builder, environment: Arc::new(self.environment), registry: Arc::new(Registry::load()), job_start_timeout: self.job_start_timeout.unwrap_or(Duration::from_secs(10)), } } } #[allow(missing_debug_implementations)] /// The core runner responsible for locking and running jobs pub struct
<Env: 'static, ConnectionPool> { connection_pool: ConnectionPool, thread_pool: ThreadPool, environment: Arc<Env>, registry: Arc<Registry<Env>>, job_start_timeout: Duration, } impl<Env> Runner<Env, NoConnectionPoolGiven> { /// Create a builder for a job runner /// /// This method takes the two required configurations, the database /// connection pool, and the environment to pass to your jobs. If your /// environment contains a connection pool, it should be the same pool given /// here. pub fn builder(environment: Env) -> Builder<Env, NoConnectionPoolGiven> { Builder { connection_pool_or_builder: NoConnectionPoolGiven, environment, thread_count: None, job_start_timeout: None, } } } impl<Env, ConnectionPool> Runner<Env, ConnectionPool> { #[doc(hidden)] /// For use in integration tests pub fn connection_pool(&self) -> &ConnectionPool { &self.connection_pool } } impl<Env, ConnectionPool> Runner<Env, ConnectionPool> where Env: RefUnwindSafe + Send + Sync + 'static, ConnectionPool: DieselPool + 'static, { /// Runs all pending jobs in the queue /// /// This function will return once all jobs in the queue have begun running, /// but does not wait for them to complete. When this function returns, at /// least one thread will have tried to acquire a new job, and found there /// were none in the queue. pub fn run_all_pending_jobs(&self) -> Result<(), FetchError<ConnectionPool>> { use std::cmp::max; let max_threads = self.thread_pool.max_count(); let (sender, receiver) = channel::new(max_threads); let mut pending_messages = 0; loop { let available_threads = max_threads - self.thread_pool.active_count(); let jobs_to_queue = if pending_messages == 0 { // If we have no queued jobs talking to us, and there are no // available threads, we still need to queue at least one job // or we'll never receive a message max(available_threads, 1) } else { available_threads }; for _ in 0..jobs_to_queue { self.run_single_job(sender.clone()); } pending_messages += jobs_to_queue; match receiver.recv_timeout(self.job_start_timeout) { Ok(Event::Working) => pending_messages -= 1, Ok(Event::NoJobAvailable) => return Ok(()), Ok(Event::ErrorLoadingJob(e)) => return Err(FetchError::FailedLoadingJob(e)), Ok(Event::FailedToAcquireConnection(e)) => { return Err(FetchError::NoDatabaseConnection(e)); } Err(_) => return Err(FetchError::NoMessageReceived), } } } fn run_single_job(&self, sender: EventSender<ConnectionPool>) { let environment = Arc::clone(&self.environment); let registry = Arc::clone(&self.registry); // FIXME: https://github.com/sfackler/r2d2/pull/70 let connection_pool = AssertUnwindSafe(self.connection_pool().clone()); self.get_single_job(sender, move |job| { let perform_job = registry .get(&job.job_type) .ok_or_else(|| PerformError::from(format!("Unknown job type {}", job.job_type)))?; perform_job.perform(job.data, &environment, &connection_pool.0) }) } fn get_single_job<F>(&self, sender: EventSender<ConnectionPool>, f: F) where F: FnOnce(storage::BackgroundJob) -> Result<(), PerformError> + Send + UnwindSafe + 'static, { use diesel::result::Error::RollbackTransaction; // The connection may not be `Send` so we need to clone the pool instead let pool = self.connection_pool.clone(); self.thread_pool.execute(move || { let conn = match pool.get() { Ok(conn) => conn, Err(e) => { sender.send(Event::FailedToAcquireConnection(e)); return; } }; let job_run_result = conn.transaction::<_, diesel::result::Error, _>(|| { let job = match storage::find_next_unlocked_job(&conn).optional() { Ok(Some(j)) => { sender.send(Event::Working); j } Ok(None) => { sender.send(Event::NoJobAvailable); return Ok(()); } Err(e) => { sender.send(Event::ErrorLoadingJob(e)); return Err(RollbackTransaction); } }; let job_id = job.id; let result = catch_unwind(|| f(job)) .map_err(|e| try_to_extract_panic_info(&e)) .and_then(|r| r); match result { Ok(_) => storage::delete_successful_job(&conn, job_id)?, Err(e) => { eprintln!("Job {} failed to run: {}", job_id, e); storage::update_failed_job(&conn, job_id); } } Ok(()) }); match job_run_result { Ok(_) | Err(RollbackTransaction) => {} Err(e) => { panic!("Failed to update job: {:?}", e); } } }) } fn connection(&self) -> Result<DieselPooledConn<ConnectionPool>, Box<dyn Error + Send + Sync>> { self.connection_pool.get().map_err(Into::into) } /// Waits for all running jobs to complete, and returns an error if any /// failed /// /// This function is intended for use in tests. If any jobs have failed, it /// will return `swirl::JobsFailed` with the number of jobs that failed. /// /// If any other unexpected errors occurred, such as panicked worker threads /// or an error loading the job count from the database, an opaque error /// will be returned. pub fn check_for_failed_jobs(&self) -> Result<(), FailedJobsError> { self.wait_for_jobs()?; let failed_jobs = storage::failed_job_count(&*self.connection()?)?; if failed_jobs == 0 { Ok(()) } else { Err(JobsFailed(failed_jobs)) } } fn wait_for_jobs(&self) -> Result<(), Box<dyn Error + Send + Sync>> { self.thread_pool.join(); let panic_count = self.thread_pool.panic_count(); if panic_count == 0 { Ok(()) } else { Err(format!("{} threads panicked", panic_count).into()) } } } /// Try to figure out what's in the box, and print it if we can. /// /// The actual error type we will get from `panic::catch_unwind` is really poorly documented. /// However, the `panic::set_hook` functions deal with a `PanicInfo` type, and its payload is /// documented as "commonly but not always `&'static str` or `String`". So we can try all of those, /// and give up if we didn't get one of those three types. fn try_to_extract_panic_info(info: &(dyn Any + Send + 'static)) -> PerformError { if let Some(x) = info.downcast_ref::<PanicInfo>() { format!("job panicked: {}", x).into() } else if let Some(x) = info.downcast_ref::<&'static str>() { format!("job panicked: {}", x).into() } else if let Some(x) = info.downcast_ref::<String>() { format!("job panicked: {}", x).into() } else { "job panicked".into() } } #[cfg(test)] mod tests { use diesel::prelude::*; use diesel::r2d2; use super::*; use crate::schema::background_jobs::dsl::*; use std::panic::AssertUnwindSafe; use std::sync::{Arc, Barrier, Mutex, MutexGuard}; #[test] fn jobs_are_locked_when_fetched() { let _guard = TestGuard::lock(); let runner = runner(); let first_job_id = create_dummy_job(&runner).id; let second_job_id = create_dummy_job(&runner).id; let fetch_barrier = Arc::new(AssertUnwindSafe(Barrier::new(2))); let fetch_barrier2 = fetch_barrier.clone(); let return_barrier = Arc::new(AssertUnwindSafe(Barrier::new(2))); let return_barrier2 = return_barrier.clone(); runner.get_single_job(channel::dummy_sender(), move |job| { fetch_barrier.0.wait(); // Tell thread 2 it can lock its job assert_eq!(first_job_id, job.id); return_barrier.0.wait(); // Wait for thread 2 to lock its job Ok(()) }); fetch_barrier2.0.wait(); // Wait until thread 1 locks its job runner.get_single_job(channel::dummy_sender(), move |job| { assert_eq!(second_job_id, job.id); return_barrier2.0.wait(); // Tell thread 1 it can unlock its job Ok(()) }); runner.wait_for_jobs().unwrap(); } #[test] fn jobs_are_deleted_when_successfully_run() { let _guard = TestGuard::lock(); let runner = runner(); create_dummy_job(&runner); runner.get_single_job(channel::dummy_sender(), |_| Ok(())); runner.wait_for_jobs().unwrap(); let remaining_jobs = background_jobs .count() .get_result(&*runner.connection().unwrap()); assert_eq!(Ok(0), remaining_jobs); } #[test] fn failed_jobs_do_not_release_lock_before_updating_retry_time() { let _guard = TestGuard::lock(); let runner = runner(); create_dummy_job(&runner); let barrier = Arc::new(AssertUnwindSafe(Barrier::new(2))); let barrier2 = barrier.clone(); runner.get_single_job(channel::dummy_sender(), move |_| { barrier.0.wait(); // error so the job goes back into the queue Err("nope".into()) }); let conn = runner.connection().unwrap(); // Wait for the first thread to acquire the lock barrier2.0.wait(); // We are intentionally not using `get_single_job` here. // `SKIP LOCKED` is intentionally omitted here, so we block until // the lock on the first job is released. // If there is any point where the row is unlocked, but the retry // count is not updated, we will get a row here. let available_jobs = background_jobs .select(id) .filter(retries.eq(0)) .for_update() .load::<i64>(&*conn) .unwrap(); assert_eq!(0, available_jobs.len()); // Sanity check to make sure the job actually is there let total_jobs_including_failed = background_jobs .select(id) .for_update() .load::<i64>(&*conn) .unwrap(); assert_eq!(1, total_jobs_including_failed.len()); runner.wait_for_jobs().unwrap(); } #[test] fn panicking_in_jobs_updates_retry_counter() { let _guard = TestGuard::lock(); let runner = runner(); let job_id = create_dummy_job(&runner).id; runner.get_single_job(channel::dummy_sender(), |_| panic!()); runner.wait_for_jobs().unwrap(); let tries = background_jobs .find(job_id) .select(retries) .for_update() .first::<i32>(&*runner.connection().unwrap()) .unwrap(); assert_eq!(1, tries); } lazy_static::lazy_static! { // Since these tests deal with behavior concerning multiple connections // running concurrently, they have to run outside of a transaction. // Therefore we can't run more than one at a time. // // Rather than forcing the whole suite to be run with `--test-threads 1`, // we just lock these tests instead. static ref TEST_MUTEX: Mutex<()> = Mutex::new(()); } struct TestGuard<'a>(MutexGuard<'a, ()>); impl<'a> TestGuard<'a> { fn lock() -> Self { TestGuard(TEST_MUTEX.lock().unwrap()) } } impl<'a> Drop for TestGuard<'a> { fn drop(&mut self) { ::diesel::sql_query("TRUNCATE TABLE background_jobs") .execute(&*runner().connection().unwrap()) .unwrap(); } } type Runner<Env> = crate::Runner<Env, r2d2::Pool<r2d2::ConnectionManager<PgConnection>>>; fn runner() -> Runner<()> { let database_url = dotenv::var("TEST_DATABASE_URL").expect("TEST_DATABASE_URL must be set to run tests"); crate::Runner::builder(()) .database_url(database_url) .thread_count(2) .build() } fn create_dummy_job(runner: &Runner<()>) -> storage::BackgroundJob { ::diesel::insert_into(background_jobs) .values((job_type.eq("Foo"), data.eq(serde_json::json!(null)))) .returning((id, job_type, data)) .get_result(&*runner.connection().unwrap()) .unwrap() } }
Runner
identifier_name
runner.rs
use diesel::prelude::*; #[cfg(feature = "r2d2")] use diesel::r2d2; use std::any::Any; use std::error::Error; use std::panic::{catch_unwind, AssertUnwindSafe, PanicInfo, RefUnwindSafe, UnwindSafe}; use std::sync::Arc; use std::time::Duration; use threadpool::ThreadPool; use crate::db::*; use crate::errors::*; use crate::{storage, Registry}; use event::*; mod channel; mod event; pub struct NoConnectionPoolGiven; #[allow(missing_debug_implementations)] pub struct Builder<Env, ConnectionPoolBuilder> { connection_pool_or_builder: ConnectionPoolBuilder, environment: Env, thread_count: Option<usize>, job_start_timeout: Option<Duration>, } impl<Env, ConnectionPoolBuilder> Builder<Env, ConnectionPoolBuilder> { /// Set the number of threads to be used to run jobs concurrently. /// /// Defaults to 5 pub fn thread_count(mut self, thread_count: usize) -> Self { self.thread_count = Some(thread_count); self } fn get_thread_count(&self) -> usize { self.thread_count.unwrap_or(5) } /// The amount of time to wait for a job to start before assuming an error /// has occurred. /// /// Defaults to 10 seconds. pub fn job_start_timeout(mut self, timeout: Duration) -> Self { self.job_start_timeout = Some(timeout); self } /// Provide a connection pool to be used by the runner pub fn connection_pool<NewPool>(self, pool: NewPool) -> Builder<Env, NewPool> { Builder { connection_pool_or_builder: pool, environment: self.environment, thread_count: self.thread_count, job_start_timeout: self.job_start_timeout, } } } #[cfg(feature = "r2d2")] impl<Env, ConnectionPoolBuilder> Builder<Env, ConnectionPoolBuilder> { /// Build the runner with an r2d2 connection pool /// /// This will override any connection pool previously provided pub fn database_url<S: Into<String>>(self, database_url: S) -> Builder<Env, R2d2Builder> { self.connection_pool_builder(database_url, r2d2::Builder::new()) } /// Provide a connection pool builder. /// /// This will override any connection pool previously provided. /// /// You should call this method if you want to provide additional /// configuration for the database connection pool. The builder will be /// configured to have its max size set to the value given to `2 * thread_count`. /// To override this behavior, call [`connection_count`](Self::connection_count) pub fn connection_pool_builder<S: Into<String>>( self, database_url: S, builder: r2d2::Builder<r2d2::ConnectionManager<PgConnection>>, ) -> Builder<Env, R2d2Builder> { self.connection_pool(R2d2Builder::new(database_url.into(), builder)) } } #[cfg(feature = "r2d2")] impl<Env> Builder<Env, R2d2Builder> { /// Set the max size of the database connection pool pub fn connection_count(mut self, connection_count: u32) -> Self { self.connection_pool_or_builder .connection_count(connection_count); self } /// Build the runner with an r2d2 connection pool. pub fn build(self) -> Runner<Env, r2d2::Pool<r2d2::ConnectionManager<PgConnection>>> { let thread_count = self.get_thread_count(); let connection_pool_size = thread_count as u32 * 2; let connection_pool = self.connection_pool_or_builder.build(connection_pool_size); Runner { connection_pool, thread_pool: ThreadPool::new(thread_count), environment: Arc::new(self.environment), registry: Arc::new(Registry::load()), job_start_timeout: self.job_start_timeout.unwrap_or(Duration::from_secs(10)), } } } impl<Env, ConnectionPool> Builder<Env, ConnectionPool> where ConnectionPool: DieselPool, { /// Build the runner pub fn build(self) -> Runner<Env, ConnectionPool> { Runner { thread_pool: ThreadPool::new(self.get_thread_count()), connection_pool: self.connection_pool_or_builder, environment: Arc::new(self.environment), registry: Arc::new(Registry::load()), job_start_timeout: self.job_start_timeout.unwrap_or(Duration::from_secs(10)), } } } #[allow(missing_debug_implementations)] /// The core runner responsible for locking and running jobs pub struct Runner<Env: 'static, ConnectionPool> { connection_pool: ConnectionPool, thread_pool: ThreadPool, environment: Arc<Env>, registry: Arc<Registry<Env>>, job_start_timeout: Duration, } impl<Env> Runner<Env, NoConnectionPoolGiven> { /// Create a builder for a job runner /// /// This method takes the two required configurations, the database /// connection pool, and the environment to pass to your jobs. If your /// environment contains a connection pool, it should be the same pool given /// here. pub fn builder(environment: Env) -> Builder<Env, NoConnectionPoolGiven> { Builder { connection_pool_or_builder: NoConnectionPoolGiven, environment, thread_count: None, job_start_timeout: None, } } } impl<Env, ConnectionPool> Runner<Env, ConnectionPool> { #[doc(hidden)] /// For use in integration tests pub fn connection_pool(&self) -> &ConnectionPool { &self.connection_pool } } impl<Env, ConnectionPool> Runner<Env, ConnectionPool> where Env: RefUnwindSafe + Send + Sync + 'static, ConnectionPool: DieselPool + 'static, { /// Runs all pending jobs in the queue /// /// This function will return once all jobs in the queue have begun running, /// but does not wait for them to complete. When this function returns, at /// least one thread will have tried to acquire a new job, and found there /// were none in the queue. pub fn run_all_pending_jobs(&self) -> Result<(), FetchError<ConnectionPool>> { use std::cmp::max; let max_threads = self.thread_pool.max_count(); let (sender, receiver) = channel::new(max_threads); let mut pending_messages = 0; loop { let available_threads = max_threads - self.thread_pool.active_count(); let jobs_to_queue = if pending_messages == 0 { // If we have no queued jobs talking to us, and there are no // available threads, we still need to queue at least one job // or we'll never receive a message max(available_threads, 1) } else { available_threads }; for _ in 0..jobs_to_queue { self.run_single_job(sender.clone()); } pending_messages += jobs_to_queue; match receiver.recv_timeout(self.job_start_timeout) { Ok(Event::Working) => pending_messages -= 1, Ok(Event::NoJobAvailable) => return Ok(()), Ok(Event::ErrorLoadingJob(e)) => return Err(FetchError::FailedLoadingJob(e)), Ok(Event::FailedToAcquireConnection(e)) => { return Err(FetchError::NoDatabaseConnection(e)); } Err(_) => return Err(FetchError::NoMessageReceived), } } } fn run_single_job(&self, sender: EventSender<ConnectionPool>) { let environment = Arc::clone(&self.environment); let registry = Arc::clone(&self.registry); // FIXME: https://github.com/sfackler/r2d2/pull/70 let connection_pool = AssertUnwindSafe(self.connection_pool().clone()); self.get_single_job(sender, move |job| { let perform_job = registry .get(&job.job_type) .ok_or_else(|| PerformError::from(format!("Unknown job type {}", job.job_type)))?; perform_job.perform(job.data, &environment, &connection_pool.0) }) } fn get_single_job<F>(&self, sender: EventSender<ConnectionPool>, f: F) where F: FnOnce(storage::BackgroundJob) -> Result<(), PerformError> + Send + UnwindSafe + 'static, { use diesel::result::Error::RollbackTransaction; // The connection may not be `Send` so we need to clone the pool instead let pool = self.connection_pool.clone(); self.thread_pool.execute(move || { let conn = match pool.get() { Ok(conn) => conn, Err(e) => { sender.send(Event::FailedToAcquireConnection(e)); return; } }; let job_run_result = conn.transaction::<_, diesel::result::Error, _>(|| { let job = match storage::find_next_unlocked_job(&conn).optional() { Ok(Some(j)) => { sender.send(Event::Working); j } Ok(None) => { sender.send(Event::NoJobAvailable); return Ok(()); } Err(e) => { sender.send(Event::ErrorLoadingJob(e)); return Err(RollbackTransaction); } }; let job_id = job.id; let result = catch_unwind(|| f(job)) .map_err(|e| try_to_extract_panic_info(&e)) .and_then(|r| r); match result { Ok(_) => storage::delete_successful_job(&conn, job_id)?, Err(e) =>
} Ok(()) }); match job_run_result { Ok(_) | Err(RollbackTransaction) => {} Err(e) => { panic!("Failed to update job: {:?}", e); } } }) } fn connection(&self) -> Result<DieselPooledConn<ConnectionPool>, Box<dyn Error + Send + Sync>> { self.connection_pool.get().map_err(Into::into) } /// Waits for all running jobs to complete, and returns an error if any /// failed /// /// This function is intended for use in tests. If any jobs have failed, it /// will return `swirl::JobsFailed` with the number of jobs that failed. /// /// If any other unexpected errors occurred, such as panicked worker threads /// or an error loading the job count from the database, an opaque error /// will be returned. pub fn check_for_failed_jobs(&self) -> Result<(), FailedJobsError> { self.wait_for_jobs()?; let failed_jobs = storage::failed_job_count(&*self.connection()?)?; if failed_jobs == 0 { Ok(()) } else { Err(JobsFailed(failed_jobs)) } } fn wait_for_jobs(&self) -> Result<(), Box<dyn Error + Send + Sync>> { self.thread_pool.join(); let panic_count = self.thread_pool.panic_count(); if panic_count == 0 { Ok(()) } else { Err(format!("{} threads panicked", panic_count).into()) } } } /// Try to figure out what's in the box, and print it if we can. /// /// The actual error type we will get from `panic::catch_unwind` is really poorly documented. /// However, the `panic::set_hook` functions deal with a `PanicInfo` type, and its payload is /// documented as "commonly but not always `&'static str` or `String`". So we can try all of those, /// and give up if we didn't get one of those three types. fn try_to_extract_panic_info(info: &(dyn Any + Send + 'static)) -> PerformError { if let Some(x) = info.downcast_ref::<PanicInfo>() { format!("job panicked: {}", x).into() } else if let Some(x) = info.downcast_ref::<&'static str>() { format!("job panicked: {}", x).into() } else if let Some(x) = info.downcast_ref::<String>() { format!("job panicked: {}", x).into() } else { "job panicked".into() } } #[cfg(test)] mod tests { use diesel::prelude::*; use diesel::r2d2; use super::*; use crate::schema::background_jobs::dsl::*; use std::panic::AssertUnwindSafe; use std::sync::{Arc, Barrier, Mutex, MutexGuard}; #[test] fn jobs_are_locked_when_fetched() { let _guard = TestGuard::lock(); let runner = runner(); let first_job_id = create_dummy_job(&runner).id; let second_job_id = create_dummy_job(&runner).id; let fetch_barrier = Arc::new(AssertUnwindSafe(Barrier::new(2))); let fetch_barrier2 = fetch_barrier.clone(); let return_barrier = Arc::new(AssertUnwindSafe(Barrier::new(2))); let return_barrier2 = return_barrier.clone(); runner.get_single_job(channel::dummy_sender(), move |job| { fetch_barrier.0.wait(); // Tell thread 2 it can lock its job assert_eq!(first_job_id, job.id); return_barrier.0.wait(); // Wait for thread 2 to lock its job Ok(()) }); fetch_barrier2.0.wait(); // Wait until thread 1 locks its job runner.get_single_job(channel::dummy_sender(), move |job| { assert_eq!(second_job_id, job.id); return_barrier2.0.wait(); // Tell thread 1 it can unlock its job Ok(()) }); runner.wait_for_jobs().unwrap(); } #[test] fn jobs_are_deleted_when_successfully_run() { let _guard = TestGuard::lock(); let runner = runner(); create_dummy_job(&runner); runner.get_single_job(channel::dummy_sender(), |_| Ok(())); runner.wait_for_jobs().unwrap(); let remaining_jobs = background_jobs .count() .get_result(&*runner.connection().unwrap()); assert_eq!(Ok(0), remaining_jobs); } #[test] fn failed_jobs_do_not_release_lock_before_updating_retry_time() { let _guard = TestGuard::lock(); let runner = runner(); create_dummy_job(&runner); let barrier = Arc::new(AssertUnwindSafe(Barrier::new(2))); let barrier2 = barrier.clone(); runner.get_single_job(channel::dummy_sender(), move |_| { barrier.0.wait(); // error so the job goes back into the queue Err("nope".into()) }); let conn = runner.connection().unwrap(); // Wait for the first thread to acquire the lock barrier2.0.wait(); // We are intentionally not using `get_single_job` here. // `SKIP LOCKED` is intentionally omitted here, so we block until // the lock on the first job is released. // If there is any point where the row is unlocked, but the retry // count is not updated, we will get a row here. let available_jobs = background_jobs .select(id) .filter(retries.eq(0)) .for_update() .load::<i64>(&*conn) .unwrap(); assert_eq!(0, available_jobs.len()); // Sanity check to make sure the job actually is there let total_jobs_including_failed = background_jobs .select(id) .for_update() .load::<i64>(&*conn) .unwrap(); assert_eq!(1, total_jobs_including_failed.len()); runner.wait_for_jobs().unwrap(); } #[test] fn panicking_in_jobs_updates_retry_counter() { let _guard = TestGuard::lock(); let runner = runner(); let job_id = create_dummy_job(&runner).id; runner.get_single_job(channel::dummy_sender(), |_| panic!()); runner.wait_for_jobs().unwrap(); let tries = background_jobs .find(job_id) .select(retries) .for_update() .first::<i32>(&*runner.connection().unwrap()) .unwrap(); assert_eq!(1, tries); } lazy_static::lazy_static! { // Since these tests deal with behavior concerning multiple connections // running concurrently, they have to run outside of a transaction. // Therefore we can't run more than one at a time. // // Rather than forcing the whole suite to be run with `--test-threads 1`, // we just lock these tests instead. static ref TEST_MUTEX: Mutex<()> = Mutex::new(()); } struct TestGuard<'a>(MutexGuard<'a, ()>); impl<'a> TestGuard<'a> { fn lock() -> Self { TestGuard(TEST_MUTEX.lock().unwrap()) } } impl<'a> Drop for TestGuard<'a> { fn drop(&mut self) { ::diesel::sql_query("TRUNCATE TABLE background_jobs") .execute(&*runner().connection().unwrap()) .unwrap(); } } type Runner<Env> = crate::Runner<Env, r2d2::Pool<r2d2::ConnectionManager<PgConnection>>>; fn runner() -> Runner<()> { let database_url = dotenv::var("TEST_DATABASE_URL").expect("TEST_DATABASE_URL must be set to run tests"); crate::Runner::builder(()) .database_url(database_url) .thread_count(2) .build() } fn create_dummy_job(runner: &Runner<()>) -> storage::BackgroundJob { ::diesel::insert_into(background_jobs) .values((job_type.eq("Foo"), data.eq(serde_json::json!(null)))) .returning((id, job_type, data)) .get_result(&*runner.connection().unwrap()) .unwrap() } }
{ eprintln!("Job {} failed to run: {}", job_id, e); storage::update_failed_job(&conn, job_id); }
conditional_block
runner.rs
use diesel::prelude::*; #[cfg(feature = "r2d2")] use diesel::r2d2; use std::any::Any; use std::error::Error; use std::panic::{catch_unwind, AssertUnwindSafe, PanicInfo, RefUnwindSafe, UnwindSafe}; use std::sync::Arc; use std::time::Duration; use threadpool::ThreadPool; use crate::db::*; use crate::errors::*; use crate::{storage, Registry}; use event::*; mod channel; mod event; pub struct NoConnectionPoolGiven; #[allow(missing_debug_implementations)] pub struct Builder<Env, ConnectionPoolBuilder> { connection_pool_or_builder: ConnectionPoolBuilder, environment: Env, thread_count: Option<usize>, job_start_timeout: Option<Duration>, } impl<Env, ConnectionPoolBuilder> Builder<Env, ConnectionPoolBuilder> { /// Set the number of threads to be used to run jobs concurrently. /// /// Defaults to 5 pub fn thread_count(mut self, thread_count: usize) -> Self { self.thread_count = Some(thread_count); self } fn get_thread_count(&self) -> usize
/// The amount of time to wait for a job to start before assuming an error /// has occurred. /// /// Defaults to 10 seconds. pub fn job_start_timeout(mut self, timeout: Duration) -> Self { self.job_start_timeout = Some(timeout); self } /// Provide a connection pool to be used by the runner pub fn connection_pool<NewPool>(self, pool: NewPool) -> Builder<Env, NewPool> { Builder { connection_pool_or_builder: pool, environment: self.environment, thread_count: self.thread_count, job_start_timeout: self.job_start_timeout, } } } #[cfg(feature = "r2d2")] impl<Env, ConnectionPoolBuilder> Builder<Env, ConnectionPoolBuilder> { /// Build the runner with an r2d2 connection pool /// /// This will override any connection pool previously provided pub fn database_url<S: Into<String>>(self, database_url: S) -> Builder<Env, R2d2Builder> { self.connection_pool_builder(database_url, r2d2::Builder::new()) } /// Provide a connection pool builder. /// /// This will override any connection pool previously provided. /// /// You should call this method if you want to provide additional /// configuration for the database connection pool. The builder will be /// configured to have its max size set to the value given to `2 * thread_count`. /// To override this behavior, call [`connection_count`](Self::connection_count) pub fn connection_pool_builder<S: Into<String>>( self, database_url: S, builder: r2d2::Builder<r2d2::ConnectionManager<PgConnection>>, ) -> Builder<Env, R2d2Builder> { self.connection_pool(R2d2Builder::new(database_url.into(), builder)) } } #[cfg(feature = "r2d2")] impl<Env> Builder<Env, R2d2Builder> { /// Set the max size of the database connection pool pub fn connection_count(mut self, connection_count: u32) -> Self { self.connection_pool_or_builder .connection_count(connection_count); self } /// Build the runner with an r2d2 connection pool. pub fn build(self) -> Runner<Env, r2d2::Pool<r2d2::ConnectionManager<PgConnection>>> { let thread_count = self.get_thread_count(); let connection_pool_size = thread_count as u32 * 2; let connection_pool = self.connection_pool_or_builder.build(connection_pool_size); Runner { connection_pool, thread_pool: ThreadPool::new(thread_count), environment: Arc::new(self.environment), registry: Arc::new(Registry::load()), job_start_timeout: self.job_start_timeout.unwrap_or(Duration::from_secs(10)), } } } impl<Env, ConnectionPool> Builder<Env, ConnectionPool> where ConnectionPool: DieselPool, { /// Build the runner pub fn build(self) -> Runner<Env, ConnectionPool> { Runner { thread_pool: ThreadPool::new(self.get_thread_count()), connection_pool: self.connection_pool_or_builder, environment: Arc::new(self.environment), registry: Arc::new(Registry::load()), job_start_timeout: self.job_start_timeout.unwrap_or(Duration::from_secs(10)), } } } #[allow(missing_debug_implementations)] /// The core runner responsible for locking and running jobs pub struct Runner<Env: 'static, ConnectionPool> { connection_pool: ConnectionPool, thread_pool: ThreadPool, environment: Arc<Env>, registry: Arc<Registry<Env>>, job_start_timeout: Duration, } impl<Env> Runner<Env, NoConnectionPoolGiven> { /// Create a builder for a job runner /// /// This method takes the two required configurations, the database /// connection pool, and the environment to pass to your jobs. If your /// environment contains a connection pool, it should be the same pool given /// here. pub fn builder(environment: Env) -> Builder<Env, NoConnectionPoolGiven> { Builder { connection_pool_or_builder: NoConnectionPoolGiven, environment, thread_count: None, job_start_timeout: None, } } } impl<Env, ConnectionPool> Runner<Env, ConnectionPool> { #[doc(hidden)] /// For use in integration tests pub fn connection_pool(&self) -> &ConnectionPool { &self.connection_pool } } impl<Env, ConnectionPool> Runner<Env, ConnectionPool> where Env: RefUnwindSafe + Send + Sync + 'static, ConnectionPool: DieselPool + 'static, { /// Runs all pending jobs in the queue /// /// This function will return once all jobs in the queue have begun running, /// but does not wait for them to complete. When this function returns, at /// least one thread will have tried to acquire a new job, and found there /// were none in the queue. pub fn run_all_pending_jobs(&self) -> Result<(), FetchError<ConnectionPool>> { use std::cmp::max; let max_threads = self.thread_pool.max_count(); let (sender, receiver) = channel::new(max_threads); let mut pending_messages = 0; loop { let available_threads = max_threads - self.thread_pool.active_count(); let jobs_to_queue = if pending_messages == 0 { // If we have no queued jobs talking to us, and there are no // available threads, we still need to queue at least one job // or we'll never receive a message max(available_threads, 1) } else { available_threads }; for _ in 0..jobs_to_queue { self.run_single_job(sender.clone()); } pending_messages += jobs_to_queue; match receiver.recv_timeout(self.job_start_timeout) { Ok(Event::Working) => pending_messages -= 1, Ok(Event::NoJobAvailable) => return Ok(()), Ok(Event::ErrorLoadingJob(e)) => return Err(FetchError::FailedLoadingJob(e)), Ok(Event::FailedToAcquireConnection(e)) => { return Err(FetchError::NoDatabaseConnection(e)); } Err(_) => return Err(FetchError::NoMessageReceived), } } } fn run_single_job(&self, sender: EventSender<ConnectionPool>) { let environment = Arc::clone(&self.environment); let registry = Arc::clone(&self.registry); // FIXME: https://github.com/sfackler/r2d2/pull/70 let connection_pool = AssertUnwindSafe(self.connection_pool().clone()); self.get_single_job(sender, move |job| { let perform_job = registry .get(&job.job_type) .ok_or_else(|| PerformError::from(format!("Unknown job type {}", job.job_type)))?; perform_job.perform(job.data, &environment, &connection_pool.0) }) } fn get_single_job<F>(&self, sender: EventSender<ConnectionPool>, f: F) where F: FnOnce(storage::BackgroundJob) -> Result<(), PerformError> + Send + UnwindSafe + 'static, { use diesel::result::Error::RollbackTransaction; // The connection may not be `Send` so we need to clone the pool instead let pool = self.connection_pool.clone(); self.thread_pool.execute(move || { let conn = match pool.get() { Ok(conn) => conn, Err(e) => { sender.send(Event::FailedToAcquireConnection(e)); return; } }; let job_run_result = conn.transaction::<_, diesel::result::Error, _>(|| { let job = match storage::find_next_unlocked_job(&conn).optional() { Ok(Some(j)) => { sender.send(Event::Working); j } Ok(None) => { sender.send(Event::NoJobAvailable); return Ok(()); } Err(e) => { sender.send(Event::ErrorLoadingJob(e)); return Err(RollbackTransaction); } }; let job_id = job.id; let result = catch_unwind(|| f(job)) .map_err(|e| try_to_extract_panic_info(&e)) .and_then(|r| r); match result { Ok(_) => storage::delete_successful_job(&conn, job_id)?, Err(e) => { eprintln!("Job {} failed to run: {}", job_id, e); storage::update_failed_job(&conn, job_id); } } Ok(()) }); match job_run_result { Ok(_) | Err(RollbackTransaction) => {} Err(e) => { panic!("Failed to update job: {:?}", e); } } }) } fn connection(&self) -> Result<DieselPooledConn<ConnectionPool>, Box<dyn Error + Send + Sync>> { self.connection_pool.get().map_err(Into::into) } /// Waits for all running jobs to complete, and returns an error if any /// failed /// /// This function is intended for use in tests. If any jobs have failed, it /// will return `swirl::JobsFailed` with the number of jobs that failed. /// /// If any other unexpected errors occurred, such as panicked worker threads /// or an error loading the job count from the database, an opaque error /// will be returned. pub fn check_for_failed_jobs(&self) -> Result<(), FailedJobsError> { self.wait_for_jobs()?; let failed_jobs = storage::failed_job_count(&*self.connection()?)?; if failed_jobs == 0 { Ok(()) } else { Err(JobsFailed(failed_jobs)) } } fn wait_for_jobs(&self) -> Result<(), Box<dyn Error + Send + Sync>> { self.thread_pool.join(); let panic_count = self.thread_pool.panic_count(); if panic_count == 0 { Ok(()) } else { Err(format!("{} threads panicked", panic_count).into()) } } } /// Try to figure out what's in the box, and print it if we can. /// /// The actual error type we will get from `panic::catch_unwind` is really poorly documented. /// However, the `panic::set_hook` functions deal with a `PanicInfo` type, and its payload is /// documented as "commonly but not always `&'static str` or `String`". So we can try all of those, /// and give up if we didn't get one of those three types. fn try_to_extract_panic_info(info: &(dyn Any + Send + 'static)) -> PerformError { if let Some(x) = info.downcast_ref::<PanicInfo>() { format!("job panicked: {}", x).into() } else if let Some(x) = info.downcast_ref::<&'static str>() { format!("job panicked: {}", x).into() } else if let Some(x) = info.downcast_ref::<String>() { format!("job panicked: {}", x).into() } else { "job panicked".into() } } #[cfg(test)] mod tests { use diesel::prelude::*; use diesel::r2d2; use super::*; use crate::schema::background_jobs::dsl::*; use std::panic::AssertUnwindSafe; use std::sync::{Arc, Barrier, Mutex, MutexGuard}; #[test] fn jobs_are_locked_when_fetched() { let _guard = TestGuard::lock(); let runner = runner(); let first_job_id = create_dummy_job(&runner).id; let second_job_id = create_dummy_job(&runner).id; let fetch_barrier = Arc::new(AssertUnwindSafe(Barrier::new(2))); let fetch_barrier2 = fetch_barrier.clone(); let return_barrier = Arc::new(AssertUnwindSafe(Barrier::new(2))); let return_barrier2 = return_barrier.clone(); runner.get_single_job(channel::dummy_sender(), move |job| { fetch_barrier.0.wait(); // Tell thread 2 it can lock its job assert_eq!(first_job_id, job.id); return_barrier.0.wait(); // Wait for thread 2 to lock its job Ok(()) }); fetch_barrier2.0.wait(); // Wait until thread 1 locks its job runner.get_single_job(channel::dummy_sender(), move |job| { assert_eq!(second_job_id, job.id); return_barrier2.0.wait(); // Tell thread 1 it can unlock its job Ok(()) }); runner.wait_for_jobs().unwrap(); } #[test] fn jobs_are_deleted_when_successfully_run() { let _guard = TestGuard::lock(); let runner = runner(); create_dummy_job(&runner); runner.get_single_job(channel::dummy_sender(), |_| Ok(())); runner.wait_for_jobs().unwrap(); let remaining_jobs = background_jobs .count() .get_result(&*runner.connection().unwrap()); assert_eq!(Ok(0), remaining_jobs); } #[test] fn failed_jobs_do_not_release_lock_before_updating_retry_time() { let _guard = TestGuard::lock(); let runner = runner(); create_dummy_job(&runner); let barrier = Arc::new(AssertUnwindSafe(Barrier::new(2))); let barrier2 = barrier.clone(); runner.get_single_job(channel::dummy_sender(), move |_| { barrier.0.wait(); // error so the job goes back into the queue Err("nope".into()) }); let conn = runner.connection().unwrap(); // Wait for the first thread to acquire the lock barrier2.0.wait(); // We are intentionally not using `get_single_job` here. // `SKIP LOCKED` is intentionally omitted here, so we block until // the lock on the first job is released. // If there is any point where the row is unlocked, but the retry // count is not updated, we will get a row here. let available_jobs = background_jobs .select(id) .filter(retries.eq(0)) .for_update() .load::<i64>(&*conn) .unwrap(); assert_eq!(0, available_jobs.len()); // Sanity check to make sure the job actually is there let total_jobs_including_failed = background_jobs .select(id) .for_update() .load::<i64>(&*conn) .unwrap(); assert_eq!(1, total_jobs_including_failed.len()); runner.wait_for_jobs().unwrap(); } #[test] fn panicking_in_jobs_updates_retry_counter() { let _guard = TestGuard::lock(); let runner = runner(); let job_id = create_dummy_job(&runner).id; runner.get_single_job(channel::dummy_sender(), |_| panic!()); runner.wait_for_jobs().unwrap(); let tries = background_jobs .find(job_id) .select(retries) .for_update() .first::<i32>(&*runner.connection().unwrap()) .unwrap(); assert_eq!(1, tries); } lazy_static::lazy_static! { // Since these tests deal with behavior concerning multiple connections // running concurrently, they have to run outside of a transaction. // Therefore we can't run more than one at a time. // // Rather than forcing the whole suite to be run with `--test-threads 1`, // we just lock these tests instead. static ref TEST_MUTEX: Mutex<()> = Mutex::new(()); } struct TestGuard<'a>(MutexGuard<'a, ()>); impl<'a> TestGuard<'a> { fn lock() -> Self { TestGuard(TEST_MUTEX.lock().unwrap()) } } impl<'a> Drop for TestGuard<'a> { fn drop(&mut self) { ::diesel::sql_query("TRUNCATE TABLE background_jobs") .execute(&*runner().connection().unwrap()) .unwrap(); } } type Runner<Env> = crate::Runner<Env, r2d2::Pool<r2d2::ConnectionManager<PgConnection>>>; fn runner() -> Runner<()> { let database_url = dotenv::var("TEST_DATABASE_URL").expect("TEST_DATABASE_URL must be set to run tests"); crate::Runner::builder(()) .database_url(database_url) .thread_count(2) .build() } fn create_dummy_job(runner: &Runner<()>) -> storage::BackgroundJob { ::diesel::insert_into(background_jobs) .values((job_type.eq("Foo"), data.eq(serde_json::json!(null)))) .returning((id, job_type, data)) .get_result(&*runner.connection().unwrap()) .unwrap() } }
{ self.thread_count.unwrap_or(5) }
identifier_body
runner.rs
use diesel::prelude::*; #[cfg(feature = "r2d2")] use diesel::r2d2; use std::any::Any; use std::error::Error; use std::panic::{catch_unwind, AssertUnwindSafe, PanicInfo, RefUnwindSafe, UnwindSafe}; use std::sync::Arc; use std::time::Duration; use threadpool::ThreadPool; use crate::db::*; use crate::errors::*; use crate::{storage, Registry}; use event::*; mod channel; mod event; pub struct NoConnectionPoolGiven; #[allow(missing_debug_implementations)] pub struct Builder<Env, ConnectionPoolBuilder> { connection_pool_or_builder: ConnectionPoolBuilder, environment: Env, thread_count: Option<usize>, job_start_timeout: Option<Duration>, } impl<Env, ConnectionPoolBuilder> Builder<Env, ConnectionPoolBuilder> { /// Set the number of threads to be used to run jobs concurrently. /// /// Defaults to 5 pub fn thread_count(mut self, thread_count: usize) -> Self { self.thread_count = Some(thread_count); self } fn get_thread_count(&self) -> usize { self.thread_count.unwrap_or(5) } /// The amount of time to wait for a job to start before assuming an error /// has occurred. /// /// Defaults to 10 seconds. pub fn job_start_timeout(mut self, timeout: Duration) -> Self { self.job_start_timeout = Some(timeout); self } /// Provide a connection pool to be used by the runner pub fn connection_pool<NewPool>(self, pool: NewPool) -> Builder<Env, NewPool> { Builder { connection_pool_or_builder: pool, environment: self.environment, thread_count: self.thread_count, job_start_timeout: self.job_start_timeout, } } } #[cfg(feature = "r2d2")] impl<Env, ConnectionPoolBuilder> Builder<Env, ConnectionPoolBuilder> { /// Build the runner with an r2d2 connection pool /// /// This will override any connection pool previously provided pub fn database_url<S: Into<String>>(self, database_url: S) -> Builder<Env, R2d2Builder> { self.connection_pool_builder(database_url, r2d2::Builder::new()) } /// Provide a connection pool builder. /// /// This will override any connection pool previously provided. /// /// You should call this method if you want to provide additional /// configuration for the database connection pool. The builder will be /// configured to have its max size set to the value given to `2 * thread_count`. /// To override this behavior, call [`connection_count`](Self::connection_count) pub fn connection_pool_builder<S: Into<String>>( self, database_url: S, builder: r2d2::Builder<r2d2::ConnectionManager<PgConnection>>, ) -> Builder<Env, R2d2Builder> { self.connection_pool(R2d2Builder::new(database_url.into(), builder)) } } #[cfg(feature = "r2d2")] impl<Env> Builder<Env, R2d2Builder> { /// Set the max size of the database connection pool pub fn connection_count(mut self, connection_count: u32) -> Self { self.connection_pool_or_builder .connection_count(connection_count); self } /// Build the runner with an r2d2 connection pool. pub fn build(self) -> Runner<Env, r2d2::Pool<r2d2::ConnectionManager<PgConnection>>> { let thread_count = self.get_thread_count(); let connection_pool_size = thread_count as u32 * 2; let connection_pool = self.connection_pool_or_builder.build(connection_pool_size); Runner { connection_pool, thread_pool: ThreadPool::new(thread_count), environment: Arc::new(self.environment), registry: Arc::new(Registry::load()), job_start_timeout: self.job_start_timeout.unwrap_or(Duration::from_secs(10)), } } } impl<Env, ConnectionPool> Builder<Env, ConnectionPool> where ConnectionPool: DieselPool, { /// Build the runner pub fn build(self) -> Runner<Env, ConnectionPool> { Runner { thread_pool: ThreadPool::new(self.get_thread_count()), connection_pool: self.connection_pool_or_builder, environment: Arc::new(self.environment), registry: Arc::new(Registry::load()), job_start_timeout: self.job_start_timeout.unwrap_or(Duration::from_secs(10)), } } } #[allow(missing_debug_implementations)] /// The core runner responsible for locking and running jobs pub struct Runner<Env: 'static, ConnectionPool> { connection_pool: ConnectionPool, thread_pool: ThreadPool,
environment: Arc<Env>, registry: Arc<Registry<Env>>, job_start_timeout: Duration, } impl<Env> Runner<Env, NoConnectionPoolGiven> { /// Create a builder for a job runner /// /// This method takes the two required configurations, the database /// connection pool, and the environment to pass to your jobs. If your /// environment contains a connection pool, it should be the same pool given /// here. pub fn builder(environment: Env) -> Builder<Env, NoConnectionPoolGiven> { Builder { connection_pool_or_builder: NoConnectionPoolGiven, environment, thread_count: None, job_start_timeout: None, } } } impl<Env, ConnectionPool> Runner<Env, ConnectionPool> { #[doc(hidden)] /// For use in integration tests pub fn connection_pool(&self) -> &ConnectionPool { &self.connection_pool } } impl<Env, ConnectionPool> Runner<Env, ConnectionPool> where Env: RefUnwindSafe + Send + Sync + 'static, ConnectionPool: DieselPool + 'static, { /// Runs all pending jobs in the queue /// /// This function will return once all jobs in the queue have begun running, /// but does not wait for them to complete. When this function returns, at /// least one thread will have tried to acquire a new job, and found there /// were none in the queue. pub fn run_all_pending_jobs(&self) -> Result<(), FetchError<ConnectionPool>> { use std::cmp::max; let max_threads = self.thread_pool.max_count(); let (sender, receiver) = channel::new(max_threads); let mut pending_messages = 0; loop { let available_threads = max_threads - self.thread_pool.active_count(); let jobs_to_queue = if pending_messages == 0 { // If we have no queued jobs talking to us, and there are no // available threads, we still need to queue at least one job // or we'll never receive a message max(available_threads, 1) } else { available_threads }; for _ in 0..jobs_to_queue { self.run_single_job(sender.clone()); } pending_messages += jobs_to_queue; match receiver.recv_timeout(self.job_start_timeout) { Ok(Event::Working) => pending_messages -= 1, Ok(Event::NoJobAvailable) => return Ok(()), Ok(Event::ErrorLoadingJob(e)) => return Err(FetchError::FailedLoadingJob(e)), Ok(Event::FailedToAcquireConnection(e)) => { return Err(FetchError::NoDatabaseConnection(e)); } Err(_) => return Err(FetchError::NoMessageReceived), } } } fn run_single_job(&self, sender: EventSender<ConnectionPool>) { let environment = Arc::clone(&self.environment); let registry = Arc::clone(&self.registry); // FIXME: https://github.com/sfackler/r2d2/pull/70 let connection_pool = AssertUnwindSafe(self.connection_pool().clone()); self.get_single_job(sender, move |job| { let perform_job = registry .get(&job.job_type) .ok_or_else(|| PerformError::from(format!("Unknown job type {}", job.job_type)))?; perform_job.perform(job.data, &environment, &connection_pool.0) }) } fn get_single_job<F>(&self, sender: EventSender<ConnectionPool>, f: F) where F: FnOnce(storage::BackgroundJob) -> Result<(), PerformError> + Send + UnwindSafe + 'static, { use diesel::result::Error::RollbackTransaction; // The connection may not be `Send` so we need to clone the pool instead let pool = self.connection_pool.clone(); self.thread_pool.execute(move || { let conn = match pool.get() { Ok(conn) => conn, Err(e) => { sender.send(Event::FailedToAcquireConnection(e)); return; } }; let job_run_result = conn.transaction::<_, diesel::result::Error, _>(|| { let job = match storage::find_next_unlocked_job(&conn).optional() { Ok(Some(j)) => { sender.send(Event::Working); j } Ok(None) => { sender.send(Event::NoJobAvailable); return Ok(()); } Err(e) => { sender.send(Event::ErrorLoadingJob(e)); return Err(RollbackTransaction); } }; let job_id = job.id; let result = catch_unwind(|| f(job)) .map_err(|e| try_to_extract_panic_info(&e)) .and_then(|r| r); match result { Ok(_) => storage::delete_successful_job(&conn, job_id)?, Err(e) => { eprintln!("Job {} failed to run: {}", job_id, e); storage::update_failed_job(&conn, job_id); } } Ok(()) }); match job_run_result { Ok(_) | Err(RollbackTransaction) => {} Err(e) => { panic!("Failed to update job: {:?}", e); } } }) } fn connection(&self) -> Result<DieselPooledConn<ConnectionPool>, Box<dyn Error + Send + Sync>> { self.connection_pool.get().map_err(Into::into) } /// Waits for all running jobs to complete, and returns an error if any /// failed /// /// This function is intended for use in tests. If any jobs have failed, it /// will return `swirl::JobsFailed` with the number of jobs that failed. /// /// If any other unexpected errors occurred, such as panicked worker threads /// or an error loading the job count from the database, an opaque error /// will be returned. pub fn check_for_failed_jobs(&self) -> Result<(), FailedJobsError> { self.wait_for_jobs()?; let failed_jobs = storage::failed_job_count(&*self.connection()?)?; if failed_jobs == 0 { Ok(()) } else { Err(JobsFailed(failed_jobs)) } } fn wait_for_jobs(&self) -> Result<(), Box<dyn Error + Send + Sync>> { self.thread_pool.join(); let panic_count = self.thread_pool.panic_count(); if panic_count == 0 { Ok(()) } else { Err(format!("{} threads panicked", panic_count).into()) } } } /// Try to figure out what's in the box, and print it if we can. /// /// The actual error type we will get from `panic::catch_unwind` is really poorly documented. /// However, the `panic::set_hook` functions deal with a `PanicInfo` type, and its payload is /// documented as "commonly but not always `&'static str` or `String`". So we can try all of those, /// and give up if we didn't get one of those three types. fn try_to_extract_panic_info(info: &(dyn Any + Send + 'static)) -> PerformError { if let Some(x) = info.downcast_ref::<PanicInfo>() { format!("job panicked: {}", x).into() } else if let Some(x) = info.downcast_ref::<&'static str>() { format!("job panicked: {}", x).into() } else if let Some(x) = info.downcast_ref::<String>() { format!("job panicked: {}", x).into() } else { "job panicked".into() } } #[cfg(test)] mod tests { use diesel::prelude::*; use diesel::r2d2; use super::*; use crate::schema::background_jobs::dsl::*; use std::panic::AssertUnwindSafe; use std::sync::{Arc, Barrier, Mutex, MutexGuard}; #[test] fn jobs_are_locked_when_fetched() { let _guard = TestGuard::lock(); let runner = runner(); let first_job_id = create_dummy_job(&runner).id; let second_job_id = create_dummy_job(&runner).id; let fetch_barrier = Arc::new(AssertUnwindSafe(Barrier::new(2))); let fetch_barrier2 = fetch_barrier.clone(); let return_barrier = Arc::new(AssertUnwindSafe(Barrier::new(2))); let return_barrier2 = return_barrier.clone(); runner.get_single_job(channel::dummy_sender(), move |job| { fetch_barrier.0.wait(); // Tell thread 2 it can lock its job assert_eq!(first_job_id, job.id); return_barrier.0.wait(); // Wait for thread 2 to lock its job Ok(()) }); fetch_barrier2.0.wait(); // Wait until thread 1 locks its job runner.get_single_job(channel::dummy_sender(), move |job| { assert_eq!(second_job_id, job.id); return_barrier2.0.wait(); // Tell thread 1 it can unlock its job Ok(()) }); runner.wait_for_jobs().unwrap(); } #[test] fn jobs_are_deleted_when_successfully_run() { let _guard = TestGuard::lock(); let runner = runner(); create_dummy_job(&runner); runner.get_single_job(channel::dummy_sender(), |_| Ok(())); runner.wait_for_jobs().unwrap(); let remaining_jobs = background_jobs .count() .get_result(&*runner.connection().unwrap()); assert_eq!(Ok(0), remaining_jobs); } #[test] fn failed_jobs_do_not_release_lock_before_updating_retry_time() { let _guard = TestGuard::lock(); let runner = runner(); create_dummy_job(&runner); let barrier = Arc::new(AssertUnwindSafe(Barrier::new(2))); let barrier2 = barrier.clone(); runner.get_single_job(channel::dummy_sender(), move |_| { barrier.0.wait(); // error so the job goes back into the queue Err("nope".into()) }); let conn = runner.connection().unwrap(); // Wait for the first thread to acquire the lock barrier2.0.wait(); // We are intentionally not using `get_single_job` here. // `SKIP LOCKED` is intentionally omitted here, so we block until // the lock on the first job is released. // If there is any point where the row is unlocked, but the retry // count is not updated, we will get a row here. let available_jobs = background_jobs .select(id) .filter(retries.eq(0)) .for_update() .load::<i64>(&*conn) .unwrap(); assert_eq!(0, available_jobs.len()); // Sanity check to make sure the job actually is there let total_jobs_including_failed = background_jobs .select(id) .for_update() .load::<i64>(&*conn) .unwrap(); assert_eq!(1, total_jobs_including_failed.len()); runner.wait_for_jobs().unwrap(); } #[test] fn panicking_in_jobs_updates_retry_counter() { let _guard = TestGuard::lock(); let runner = runner(); let job_id = create_dummy_job(&runner).id; runner.get_single_job(channel::dummy_sender(), |_| panic!()); runner.wait_for_jobs().unwrap(); let tries = background_jobs .find(job_id) .select(retries) .for_update() .first::<i32>(&*runner.connection().unwrap()) .unwrap(); assert_eq!(1, tries); } lazy_static::lazy_static! { // Since these tests deal with behavior concerning multiple connections // running concurrently, they have to run outside of a transaction. // Therefore we can't run more than one at a time. // // Rather than forcing the whole suite to be run with `--test-threads 1`, // we just lock these tests instead. static ref TEST_MUTEX: Mutex<()> = Mutex::new(()); } struct TestGuard<'a>(MutexGuard<'a, ()>); impl<'a> TestGuard<'a> { fn lock() -> Self { TestGuard(TEST_MUTEX.lock().unwrap()) } } impl<'a> Drop for TestGuard<'a> { fn drop(&mut self) { ::diesel::sql_query("TRUNCATE TABLE background_jobs") .execute(&*runner().connection().unwrap()) .unwrap(); } } type Runner<Env> = crate::Runner<Env, r2d2::Pool<r2d2::ConnectionManager<PgConnection>>>; fn runner() -> Runner<()> { let database_url = dotenv::var("TEST_DATABASE_URL").expect("TEST_DATABASE_URL must be set to run tests"); crate::Runner::builder(()) .database_url(database_url) .thread_count(2) .build() } fn create_dummy_job(runner: &Runner<()>) -> storage::BackgroundJob { ::diesel::insert_into(background_jobs) .values((job_type.eq("Foo"), data.eq(serde_json::json!(null)))) .returning((id, job_type, data)) .get_result(&*runner.connection().unwrap()) .unwrap() } }
random_line_split
tool.ts
import {spellInfo} from './spellToWord'; import {has} from './util'; import Dict from '../dict'; import {AllArgs, ICnChar, TypeProp, ToneType, SpellArg, StrokeArg, TypeValueObject} from 'cnchar-types/main/index'; import {Json, ITransformReturn} from 'cnchar-types/main/common'; import {TSpellArg, IDealUpLowFirst, IRemoveTone, IFunc, ICheckArgs, ITransformTone} from 'cnchar-types/main/tool'; import {_warn, isCnChar} from '@common/util'; export const tones: string = 'āáǎàōóǒòēéěèīíǐìūúǔùǖǘǚǜ*ńňǹ'; // * 表示n的一声 const noTones: string = 'aoeiuün'; export const arg: TSpellArg = { array: 'array', low: 'low', up: 'up', first: 'first', poly: 'poly', tone: 'tone', simple: 'simple', trad: 'trad', flat: 'flat', }; let _cnchar: ICnChar; export function initCnchar (cnchar: ICnChar): void { _cnchar = cnchar; } export function getCnChar () { return _cnchar; } const NOT_CNCHAR: string = 'NOT_CNCHAR'; export function spell (dict: Json<string>, originArgs: Array<string>): string | Array<string> { const strs = originArgs[0].split(''); const args = (originArgs.splice(1)) as Array<SpellArg>; checkArgs('spell', args); const poly = has(args, arg.poly); const tone = has(args, arg.tone); const res: Array<Array<string>> = []; for (const sp in dict) { // 遍历拼音 const ds: string = dict[sp]; // 某个拼音的所有汉字字符串 const pos = parseInt(ds[0]); // 某个拼音的音调位置 for (let i = 0; i < strs.length; i++) { // 遍历字符数组 const ch: string = strs[i]; const addIntoPolyRes = (spell: string) => { isDefaultSpell(ch, spell) ? res[i].unshift(spell) : res[i].push(spell); }; if (isCnChar(ch)) { // 如果是汉字 let index = ds.indexOf(ch); if (index !== -1) { const ssp = getSpell(sp, ds, index, poly, tone, pos); // single spell if (ssp.poly) { // 多音字模式 且 当前汉字是多音字 if (!res[i]) res[i] = []; addIntoPolyRes(ssp.res); let dsNew = ds; const n = (dsNew.match(new RegExp(ch, 'g')) as Array<string>).length; for (let k = 1; k < n; k++) { dsNew = dsNew.substr(index + 2); index = dsNew.indexOf(ch); addIntoPolyRes(getSpell(sp, dsNew, index, poly, tone, pos).res); } } else { if (ssp.isPolyWord) { // 是多音字 不是多音字模式 if (Dict.spellDefault[ch]) { // 设置了多音字的默认拼音 ssp.res = removeTone(Dict.spellDefault[ch], tone).spell; // 默认有音调 } } res[i] = [ssp.res]; strs[i] = ''; } } } else if (ch !== '') { // 如果不是汉字 res[i] = [NOT_CNCHAR, ch]; } } } dealUpLowFirst(res, args); // 从res中读取数据 const result: Array<string> = []; for (let i = 0; i < strs.length; i++) { const item = res[i]; if (typeof item === 'undefined') { result[i] = strs[i]; // 查不到的汉字返回原字 } else if (item.length > 1) { if (item[0] === NOT_CNCHAR) { result[i] = item[1]; // 非汉字返回原字符 } else { result[i] = `(${item.join('|')})`; } } else { result[i] = item[0]; } if (has(args, arg.flat) && has(args, arg.tone)) { result[i] = shapeSpell(result[i], true); } } if (!has(args, arg.array)) { return result.join(''); } return result; } export const dealUpLowFirst: IDealUpLowFirst = ( res: Array<Array<string>> | Array<string>, args: Array<SpellArg> ): void => { if (_cnchar._.poly) { dealResCase(res, low); // 当启用了 多音词时 需要强制默认小写 // 因为会被覆盖 } if (has(args, arg.first)) { dealResCase(res, first); } if (has(args, arg.up)) { dealResCase(res, up); } else if (!has(args, arg.low)) { dealResCase(res, upFirst); } }; function dealResCase ( res: Array<Array<string>> | Array<string>, func:(str: string) => string ): void { res.forEach((item: Array<string> | string, index: number) => { if (typeof item !== 'string') { if (item[0] !== NOT_CNCHAR) { item.forEach((s, j) => {item[j] = func(s);}); } } else { res[index] = func(item); } }); } function first (s: string): string { return s[0]; } function up (s: string): string { return s.toUpperCase(); } function upFirst (s: string): string { return up(s[0]) + s.substr(1); } function low (s: string): string { return s.toLowerCase(); } function getSpell ( spell: string, str: string, index: number, isPoly: boolean, isTone: boolean, pos: number ): { res: string, poly: boolean, isPolyWord: boolean } { let tone = parseInt(str[index + 1]); const res = {res: spell, poly: false, isPolyWord: (tone >= 5)}; if (!isPoly && !isTone) { return res; } if (res.isPolyWord) { // 是多音字 tone -= 5; // 正确的音调 if (isPoly) { // 既是多音字模式 又是 多音字 res.poly = true; } } if (isTone) { res.res = setTone(spell, pos, tone as ToneType); } return res; } function isDefaultSpell (word: string, spell: string) { const def = Dict.spellDefault[word]; if (!def) return false; return def === spell || (shapeSpell(def, true).replace(/[0-4]/, '') === spell); } // tone=false : 根据有音调的拼音获得无音调的拼音和音调 // tone=true : 返回原拼音 export const removeTone: IRemoveTone = (spell: string, tone: boolean): { spell: string, tone?: ToneType, index?: number } => { if (tone) { return {spell}; } for (let i = 0; i < spell.length; i++) { const index: number = tones.indexOf(spell[i]); if (index !== -1) { // 命中 return { spell: spell.substr(0, i) + noTones[Math.floor(index / 4)] + spell.substr(i + 1), tone: ((index % 4) + 1) as ToneType, index: i + 1 }; } } return {spell, tone: 0, index: -1}; }; /** * 给拼音添加音调 * setTone('ni', 1, 3) = nǐ */ export function setTone (spell: string, index: number, tone: ToneType): string { if (tone === 0) { // 轻声 return spell; } const p = spell[index]; const toneP = tones[noTones.indexOf(p) * 4 + (tone - 1)]; if (p !== toneP) { return spell.replace(p, toneP); } return spell; } // 计算笔画基础方法 export function stroke ( dict: Json<string>, originArgs: Array<string> ): number | Array<number> { const strs = originArgs[0].split(''); const strokes: Array<number> = []; const args = originArgs.splice(1) as Array<StrokeArg>; checkArgs('stroke', args); for (const i in dict) { for (let j = 0; j < strs.length; j++) { if (strs[j]) { if (dict[i].indexOf(strs[j] as string) !== -1) { strs[j] = ''; strokes[j] = parseInt(i); } } } } strs.forEach((c: string, i: number): void => { if (c) {strokes[i] = 0;} }); if (!has(args, arg.array as StrokeArg)) { return sumStroke(strokes); } return strokes; } export const sumStroke: IFunc<number, Array<number>> = (strs: Array<number>): number => { let sum: number = 0; strs.forEach(function (c) { sum += c; }); return sum; }; /* 检查cnchar中某方法 传入的参数是否合法 spell 所有参数 ["array", "low", "up", "first", "poly", "tone", "simple"] // simple 禁用繁体字 stroke 所有参数 ["letter", "shape", "count", "name", "detail", "array", "order", "simple"] */ let _hasCheck: boolean = false; export const checkArgs: ICheckArgs = ( type: TypeProp, args: Array<AllArgs>, jumpNext?: boolean ): void => { if (!_cnchar.check) { return; } if (_hasCheck) { _hasCheck = false; return; } if (jumpNext) { _hasCheck = true; } const useless: Array<AllArgs> = []; for (let i = args.length - 1; i >= 0; i--) { const arg = args[i]; if (!(_cnchar.type[type] as TypeValueObject)[arg]) { useless.push(arg); args.splice(i, 1); } } const ignore: Array<AllArgs> = []; const redunt: Array<AllArgs> = []; const check = (name: AllArgs | Array<AllArgs>, arr: Array<AllArgs> = ignore): void => { if (name instanceof Array) { name.forEach((item) => { check(item, arr); }); return; } if (has(args, name)) { arr.push(name); } }; if (_cnchar.plugins.indexOf('trad') === -1) { if (has(args, 'simple')) ignore.push('simple'); if (has(args, 'trad')) ignore.push('trad'); } if (type === 'spell') { if (has(args, 'up') && has(args, 'low')) { ignore.push('low'); } // t.spell.origin 表示启用了多音词 // !has(args,'origin') 表示没有禁用多音词 // 此时的 poly 就会被忽略 // if(t.spell.origin && !has(args,'origin') && has(args,'poly')){ // ignore.push('poly'); // } } else if (type === 'stroke') { // stroke if (has(args, 'order')) { // 笔画顺序模式 check('array', redunt); // detail > shape > name > count > letter 默认值是 letter if (has(args, 'letter')) { check(['detail', 'shape', 'name', 'count']); check('letter', redunt); } else if (has(args, 'detail')) { check(['shape', 'name', 'count']); } else if (has(args, 'shape')) { check(['name', 'count']); } else if (has(args, 'name')) { check(['count']); } } else { // 笔画数模式 check(['detail', 'shape', 'name', 'letter']); check('count', redunt); } } else if (type === 'orderToWord') { if (has(args, 'match')) { check(['matchorder', 'contain', 'start']); } else if (has(args, 'matchorder')) { check(['contain', 'start']); } else if (has(args, 'contain')) { check(['start']); } } else if (type === 'strokeToWord') { } else if (type === 'spellToWord') { } else if (type === 'idiom') { if (has(args, 'spell')) { check(['stroke', 'char']); } else if (has(args, 'stroke')) { check(['tone', 'char']); } else { check(['tone']); } } else if (type === 'xhy') { } else if (type === 'radical') {
warnArgs(useless, '无效', type, args); warnArgs(ignore, '被忽略', type, args); warnArgs(redunt, '冗余', type, args); }; function warnArgs ( arr: Array<AllArgs>, txt: string, type: TypeProp, args: Array<AllArgs> ): void { if (arr.length > 0) { let mes: string = `以下参数${txt}:${JSON.stringify(arr)};`; if (txt === '被忽略' && type === 'stroke' && !has(args, 'order')) { mes += ' 要启用笔顺模式必须使用 order 参数'; } else { mes += ` 可选值:[${Object.keys((_cnchar.type[type] as TypeValueObject))}]`; } _warn(mes); } } /* 将拼音转换成含有音调的拼音 lv2 => lǘ reverse=true: lǘ => lv2 */ export function shapeSpell (spell: string, reverse: boolean = false): string { const tones: string = '01234'; const hasNumTone = tones.indexOf(spell[spell.length - 1]) !== -1; if (!reverse) { return hasNumTone ? transformTone(spell, true, 'low').spell : spell; } if (hasNumTone) { return spell; } const info = transformTone(spell, false, 'low'); if (info.spell.indexOf('ü') !== -1) { info.spell = info.spell.replace('ü', 'v'); } return hasNumTone ? spell : info.spell + info.tone; } /* 将拼音转换成json数据 lv2 => {spell:'lü', tone: 2, index: 2, isTrans: true} lǘ => {spell:'lü', tone: 2, index: 2, isTrans: false} needTone = true: lv2 => {spell:'lǘ', tone: 2, index: 2, isTrans: true} */ export const transformTone: ITransformTone = ( spell: string, needTone: boolean = false, type: 'low' | 'up' = 'low' ): ITransformReturn => { if (spell.indexOf('v') !== -1) { spell = spell.replace('v', 'ü'); } const lastStr: string = spell[spell.length - 1]; let tone: ToneType; let index: number = -1; let isTrans: boolean = false; if (parseInt(lastStr).toString() === lastStr) { // lv2 spell = spell.substr(0, spell.length - 1); const info = spellInfo(spell); index = info.index; tone = parseInt(lastStr) as ToneType; isTrans = true; if (needTone) { spell = setTone(spell, index - 1, tone); } } else { // lǘ const info = spellInfo(spell); index = info.index; tone = info.tone; // 声调已经带好了的情况 if (!needTone && tone !== 0) { // 需要去除音调并且有音调 spell = info.spell; } } if (type === 'low') { spell = spell.toLowerCase(); } else if (type === 'up') { spell = spell.toUpperCase(); } return {spell, tone, index, isTrans}; }; export function checkTrad (input: string|string[], args: string[]) { if (args.indexOf('trad') === -1 || _cnchar.plugins.indexOf('trad') === -1) { return input; } let isArr = false; if (input instanceof Array) { isArr = true; input = input.join(''); } input = _cnchar.convert.tradToSimple(input); if (isArr) return input.split(''); return input; }
}
random_line_split
tool.ts
import {spellInfo} from './spellToWord'; import {has} from './util'; import Dict from '../dict'; import {AllArgs, ICnChar, TypeProp, ToneType, SpellArg, StrokeArg, TypeValueObject} from 'cnchar-types/main/index'; import {Json, ITransformReturn} from 'cnchar-types/main/common'; import {TSpellArg, IDealUpLowFirst, IRemoveTone, IFunc, ICheckArgs, ITransformTone} from 'cnchar-types/main/tool'; import {_warn, isCnChar} from '@common/util'; export const tones: string = 'āáǎàōóǒòēéěèīíǐìūúǔùǖǘǚǜ*ńňǹ'; // * 表示n的一声 const noTones: string = 'aoeiuün'; export const arg: TSpellArg = { array: 'array', low: 'low', up: 'up', first: 'first', poly: 'poly', tone: 'tone', simple: 'simple', trad: 'trad', flat: 'flat', }; let _cnchar: ICnChar; export function initCnchar (cnchar: ICnChar): void {
= cnchar; } export function getCnChar () { return _cnchar; } const NOT_CNCHAR: string = 'NOT_CNCHAR'; export function spell (dict: Json<string>, originArgs: Array<string>): string | Array<string> { const strs = originArgs[0].split(''); const args = (originArgs.splice(1)) as Array<SpellArg>; checkArgs('spell', args); const poly = has(args, arg.poly); const tone = has(args, arg.tone); const res: Array<Array<string>> = []; for (const sp in dict) { // 遍历拼音 const ds: string = dict[sp]; // 某个拼音的所有汉字字符串 const pos = parseInt(ds[0]); // 某个拼音的音调位置 for (let i = 0; i < strs.length; i++) { // 遍历字符数组 const ch: string = strs[i]; const addIntoPolyRes = (spell: string) => { isDefaultSpell(ch, spell) ? res[i].unshift(spell) : res[i].push(spell); }; if (isCnChar(ch)) { // 如果是汉字 let index = ds.indexOf(ch); if (index !== -1) { const ssp = getSpell(sp, ds, index, poly, tone, pos); // single spell if (ssp.poly) { // 多音字模式 且 当前汉字是多音字 if (!res[i]) res[i] = []; addIntoPolyRes(ssp.res); let dsNew = ds; const n = (dsNew.match(new RegExp(ch, 'g')) as Array<string>).length; for (let k = 1; k < n; k++) { dsNew = dsNew.substr(index + 2); index = dsNew.indexOf(ch); addIntoPolyRes(getSpell(sp, dsNew, index, poly, tone, pos).res); } } else { if (ssp.isPolyWord) { // 是多音字 不是多音字模式 if (Dict.spellDefault[ch]) { // 设置了多音字的默认拼音 ssp.res = removeTone(Dict.spellDefault[ch], tone).spell; // 默认有音调 } } res[i] = [ssp.res]; strs[i] = ''; } } } else if (ch !== '') { // 如果不是汉字 res[i] = [NOT_CNCHAR, ch]; } } } dealUpLowFirst(res, args); // 从res中读取数据 const result: Array<string> = []; for (let i = 0; i < strs.length; i++) { const item = res[i]; if (typeof item === 'undefined') { result[i] = strs[i]; // 查不到的汉字返回原字 } else if (item.length > 1) { if (item[0] === NOT_CNCHAR) { result[i] = item[1]; // 非汉字返回原字符 } else { result[i] = `(${item.join('|')})`; } } else { result[i] = item[0]; } if (has(args, arg.flat) && has(args, arg.tone)) { result[i] = shapeSpell(result[i], true); } } if (!has(args, arg.array)) { return result.join(''); } return result; } export const dealUpLowFirst: IDealUpLowFirst = ( res: Array<Array<string>> | Array<string>, args: Array<SpellArg> ): void => { if (_cnchar._.poly) { dealResCase(res, low); // 当启用了 多音词时 需要强制默认小写 // 因为会被覆盖 } if (has(args, arg.first)) { dealResCase(res, first); } if (has(args, arg.up)) { dealResCase(res, up); } else if (!has(args, arg.low)) { dealResCase(res, upFirst); } }; function dealResCase ( res: Array<Array<string>> | Array<string>, func:(str: string) => string ): void { res.forEach((item: Array<string> | string, index: number) => { if (typeof item !== 'string') { if (item[0] !== NOT_CNCHAR) { item.forEach((s, j) => {item[j] = func(s);}); } } else { res[index] = func(item); } }); } function first (s: string): string { return s[0]; } function up (s: string): string { return s.toUpperCase(); } function upFirst (s: string): string { return up(s[0]) + s.substr(1); } function low (s: string): string { return s.toLowerCase(); } function getSpell ( spell: string, str: string, index: number, isPoly: boolean, isTone: boolean, pos: number ): { res: string, poly: boolean, isPolyWord: boolean } { let tone = parseInt(str[index + 1]); const res = {res: spell, poly: false, isPolyWord: (tone >= 5)}; if (!isPoly && !isTone) { return res; } if (res.isPolyWord) { // 是多音字 tone -= 5; // 正确的音调 if (isPoly) { // 既是多音字模式 又是 多音字 res.poly = true; } } if (isTone) { res.res = setTone(spell, pos, tone as ToneType); } return res; } function isDefaultSpell (word: string, spell: string) { const def = Dict.spellDefault[word]; if (!def) return false; return def === spell || (shapeSpell(def, true).replace(/[0-4]/, '') === spell); } // tone=false : 根据有音调的拼音获得无音调的拼音和音调 // tone=true : 返回原拼音 export const removeTone: IRemoveTone = (spell: string, tone: boolean): { spell: string, tone?: ToneType, index?: number } => { if (tone) { return {spell}; } for (let i = 0; i < spell.length; i++) { const index: number = tones.indexOf(spell[i]); if (index !== -1) { // 命中 return { spell: spell.substr(0, i) + noTones[Math.floor(index / 4)] + spell.substr(i + 1), tone: ((index % 4) + 1) as ToneType, index: i + 1 }; } } return {spell, tone: 0, index: -1}; }; /** * 给拼音添加音调 * setTone('ni', 1, 3) = nǐ */ export function setTone (spell: string, index: number, tone: ToneType): string { if (tone === 0) { // 轻声 return spell; } const p = spell[index]; const toneP = tones[noTones.indexOf(p) * 4 + (tone - 1)]; if (p !== toneP) { return spell.replace(p, toneP); } return spell; } // 计算笔画基础方法 export function stroke ( dict: Json<string>, originArgs: Array<string> ): number | Array<number> { const strs = originArgs[0].split(''); const strokes: Array<number> = []; const args = originArgs.splice(1) as Array<StrokeArg>; checkArgs('stroke', args); for (const i in dict) { for (let j = 0; j < strs.length; j++) { if (strs[j]) { if (dict[i].indexOf(strs[j] as string) !== -1) { strs[j] = ''; strokes[j] = parseInt(i); } } } } strs.forEach((c: string, i: number): void => { if (c) {strokes[i] = 0;} }); if (!has(args, arg.array as StrokeArg)) { return sumStroke(strokes); } return strokes; } export const sumStroke: IFunc<number, Array<number>> = (strs: Array<number>): number => { let sum: number = 0; strs.forEach(function (c) { sum += c; }); return sum; }; /* 检查cnchar中某方法 传入的参数是否合法 spell 所有参数 ["array", "low", "up", "first", "poly", "tone", "simple"] // simple 禁用繁体字 stroke 所有参数 ["letter", "shape", "count", "name", "detail", "array", "order", "simple"] */ let _hasCheck: boolean = false; export const checkArgs: ICheckArgs = ( type: TypeProp, args: Array<AllArgs>, jumpNext?: boolean ): void => { if (!_cnchar.check) { return; } if (_hasCheck) { _hasCheck = false; return; } if (jumpNext) { _hasCheck = true; } const useless: Array<AllArgs> = []; for (let i = args.length - 1; i >= 0; i--) { const arg = args[i]; if (!(_cnchar.type[type] as TypeValueObject)[arg]) { useless.push(arg); args.splice(i, 1); } } const ignore: Array<AllArgs> = []; const redunt: Array<AllArgs> = []; const check = (name: AllArgs | Array<AllArgs>, arr: Array<AllArgs> = ignore): void => { if (name instanceof Array) { name.forEach((item) => { check(item, arr); }); return; } if (has(args, name)) { arr.push(name); } }; if (_cnchar.plugins.indexOf('trad') === -1) { if (has(args, 'simple')) ignore.push('simple'); if (has(args, 'trad')) ignore.push('trad'); } if (type === 'spell') { if (has(args, 'up') && has(args, 'low')) { ignore.push('low'); } // t.spell.origin 表示启用了多音词 // !has(args,'origin') 表示没有禁用多音词 // 此时的 poly 就会被忽略 // if(t.spell.origin && !has(args,'origin') && has(args,'poly')){ // ignore.push('poly'); // } } else if (type === 'stroke') { // stroke if (has(args, 'order')) { // 笔画顺序模式 check('array', redunt); // detail > shape > name > count > letter 默认值是 letter if (has(args, 'letter')) { check(['detail', 'shape', 'name', 'count']); check('letter', redunt); } else if (has(args, 'detail')) { check(['shape', 'name', 'count']); } else if (has(args, 'shape')) { check(['name', 'count']); } else if (has(args, 'name')) { check(['count']); } } else { // 笔画数模式 check(['detail', 'shape', 'name', 'letter']); check('count', redunt); } } else if (type === 'orderToWord') { if (has(args, 'match')) { check(['matchorder', 'contain', 'start']); } else if (has(args, 'matchorder')) { check(['contain', 'start']); } else if (has(args, 'contain')) { check(['start']); } } else if (type === 'strokeToWord') { } else if (type === 'spellToWord') { } else if (type === 'idiom') { if (has(args, 'spell')) { check(['stroke', 'char']); } else if (has(args, 'stroke')) { check(['tone', 'char']); } else { check(['tone']); } } else if (type === 'xhy') { } else if (type === 'radical') { } warnArgs(useless, '无效', type, args); warnArgs(ignore, '被忽略', type, args); warnArgs(redunt, '冗余', type, args); }; function warnArgs ( arr: Array<AllArgs>, txt: string, type: TypeProp, args: Array<AllArgs> ): void { if (arr.length > 0) { let mes: string = `以下参数${txt}:${JSON.stringify(arr)};`; if (txt === '被忽略' && type === 'stroke' && !has(args, 'order')) { mes += ' 要启用笔顺模式必须使用 order 参数'; } else { mes += ` 可选值:[${Object.keys((_cnchar.type[type] as TypeValueObject))}]`; } _warn(mes); } } /* 将拼音转换成含有音调的拼音 lv2 => lǘ reverse=true: lǘ => lv2 */ export function shapeSpell (spell: string, reverse: boolean = false): string { const tones: string = '01234'; const hasNumTone = tones.indexOf(spell[spell.length - 1]) !== -1; if (!reverse) { return hasNumTone ? transformTone(spell, true, 'low').spell : spell; } if (hasNumTone) { return spell; } const info = transformTone(spell, false, 'low'); if (info.spell.indexOf('ü') !== -1) { info.spell = info.spell.replace('ü', 'v'); } return hasNumTone ? spell : info.spell + info.tone; } /* 将拼音转换成json数据 lv2 => {spell:'lü', tone: 2, index: 2, isTrans: true} lǘ => {spell:'lü', tone: 2, index: 2, isTrans: false} needTone = true: lv2 => {spell:'lǘ', tone: 2, index: 2, isTrans: true} */ export const transformTone: ITransformTone = ( spell: string, needTone: boolean = false, type: 'low' | 'up' = 'low' ): ITransformReturn => { if (spell.indexOf('v') !== -1) { spell = spell.replace('v', 'ü'); } const lastStr: string = spell[spell.length - 1]; let tone: ToneType; let index: number = -1; let isTrans: boolean = false; if (parseInt(lastStr).toString() === lastStr) { // lv2 spell = spell.substr(0, spell.length - 1); const info = spellInfo(spell); index = info.index; tone = parseInt(lastStr) as ToneType; isTrans = true; if (needTone) { spell = setTone(spell, index - 1, tone); } } else { // lǘ const info = spellInfo(spell); index = info.index; tone = info.tone; // 声调已经带好了的情况 if (!needTone && tone !== 0) { // 需要去除音调并且有音调 spell = info.spell; } } if (type === 'low') { spell = spell.toLowerCase(); } else if (type === 'up') { spell = spell.toUpperCase(); } return {spell, tone, index, isTrans}; }; export function checkTrad (input: string|string[], args: string[]) { if (args.indexOf('trad') === -1 || _cnchar.plugins.indexOf('trad') === -1) { return input; } let isArr = false; if (input instanceof Array) { isArr = true; input = input.join(''); } input = _cnchar.convert.tradToSimple(input); if (isArr) return input.split(''); return input; }
_cnchar
identifier_name
tool.ts
import {spellInfo} from './spellToWord'; import {has} from './util'; import Dict from '../dict'; import {AllArgs, ICnChar, TypeProp, ToneType, SpellArg, StrokeArg, TypeValueObject} from 'cnchar-types/main/index'; import {Json, ITransformReturn} from 'cnchar-types/main/common'; import {TSpellArg, IDealUpLowFirst, IRemoveTone, IFunc, ICheckArgs, ITransformTone} from 'cnchar-types/main/tool'; import {_warn, isCnChar} from '@common/util'; export const tones: string = 'āáǎàōóǒòēéěèīíǐìūúǔùǖǘǚǜ*ńňǹ'; // * 表示n的一声 const noTones: string = 'aoeiuün'; export const arg: TSpellArg = { array: 'array', low: 'low', up: 'up', first: 'first', poly: 'poly', tone: 'tone', simple: 'simple', trad: 'trad', flat: 'flat', }; let _cnchar: ICnChar; export function initCnchar (cnchar: ICnChar): void { _cnchar = cnchar; } export function getCnChar () { return _cnchar; } const NOT_CNCHAR: string = 'NOT_CNCHAR'; export function spell (dict: Json<string>, originArgs: Array<string>): string | Array<string> { const strs = originArgs[0].split(''); const args = (originArgs.splice(1)) as Array<SpellArg>; checkArgs('spell', args); const poly = has(args, arg.poly); const tone = has(args, arg.tone); const res: Array<Array<string>> = []; for (const sp in dict) { // 遍历拼音 const ds: string = dict[sp]; // 某个拼音的所有汉字字符串 const pos = parseInt(ds[0]); // 某个拼音的音调位置 for (let i = 0; i < strs.length; i++) { // 遍历字符数组 const ch: string = strs[i]; const addIntoPolyRes = (spell: string) => { isDefaultSpell(ch, spell) ? res[i].unshift(spell) : res[i].push(spell); }; if (isCnChar(ch)) { // 如果是汉字 let index = ds.indexOf(ch); if (index !== -1) { const ssp = getSpell(sp, ds, index, poly, tone, pos); // single spell if (ssp.poly) { // 多音字模式 且 当前汉字是多音字 if (!res[i]) res[i] = []; addIntoPolyRes(ssp.res); let dsNew = ds; const n = (dsNew.match(new RegExp(ch, 'g')) as Array<string>).length; for (let k = 1; k < n; k++) { dsNew = dsNew.substr(index + 2); index = dsNew.indexOf(ch); addIntoPolyRes(getSpell(sp, dsNew, index, poly, tone, pos).res); } } else { if (ssp.isPolyWord) { // 是多音字 不是多音字模式 if (Dict.spellDefault[ch]) { // 设置了多音字的默认拼音 ssp.res = removeTone(Dict.spellDefault[ch], tone).spell; // 默认有音调 } } res[i] = [ssp.res]; strs[i] = ''; } } } else if (ch !== '') { // 如果不是汉字 res[i] = [NOT_CNCHAR, ch]; } } } dealUpLowFirst(res, args); // 从res中读取数据 const result: Array<string> = []; for (let i = 0; i < strs.length; i++) { const item = res[i]; if (typeof item === 'undefined') { result[i] = strs[i]; // 查不到的汉字返回原字 } else if (item.length > 1) { if (item[0] === NOT_CNCHAR) { result[i] = item[1]; // 非汉字返回原字符 } else { result[i] = `(${item.join('|')})`; } } else { result[i] = item[0]; } if (has(args, arg.flat) && has(args, arg.tone)) { result[i] = shapeSpell(result[i], true); } } if (!has(args, arg.array)) { return result.join(''); } return result; } export const dealUpLowFirst: IDealUpLowFirst = ( res: Array<Array<string>> | Array<string>, args: Array<SpellArg> ): void => { if (_cnchar._.poly) { dealResCase(res, low); // 当启用了 多音词时 需要强制默认小写 // 因为会被覆盖 } if (has(args, arg.first)) { dealResCase(res, first); } if (has(args, arg.up)) { dealResCase(res, up); } else if (!has(args, arg.low)) { dealResCase(res, upFirst); } }; function dealResCase ( res: Array<Array<string>> | Array<string>, func:(str: string) => string ): void { res.forEach((item: Array<string> | string, index: number) => { if (typeof item !== 'string') { if (item[0] !== NOT_CNCHAR) { item.forEach((s, j) => {item[j] = func(s);}); } } else { res[index] = func(item); } }); } function first (s: string): string { return s[0]; } function up (s: string): string { return s.toUpperCase(); } function upFirst (s: string): string { return up(s[0]) + s.substr(1); } function low (s: string): string { return s.toLowerCase(); } function getSpell ( spell: string, str: string, index: number, isPoly: boolean, isTone: boolean, pos: number ): { res: string, poly: boolean, isPolyWord: boolean } { let tone = parseInt(str[index + 1]); const res = {res: spell, poly: false, isPolyWord: (tone >= 5)}; if (!isPoly && !isTone) { return res; } if (res.isPolyWord) { // 是多音字 tone -= 5; // 正确的音调 if (isPoly) { // 既是多音字模式 又是 多音字 res.poly = true
n): { spell: string, tone?: ToneType, index?: number } => { if (tone) { return {spell}; } for (let i = 0; i < spell.length; i++) { const index: number = tones.indexOf(spell[i]); if (index !== -1) { // 命中 return { spell: spell.substr(0, i) + noTones[Math.floor(index / 4)] + spell.substr(i + 1), tone: ((index % 4) + 1) as ToneType, index: i + 1 }; } } return {spell, tone: 0, index: -1}; }; /** * 给拼音添加音调 * setTone('ni', 1, 3) = nǐ */ export function setTone (spell: string, index: number, tone: ToneType): string { if (tone === 0) { // 轻声 return spell; } const p = spell[index]; const toneP = tones[noTones.indexOf(p) * 4 + (tone - 1)]; if (p !== toneP) { return spell.replace(p, toneP); } return spell; } // 计算笔画基础方法 export function stroke ( dict: Json<string>, originArgs: Array<string> ): number | Array<number> { const strs = originArgs[0].split(''); const strokes: Array<number> = []; const args = originArgs.splice(1) as Array<StrokeArg>; checkArgs('stroke', args); for (const i in dict) { for (let j = 0; j < strs.length; j++) { if (strs[j]) { if (dict[i].indexOf(strs[j] as string) !== -1) { strs[j] = ''; strokes[j] = parseInt(i); } } } } strs.forEach((c: string, i: number): void => { if (c) {strokes[i] = 0;} }); if (!has(args, arg.array as StrokeArg)) { return sumStroke(strokes); } return strokes; } export const sumStroke: IFunc<number, Array<number>> = (strs: Array<number>): number => { let sum: number = 0; strs.forEach(function (c) { sum += c; }); return sum; }; /* 检查cnchar中某方法 传入的参数是否合法 spell 所有参数 ["array", "low", "up", "first", "poly", "tone", "simple"] // simple 禁用繁体字 stroke 所有参数 ["letter", "shape", "count", "name", "detail", "array", "order", "simple"] */ let _hasCheck: boolean = false; export const checkArgs: ICheckArgs = ( type: TypeProp, args: Array<AllArgs>, jumpNext?: boolean ): void => { if (!_cnchar.check) { return; } if (_hasCheck) { _hasCheck = false; return; } if (jumpNext) { _hasCheck = true; } const useless: Array<AllArgs> = []; for (let i = args.length - 1; i >= 0; i--) { const arg = args[i]; if (!(_cnchar.type[type] as TypeValueObject)[arg]) { useless.push(arg); args.splice(i, 1); } } const ignore: Array<AllArgs> = []; const redunt: Array<AllArgs> = []; const check = (name: AllArgs | Array<AllArgs>, arr: Array<AllArgs> = ignore): void => { if (name instanceof Array) { name.forEach((item) => { check(item, arr); }); return; } if (has(args, name)) { arr.push(name); } }; if (_cnchar.plugins.indexOf('trad') === -1) { if (has(args, 'simple')) ignore.push('simple'); if (has(args, 'trad')) ignore.push('trad'); } if (type === 'spell') { if (has(args, 'up') && has(args, 'low')) { ignore.push('low'); } // t.spell.origin 表示启用了多音词 // !has(args,'origin') 表示没有禁用多音词 // 此时的 poly 就会被忽略 // if(t.spell.origin && !has(args,'origin') && has(args,'poly')){ // ignore.push('poly'); // } } else if (type === 'stroke') { // stroke if (has(args, 'order')) { // 笔画顺序模式 check('array', redunt); // detail > shape > name > count > letter 默认值是 letter if (has(args, 'letter')) { check(['detail', 'shape', 'name', 'count']); check('letter', redunt); } else if (has(args, 'detail')) { check(['shape', 'name', 'count']); } else if (has(args, 'shape')) { check(['name', 'count']); } else if (has(args, 'name')) { check(['count']); } } else { // 笔画数模式 check(['detail', 'shape', 'name', 'letter']); check('count', redunt); } } else if (type === 'orderToWord') { if (has(args, 'match')) { check(['matchorder', 'contain', 'start']); } else if (has(args, 'matchorder')) { check(['contain', 'start']); } else if (has(args, 'contain')) { check(['start']); } } else if (type === 'strokeToWord') { } else if (type === 'spellToWord') { } else if (type === 'idiom') { if (has(args, 'spell')) { check(['stroke', 'char']); } else if (has(args, 'stroke')) { check(['tone', 'char']); } else { check(['tone']); } } else if (type === 'xhy') { } else if (type === 'radical') { } warnArgs(useless, '无效', type, args); warnArgs(ignore, '被忽略', type, args); warnArgs(redunt, '冗余', type, args); }; function warnArgs ( arr: Array<AllArgs>, txt: string, type: TypeProp, args: Array<AllArgs> ): void { if (arr.length > 0) { let mes: string = `以下参数${txt}:${JSON.stringify(arr)};`; if (txt === '被忽略' && type === 'stroke' && !has(args, 'order')) { mes += ' 要启用笔顺模式必须使用 order 参数'; } else { mes += ` 可选值:[${Object.keys((_cnchar.type[type] as TypeValueObject))}]`; } _warn(mes); } } /* 将拼音转换成含有音调的拼音 lv2 => lǘ reverse=true: lǘ => lv2 */ export function shapeSpell (spell: string, reverse: boolean = false): string { const tones: string = '01234'; const hasNumTone = tones.indexOf(spell[spell.length - 1]) !== -1; if (!reverse) { return hasNumTone ? transformTone(spell, true, 'low').spell : spell; } if (hasNumTone) { return spell; } const info = transformTone(spell, false, 'low'); if (info.spell.indexOf('ü') !== -1) { info.spell = info.spell.replace('ü', 'v'); } return hasNumTone ? spell : info.spell + info.tone; } /* 将拼音转换成json数据 lv2 => {spell:'lü', tone: 2, index: 2, isTrans: true} lǘ => {spell:'lü', tone: 2, index: 2, isTrans: false} needTone = true: lv2 => {spell:'lǘ', tone: 2, index: 2, isTrans: true} */ export const transformTone: ITransformTone = ( spell: string, needTone: boolean = false, type: 'low' | 'up' = 'low' ): ITransformReturn => { if (spell.indexOf('v') !== -1) { spell = spell.replace('v', 'ü'); } const lastStr: string = spell[spell.length - 1]; let tone: ToneType; let index: number = -1; let isTrans: boolean = false; if (parseInt(lastStr).toString() === lastStr) { // lv2 spell = spell.substr(0, spell.length - 1); const info = spellInfo(spell); index = info.index; tone = parseInt(lastStr) as ToneType; isTrans = true; if (needTone) { spell = setTone(spell, index - 1, tone); } } else { // lǘ const info = spellInfo(spell); index = info.index; tone = info.tone; // 声调已经带好了的情况 if (!needTone && tone !== 0) { // 需要去除音调并且有音调 spell = info.spell; } } if (type === 'low') { spell = spell.toLowerCase(); } else if (type === 'up') { spell = spell.toUpperCase(); } return {spell, tone, index, isTrans}; }; export function checkTrad (input: string|string[], args: string[]) { if (args.indexOf('trad') === -1 || _cnchar.plugins.indexOf('trad') === -1) { return input; } let isArr = false; if (input instanceof Array) { isArr = true; input = input.join(''); } input = _cnchar.convert.tradToSimple(input); if (isArr) return input.split(''); return input; }
; } } if (isTone) { res.res = setTone(spell, pos, tone as ToneType); } return res; } function isDefaultSpell (word: string, spell: string) { const def = Dict.spellDefault[word]; if (!def) return false; return def === spell || (shapeSpell(def, true).replace(/[0-4]/, '') === spell); } // tone=false : 根据有音调的拼音获得无音调的拼音和音调 // tone=true : 返回原拼音 export const removeTone: IRemoveTone = (spell: string, tone: boolea
identifier_body
tool.ts
import {spellInfo} from './spellToWord'; import {has} from './util'; import Dict from '../dict'; import {AllArgs, ICnChar, TypeProp, ToneType, SpellArg, StrokeArg, TypeValueObject} from 'cnchar-types/main/index'; import {Json, ITransformReturn} from 'cnchar-types/main/common'; import {TSpellArg, IDealUpLowFirst, IRemoveTone, IFunc, ICheckArgs, ITransformTone} from 'cnchar-types/main/tool'; import {_warn, isCnChar} from '@common/util'; export const tones: string = 'āáǎàōóǒòēéěèīíǐìūúǔùǖǘǚǜ*ńňǹ'; // * 表示n的一声 const noTones: string = 'aoeiuün'; export const arg: TSpellArg = { array: 'array', low: 'low', up: 'up', first: 'first', poly: 'poly', tone: 'tone', simple: 'simple', trad: 'trad', flat: 'flat', }; let _cnchar: ICnChar; export function initCnchar (cnchar: ICnChar): void { _cnchar = cnchar; } export function getCnChar () { return _cnchar; } const NOT_CNCHAR: string = 'NOT_CNCHAR'; export function spell (dict: Json<string>, originArgs: Array<string>): string | Array<string> { const strs = originArgs[0].split(''); const args = (originArgs.splice(1)) as Array<SpellArg>; checkArgs('spell', args); const poly = has(args, arg.poly); const tone = has(args, arg.tone); const res: Array<Array<string>> = []; for (const sp in dict) { // 遍历拼音 const ds: string = dict[sp]; // 某个拼音的所有汉字字符串 const pos = parseInt(ds[0]); // 某个拼音的音调位置 for (let i = 0; i < strs.length; i++) { // 遍历字符数组 const ch: string = strs[i]; const addIntoPolyRes = (spell: string) => { isDefaultSpell(ch, spell) ? res[i].unshift(spell) : res[i].push(spell); }; if (isCnChar(ch)) { // 如果是汉字 let index = ds.indexOf(ch); if (index !== -1) { const ssp = getSpell(sp, ds, index, poly, tone, pos); // single spell if (ssp.poly) { // 多音字模式 且 当前汉字是多音字 if (!res[i]) res[i] = []; addIntoPolyRes(ssp.res); let dsNew = ds; const n = (dsNew.match(new RegExp(ch, 'g')) as Array<string>).length; for (let k = 1; k < n; k++) { dsNew = dsNew.substr(index + 2); index = dsNew.indexOf(ch); addIntoPolyRes(getSpell(sp, dsNew, index, poly, tone, pos).res); } } else { if (ssp.isPolyWord) { // 是多音字 不是多音字模式 if (Dict.spellDefault[ch]) { // 设置了多音字的默认拼音 ssp.res = removeTone(Dict.spellDefault[ch], tone).spell; // 默认有音调 } } res[i] = [ssp.res]; strs[i] = ''; } } } else if (ch !== '') { // 如果不是汉字 res[i] = [NOT_CNCHAR, ch]; } } } dealUpLowFirst(res, args); // 从res中读取数据 const result: Array<string> = []; for (let i = 0; i < strs.length; i++) { const item = res[i]; if (typeof item === 'undefined') { result[i] = strs[i]; // 查不到的汉字返回原字 } else if (item.length > 1) { if (item[0] === NOT_CNCHAR) { result[i] = item[1]; // 非汉字返回原字符 } else { result[i] = `(${item.join('|')})`; } } else { result[i] = item[0]; } if (has(args, arg.flat) && has(args, arg.tone)) { result[i] = shapeSpell(result[i], true); } } if (!has(args, arg.array)) { return result.join(''); } return result; } export const dealUpLowFirst: IDealUpLowFirst = ( res: Array<Array<string>> | Array<string>, args: Array<SpellArg> ): void => { if (_cnchar._.poly) { dealResCase(res, low); // 当启用了 多音词时 需要强制默认小写 // 因为会被覆盖 } if (has(args, arg.first)) { dealResCase(res, first); } if (has(args, arg.up)) { dealResCase(res, up); } else if (!has(args, arg.low)) { dealResCase(res, upFirst); } }; function dealResCase ( res: Array<Array<string>> | Array<string>, func:(str: string) => string ): void { res.forEach((item: Array<string> | string, index: number) => { if (typeof item !== 'string') { if (item[0] !== NOT_CNCHAR) { item.forEach((s, j) => {item[j] = func(s);}); } } else { res[index] = func(item); } }); } function first (s: string): string { return s[0]; } function up (s: string): string { return s.toUpperCase(); } function upFirst (s: string): string { return up(s[0]) + s.substr(1); } function low (s: string): string { return s.toLowerCase(); } function getSpell ( spell: string, str: string, index: number, isPoly: boolean, isTone: boolean, pos: number ): { res: string, poly: boolean, isPolyWord: boolean } { let tone = parseInt(str[index + 1]); const res = {res: spell, poly: false, isPolyWord: (tone >= 5)}; if (!isPoly && !isTone) { return res; } if (res.isPolyWord) { // 是多音字 tone -= 5; // 正确的音调 if (isPoly) { // 既是多音字模式 又是 多音字 res.poly = true; } } if (isTone) { res.res = setTone(spell, pos, tone as ToneType); } return res; } function isDefaultSpell (word: string, spell: string) { const def = Dict.spellDefault[word]; if (!def) return false; return def === spell || (shapeSpell(def, true).replace(/[0-4]/, '') === spell); } // tone=false : 根据有音调的拼音获得无音调的拼音和音调 // tone=true : 返回原拼音 export const removeTone: IRemoveTone = (spell: string, tone: boolean): { spell: string, tone?: ToneType, index?: number } => { if (tone) { return {spell}; } for (let i = 0; i < spell.length; i++) { const index: number = tones.indexOf(spell[i]); if (index !== -1) { // 命中 return { spell: spell.substr(0, i) + noTones[Math.floor(index / 4)] + spell.substr(i + 1), tone: ((index % 4) + 1) as ToneType, index: i + 1 }; } } return {spell, tone: 0, index: -1}; }; /** * 给拼音添加音调 * setTone('ni', 1, 3) = nǐ */ export function setTone (spell: string, index: number, tone: ToneType): string { if (tone === 0) { // 轻声 return spell; } const p = spell[index]; const toneP = tones[noTones.indexOf(p) * 4 + (tone - 1)]; if (p !== toneP) { return spell.replace(p, toneP); } return spell; } // 计算笔画基础方法 export function stroke ( dict: Json<string>, originArgs: Array<string> ): number | Array<number> { const strs = originArgs[0].split(''); const strokes: Array<number> = []; const args = originArgs.splice(1) as Array<StrokeArg>; checkArgs('stroke', args); for (const i in dict) { for (let j = 0; j < strs.length; j++) { if (strs[j]) { if (dict[i].indexOf(strs[j] as string) !== -1) { strs[j] = ''; strokes[j] = parseInt(i); } } } } strs.forEach((c: string, i: number): void => { if (c) {strokes[i] = 0;} }); if (!has(args, arg.array as StrokeArg)) { return sumStroke(strokes); } return strokes; } export const sumStroke: IFunc<number, Array<number>> = (strs: Array<number>): number => { let sum: number = 0; strs.forEach(function (c) { sum += c; }); return sum; }; /* 检查cnchar中某方法 传入的参数是否合法 spell 所有参数 ["array", "low", "up", "first", "poly", "tone", "simple"] // simple 禁用繁体字 stroke 所有参数 ["letter", "shape", "count", "name", "detail", "array", "order", "simple"] */ let _hasCheck: boolean = false; export const checkArgs: ICheckArgs = ( type: TypeProp, args: Array<AllArgs>, jumpNext?: boolean ): void => { if (!_cnchar.check) { return; } if (_hasCheck) { _hasCheck = false; return; } if (jumpNext) { _hasCheck = true; } const useless: Array<AllArgs> = []; for (let i = args.length - 1; i >= 0; i--) { const arg = args[i]; if (!(_cnchar.type[type] as TypeValueObject)[arg]) { useless.push(arg); args.splice(i, 1); } } const ignore: Array<AllArgs> = []; const redunt: Array<AllArgs> = []; const check = (name: AllArgs | Array<AllArgs>, arr: Array<AllArgs> = ignore): void => { if (name instanceof Array) { name.forEach((item) => { check(item, arr); }); return; } if (has(args, name)) { arr.push(name); } }; if (_cnchar.plugins.indexOf('trad') === -1) { if (has(args, 'simple')) ignore.push('simple'); if (has(args, 'trad')) ignore.push('trad'); } if (type === 'spell') { if (has(args, 'up') && has(args, 'low')) { ignore.push('low'); } // t.spell.origin 表示启用了多音词 // !has(args,'origin') 表示没有禁用多音词 // 此时的 poly 就会被忽略 // if(t.spell.origin && !has(args,'origin') && has(args,'poly')){ // ignore.push('poly'); // } } else if (type === 'stroke') { // stroke if (has(args, 'order')) { // 笔画顺序模式 check('array', redunt); // detail > shape > name > count > letter 默认值是 letter if (has(args, 'letter')) { check(['detail', 'shape', 'name', 'count']); check('letter', redunt); } else if (has(args, 'detail')) { check(['shape', 'name', 'count']); } else if (has(args, 'shape')) { check(['name', 'count']); } else if (has(args, 'name')) { check(['count']); } } else { // 笔画数模式 check(['detail', 'shape', 'name', 'letter']); check('count', redunt); } } else if (type === 'orderToWord') { if (has(args, 'match')) { check(['matchorder', 'contain', 'start']); } else if (has(args, 'matchorder')) { check(['contain', 'start']); } else if (has(args, 'contain')) { check(['start']); } } else if (type === 'strokeToWord') { } else if (type === 'spellToWord') { } else if (type === 'idiom') { if (has(args, 'spell')) { check(['stroke', 'char']); } else if (has(args, 'stroke')) { check(['tone', 'char']); } else { check(['tone']); } } else if (type === 'xhy') { } else if (type === 'radical') { } warnArgs(useless, '无效', type, args); warnArgs(ignore, '被忽略', type, args); warnArgs(redunt, '冗余', type, args); }; function warnArgs ( arr: Array<AllArgs>, txt: string, type: TypeProp, args: Array<AllArgs> ): void { if (arr.length > 0) {
:[${Object.keys((_cnchar.type[type] as TypeValueObject))}]`; } _warn(mes); } } /* 将拼音转换成含有音调的拼音 lv2 => lǘ reverse=true: lǘ => lv2 */ export function shapeSpell (spell: string, reverse: boolean = false): string { const tones: string = '01234'; const hasNumTone = tones.indexOf(spell[spell.length - 1]) !== -1; if (!reverse) { return hasNumTone ? transformTone(spell, true, 'low').spell : spell; } if (hasNumTone) { return spell; } const info = transformTone(spell, false, 'low'); if (info.spell.indexOf('ü') !== -1) { info.spell = info.spell.replace('ü', 'v'); } return hasNumTone ? spell : info.spell + info.tone; } /* 将拼音转换成json数据 lv2 => {spell:'lü', tone: 2, index: 2, isTrans: true} lǘ => {spell:'lü', tone: 2, index: 2, isTrans: false} needTone = true: lv2 => {spell:'lǘ', tone: 2, index: 2, isTrans: true} */ export const transformTone: ITransformTone = ( spell: string, needTone: boolean = false, type: 'low' | 'up' = 'low' ): ITransformReturn => { if (spell.indexOf('v') !== -1) { spell = spell.replace('v', 'ü'); } const lastStr: string = spell[spell.length - 1]; let tone: ToneType; let index: number = -1; let isTrans: boolean = false; if (parseInt(lastStr).toString() === lastStr) { // lv2 spell = spell.substr(0, spell.length - 1); const info = spellInfo(spell); index = info.index; tone = parseInt(lastStr) as ToneType; isTrans = true; if (needTone) { spell = setTone(spell, index - 1, tone); } } else { // lǘ const info = spellInfo(spell); index = info.index; tone = info.tone; // 声调已经带好了的情况 if (!needTone && tone !== 0) { // 需要去除音调并且有音调 spell = info.spell; } } if (type === 'low') { spell = spell.toLowerCase(); } else if (type === 'up') { spell = spell.toUpperCase(); } return {spell, tone, index, isTrans}; }; export function checkTrad (input: string|string[], args: string[]) { if (args.indexOf('trad') === -1 || _cnchar.plugins.indexOf('trad') === -1) { return input; } let isArr = false; if (input instanceof Array) { isArr = true; input = input.join(''); } input = _cnchar.convert.tradToSimple(input); if (isArr) return input.split(''); return input; }
let mes: string = `以下参数${txt}:${JSON.stringify(arr)};`; if (txt === '被忽略' && type === 'stroke' && !has(args, 'order')) { mes += ' 要启用笔顺模式必须使用 order 参数'; } else { mes += ` 可选值
conditional_block
lib.rs
//! The Pikelet Compiler //! //! # Compiler Architecture //! //! In order to create a separation of concerns, we break up our compiler into many //! small stages, beginning with a source string, and ultimately ending up with //! compiled machine code. //! //! Below is a rough flow chart showing how source strings are currently lexed, //! parsed, desugared, and type checked/elaborated: //! //! ```bob //! .------------. //! | String | //! '------------' //! | //! - - - - - - - - - - - | - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //! Frontend | //! | //! pikelet_concrete::parse::lexer //! | //! v //! .---------------------------------------. //! | pikelet_concrete::parse::lexer::Token | //! '---------------------------------------' //! | //! pikelet_concrete::parse //! | //! v //! .------------------------------------------. //! | pikelet_concrete::syntax::concrete::Term |---------> Code formatter (TODO) //! '------------------------------------------' //! | //! pikelet_concrete::desugar //! | //! v //! .-------------------------------------. //! | pikelet_concrete::syntax::raw::Term | //! '-------------------------------------' //! | .-------------------------------------. //! pikelet_concrete::elaborate::{check,infer} <---------- | pikelet_core::syntax::domain::Value | //! | '-------------------------------------' //! v ^ //! .----------------------------------. | //! | pikelet_core::syntax::core::Term | -- pikelet_core::normalize -------' //! '----------------------------------' //! | //! | //! - - - - - - - - - - - | - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //! Middle (TODO) | //! | //! v //! A-Normal Form (ANF) //! | //! v //! Closure Conversion (CC) //! | //! v //! Static Single Assignment (SSA) //! | //! | //! - - - - - - - - - - - | - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //! Backend (TODO) | //! | //! v //! Codegen //! | //! *-------> Bytecode? //! | //! *-------> WASM? //! | //! *-------> Cranelift IR? //! | //! '-------> LLVM IR? //! ``` //! //! As you can see we have only built the front-end as of the time of writing. When //! we begin to build out a [compiler back end](https://github.com/pikelet-lang/pikelet/issues/9), //! more stages will be added after type checking and elaboration. //! //! ## Name binding //! //! Name binding is a surprisingly challenging thing to implement in type checkers //! and compilers. We use the [`moniker` crate](https://github.com/brendanzab/moniker) //! for this. Unfortunately this uses a quite slow method of name binding, and could //! result in performance blowouts in the future. This is something to keep an eye on! //! //! ## Performance considerations //! //! As you can see from the diagram above, this architecture leads to an //! easy-to-reason about pipeline. It does however result in the creation of lots of //! intermediate allocations of heap-allocated tree data structures that will //! ultimately be discarded. This is quite similar to the problem we face with //! iterators: //! //! ```rust,ignore //! // 'internal' iteration //! vec![1, 2, 3].map(|x| x * x).filter(|x| x < 3) //! //! // 'external' iteration //! vec![1, 2, 3].iter().map(|x| x * x).filter(|x| x < 3).collect() //! ``` //! //! The first example, which uses 'internal' iteration allocates a new collection //! after each operation, resulting in three allocated collections. We can improve //! the performance however by using 'external' iteration - ie. returning a series //! of chained iterator adaptors, that only perform the allocation on the call to //! `collect`. This emulates the 'fusion' that languages like Haskell perform to //! reduce intermediate allocations. //! //! We could potentially get some fusion between the stages of our compiler by way //! of the [visitor pattern](https://github.com/pikelet-lang/pikelet/issues/75). //! //! ## Support for interactive development //! //! It would be interesting to see how Pikelet could be implemented using an //! [asynchronous, query-based architecture](https://github.com/pikelet-lang/pikelet/issues/103). //! This will become more important as the demands of interactive development //! and incremental compilation become more pressing. In this model we would //! have to think of compilation as less a pure function from source code to //! machine code, and more as interacting with a database. //! //! ### Resources //! //! - [Queries: demand-driven compilation (Rustc Book)](https://rust-lang-nursery.github.io/rustc-guide/query.html) //! - [Anders Hejlsberg on Modern Compiler Construction (YouTube)](https://www.youtube.com/watch?v=wSdV1M7n4gQ) use codespan::CodeMap; pub use codespan::FileName; pub use codespan_reporting::{termcolor, ColorArg, Diagnostic}; use std::io; use pikelet_concrete::desugar::{Desugar, DesugarEnv}; use pikelet_concrete::elaborate::Context; use pikelet_concrete::resugar::Resugar; use pikelet_concrete::syntax::raw; use pikelet_core::syntax::{core, domain, Import}; /// An environment that keeps track of the state of a Pikelet program during /// compilation or interactive sessions #[derive(Debug, Clone)] pub struct Driver { /// The base type checking context, containing the built-in definitions context: Context, /// The base desugar environment, using the definitions from the `context` desugar_env: DesugarEnv, /// A codemap that owns the source code for any terms that are currently loaded code_map: CodeMap, } impl Driver { /// Create a new Pikelet environment, containing only the built-in definitions pub fn
() -> Driver { let context = Context::default(); let desugar_env = DesugarEnv::new(context.mappings()); Driver { context, desugar_env, code_map: CodeMap::new(), } } /// Create a new Pikelet environment, with the prelude loaded as well pub fn with_prelude() -> Driver { let mut pikelet = Driver::new(); pikelet .register_file( "prim".to_owned(), FileName::virtual_("prim"), pikelet_library::PRIM.to_owned(), ) .unwrap(); pikelet .register_file( "prelude".to_owned(), FileName::virtual_("prelude"), pikelet_library::PRELUDE.to_owned(), ) .unwrap(); pikelet } /// Add a binding to the driver's top-level environment pub fn add_binding(&mut self, name: &str, term: core::RcTerm, ann: domain::RcType) { let fv = self.desugar_env.on_binding(&name); self.context.insert_declaration(fv.clone(), ann.clone()); self.context.insert_definition(fv.clone(), term.clone()); } /// Register a file with the driver pub fn register_file( &mut self, path: String, name: FileName, src: String, ) -> Result<(), Vec<Diagnostic>> { let (term, ty) = self.infer_file(name, src)?; // FIXME: Check if import already exists self.context.insert_import(path, Import::Term(term), ty); Ok(()) } /// Infer the type of a file pub fn infer_file( &mut self, name: FileName, src: String, ) -> Result<(core::RcTerm, domain::RcType), Vec<Diagnostic>> { let file_map = self.code_map.add_filemap(name, src); // TODO: follow import paths let (concrete_term, _import_paths, errors) = pikelet_concrete::parse::term(&file_map); if !errors.is_empty() { return Err(errors.iter().map(|error| error.to_diagnostic()).collect()); } let raw_term = self.desugar(&concrete_term)?; self.infer_term(&raw_term) } /// Normalize the contents of a file pub fn normalize_file( &mut self, name: FileName, src: String, ) -> Result<domain::RcValue, Vec<Diagnostic>> { use pikelet_concrete::elaborate::InternalError; let (term, _) = self.infer_file(name, src)?; pikelet_core::nbe::nf_term(&self.context, &term) .map_err(|err| vec![InternalError::from(err).to_diagnostic()]) } /// Infer the type of a term pub fn infer_term( &self, raw_term: &raw::RcTerm, ) -> Result<(core::RcTerm, domain::RcType), Vec<Diagnostic>> { pikelet_concrete::elaborate::infer_term(&self.context, &raw_term) .map_err(|err| vec![err.to_diagnostic()]) } /// Normalize a term pub fn normalize_term(&self, term: &core::RcTerm) -> Result<domain::RcValue, Vec<Diagnostic>> { use pikelet_concrete::elaborate::InternalError; pikelet_core::nbe::nf_term(&self.context, term) .map_err(|err| vec![InternalError::from(err).to_diagnostic()]) } /// Desugar a term pub fn desugar<T>(&self, src: &impl Desugar<T>) -> Result<T, Vec<Diagnostic>> { src.desugar(&self.desugar_env) .map_err(|e| vec![e.to_diagnostic()]) } /// Resugar a term pub fn resugar<T>(&self, src: &impl Resugar<T>) -> T { self.context.resugar(src) } /// Emit the diagnostics using the given writer pub fn emit<'a>( &self, mut writer: impl termcolor::WriteColor, diagnostics: impl IntoIterator<Item = &'a Diagnostic>, ) -> io::Result<()> { for diagnostic in diagnostics { codespan_reporting::emit(&mut writer, &self.code_map, diagnostic)?; } Ok(()) } }
new
identifier_name
lib.rs
//! The Pikelet Compiler //! //! # Compiler Architecture //! //! In order to create a separation of concerns, we break up our compiler into many //! small stages, beginning with a source string, and ultimately ending up with //! compiled machine code. //! //! Below is a rough flow chart showing how source strings are currently lexed, //! parsed, desugared, and type checked/elaborated: //! //! ```bob //! .------------. //! | String | //! '------------' //! | //! - - - - - - - - - - - | - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //! Frontend | //! | //! pikelet_concrete::parse::lexer //! | //! v //! .---------------------------------------. //! | pikelet_concrete::parse::lexer::Token | //! '---------------------------------------' //! | //! pikelet_concrete::parse //! | //! v //! .------------------------------------------. //! | pikelet_concrete::syntax::concrete::Term |---------> Code formatter (TODO) //! '------------------------------------------' //! | //! pikelet_concrete::desugar //! | //! v //! .-------------------------------------. //! | pikelet_concrete::syntax::raw::Term | //! '-------------------------------------' //! | .-------------------------------------. //! pikelet_concrete::elaborate::{check,infer} <---------- | pikelet_core::syntax::domain::Value | //! | '-------------------------------------' //! v ^ //! .----------------------------------. | //! | pikelet_core::syntax::core::Term | -- pikelet_core::normalize -------' //! '----------------------------------' //! | //! | //! - - - - - - - - - - - | - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //! Middle (TODO) | //! | //! v //! A-Normal Form (ANF) //! | //! v //! Closure Conversion (CC) //! | //! v //! Static Single Assignment (SSA) //! | //! | //! - - - - - - - - - - - | - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //! Backend (TODO) | //! | //! v //! Codegen //! | //! *-------> Bytecode? //! | //! *-------> WASM? //! | //! *-------> Cranelift IR? //! | //! '-------> LLVM IR? //! ``` //! //! As you can see we have only built the front-end as of the time of writing. When //! we begin to build out a [compiler back end](https://github.com/pikelet-lang/pikelet/issues/9), //! more stages will be added after type checking and elaboration. //! //! ## Name binding //! //! Name binding is a surprisingly challenging thing to implement in type checkers //! and compilers. We use the [`moniker` crate](https://github.com/brendanzab/moniker) //! for this. Unfortunately this uses a quite slow method of name binding, and could //! result in performance blowouts in the future. This is something to keep an eye on! //! //! ## Performance considerations //! //! As you can see from the diagram above, this architecture leads to an //! easy-to-reason about pipeline. It does however result in the creation of lots of //! intermediate allocations of heap-allocated tree data structures that will //! ultimately be discarded. This is quite similar to the problem we face with //! iterators: //! //! ```rust,ignore //! // 'internal' iteration //! vec![1, 2, 3].map(|x| x * x).filter(|x| x < 3) //! //! // 'external' iteration //! vec![1, 2, 3].iter().map(|x| x * x).filter(|x| x < 3).collect() //! ``` //! //! The first example, which uses 'internal' iteration allocates a new collection //! after each operation, resulting in three allocated collections. We can improve //! the performance however by using 'external' iteration - ie. returning a series //! of chained iterator adaptors, that only perform the allocation on the call to //! `collect`. This emulates the 'fusion' that languages like Haskell perform to //! reduce intermediate allocations. //! //! We could potentially get some fusion between the stages of our compiler by way //! of the [visitor pattern](https://github.com/pikelet-lang/pikelet/issues/75). //! //! ## Support for interactive development //! //! It would be interesting to see how Pikelet could be implemented using an //! [asynchronous, query-based architecture](https://github.com/pikelet-lang/pikelet/issues/103). //! This will become more important as the demands of interactive development //! and incremental compilation become more pressing. In this model we would //! have to think of compilation as less a pure function from source code to //! machine code, and more as interacting with a database. //! //! ### Resources //! //! - [Queries: demand-driven compilation (Rustc Book)](https://rust-lang-nursery.github.io/rustc-guide/query.html) //! - [Anders Hejlsberg on Modern Compiler Construction (YouTube)](https://www.youtube.com/watch?v=wSdV1M7n4gQ) use codespan::CodeMap; pub use codespan::FileName; pub use codespan_reporting::{termcolor, ColorArg, Diagnostic}; use std::io; use pikelet_concrete::desugar::{Desugar, DesugarEnv}; use pikelet_concrete::elaborate::Context; use pikelet_concrete::resugar::Resugar; use pikelet_concrete::syntax::raw; use pikelet_core::syntax::{core, domain, Import}; /// An environment that keeps track of the state of a Pikelet program during /// compilation or interactive sessions #[derive(Debug, Clone)] pub struct Driver { /// The base type checking context, containing the built-in definitions context: Context, /// The base desugar environment, using the definitions from the `context` desugar_env: DesugarEnv, /// A codemap that owns the source code for any terms that are currently loaded code_map: CodeMap, } impl Driver { /// Create a new Pikelet environment, containing only the built-in definitions pub fn new() -> Driver { let context = Context::default(); let desugar_env = DesugarEnv::new(context.mappings()); Driver { context, desugar_env, code_map: CodeMap::new(), } } /// Create a new Pikelet environment, with the prelude loaded as well pub fn with_prelude() -> Driver { let mut pikelet = Driver::new(); pikelet .register_file( "prim".to_owned(), FileName::virtual_("prim"), pikelet_library::PRIM.to_owned(), ) .unwrap(); pikelet .register_file( "prelude".to_owned(), FileName::virtual_("prelude"), pikelet_library::PRELUDE.to_owned(), ) .unwrap(); pikelet } /// Add a binding to the driver's top-level environment pub fn add_binding(&mut self, name: &str, term: core::RcTerm, ann: domain::RcType) { let fv = self.desugar_env.on_binding(&name); self.context.insert_declaration(fv.clone(), ann.clone()); self.context.insert_definition(fv.clone(), term.clone()); } /// Register a file with the driver pub fn register_file( &mut self, path: String, name: FileName, src: String, ) -> Result<(), Vec<Diagnostic>> { let (term, ty) = self.infer_file(name, src)?; // FIXME: Check if import already exists self.context.insert_import(path, Import::Term(term), ty); Ok(()) } /// Infer the type of a file pub fn infer_file( &mut self, name: FileName, src: String, ) -> Result<(core::RcTerm, domain::RcType), Vec<Diagnostic>> { let file_map = self.code_map.add_filemap(name, src); // TODO: follow import paths let (concrete_term, _import_paths, errors) = pikelet_concrete::parse::term(&file_map); if !errors.is_empty()
let raw_term = self.desugar(&concrete_term)?; self.infer_term(&raw_term) } /// Normalize the contents of a file pub fn normalize_file( &mut self, name: FileName, src: String, ) -> Result<domain::RcValue, Vec<Diagnostic>> { use pikelet_concrete::elaborate::InternalError; let (term, _) = self.infer_file(name, src)?; pikelet_core::nbe::nf_term(&self.context, &term) .map_err(|err| vec![InternalError::from(err).to_diagnostic()]) } /// Infer the type of a term pub fn infer_term( &self, raw_term: &raw::RcTerm, ) -> Result<(core::RcTerm, domain::RcType), Vec<Diagnostic>> { pikelet_concrete::elaborate::infer_term(&self.context, &raw_term) .map_err(|err| vec![err.to_diagnostic()]) } /// Normalize a term pub fn normalize_term(&self, term: &core::RcTerm) -> Result<domain::RcValue, Vec<Diagnostic>> { use pikelet_concrete::elaborate::InternalError; pikelet_core::nbe::nf_term(&self.context, term) .map_err(|err| vec![InternalError::from(err).to_diagnostic()]) } /// Desugar a term pub fn desugar<T>(&self, src: &impl Desugar<T>) -> Result<T, Vec<Diagnostic>> { src.desugar(&self.desugar_env) .map_err(|e| vec![e.to_diagnostic()]) } /// Resugar a term pub fn resugar<T>(&self, src: &impl Resugar<T>) -> T { self.context.resugar(src) } /// Emit the diagnostics using the given writer pub fn emit<'a>( &self, mut writer: impl termcolor::WriteColor, diagnostics: impl IntoIterator<Item = &'a Diagnostic>, ) -> io::Result<()> { for diagnostic in diagnostics { codespan_reporting::emit(&mut writer, &self.code_map, diagnostic)?; } Ok(()) } }
{ return Err(errors.iter().map(|error| error.to_diagnostic()).collect()); }
conditional_block
lib.rs
//! The Pikelet Compiler //! //! # Compiler Architecture //! //! In order to create a separation of concerns, we break up our compiler into many //! small stages, beginning with a source string, and ultimately ending up with //! compiled machine code. //! //! Below is a rough flow chart showing how source strings are currently lexed, //! parsed, desugared, and type checked/elaborated: //! //! ```bob //! .------------. //! | String | //! '------------' //! | //! - - - - - - - - - - - | - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //! Frontend | //! | //! pikelet_concrete::parse::lexer //! | //! v //! .---------------------------------------. //! | pikelet_concrete::parse::lexer::Token | //! '---------------------------------------' //! | //! pikelet_concrete::parse //! | //! v //! .------------------------------------------. //! | pikelet_concrete::syntax::concrete::Term |---------> Code formatter (TODO) //! '------------------------------------------' //! | //! pikelet_concrete::desugar //! | //! v //! .-------------------------------------. //! | pikelet_concrete::syntax::raw::Term | //! '-------------------------------------' //! | .-------------------------------------. //! pikelet_concrete::elaborate::{check,infer} <---------- | pikelet_core::syntax::domain::Value | //! | '-------------------------------------' //! v ^ //! .----------------------------------. | //! | pikelet_core::syntax::core::Term | -- pikelet_core::normalize -------' //! '----------------------------------' //! | //! | //! - - - - - - - - - - - | - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //! Middle (TODO) | //! | //! v //! A-Normal Form (ANF) //! | //! v //! Closure Conversion (CC) //! | //! v //! Static Single Assignment (SSA) //! | //! | //! - - - - - - - - - - - | - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //! Backend (TODO) | //! | //! v //! Codegen //! | //! *-------> Bytecode? //! | //! *-------> WASM? //! | //! *-------> Cranelift IR? //! | //! '-------> LLVM IR? //! ``` //! //! As you can see we have only built the front-end as of the time of writing. When //! we begin to build out a [compiler back end](https://github.com/pikelet-lang/pikelet/issues/9), //! more stages will be added after type checking and elaboration. //! //! ## Name binding //! //! Name binding is a surprisingly challenging thing to implement in type checkers //! and compilers. We use the [`moniker` crate](https://github.com/brendanzab/moniker) //! for this. Unfortunately this uses a quite slow method of name binding, and could //! result in performance blowouts in the future. This is something to keep an eye on! //! //! ## Performance considerations //! //! As you can see from the diagram above, this architecture leads to an //! easy-to-reason about pipeline. It does however result in the creation of lots of //! intermediate allocations of heap-allocated tree data structures that will //! ultimately be discarded. This is quite similar to the problem we face with //! iterators: //! //! ```rust,ignore //! // 'internal' iteration //! vec![1, 2, 3].map(|x| x * x).filter(|x| x < 3) //! //! // 'external' iteration //! vec![1, 2, 3].iter().map(|x| x * x).filter(|x| x < 3).collect() //! ``` //! //! The first example, which uses 'internal' iteration allocates a new collection //! after each operation, resulting in three allocated collections. We can improve //! the performance however by using 'external' iteration - ie. returning a series //! of chained iterator adaptors, that only perform the allocation on the call to //! `collect`. This emulates the 'fusion' that languages like Haskell perform to //! reduce intermediate allocations. //! //! We could potentially get some fusion between the stages of our compiler by way //! of the [visitor pattern](https://github.com/pikelet-lang/pikelet/issues/75). //! //! ## Support for interactive development //! //! It would be interesting to see how Pikelet could be implemented using an //! [asynchronous, query-based architecture](https://github.com/pikelet-lang/pikelet/issues/103). //! This will become more important as the demands of interactive development //! and incremental compilation become more pressing. In this model we would //! have to think of compilation as less a pure function from source code to //! machine code, and more as interacting with a database. //! //! ### Resources //! //! - [Queries: demand-driven compilation (Rustc Book)](https://rust-lang-nursery.github.io/rustc-guide/query.html) //! - [Anders Hejlsberg on Modern Compiler Construction (YouTube)](https://www.youtube.com/watch?v=wSdV1M7n4gQ) use codespan::CodeMap; pub use codespan::FileName; pub use codespan_reporting::{termcolor, ColorArg, Diagnostic}; use std::io; use pikelet_concrete::desugar::{Desugar, DesugarEnv}; use pikelet_concrete::elaborate::Context; use pikelet_concrete::resugar::Resugar; use pikelet_concrete::syntax::raw; use pikelet_core::syntax::{core, domain, Import}; /// An environment that keeps track of the state of a Pikelet program during /// compilation or interactive sessions #[derive(Debug, Clone)] pub struct Driver { /// The base type checking context, containing the built-in definitions context: Context, /// The base desugar environment, using the definitions from the `context` desugar_env: DesugarEnv, /// A codemap that owns the source code for any terms that are currently loaded code_map: CodeMap, } impl Driver { /// Create a new Pikelet environment, containing only the built-in definitions pub fn new() -> Driver { let context = Context::default(); let desugar_env = DesugarEnv::new(context.mappings()); Driver { context, desugar_env, code_map: CodeMap::new(), } } /// Create a new Pikelet environment, with the prelude loaded as well pub fn with_prelude() -> Driver { let mut pikelet = Driver::new(); pikelet .register_file( "prim".to_owned(), FileName::virtual_("prim"), pikelet_library::PRIM.to_owned(), ) .unwrap(); pikelet .register_file( "prelude".to_owned(), FileName::virtual_("prelude"), pikelet_library::PRELUDE.to_owned(), ) .unwrap(); pikelet } /// Add a binding to the driver's top-level environment pub fn add_binding(&mut self, name: &str, term: core::RcTerm, ann: domain::RcType) { let fv = self.desugar_env.on_binding(&name); self.context.insert_declaration(fv.clone(), ann.clone()); self.context.insert_definition(fv.clone(), term.clone()); } /// Register a file with the driver pub fn register_file( &mut self, path: String, name: FileName, src: String, ) -> Result<(), Vec<Diagnostic>> { let (term, ty) = self.infer_file(name, src)?; // FIXME: Check if import already exists self.context.insert_import(path, Import::Term(term), ty); Ok(()) }
pub fn infer_file( &mut self, name: FileName, src: String, ) -> Result<(core::RcTerm, domain::RcType), Vec<Diagnostic>> { let file_map = self.code_map.add_filemap(name, src); // TODO: follow import paths let (concrete_term, _import_paths, errors) = pikelet_concrete::parse::term(&file_map); if !errors.is_empty() { return Err(errors.iter().map(|error| error.to_diagnostic()).collect()); } let raw_term = self.desugar(&concrete_term)?; self.infer_term(&raw_term) } /// Normalize the contents of a file pub fn normalize_file( &mut self, name: FileName, src: String, ) -> Result<domain::RcValue, Vec<Diagnostic>> { use pikelet_concrete::elaborate::InternalError; let (term, _) = self.infer_file(name, src)?; pikelet_core::nbe::nf_term(&self.context, &term) .map_err(|err| vec![InternalError::from(err).to_diagnostic()]) } /// Infer the type of a term pub fn infer_term( &self, raw_term: &raw::RcTerm, ) -> Result<(core::RcTerm, domain::RcType), Vec<Diagnostic>> { pikelet_concrete::elaborate::infer_term(&self.context, &raw_term) .map_err(|err| vec![err.to_diagnostic()]) } /// Normalize a term pub fn normalize_term(&self, term: &core::RcTerm) -> Result<domain::RcValue, Vec<Diagnostic>> { use pikelet_concrete::elaborate::InternalError; pikelet_core::nbe::nf_term(&self.context, term) .map_err(|err| vec![InternalError::from(err).to_diagnostic()]) } /// Desugar a term pub fn desugar<T>(&self, src: &impl Desugar<T>) -> Result<T, Vec<Diagnostic>> { src.desugar(&self.desugar_env) .map_err(|e| vec![e.to_diagnostic()]) } /// Resugar a term pub fn resugar<T>(&self, src: &impl Resugar<T>) -> T { self.context.resugar(src) } /// Emit the diagnostics using the given writer pub fn emit<'a>( &self, mut writer: impl termcolor::WriteColor, diagnostics: impl IntoIterator<Item = &'a Diagnostic>, ) -> io::Result<()> { for diagnostic in diagnostics { codespan_reporting::emit(&mut writer, &self.code_map, diagnostic)?; } Ok(()) } }
/// Infer the type of a file
random_line_split
Histo.js
/** * @jsx React.DOM */ var React = require('react/addons'); var cx = React.addons.classSet; var moment = require('moment'); var Router = require('react-router'); var Route = Router.Route; var NotFoundRoute = Router.NotFoundRoute; var DefaultRoute = Router.DefaultRoute; var Link = Router.Link; var RouteHandler = Router.RouteHandler; var Row = require('react-bootstrap').Row; var Accordion = require('react-bootstrap').Accordion; var Panel = require('react-bootstrap').Panel; var Grid = require('react-bootstrap').Grid; var Label = require('react-bootstrap').Label; var Col = require('react-bootstrap').Col; var ModalTrigger = require('react-bootstrap').ModalTrigger; var ButtonGroup = require('react-bootstrap').ButtonGroup; var Button = require('react-bootstrap').Button; var OverlayTrigger = require('react-bootstrap').OverlayTrigger; var Tooltip = require('react-bootstrap').Tooltip; var Modal = require('react-bootstrap').Modal; var Badge = require('react-bootstrap').Badge; var TabbedArea = require('react-bootstrap').TabbedArea; var TabPane = require('react-bootstrap').TabPane; var DropdownButton = require('react-bootstrap').DropdownButton; var MenuItem = require('react-bootstrap').MenuItem; var Table = require('react-bootstrap').Table; var Promise = require('es6-promise').Promise; var Utils = require('./Utils'); var $ = require('jquery'); var d3 = require('d3'); require('../libs/d3.tip.js'); var debug = require('debug')('Histo.js'); var startYear; var Histo = React.createClass({ toggleGraph: function() { if(this.state.chartType === 'pi') { this.setState({chartType: 'real'}); } else { this.setState({chartType: 'pi'}); } }, getInitialState: function() { var refval; if(localStorage.getItem(this.props.title)) { refval = localStorage.getItem(this.props.title); } else { localStorage.setItem(this.props.title, 50); refval = localStorage.getItem(this.props.title); } return { selected: false, referenceValue: refval, chartType: 'pi' // Can be 'pi' or 'real' }; }, handleReferenceValueChange: function(e) { debug(e.target.value); localStorage.setItem(this.props.title, e.target.value); this.setState({ referenceValue: e.target.value }); }, handleHistoClick: function() { var self = this; self.props.handleSelection({ 'title': self.props.title, 'selected': !self.state.selected }); if(self.props.active) { self.setState({selected: false}); } else { self.setState({selected: true}); } }, render: function() { var self = this; var title = this.props.title; var chartType = this.state.chartType; var values = this.props.values; var period = this.props.period; var referenceValue = this.state.referenceValue; var line, lastValue; var tooltipString = 'PI'; // if(values[values.length - 1].Value === 'NULL') { // // Last value is NULL... do not draw this chart! // return <div style={{display:'none'}} />; // } if(chartType === 'real') { lastValue = Math.round(values[values.length - 1].Abs) || 0; tooltipString = 'Aantal'; } else { lastValue = Math.round(values[values.length - 1].Score) || 0; tooltipString = 'PI'; } // D3 configuration var margin = {top: 20, right: 20, bottom: 60, left: 50}, width = 500 - margin.left - margin.right, height = 200 - margin.top - margin.bottom; var parseDate = d3.time.format("%m/%d/%Y").parse; if(period) { startYear = moment('2014').subtract(period, 'years'); } else { startYear = moment('2014').subtract(5, 'years'); } var x = d3.time.scale() .range([0, width]) .domain([startYear.toDate(), moment('12-30-2014').toDate()]).clamp(true); var y = d3.scale.linear() .range([height, 1]); var xAxis = d3.svg.axis() .scale(x) .tickFormat(d3.time.format("%m/%y")) .tickPadding(12) .orient("bottom"); var yAxis = d3.svg.axis() .scale(y) .orient("left"); if(chartType === 'real') { line = d3.svg.line() .defined(function(d) { return d.Abs != 'NULL'; }) .interpolate("cardinal") .x(function(d) { return x(parseDate(d.Date)); }) .y(function(d) { return y(Number(d.Abs)); }); } else { line = d3.svg.line() .defined(function(d) { return d.Score != 'NULL'; }) .x(function(d) { return x(parseDate(d.Date)); }) .y(function(d) { return y(Number(d.Score)); }); } d3.select('#'+title.replace(/ /g, '-')).select('svg').remove(); // This should not be necessary, break up d3 into smaller components? var svg = d3.select('#'+title.replace(/ /g, '-')).append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); if(chartType === 'real') { y.domain(d3.extent(values, function(d) { return Number(d.Abs); })); } else { y.domain([1, 10]); } var xaxis = svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xAxis); xaxis.selectAll("text") .style("text-anchor", "end") .attr("dx", "-.8em") .attr("dy", ".15em") .attr("transform", function(d) { return "rotate(-65)"; }); svg.append("g") .attr("class", "y axis") .call(yAxis) .append("text") .text(chartType === 'real' ? 'Aantal' : 'PI') .attr("transform", "rotate(-90)") .attr("y", 6) .attr("dy", ".71em") .style("text-anchor", "end"); try { if(chartType === 'pi')
} catch(error) { console.log(error); } var path = svg.append("path") .datum(values) .attr("class", "line") .attr("d", line); path.each(function(d) { d.totalLength = this.getTotalLength(); }); // Add total length per path, needed for animating over full length if(chartType === 'pi') { path .attr("stroke-dasharray", function(d) { return d.totalLength + " " + d.totalLength; }) .attr("stroke-dashoffset", function(d) { return d.totalLength; }) .transition() .duration(1000) .ease("linear") .attr("stroke-dashoffset", 0); } var bisectDate = d3.bisector(function(d) { return parseDate(d.Date); }).left; var focus = svg.append("g") .attr("class", "focus") .style("display", "none"); focus.append("circle") .attr("r", 4.5); focus.append("text") .attr("x", 9) .attr("dy", ".35em"); svg.append("rect") .attr("class", "overlay") .attr("width", width) .attr("height", height) .on("mouseover", function() { focus.style("display", null); }) .on("mouseout", function() { focus.style("display", "none"); }) .on("mousemove", mousemove); function mousemove() { var x0 = x.invert(d3.mouse(this)[0]), i = bisectDate(values, x0, 1), d0 = values[i - 1], d1 = values[i], d = x0 - d0.Date > d1.Date - x0 ? d1 : d0; if(chartType === 'pi') { focus.attr("transform", "translate(" + x(parseDate(d.Date)) + "," + y(d.Score) + ")"); focus.select("text").text(d.Score); } else { focus.attr("transform", "translate(" + x(parseDate(d.Date)) + "," + y(d.Abs) + ")"); focus.select("text").text(d.Abs); } } var max = d3.max(values, function(d) { return Number(d.Abs); }); if(self.state.referenceValue && chartType === 'real') { svg.append('line') .attr({ x1: xAxis.scale()(0), y1: yAxis.scale()((self.state.referenceValue * max) / 100), x2: 1000, y2: yAxis.scale()((self.state.referenceValue * max) / 100) }) .style("stroke-dasharray", "5,5") .style("stroke", "#000"); } var refval = ((self.state.referenceValue * max) / 100); var alarmTxt = ''; var alarmClass = false; if(refval > lastValue) { alarmClass = true; alarmTxt = 'Onder referentiewaarde' } else { alarmClass = false; alarmTxt = 'Boven referentiewaarde' } self.props.setRefVal(refval); var alarmClasses = cx({ 'danger': alarmClass }); var classesTitlebar = cx({ 'panel-heading': true, 'rightarrowdiv': self.props.active, 'active': self.props.active }); var classesContainer = cx({ 'panel': true, 'panel-default': true, 'active': self.props.active }); var classesToggleSlider = cx({ 'hide': self.state.chartType === 'pi' }); var bgCol = '#fff'; if(self.state.chartType === 'pi') { bgCol = Utils.quantize(lastValue); } else { bgCol = '#fff'; } var txtCol = (self.state.chartType === 'pi') ? '#fff' : '#000'; return ( <div className={classesContainer} onClick={this.handleHistoClick} ref="histoRoot"> <div style={{position:'relative'}} className={classesTitlebar}> <OverlayTrigger placement="right" overlay={<Tooltip><strong>{tooltipString}</strong></Tooltip>}> <Label onClick={this.toggleGraph} style={{float:'right', fontSize:'1.1em', cursor: 'pointer', backgroundColor: bgCol, color: txtCol}}> {lastValue} {(self.state.chartType === 'pi') ? '' : ' ('+alarmTxt+')'} </Label> </OverlayTrigger>&nbsp; <span onClick={this.handleHistoClick} style={{cursor:'pointer', fontWeight:'bold', fontSize:'1.1em'}}> {title} </span> </div> <div className="panel-body"> <div className="histoChart" ref="chart" id={title.replace(/ /g, '-')}> <input onChange={this.handleReferenceValueChange} className={classesToggleSlider} type='range' defaultValue={this.state.referenceValue} style={{width:159, position:'relative', top:103, left:437, '-webkit-transform':'rotate(-90deg)', '-moz-transform':'rotate(-90deg)', transform:'rotate(-90deg)'}} /> </div> </div> </div> ); } }); module.exports = Histo;
{ var withoutNull = _.without(values, 'NULL'); svg.append('circle') .attr('class', 'sparkcircle') .attr('cx', x(parseDate(withoutNull[withoutNull.length - 1].Date))) .attr('cy', y(Number(withoutNull[withoutNull.length - 1].Score))) .attr('r', 5); }
conditional_block
Histo.js
/** * @jsx React.DOM */ var React = require('react/addons'); var cx = React.addons.classSet; var moment = require('moment'); var Router = require('react-router'); var Route = Router.Route; var NotFoundRoute = Router.NotFoundRoute; var DefaultRoute = Router.DefaultRoute; var Link = Router.Link; var RouteHandler = Router.RouteHandler; var Row = require('react-bootstrap').Row; var Accordion = require('react-bootstrap').Accordion; var Panel = require('react-bootstrap').Panel; var Grid = require('react-bootstrap').Grid; var Label = require('react-bootstrap').Label; var Col = require('react-bootstrap').Col; var ModalTrigger = require('react-bootstrap').ModalTrigger; var ButtonGroup = require('react-bootstrap').ButtonGroup; var Button = require('react-bootstrap').Button; var OverlayTrigger = require('react-bootstrap').OverlayTrigger; var Tooltip = require('react-bootstrap').Tooltip; var Modal = require('react-bootstrap').Modal; var Badge = require('react-bootstrap').Badge; var TabbedArea = require('react-bootstrap').TabbedArea; var TabPane = require('react-bootstrap').TabPane; var DropdownButton = require('react-bootstrap').DropdownButton; var MenuItem = require('react-bootstrap').MenuItem; var Table = require('react-bootstrap').Table; var Promise = require('es6-promise').Promise; var Utils = require('./Utils'); var $ = require('jquery'); var d3 = require('d3'); require('../libs/d3.tip.js'); var debug = require('debug')('Histo.js'); var startYear; var Histo = React.createClass({ toggleGraph: function() { if(this.state.chartType === 'pi') { this.setState({chartType: 'real'}); } else { this.setState({chartType: 'pi'}); } }, getInitialState: function() { var refval; if(localStorage.getItem(this.props.title)) { refval = localStorage.getItem(this.props.title); } else { localStorage.setItem(this.props.title, 50); refval = localStorage.getItem(this.props.title); } return { selected: false, referenceValue: refval, chartType: 'pi' // Can be 'pi' or 'real' }; }, handleReferenceValueChange: function(e) { debug(e.target.value); localStorage.setItem(this.props.title, e.target.value); this.setState({ referenceValue: e.target.value }); }, handleHistoClick: function() { var self = this; self.props.handleSelection({ 'title': self.props.title, 'selected': !self.state.selected }); if(self.props.active) { self.setState({selected: false}); } else { self.setState({selected: true}); } }, render: function() { var self = this; var title = this.props.title; var chartType = this.state.chartType; var values = this.props.values; var period = this.props.period; var referenceValue = this.state.referenceValue; var line, lastValue; var tooltipString = 'PI'; // if(values[values.length - 1].Value === 'NULL') { // // Last value is NULL... do not draw this chart! // return <div style={{display:'none'}} />; // } if(chartType === 'real') { lastValue = Math.round(values[values.length - 1].Abs) || 0; tooltipString = 'Aantal'; } else { lastValue = Math.round(values[values.length - 1].Score) || 0; tooltipString = 'PI'; } // D3 configuration var margin = {top: 20, right: 20, bottom: 60, left: 50}, width = 500 - margin.left - margin.right, height = 200 - margin.top - margin.bottom; var parseDate = d3.time.format("%m/%d/%Y").parse; if(period) { startYear = moment('2014').subtract(period, 'years'); } else { startYear = moment('2014').subtract(5, 'years'); } var x = d3.time.scale() .range([0, width]) .domain([startYear.toDate(), moment('12-30-2014').toDate()]).clamp(true); var y = d3.scale.linear() .range([height, 1]); var xAxis = d3.svg.axis() .scale(x) .tickFormat(d3.time.format("%m/%y")) .tickPadding(12) .orient("bottom"); var yAxis = d3.svg.axis() .scale(y) .orient("left"); if(chartType === 'real') { line = d3.svg.line() .defined(function(d) { return d.Abs != 'NULL'; }) .interpolate("cardinal") .x(function(d) { return x(parseDate(d.Date)); }) .y(function(d) { return y(Number(d.Abs)); }); } else { line = d3.svg.line() .defined(function(d) { return d.Score != 'NULL'; }) .x(function(d) { return x(parseDate(d.Date)); }) .y(function(d) { return y(Number(d.Score)); }); } d3.select('#'+title.replace(/ /g, '-')).select('svg').remove(); // This should not be necessary, break up d3 into smaller components? var svg = d3.select('#'+title.replace(/ /g, '-')).append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); if(chartType === 'real') { y.domain(d3.extent(values, function(d) { return Number(d.Abs); })); } else { y.domain([1, 10]); } var xaxis = svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xAxis); xaxis.selectAll("text") .style("text-anchor", "end") .attr("dx", "-.8em") .attr("dy", ".15em") .attr("transform", function(d) { return "rotate(-65)"; }); svg.append("g") .attr("class", "y axis") .call(yAxis) .append("text") .text(chartType === 'real' ? 'Aantal' : 'PI') .attr("transform", "rotate(-90)") .attr("y", 6) .attr("dy", ".71em") .style("text-anchor", "end"); try { if(chartType === 'pi') { var withoutNull = _.without(values, 'NULL'); svg.append('circle') .attr('class', 'sparkcircle') .attr('cx', x(parseDate(withoutNull[withoutNull.length - 1].Date))) .attr('cy', y(Number(withoutNull[withoutNull.length - 1].Score))) .attr('r', 5); } } catch(error) { console.log(error); } var path = svg.append("path") .datum(values) .attr("class", "line") .attr("d", line); path.each(function(d) { d.totalLength = this.getTotalLength(); }); // Add total length per path, needed for animating over full length if(chartType === 'pi') { path .attr("stroke-dasharray", function(d) { return d.totalLength + " " + d.totalLength; }) .attr("stroke-dashoffset", function(d) { return d.totalLength; }) .transition() .duration(1000) .ease("linear") .attr("stroke-dashoffset", 0); } var bisectDate = d3.bisector(function(d) { return parseDate(d.Date); }).left; var focus = svg.append("g") .attr("class", "focus") .style("display", "none"); focus.append("circle") .attr("r", 4.5); focus.append("text") .attr("x", 9) .attr("dy", ".35em"); svg.append("rect") .attr("class", "overlay") .attr("width", width) .attr("height", height) .on("mouseover", function() { focus.style("display", null); }) .on("mouseout", function() { focus.style("display", "none"); }) .on("mousemove", mousemove); function mousemove() { var x0 = x.invert(d3.mouse(this)[0]), i = bisectDate(values, x0, 1), d0 = values[i - 1], d1 = values[i], d = x0 - d0.Date > d1.Date - x0 ? d1 : d0; if(chartType === 'pi') { focus.attr("transform", "translate(" + x(parseDate(d.Date)) + "," + y(d.Score) + ")"); focus.select("text").text(d.Score); } else { focus.attr("transform", "translate(" + x(parseDate(d.Date)) + "," + y(d.Abs) + ")"); focus.select("text").text(d.Abs); } } var max = d3.max(values, function(d) { return Number(d.Abs); }); if(self.state.referenceValue && chartType === 'real') { svg.append('line') .attr({ x1: xAxis.scale()(0), y1: yAxis.scale()((self.state.referenceValue * max) / 100), x2: 1000, y2: yAxis.scale()((self.state.referenceValue * max) / 100) }) .style("stroke-dasharray", "5,5") .style("stroke", "#000"); } var refval = ((self.state.referenceValue * max) / 100); var alarmTxt = ''; var alarmClass = false; if(refval > lastValue) { alarmClass = true; alarmTxt = 'Onder referentiewaarde' } else { alarmClass = false; alarmTxt = 'Boven referentiewaarde' } self.props.setRefVal(refval); var alarmClasses = cx({ 'danger': alarmClass }); var classesTitlebar = cx({ 'panel-heading': true, 'rightarrowdiv': self.props.active, 'active': self.props.active }); var classesContainer = cx({ 'panel': true, 'panel-default': true, 'active': self.props.active }); var classesToggleSlider = cx({ 'hide': self.state.chartType === 'pi' }); var bgCol = '#fff'; if(self.state.chartType === 'pi') { bgCol = Utils.quantize(lastValue); } else { bgCol = '#fff'; } var txtCol = (self.state.chartType === 'pi') ? '#fff' : '#000'; return ( <div className={classesContainer} onClick={this.handleHistoClick} ref="histoRoot"> <div style={{position:'relative'}} className={classesTitlebar}> <OverlayTrigger placement="right" overlay={<Tooltip><strong>{tooltipString}</strong></Tooltip>}> <Label onClick={this.toggleGraph} style={{float:'right', fontSize:'1.1em', cursor: 'pointer', backgroundColor: bgCol, color: txtCol}}> {lastValue} {(self.state.chartType === 'pi') ? '' : ' ('+alarmTxt+')'} </Label> </OverlayTrigger>&nbsp; <span onClick={this.handleHistoClick} style={{cursor:'pointer', fontWeight:'bold', fontSize:'1.1em'}}> {title} </span> </div> <div className="panel-body">
<div className="histoChart" ref="chart" id={title.replace(/ /g, '-')}> <input onChange={this.handleReferenceValueChange} className={classesToggleSlider} type='range' defaultValue={this.state.referenceValue} style={{width:159, position:'relative', top:103, left:437, '-webkit-transform':'rotate(-90deg)', '-moz-transform':'rotate(-90deg)', transform:'rotate(-90deg)'}} /> </div> </div> </div> ); } }); module.exports = Histo;
random_line_split
Histo.js
/** * @jsx React.DOM */ var React = require('react/addons'); var cx = React.addons.classSet; var moment = require('moment'); var Router = require('react-router'); var Route = Router.Route; var NotFoundRoute = Router.NotFoundRoute; var DefaultRoute = Router.DefaultRoute; var Link = Router.Link; var RouteHandler = Router.RouteHandler; var Row = require('react-bootstrap').Row; var Accordion = require('react-bootstrap').Accordion; var Panel = require('react-bootstrap').Panel; var Grid = require('react-bootstrap').Grid; var Label = require('react-bootstrap').Label; var Col = require('react-bootstrap').Col; var ModalTrigger = require('react-bootstrap').ModalTrigger; var ButtonGroup = require('react-bootstrap').ButtonGroup; var Button = require('react-bootstrap').Button; var OverlayTrigger = require('react-bootstrap').OverlayTrigger; var Tooltip = require('react-bootstrap').Tooltip; var Modal = require('react-bootstrap').Modal; var Badge = require('react-bootstrap').Badge; var TabbedArea = require('react-bootstrap').TabbedArea; var TabPane = require('react-bootstrap').TabPane; var DropdownButton = require('react-bootstrap').DropdownButton; var MenuItem = require('react-bootstrap').MenuItem; var Table = require('react-bootstrap').Table; var Promise = require('es6-promise').Promise; var Utils = require('./Utils'); var $ = require('jquery'); var d3 = require('d3'); require('../libs/d3.tip.js'); var debug = require('debug')('Histo.js'); var startYear; var Histo = React.createClass({ toggleGraph: function() { if(this.state.chartType === 'pi') { this.setState({chartType: 'real'}); } else { this.setState({chartType: 'pi'}); } }, getInitialState: function() { var refval; if(localStorage.getItem(this.props.title)) { refval = localStorage.getItem(this.props.title); } else { localStorage.setItem(this.props.title, 50); refval = localStorage.getItem(this.props.title); } return { selected: false, referenceValue: refval, chartType: 'pi' // Can be 'pi' or 'real' }; }, handleReferenceValueChange: function(e) { debug(e.target.value); localStorage.setItem(this.props.title, e.target.value); this.setState({ referenceValue: e.target.value }); }, handleHistoClick: function() { var self = this; self.props.handleSelection({ 'title': self.props.title, 'selected': !self.state.selected }); if(self.props.active) { self.setState({selected: false}); } else { self.setState({selected: true}); } }, render: function() { var self = this; var title = this.props.title; var chartType = this.state.chartType; var values = this.props.values; var period = this.props.period; var referenceValue = this.state.referenceValue; var line, lastValue; var tooltipString = 'PI'; // if(values[values.length - 1].Value === 'NULL') { // // Last value is NULL... do not draw this chart! // return <div style={{display:'none'}} />; // } if(chartType === 'real') { lastValue = Math.round(values[values.length - 1].Abs) || 0; tooltipString = 'Aantal'; } else { lastValue = Math.round(values[values.length - 1].Score) || 0; tooltipString = 'PI'; } // D3 configuration var margin = {top: 20, right: 20, bottom: 60, left: 50}, width = 500 - margin.left - margin.right, height = 200 - margin.top - margin.bottom; var parseDate = d3.time.format("%m/%d/%Y").parse; if(period) { startYear = moment('2014').subtract(period, 'years'); } else { startYear = moment('2014').subtract(5, 'years'); } var x = d3.time.scale() .range([0, width]) .domain([startYear.toDate(), moment('12-30-2014').toDate()]).clamp(true); var y = d3.scale.linear() .range([height, 1]); var xAxis = d3.svg.axis() .scale(x) .tickFormat(d3.time.format("%m/%y")) .tickPadding(12) .orient("bottom"); var yAxis = d3.svg.axis() .scale(y) .orient("left"); if(chartType === 'real') { line = d3.svg.line() .defined(function(d) { return d.Abs != 'NULL'; }) .interpolate("cardinal") .x(function(d) { return x(parseDate(d.Date)); }) .y(function(d) { return y(Number(d.Abs)); }); } else { line = d3.svg.line() .defined(function(d) { return d.Score != 'NULL'; }) .x(function(d) { return x(parseDate(d.Date)); }) .y(function(d) { return y(Number(d.Score)); }); } d3.select('#'+title.replace(/ /g, '-')).select('svg').remove(); // This should not be necessary, break up d3 into smaller components? var svg = d3.select('#'+title.replace(/ /g, '-')).append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); if(chartType === 'real') { y.domain(d3.extent(values, function(d) { return Number(d.Abs); })); } else { y.domain([1, 10]); } var xaxis = svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xAxis); xaxis.selectAll("text") .style("text-anchor", "end") .attr("dx", "-.8em") .attr("dy", ".15em") .attr("transform", function(d) { return "rotate(-65)"; }); svg.append("g") .attr("class", "y axis") .call(yAxis) .append("text") .text(chartType === 'real' ? 'Aantal' : 'PI') .attr("transform", "rotate(-90)") .attr("y", 6) .attr("dy", ".71em") .style("text-anchor", "end"); try { if(chartType === 'pi') { var withoutNull = _.without(values, 'NULL'); svg.append('circle') .attr('class', 'sparkcircle') .attr('cx', x(parseDate(withoutNull[withoutNull.length - 1].Date))) .attr('cy', y(Number(withoutNull[withoutNull.length - 1].Score))) .attr('r', 5); } } catch(error) { console.log(error); } var path = svg.append("path") .datum(values) .attr("class", "line") .attr("d", line); path.each(function(d) { d.totalLength = this.getTotalLength(); }); // Add total length per path, needed for animating over full length if(chartType === 'pi') { path .attr("stroke-dasharray", function(d) { return d.totalLength + " " + d.totalLength; }) .attr("stroke-dashoffset", function(d) { return d.totalLength; }) .transition() .duration(1000) .ease("linear") .attr("stroke-dashoffset", 0); } var bisectDate = d3.bisector(function(d) { return parseDate(d.Date); }).left; var focus = svg.append("g") .attr("class", "focus") .style("display", "none"); focus.append("circle") .attr("r", 4.5); focus.append("text") .attr("x", 9) .attr("dy", ".35em"); svg.append("rect") .attr("class", "overlay") .attr("width", width) .attr("height", height) .on("mouseover", function() { focus.style("display", null); }) .on("mouseout", function() { focus.style("display", "none"); }) .on("mousemove", mousemove); function mousemove()
var max = d3.max(values, function(d) { return Number(d.Abs); }); if(self.state.referenceValue && chartType === 'real') { svg.append('line') .attr({ x1: xAxis.scale()(0), y1: yAxis.scale()((self.state.referenceValue * max) / 100), x2: 1000, y2: yAxis.scale()((self.state.referenceValue * max) / 100) }) .style("stroke-dasharray", "5,5") .style("stroke", "#000"); } var refval = ((self.state.referenceValue * max) / 100); var alarmTxt = ''; var alarmClass = false; if(refval > lastValue) { alarmClass = true; alarmTxt = 'Onder referentiewaarde' } else { alarmClass = false; alarmTxt = 'Boven referentiewaarde' } self.props.setRefVal(refval); var alarmClasses = cx({ 'danger': alarmClass }); var classesTitlebar = cx({ 'panel-heading': true, 'rightarrowdiv': self.props.active, 'active': self.props.active }); var classesContainer = cx({ 'panel': true, 'panel-default': true, 'active': self.props.active }); var classesToggleSlider = cx({ 'hide': self.state.chartType === 'pi' }); var bgCol = '#fff'; if(self.state.chartType === 'pi') { bgCol = Utils.quantize(lastValue); } else { bgCol = '#fff'; } var txtCol = (self.state.chartType === 'pi') ? '#fff' : '#000'; return ( <div className={classesContainer} onClick={this.handleHistoClick} ref="histoRoot"> <div style={{position:'relative'}} className={classesTitlebar}> <OverlayTrigger placement="right" overlay={<Tooltip><strong>{tooltipString}</strong></Tooltip>}> <Label onClick={this.toggleGraph} style={{float:'right', fontSize:'1.1em', cursor: 'pointer', backgroundColor: bgCol, color: txtCol}}> {lastValue} {(self.state.chartType === 'pi') ? '' : ' ('+alarmTxt+')'} </Label> </OverlayTrigger>&nbsp; <span onClick={this.handleHistoClick} style={{cursor:'pointer', fontWeight:'bold', fontSize:'1.1em'}}> {title} </span> </div> <div className="panel-body"> <div className="histoChart" ref="chart" id={title.replace(/ /g, '-')}> <input onChange={this.handleReferenceValueChange} className={classesToggleSlider} type='range' defaultValue={this.state.referenceValue} style={{width:159, position:'relative', top:103, left:437, '-webkit-transform':'rotate(-90deg)', '-moz-transform':'rotate(-90deg)', transform:'rotate(-90deg)'}} /> </div> </div> </div> ); } }); module.exports = Histo;
{ var x0 = x.invert(d3.mouse(this)[0]), i = bisectDate(values, x0, 1), d0 = values[i - 1], d1 = values[i], d = x0 - d0.Date > d1.Date - x0 ? d1 : d0; if(chartType === 'pi') { focus.attr("transform", "translate(" + x(parseDate(d.Date)) + "," + y(d.Score) + ")"); focus.select("text").text(d.Score); } else { focus.attr("transform", "translate(" + x(parseDate(d.Date)) + "," + y(d.Abs) + ")"); focus.select("text").text(d.Abs); } }
identifier_body